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" 45 using namespace clang; 46 using namespace sema; 47 48 /// \brief Determine whether the use of this declaration is valid, without 49 /// emitting diagnostics. 50 bool 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 69 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S, 70 NamedDecl *D, SourceLocation Loc, 71 const ObjCInterfaceDecl *UnknownObjCClass) { 72 // See if this declaration is unavailable or deprecated. 73 std::string Message; 74 AvailabilityResult Result = D->getAvailability(&Message); 75 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 76 if (Result == AR_Available) { 77 const DeclContext *DC = ECD->getDeclContext(); 78 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 79 Result = TheEnumDecl->getAvailability(&Message); 80 } 81 82 switch (Result) { 83 case AR_Available: 84 case AR_NotYetIntroduced: 85 break; 86 87 case AR_Deprecated: 88 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass); 89 break; 90 91 case AR_Unavailable: 92 if (S.getCurContextAvailability() != AR_Unavailable) { 93 if (Message.empty()) { 94 if (!UnknownObjCClass) 95 S.Diag(Loc, diag::err_unavailable) << D->getDeclName(); 96 else 97 S.Diag(Loc, diag::warn_unavailable_fwdclass_message) 98 << D->getDeclName(); 99 } 100 else 101 S.Diag(Loc, diag::err_unavailable_message) 102 << D->getDeclName() << Message; 103 S.Diag(D->getLocation(), diag::note_unavailable_here) 104 << isa<FunctionDecl>(D) << false; 105 } 106 break; 107 } 108 return Result; 109 } 110 111 /// \brief Emit a note explaining that this function is deleted or unavailable. 112 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 113 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 114 115 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) { 116 // If the method was explicitly defaulted, point at that declaration. 117 if (!Method->isImplicit()) 118 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 119 120 // Try to diagnose why this special member function was implicitly 121 // deleted. This might fail, if that reason no longer applies. 122 CXXSpecialMember CSM = getSpecialMember(Method); 123 if (CSM != CXXInvalid) 124 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 125 126 return; 127 } 128 129 Diag(Decl->getLocation(), diag::note_unavailable_here) 130 << 1 << Decl->isDeleted(); 131 } 132 133 /// \brief Determine whether a FunctionDecl was ever declared with an 134 /// explicit storage class. 135 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 136 for (FunctionDecl::redecl_iterator I = D->redecls_begin(), 137 E = D->redecls_end(); 138 I != E; ++I) { 139 if (I->getStorageClassAsWritten() != SC_None) 140 return true; 141 } 142 return false; 143 } 144 145 /// \brief Check whether we're in an extern inline function and referring to a 146 /// variable or function with internal linkage (C11 6.7.4p3). 147 /// 148 /// This is only a warning because we used to silently accept this code, but 149 /// in many cases it will not behave correctly. This is not enabled in C++ mode 150 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 151 /// and so while there may still be user mistakes, most of the time we can't 152 /// prove that there are errors. 153 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 154 const NamedDecl *D, 155 SourceLocation Loc) { 156 // This is disabled under C++; there are too many ways for this to fire in 157 // contexts where the warning is a false positive, or where it is technically 158 // correct but benign. 159 if (S.getLangOpts().CPlusPlus) 160 return; 161 162 // Check if this is an inlined function or method. 163 FunctionDecl *Current = S.getCurFunctionDecl(); 164 if (!Current) 165 return; 166 if (!Current->isInlined()) 167 return; 168 if (Current->getLinkage() != ExternalLinkage) 169 return; 170 171 // Check if the decl has internal linkage. 172 if (D->getLinkage() != InternalLinkage) 173 return; 174 175 // Downgrade from ExtWarn to Extension if 176 // (1) the supposedly external inline function is in the main file, 177 // and probably won't be included anywhere else. 178 // (2) the thing we're referencing is a pure function. 179 // (3) the thing we're referencing is another inline function. 180 // This last can give us false negatives, but it's better than warning on 181 // wrappers for simple C library functions. 182 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 183 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc); 184 if (!DowngradeWarning && UsedFn) 185 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 186 187 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline 188 : diag::warn_internal_in_extern_inline) 189 << /*IsVar=*/!UsedFn << D; 190 191 // Suggest "static" on the inline function, if possible. 192 if (!hasAnyExplicitStorageClass(Current)) { 193 const FunctionDecl *FirstDecl = Current->getCanonicalDecl(); 194 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin(); 195 S.Diag(DeclBegin, diag::note_convert_inline_to_static) 196 << Current << FixItHint::CreateInsertion(DeclBegin, "static "); 197 } 198 199 S.Diag(D->getCanonicalDecl()->getLocation(), 200 diag::note_internal_decl_declared_here) 201 << D; 202 } 203 204 /// \brief Determine whether the use of this declaration is valid, and 205 /// emit any corresponding diagnostics. 206 /// 207 /// This routine diagnoses various problems with referencing 208 /// declarations that can occur when using a declaration. For example, 209 /// it might warn if a deprecated or unavailable declaration is being 210 /// used, or produce an error (and return true) if a C++0x deleted 211 /// function is being used. 212 /// 213 /// \returns true if there was an error (this declaration cannot be 214 /// referenced), false otherwise. 215 /// 216 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 217 const ObjCInterfaceDecl *UnknownObjCClass) { 218 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 219 // If there were any diagnostics suppressed by template argument deduction, 220 // emit them now. 221 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator 222 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 223 if (Pos != SuppressedDiagnostics.end()) { 224 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 225 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 226 Diag(Suppressed[I].first, Suppressed[I].second); 227 228 // Clear out the list of suppressed diagnostics, so that we don't emit 229 // them again for this specialization. However, we don't obsolete this 230 // entry from the table, because we want to avoid ever emitting these 231 // diagnostics again. 232 Suppressed.clear(); 233 } 234 } 235 236 // See if this is an auto-typed variable whose initializer we are parsing. 237 if (ParsingInitForAutoVars.count(D)) { 238 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 239 << D->getDeclName(); 240 return true; 241 } 242 243 // See if this is a deleted function. 244 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 245 if (FD->isDeleted()) { 246 Diag(Loc, diag::err_deleted_function_use); 247 NoteDeletedFunction(FD); 248 return true; 249 } 250 } 251 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass); 252 253 // Warn if this is used but marked unused. 254 if (D->hasAttr<UnusedAttr>()) 255 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 256 257 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 258 259 return false; 260 } 261 262 /// \brief Retrieve the message suffix that should be added to a 263 /// diagnostic complaining about the given function being deleted or 264 /// unavailable. 265 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 266 // FIXME: C++0x implicitly-deleted special member functions could be 267 // detected here so that we could improve diagnostics to say, e.g., 268 // "base class 'A' had a deleted copy constructor". 269 if (FD->isDeleted()) 270 return std::string(); 271 272 std::string Message; 273 if (FD->getAvailability(&Message)) 274 return ": " + Message; 275 276 return std::string(); 277 } 278 279 /// DiagnoseSentinelCalls - This routine checks whether a call or 280 /// message-send is to a declaration with the sentinel attribute, and 281 /// if so, it checks that the requirements of the sentinel are 282 /// satisfied. 283 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 284 Expr **args, unsigned numArgs) { 285 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 286 if (!attr) 287 return; 288 289 // The number of formal parameters of the declaration. 290 unsigned numFormalParams; 291 292 // The kind of declaration. This is also an index into a %select in 293 // the diagnostic. 294 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 295 296 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 297 numFormalParams = MD->param_size(); 298 calleeType = CT_Method; 299 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 300 numFormalParams = FD->param_size(); 301 calleeType = CT_Function; 302 } else if (isa<VarDecl>(D)) { 303 QualType type = cast<ValueDecl>(D)->getType(); 304 const FunctionType *fn = 0; 305 if (const PointerType *ptr = type->getAs<PointerType>()) { 306 fn = ptr->getPointeeType()->getAs<FunctionType>(); 307 if (!fn) return; 308 calleeType = CT_Function; 309 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 310 fn = ptr->getPointeeType()->castAs<FunctionType>(); 311 calleeType = CT_Block; 312 } else { 313 return; 314 } 315 316 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 317 numFormalParams = proto->getNumArgs(); 318 } else { 319 numFormalParams = 0; 320 } 321 } else { 322 return; 323 } 324 325 // "nullPos" is the number of formal parameters at the end which 326 // effectively count as part of the variadic arguments. This is 327 // useful if you would prefer to not have *any* formal parameters, 328 // but the language forces you to have at least one. 329 unsigned nullPos = attr->getNullPos(); 330 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 331 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 332 333 // The number of arguments which should follow the sentinel. 334 unsigned numArgsAfterSentinel = attr->getSentinel(); 335 336 // If there aren't enough arguments for all the formal parameters, 337 // the sentinel, and the args after the sentinel, complain. 338 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) { 339 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 340 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType; 341 return; 342 } 343 344 // Otherwise, find the sentinel expression. 345 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1]; 346 if (!sentinelExpr) return; 347 if (sentinelExpr->isValueDependent()) return; 348 if (Context.isSentinelNullExpr(sentinelExpr)) return; 349 350 // Pick a reasonable string to insert. Optimistically use 'nil' or 351 // 'NULL' if those are actually defined in the context. Only use 352 // 'nil' for ObjC methods, where it's much more likely that the 353 // variadic arguments form a list of object pointers. 354 SourceLocation MissingNilLoc 355 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 356 std::string NullValue; 357 if (calleeType == CT_Method && 358 PP.getIdentifierInfo("nil")->hasMacroDefinition()) 359 NullValue = "nil"; 360 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition()) 361 NullValue = "NULL"; 362 else 363 NullValue = "(void*) 0"; 364 365 if (MissingNilLoc.isInvalid()) 366 Diag(Loc, diag::warn_missing_sentinel) << calleeType; 367 else 368 Diag(MissingNilLoc, diag::warn_missing_sentinel) 369 << calleeType 370 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 371 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType; 372 } 373 374 SourceRange Sema::getExprRange(Expr *E) const { 375 return E ? E->getSourceRange() : SourceRange(); 376 } 377 378 //===----------------------------------------------------------------------===// 379 // Standard Promotions and Conversions 380 //===----------------------------------------------------------------------===// 381 382 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 383 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 384 // Handle any placeholder expressions which made it here. 385 if (E->getType()->isPlaceholderType()) { 386 ExprResult result = CheckPlaceholderExpr(E); 387 if (result.isInvalid()) return ExprError(); 388 E = result.take(); 389 } 390 391 QualType Ty = E->getType(); 392 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 393 394 if (Ty->isFunctionType()) 395 E = ImpCastExprToType(E, Context.getPointerType(Ty), 396 CK_FunctionToPointerDecay).take(); 397 else if (Ty->isArrayType()) { 398 // In C90 mode, arrays only promote to pointers if the array expression is 399 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 400 // type 'array of type' is converted to an expression that has type 'pointer 401 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 402 // that has type 'array of type' ...". The relevant change is "an lvalue" 403 // (C90) to "an expression" (C99). 404 // 405 // C++ 4.2p1: 406 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 407 // T" can be converted to an rvalue of type "pointer to T". 408 // 409 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 410 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 411 CK_ArrayToPointerDecay).take(); 412 } 413 return Owned(E); 414 } 415 416 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 417 // Check to see if we are dereferencing a null pointer. If so, 418 // and if not volatile-qualified, this is undefined behavior that the 419 // optimizer will delete, so warn about it. People sometimes try to use this 420 // to get a deterministic trap and are surprised by clang's behavior. This 421 // only handles the pattern "*null", which is a very syntactic check. 422 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 423 if (UO->getOpcode() == UO_Deref && 424 UO->getSubExpr()->IgnoreParenCasts()-> 425 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 426 !UO->getType().isVolatileQualified()) { 427 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 428 S.PDiag(diag::warn_indirection_through_null) 429 << UO->getSubExpr()->getSourceRange()); 430 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 431 S.PDiag(diag::note_indirection_through_null)); 432 } 433 } 434 435 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 436 // Handle any placeholder expressions which made it here. 437 if (E->getType()->isPlaceholderType()) { 438 ExprResult result = CheckPlaceholderExpr(E); 439 if (result.isInvalid()) return ExprError(); 440 E = result.take(); 441 } 442 443 // C++ [conv.lval]p1: 444 // A glvalue of a non-function, non-array type T can be 445 // converted to a prvalue. 446 if (!E->isGLValue()) return Owned(E); 447 448 QualType T = E->getType(); 449 assert(!T.isNull() && "r-value conversion on typeless expression?"); 450 451 // We don't want to throw lvalue-to-rvalue casts on top of 452 // expressions of certain types in C++. 453 if (getLangOpts().CPlusPlus && 454 (E->getType() == Context.OverloadTy || 455 T->isDependentType() || 456 T->isRecordType())) 457 return Owned(E); 458 459 // The C standard is actually really unclear on this point, and 460 // DR106 tells us what the result should be but not why. It's 461 // generally best to say that void types just doesn't undergo 462 // lvalue-to-rvalue at all. Note that expressions of unqualified 463 // 'void' type are never l-values, but qualified void can be. 464 if (T->isVoidType()) 465 return Owned(E); 466 467 CheckForNullPointerDereference(*this, E); 468 469 // C++ [conv.lval]p1: 470 // [...] If T is a non-class type, the type of the prvalue is the 471 // cv-unqualified version of T. Otherwise, the type of the 472 // rvalue is T. 473 // 474 // C99 6.3.2.1p2: 475 // If the lvalue has qualified type, the value has the unqualified 476 // version of the type of the lvalue; otherwise, the value has the 477 // type of the lvalue. 478 if (T.hasQualifiers()) 479 T = T.getUnqualifiedType(); 480 481 UpdateMarkingForLValueToRValue(E); 482 483 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, 484 E, 0, VK_RValue)); 485 486 // C11 6.3.2.1p2: 487 // ... if the lvalue has atomic type, the value has the non-atomic version 488 // of the type of the lvalue ... 489 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 490 T = Atomic->getValueType().getUnqualifiedType(); 491 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, 492 Res.get(), 0, VK_RValue)); 493 } 494 495 return Res; 496 } 497 498 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 499 ExprResult Res = DefaultFunctionArrayConversion(E); 500 if (Res.isInvalid()) 501 return ExprError(); 502 Res = DefaultLvalueConversion(Res.take()); 503 if (Res.isInvalid()) 504 return ExprError(); 505 return move(Res); 506 } 507 508 509 /// UsualUnaryConversions - Performs various conversions that are common to most 510 /// operators (C99 6.3). The conversions of array and function types are 511 /// sometimes suppressed. For example, the array->pointer conversion doesn't 512 /// apply if the array is an argument to the sizeof or address (&) operators. 513 /// In these instances, this routine should *not* be called. 514 ExprResult Sema::UsualUnaryConversions(Expr *E) { 515 // First, convert to an r-value. 516 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 517 if (Res.isInvalid()) 518 return Owned(E); 519 E = Res.take(); 520 521 QualType Ty = E->getType(); 522 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 523 524 // Half FP is a bit different: it's a storage-only type, meaning that any 525 // "use" of it should be promoted to float. 526 if (Ty->isHalfType()) 527 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast); 528 529 // Try to perform integral promotions if the object has a theoretically 530 // promotable type. 531 if (Ty->isIntegralOrUnscopedEnumerationType()) { 532 // C99 6.3.1.1p2: 533 // 534 // The following may be used in an expression wherever an int or 535 // unsigned int may be used: 536 // - an object or expression with an integer type whose integer 537 // conversion rank is less than or equal to the rank of int 538 // and unsigned int. 539 // - A bit-field of type _Bool, int, signed int, or unsigned int. 540 // 541 // If an int can represent all values of the original type, the 542 // value is converted to an int; otherwise, it is converted to an 543 // unsigned int. These are called the integer promotions. All 544 // other types are unchanged by the integer promotions. 545 546 QualType PTy = Context.isPromotableBitField(E); 547 if (!PTy.isNull()) { 548 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take(); 549 return Owned(E); 550 } 551 if (Ty->isPromotableIntegerType()) { 552 QualType PT = Context.getPromotedIntegerType(Ty); 553 E = ImpCastExprToType(E, PT, CK_IntegralCast).take(); 554 return Owned(E); 555 } 556 } 557 return Owned(E); 558 } 559 560 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 561 /// do not have a prototype. Arguments that have type float are promoted to 562 /// double. All other argument types are converted by UsualUnaryConversions(). 563 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 564 QualType Ty = E->getType(); 565 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 566 567 ExprResult Res = UsualUnaryConversions(E); 568 if (Res.isInvalid()) 569 return Owned(E); 570 E = Res.take(); 571 572 // If this is a 'float' (CVR qualified or typedef) promote to double. 573 if (Ty->isSpecificBuiltinType(BuiltinType::Float)) 574 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take(); 575 576 // C++ performs lvalue-to-rvalue conversion as a default argument 577 // promotion, even on class types, but note: 578 // C++11 [conv.lval]p2: 579 // When an lvalue-to-rvalue conversion occurs in an unevaluated 580 // operand or a subexpression thereof the value contained in the 581 // referenced object is not accessed. Otherwise, if the glvalue 582 // has a class type, the conversion copy-initializes a temporary 583 // of type T from the glvalue and the result of the conversion 584 // is a prvalue for the temporary. 585 // FIXME: add some way to gate this entire thing for correctness in 586 // potentially potentially evaluated contexts. 587 if (getLangOpts().CPlusPlus && E->isGLValue() && 588 ExprEvalContexts.back().Context != Unevaluated) { 589 ExprResult Temp = PerformCopyInitialization( 590 InitializedEntity::InitializeTemporary(E->getType()), 591 E->getExprLoc(), 592 Owned(E)); 593 if (Temp.isInvalid()) 594 return ExprError(); 595 E = Temp.get(); 596 } 597 598 return Owned(E); 599 } 600 601 /// Determine the degree of POD-ness for an expression. 602 /// Incomplete types are considered POD, since this check can be performed 603 /// when we're in an unevaluated context. 604 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 605 if (Ty->isIncompleteType() || Ty.isCXX98PODType(Context)) 606 return VAK_Valid; 607 // C++0x [expr.call]p7: 608 // Passing a potentially-evaluated argument of class type (Clause 9) 609 // having a non-trivial copy constructor, a non-trivial move constructor, 610 // or a non-trivial destructor, with no corresponding parameter, 611 // is conditionally-supported with implementation-defined semantics. 612 613 if (getLangOpts().CPlusPlus0x && !Ty->isDependentType()) 614 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 615 if (Record->hasTrivialCopyConstructor() && 616 Record->hasTrivialMoveConstructor() && 617 Record->hasTrivialDestructor()) 618 return VAK_ValidInCXX11; 619 620 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 621 return VAK_Valid; 622 return VAK_Invalid; 623 } 624 625 bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) { 626 // Don't allow one to pass an Objective-C interface to a vararg. 627 const QualType & Ty = E->getType(); 628 629 // Complain about passing non-POD types through varargs. 630 switch (isValidVarArgType(Ty)) { 631 case VAK_Valid: 632 break; 633 case VAK_ValidInCXX11: 634 DiagRuntimeBehavior(E->getLocStart(), 0, 635 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 636 << E->getType() << CT); 637 break; 638 case VAK_Invalid: 639 return DiagRuntimeBehavior(E->getLocStart(), 0, 640 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 641 << getLangOpts().CPlusPlus0x << Ty << CT); 642 } 643 // c++ rules are enforced elsewhere. 644 return false; 645 } 646 647 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 648 /// will warn if the resulting type is not a POD type, and rejects ObjC 649 /// interfaces passed by value. 650 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 651 FunctionDecl *FDecl) { 652 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 653 // Strip the unbridged-cast placeholder expression off, if applicable. 654 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 655 (CT == VariadicMethod || 656 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 657 E = stripARCUnbridgedCast(E); 658 659 // Otherwise, do normal placeholder checking. 660 } else { 661 ExprResult ExprRes = CheckPlaceholderExpr(E); 662 if (ExprRes.isInvalid()) 663 return ExprError(); 664 E = ExprRes.take(); 665 } 666 } 667 668 ExprResult ExprRes = DefaultArgumentPromotion(E); 669 if (ExprRes.isInvalid()) 670 return ExprError(); 671 E = ExprRes.take(); 672 673 if (E->getType()->isObjCObjectType() && 674 DiagRuntimeBehavior(E->getLocStart(), 0, 675 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 676 << E->getType() << CT)) 677 return ExprError(); 678 679 // Diagnostics regarding non-POD argument types are 680 // emitted along with format string checking in Sema::CheckFunctionCall(). 681 if (isValidVarArgType(E->getType()) == VAK_Invalid) { 682 // Turn this into a trap. 683 CXXScopeSpec SS; 684 SourceLocation TemplateKWLoc; 685 UnqualifiedId Name; 686 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 687 E->getLocStart()); 688 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 689 Name, true, false); 690 if (TrapFn.isInvalid()) 691 return ExprError(); 692 693 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 694 E->getLocStart(), MultiExprArg(), 695 E->getLocEnd()); 696 if (Call.isInvalid()) 697 return ExprError(); 698 699 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 700 Call.get(), E); 701 if (Comma.isInvalid()) 702 return ExprError(); 703 return Comma.get(); 704 } 705 706 if (!getLangOpts().CPlusPlus && 707 RequireCompleteType(E->getExprLoc(), E->getType(), 708 diag::err_call_incomplete_argument)) 709 return ExprError(); 710 711 return Owned(E); 712 } 713 714 /// \brief Converts an integer to complex float type. Helper function of 715 /// UsualArithmeticConversions() 716 /// 717 /// \return false if the integer expression is an integer type and is 718 /// successfully converted to the complex type. 719 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 720 ExprResult &ComplexExpr, 721 QualType IntTy, 722 QualType ComplexTy, 723 bool SkipCast) { 724 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 725 if (SkipCast) return false; 726 if (IntTy->isIntegerType()) { 727 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 728 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating); 729 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 730 CK_FloatingRealToComplex); 731 } else { 732 assert(IntTy->isComplexIntegerType()); 733 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 734 CK_IntegralComplexToFloatingComplex); 735 } 736 return false; 737 } 738 739 /// \brief Takes two complex float types and converts them to the same type. 740 /// Helper function of UsualArithmeticConversions() 741 static QualType 742 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS, 743 ExprResult &RHS, QualType LHSType, 744 QualType RHSType, 745 bool IsCompAssign) { 746 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 747 748 if (order < 0) { 749 // _Complex float -> _Complex double 750 if (!IsCompAssign) 751 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast); 752 return RHSType; 753 } 754 if (order > 0) 755 // _Complex float -> _Complex double 756 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast); 757 return LHSType; 758 } 759 760 /// \brief Converts otherExpr to complex float and promotes complexExpr if 761 /// necessary. Helper function of UsualArithmeticConversions() 762 static QualType handleOtherComplexFloatConversion(Sema &S, 763 ExprResult &ComplexExpr, 764 ExprResult &OtherExpr, 765 QualType ComplexTy, 766 QualType OtherTy, 767 bool ConvertComplexExpr, 768 bool ConvertOtherExpr) { 769 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy); 770 771 // If just the complexExpr is complex, the otherExpr needs to be converted, 772 // and the complexExpr might need to be promoted. 773 if (order > 0) { // complexExpr is wider 774 // float -> _Complex double 775 if (ConvertOtherExpr) { 776 QualType fp = cast<ComplexType>(ComplexTy)->getElementType(); 777 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast); 778 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy, 779 CK_FloatingRealToComplex); 780 } 781 return ComplexTy; 782 } 783 784 // otherTy is at least as wide. Find its corresponding complex type. 785 QualType result = (order == 0 ? ComplexTy : 786 S.Context.getComplexType(OtherTy)); 787 788 // double -> _Complex double 789 if (ConvertOtherExpr) 790 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result, 791 CK_FloatingRealToComplex); 792 793 // _Complex float -> _Complex double 794 if (ConvertComplexExpr && order < 0) 795 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result, 796 CK_FloatingComplexCast); 797 798 return result; 799 } 800 801 /// \brief Handle arithmetic conversion with complex types. Helper function of 802 /// UsualArithmeticConversions() 803 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 804 ExprResult &RHS, QualType LHSType, 805 QualType RHSType, 806 bool IsCompAssign) { 807 // if we have an integer operand, the result is the complex type. 808 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 809 /*skipCast*/false)) 810 return LHSType; 811 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 812 /*skipCast*/IsCompAssign)) 813 return RHSType; 814 815 // This handles complex/complex, complex/float, or float/complex. 816 // When both operands are complex, the shorter operand is converted to the 817 // type of the longer, and that is the type of the result. This corresponds 818 // to what is done when combining two real floating-point operands. 819 // The fun begins when size promotion occur across type domains. 820 // From H&S 6.3.4: When one operand is complex and the other is a real 821 // floating-point type, the less precise type is converted, within it's 822 // real or complex domain, to the precision of the other type. For example, 823 // when combining a "long double" with a "double _Complex", the 824 // "double _Complex" is promoted to "long double _Complex". 825 826 bool LHSComplexFloat = LHSType->isComplexType(); 827 bool RHSComplexFloat = RHSType->isComplexType(); 828 829 // If both are complex, just cast to the more precise type. 830 if (LHSComplexFloat && RHSComplexFloat) 831 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS, 832 LHSType, RHSType, 833 IsCompAssign); 834 835 // If only one operand is complex, promote it if necessary and convert the 836 // other operand to complex. 837 if (LHSComplexFloat) 838 return handleOtherComplexFloatConversion( 839 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign, 840 /*convertOtherExpr*/ true); 841 842 assert(RHSComplexFloat); 843 return handleOtherComplexFloatConversion( 844 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true, 845 /*convertOtherExpr*/ !IsCompAssign); 846 } 847 848 /// \brief Hande arithmetic conversion from integer to float. Helper function 849 /// of UsualArithmeticConversions() 850 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 851 ExprResult &IntExpr, 852 QualType FloatTy, QualType IntTy, 853 bool ConvertFloat, bool ConvertInt) { 854 if (IntTy->isIntegerType()) { 855 if (ConvertInt) 856 // Convert intExpr to the lhs floating point type. 857 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy, 858 CK_IntegralToFloating); 859 return FloatTy; 860 } 861 862 // Convert both sides to the appropriate complex float. 863 assert(IntTy->isComplexIntegerType()); 864 QualType result = S.Context.getComplexType(FloatTy); 865 866 // _Complex int -> _Complex float 867 if (ConvertInt) 868 IntExpr = S.ImpCastExprToType(IntExpr.take(), result, 869 CK_IntegralComplexToFloatingComplex); 870 871 // float -> _Complex float 872 if (ConvertFloat) 873 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result, 874 CK_FloatingRealToComplex); 875 876 return result; 877 } 878 879 /// \brief Handle arithmethic conversion with floating point types. Helper 880 /// function of UsualArithmeticConversions() 881 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 882 ExprResult &RHS, QualType LHSType, 883 QualType RHSType, bool IsCompAssign) { 884 bool LHSFloat = LHSType->isRealFloatingType(); 885 bool RHSFloat = RHSType->isRealFloatingType(); 886 887 // If we have two real floating types, convert the smaller operand 888 // to the bigger result. 889 if (LHSFloat && RHSFloat) { 890 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 891 if (order > 0) { 892 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast); 893 return LHSType; 894 } 895 896 assert(order < 0 && "illegal float comparison"); 897 if (!IsCompAssign) 898 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast); 899 return RHSType; 900 } 901 902 if (LHSFloat) 903 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 904 /*convertFloat=*/!IsCompAssign, 905 /*convertInt=*/ true); 906 assert(RHSFloat); 907 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 908 /*convertInt=*/ true, 909 /*convertFloat=*/!IsCompAssign); 910 } 911 912 /// \brief Handle conversions with GCC complex int extension. Helper function 913 /// of UsualArithmeticConversions() 914 // FIXME: if the operands are (int, _Complex long), we currently 915 // don't promote the complex. Also, signedness? 916 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 917 ExprResult &RHS, QualType LHSType, 918 QualType RHSType, 919 bool IsCompAssign) { 920 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 921 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 922 923 if (LHSComplexInt && RHSComplexInt) { 924 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(), 925 RHSComplexInt->getElementType()); 926 assert(order && "inequal types with equal element ordering"); 927 if (order > 0) { 928 // _Complex int -> _Complex long 929 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast); 930 return LHSType; 931 } 932 933 if (!IsCompAssign) 934 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast); 935 return RHSType; 936 } 937 938 if (LHSComplexInt) { 939 // int -> _Complex int 940 // FIXME: This needs to take integer ranks into account 941 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(), 942 CK_IntegralCast); 943 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex); 944 return LHSType; 945 } 946 947 assert(RHSComplexInt); 948 // int -> _Complex int 949 // FIXME: This needs to take integer ranks into account 950 if (!IsCompAssign) { 951 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(), 952 CK_IntegralCast); 953 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex); 954 } 955 return RHSType; 956 } 957 958 /// \brief Handle integer arithmetic conversions. Helper function of 959 /// UsualArithmeticConversions() 960 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 961 ExprResult &RHS, QualType LHSType, 962 QualType RHSType, bool IsCompAssign) { 963 // The rules for this case are in C99 6.3.1.8 964 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 965 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 966 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 967 if (LHSSigned == RHSSigned) { 968 // Same signedness; use the higher-ranked type 969 if (order >= 0) { 970 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast); 971 return LHSType; 972 } else if (!IsCompAssign) 973 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast); 974 return RHSType; 975 } else if (order != (LHSSigned ? 1 : -1)) { 976 // The unsigned type has greater than or equal rank to the 977 // signed type, so use the unsigned type 978 if (RHSSigned) { 979 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast); 980 return LHSType; 981 } else if (!IsCompAssign) 982 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast); 983 return RHSType; 984 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 985 // The two types are different widths; if we are here, that 986 // means the signed type is larger than the unsigned type, so 987 // use the signed type. 988 if (LHSSigned) { 989 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast); 990 return LHSType; 991 } else if (!IsCompAssign) 992 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast); 993 return RHSType; 994 } else { 995 // The signed type is higher-ranked than the unsigned type, 996 // but isn't actually any bigger (like unsigned int and long 997 // on most 32-bit systems). Use the unsigned type corresponding 998 // to the signed type. 999 QualType result = 1000 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1001 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast); 1002 if (!IsCompAssign) 1003 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast); 1004 return result; 1005 } 1006 } 1007 1008 /// UsualArithmeticConversions - Performs various conversions that are common to 1009 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1010 /// routine returns the first non-arithmetic type found. The client is 1011 /// responsible for emitting appropriate error diagnostics. 1012 /// FIXME: verify the conversion rules for "complex int" are consistent with 1013 /// GCC. 1014 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1015 bool IsCompAssign) { 1016 if (!IsCompAssign) { 1017 LHS = UsualUnaryConversions(LHS.take()); 1018 if (LHS.isInvalid()) 1019 return QualType(); 1020 } 1021 1022 RHS = UsualUnaryConversions(RHS.take()); 1023 if (RHS.isInvalid()) 1024 return QualType(); 1025 1026 // For conversion purposes, we ignore any qualifiers. 1027 // For example, "const float" and "float" are equivalent. 1028 QualType LHSType = 1029 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1030 QualType RHSType = 1031 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1032 1033 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1034 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1035 LHSType = AtomicLHS->getValueType(); 1036 1037 // If both types are identical, no conversion is needed. 1038 if (LHSType == RHSType) 1039 return LHSType; 1040 1041 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1042 // The caller can deal with this (e.g. pointer + int). 1043 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1044 return QualType(); 1045 1046 // Apply unary and bitfield promotions to the LHS's type. 1047 QualType LHSUnpromotedType = LHSType; 1048 if (LHSType->isPromotableIntegerType()) 1049 LHSType = Context.getPromotedIntegerType(LHSType); 1050 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1051 if (!LHSBitfieldPromoteTy.isNull()) 1052 LHSType = LHSBitfieldPromoteTy; 1053 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1054 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast); 1055 1056 // If both types are identical, no conversion is needed. 1057 if (LHSType == RHSType) 1058 return LHSType; 1059 1060 // At this point, we have two different arithmetic types. 1061 1062 // Handle complex types first (C99 6.3.1.8p1). 1063 if (LHSType->isComplexType() || RHSType->isComplexType()) 1064 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1065 IsCompAssign); 1066 1067 // Now handle "real" floating types (i.e. float, double, long double). 1068 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1069 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1070 IsCompAssign); 1071 1072 // Handle GCC complex int extension. 1073 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1074 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1075 IsCompAssign); 1076 1077 // Finally, we have two differing integer types. 1078 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType, 1079 IsCompAssign); 1080 } 1081 1082 //===----------------------------------------------------------------------===// 1083 // Semantic Analysis for various Expression Types 1084 //===----------------------------------------------------------------------===// 1085 1086 1087 ExprResult 1088 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1089 SourceLocation DefaultLoc, 1090 SourceLocation RParenLoc, 1091 Expr *ControllingExpr, 1092 MultiTypeArg ArgTypes, 1093 MultiExprArg ArgExprs) { 1094 unsigned NumAssocs = ArgTypes.size(); 1095 assert(NumAssocs == ArgExprs.size()); 1096 1097 ParsedType *ParsedTypes = ArgTypes.release(); 1098 Expr **Exprs = ArgExprs.release(); 1099 1100 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1101 for (unsigned i = 0; i < NumAssocs; ++i) { 1102 if (ParsedTypes[i]) 1103 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]); 1104 else 1105 Types[i] = 0; 1106 } 1107 1108 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1109 ControllingExpr, Types, Exprs, 1110 NumAssocs); 1111 delete [] Types; 1112 return ER; 1113 } 1114 1115 ExprResult 1116 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1117 SourceLocation DefaultLoc, 1118 SourceLocation RParenLoc, 1119 Expr *ControllingExpr, 1120 TypeSourceInfo **Types, 1121 Expr **Exprs, 1122 unsigned NumAssocs) { 1123 bool TypeErrorFound = false, 1124 IsResultDependent = ControllingExpr->isTypeDependent(), 1125 ContainsUnexpandedParameterPack 1126 = ControllingExpr->containsUnexpandedParameterPack(); 1127 1128 for (unsigned i = 0; i < NumAssocs; ++i) { 1129 if (Exprs[i]->containsUnexpandedParameterPack()) 1130 ContainsUnexpandedParameterPack = true; 1131 1132 if (Types[i]) { 1133 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1134 ContainsUnexpandedParameterPack = true; 1135 1136 if (Types[i]->getType()->isDependentType()) { 1137 IsResultDependent = true; 1138 } else { 1139 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1140 // complete object type other than a variably modified type." 1141 unsigned D = 0; 1142 if (Types[i]->getType()->isIncompleteType()) 1143 D = diag::err_assoc_type_incomplete; 1144 else if (!Types[i]->getType()->isObjectType()) 1145 D = diag::err_assoc_type_nonobject; 1146 else if (Types[i]->getType()->isVariablyModifiedType()) 1147 D = diag::err_assoc_type_variably_modified; 1148 1149 if (D != 0) { 1150 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1151 << Types[i]->getTypeLoc().getSourceRange() 1152 << Types[i]->getType(); 1153 TypeErrorFound = true; 1154 } 1155 1156 // C11 6.5.1.1p2 "No two generic associations in the same generic 1157 // selection shall specify compatible types." 1158 for (unsigned j = i+1; j < NumAssocs; ++j) 1159 if (Types[j] && !Types[j]->getType()->isDependentType() && 1160 Context.typesAreCompatible(Types[i]->getType(), 1161 Types[j]->getType())) { 1162 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1163 diag::err_assoc_compatible_types) 1164 << Types[j]->getTypeLoc().getSourceRange() 1165 << Types[j]->getType() 1166 << Types[i]->getType(); 1167 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1168 diag::note_compat_assoc) 1169 << Types[i]->getTypeLoc().getSourceRange() 1170 << Types[i]->getType(); 1171 TypeErrorFound = true; 1172 } 1173 } 1174 } 1175 } 1176 if (TypeErrorFound) 1177 return ExprError(); 1178 1179 // If we determined that the generic selection is result-dependent, don't 1180 // try to compute the result expression. 1181 if (IsResultDependent) 1182 return Owned(new (Context) GenericSelectionExpr( 1183 Context, KeyLoc, ControllingExpr, 1184 Types, Exprs, NumAssocs, DefaultLoc, 1185 RParenLoc, ContainsUnexpandedParameterPack)); 1186 1187 SmallVector<unsigned, 1> CompatIndices; 1188 unsigned DefaultIndex = -1U; 1189 for (unsigned i = 0; i < NumAssocs; ++i) { 1190 if (!Types[i]) 1191 DefaultIndex = i; 1192 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1193 Types[i]->getType())) 1194 CompatIndices.push_back(i); 1195 } 1196 1197 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1198 // type compatible with at most one of the types named in its generic 1199 // association list." 1200 if (CompatIndices.size() > 1) { 1201 // We strip parens here because the controlling expression is typically 1202 // parenthesized in macro definitions. 1203 ControllingExpr = ControllingExpr->IgnoreParens(); 1204 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1205 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1206 << (unsigned) CompatIndices.size(); 1207 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(), 1208 E = CompatIndices.end(); I != E; ++I) { 1209 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1210 diag::note_compat_assoc) 1211 << Types[*I]->getTypeLoc().getSourceRange() 1212 << Types[*I]->getType(); 1213 } 1214 return ExprError(); 1215 } 1216 1217 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1218 // its controlling expression shall have type compatible with exactly one of 1219 // the types named in its generic association list." 1220 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1221 // We strip parens here because the controlling expression is typically 1222 // parenthesized in macro definitions. 1223 ControllingExpr = ControllingExpr->IgnoreParens(); 1224 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1225 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1226 return ExprError(); 1227 } 1228 1229 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1230 // type name that is compatible with the type of the controlling expression, 1231 // then the result expression of the generic selection is the expression 1232 // in that generic association. Otherwise, the result expression of the 1233 // generic selection is the expression in the default generic association." 1234 unsigned ResultIndex = 1235 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1236 1237 return Owned(new (Context) GenericSelectionExpr( 1238 Context, KeyLoc, ControllingExpr, 1239 Types, Exprs, NumAssocs, DefaultLoc, 1240 RParenLoc, ContainsUnexpandedParameterPack, 1241 ResultIndex)); 1242 } 1243 1244 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1245 /// location of the token and the offset of the ud-suffix within it. 1246 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1247 unsigned Offset) { 1248 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1249 S.getLangOpts()); 1250 } 1251 1252 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1253 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1254 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1255 IdentifierInfo *UDSuffix, 1256 SourceLocation UDSuffixLoc, 1257 ArrayRef<Expr*> Args, 1258 SourceLocation LitEndLoc) { 1259 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1260 1261 QualType ArgTy[2]; 1262 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1263 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1264 if (ArgTy[ArgIdx]->isArrayType()) 1265 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1266 } 1267 1268 DeclarationName OpName = 1269 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1270 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1271 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1272 1273 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1274 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1275 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error) 1276 return ExprError(); 1277 1278 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1279 } 1280 1281 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1282 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1283 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1284 /// multiple tokens. However, the common case is that StringToks points to one 1285 /// string. 1286 /// 1287 ExprResult 1288 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks, 1289 Scope *UDLScope) { 1290 assert(NumStringToks && "Must have at least one string!"); 1291 1292 StringLiteralParser Literal(StringToks, NumStringToks, PP); 1293 if (Literal.hadError) 1294 return ExprError(); 1295 1296 SmallVector<SourceLocation, 4> StringTokLocs; 1297 for (unsigned i = 0; i != NumStringToks; ++i) 1298 StringTokLocs.push_back(StringToks[i].getLocation()); 1299 1300 QualType StrTy = Context.CharTy; 1301 if (Literal.isWide()) 1302 StrTy = Context.getWCharType(); 1303 else if (Literal.isUTF16()) 1304 StrTy = Context.Char16Ty; 1305 else if (Literal.isUTF32()) 1306 StrTy = Context.Char32Ty; 1307 else if (Literal.isPascal()) 1308 StrTy = Context.UnsignedCharTy; 1309 1310 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1311 if (Literal.isWide()) 1312 Kind = StringLiteral::Wide; 1313 else if (Literal.isUTF8()) 1314 Kind = StringLiteral::UTF8; 1315 else if (Literal.isUTF16()) 1316 Kind = StringLiteral::UTF16; 1317 else if (Literal.isUTF32()) 1318 Kind = StringLiteral::UTF32; 1319 1320 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1321 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1322 StrTy.addConst(); 1323 1324 // Get an array type for the string, according to C99 6.4.5. This includes 1325 // the nul terminator character as well as the string length for pascal 1326 // strings. 1327 StrTy = Context.getConstantArrayType(StrTy, 1328 llvm::APInt(32, Literal.GetNumStringChars()+1), 1329 ArrayType::Normal, 0); 1330 1331 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1332 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1333 Kind, Literal.Pascal, StrTy, 1334 &StringTokLocs[0], 1335 StringTokLocs.size()); 1336 if (Literal.getUDSuffix().empty()) 1337 return Owned(Lit); 1338 1339 // We're building a user-defined literal. 1340 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1341 SourceLocation UDSuffixLoc = 1342 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1343 Literal.getUDSuffixOffset()); 1344 1345 // Make sure we're allowed user-defined literals here. 1346 if (!UDLScope) 1347 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1348 1349 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1350 // operator "" X (str, len) 1351 QualType SizeType = Context.getSizeType(); 1352 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1353 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1354 StringTokLocs[0]); 1355 Expr *Args[] = { Lit, LenArg }; 1356 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 1357 Args, StringTokLocs.back()); 1358 } 1359 1360 ExprResult 1361 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1362 SourceLocation Loc, 1363 const CXXScopeSpec *SS) { 1364 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1365 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1366 } 1367 1368 /// BuildDeclRefExpr - Build an expression that references a 1369 /// declaration that does not require a closure capture. 1370 ExprResult 1371 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1372 const DeclarationNameInfo &NameInfo, 1373 const CXXScopeSpec *SS) { 1374 if (getLangOpts().CUDA) 1375 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1376 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1377 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller), 1378 CalleeTarget = IdentifyCUDATarget(Callee); 1379 if (CheckCUDATarget(CallerTarget, CalleeTarget)) { 1380 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1381 << CalleeTarget << D->getIdentifier() << CallerTarget; 1382 Diag(D->getLocation(), diag::note_previous_decl) 1383 << D->getIdentifier(); 1384 return ExprError(); 1385 } 1386 } 1387 1388 bool refersToEnclosingScope = 1389 (CurContext != D->getDeclContext() && 1390 D->getDeclContext()->isFunctionOrMethod()); 1391 1392 DeclRefExpr *E = DeclRefExpr::Create(Context, 1393 SS ? SS->getWithLocInContext(Context) 1394 : NestedNameSpecifierLoc(), 1395 SourceLocation(), 1396 D, refersToEnclosingScope, 1397 NameInfo, Ty, VK); 1398 1399 MarkDeclRefReferenced(E); 1400 1401 // Just in case we're building an illegal pointer-to-member. 1402 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1403 if (FD && FD->isBitField()) 1404 E->setObjectKind(OK_BitField); 1405 1406 return Owned(E); 1407 } 1408 1409 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1410 /// possibly a list of template arguments. 1411 /// 1412 /// If this produces template arguments, it is permitted to call 1413 /// DecomposeTemplateName. 1414 /// 1415 /// This actually loses a lot of source location information for 1416 /// non-standard name kinds; we should consider preserving that in 1417 /// some way. 1418 void 1419 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1420 TemplateArgumentListInfo &Buffer, 1421 DeclarationNameInfo &NameInfo, 1422 const TemplateArgumentListInfo *&TemplateArgs) { 1423 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1424 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1425 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1426 1427 ASTTemplateArgsPtr TemplateArgsPtr(*this, 1428 Id.TemplateId->getTemplateArgs(), 1429 Id.TemplateId->NumArgs); 1430 translateTemplateArguments(TemplateArgsPtr, Buffer); 1431 TemplateArgsPtr.release(); 1432 1433 TemplateName TName = Id.TemplateId->Template.get(); 1434 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1435 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1436 TemplateArgs = &Buffer; 1437 } else { 1438 NameInfo = GetNameFromUnqualifiedId(Id); 1439 TemplateArgs = 0; 1440 } 1441 } 1442 1443 /// Diagnose an empty lookup. 1444 /// 1445 /// \return false if new lookup candidates were found 1446 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1447 CorrectionCandidateCallback &CCC, 1448 TemplateArgumentListInfo *ExplicitTemplateArgs, 1449 llvm::ArrayRef<Expr *> Args) { 1450 DeclarationName Name = R.getLookupName(); 1451 1452 unsigned diagnostic = diag::err_undeclared_var_use; 1453 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1454 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1455 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1456 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1457 diagnostic = diag::err_undeclared_use; 1458 diagnostic_suggest = diag::err_undeclared_use_suggest; 1459 } 1460 1461 // If the original lookup was an unqualified lookup, fake an 1462 // unqualified lookup. This is useful when (for example) the 1463 // original lookup would not have found something because it was a 1464 // dependent name. 1465 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty()) 1466 ? CurContext : 0; 1467 while (DC) { 1468 if (isa<CXXRecordDecl>(DC)) { 1469 LookupQualifiedName(R, DC); 1470 1471 if (!R.empty()) { 1472 // Don't give errors about ambiguities in this lookup. 1473 R.suppressDiagnostics(); 1474 1475 // During a default argument instantiation the CurContext points 1476 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1477 // function parameter list, hence add an explicit check. 1478 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1479 ActiveTemplateInstantiations.back().Kind == 1480 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1481 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1482 bool isInstance = CurMethod && 1483 CurMethod->isInstance() && 1484 DC == CurMethod->getParent() && !isDefaultArgument; 1485 1486 1487 // Give a code modification hint to insert 'this->'. 1488 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1489 // Actually quite difficult! 1490 if (getLangOpts().MicrosoftMode) 1491 diagnostic = diag::warn_found_via_dependent_bases_lookup; 1492 if (isInstance) { 1493 Diag(R.getNameLoc(), diagnostic) << Name 1494 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1495 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1496 CallsUndergoingInstantiation.back()->getCallee()); 1497 1498 1499 CXXMethodDecl *DepMethod; 1500 if (CurMethod->getTemplatedKind() == 1501 FunctionDecl::TK_FunctionTemplateSpecialization) 1502 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()-> 1503 getInstantiatedFromMemberTemplate()->getTemplatedDecl()); 1504 else 1505 DepMethod = cast<CXXMethodDecl>( 1506 CurMethod->getInstantiatedFromMemberFunction()); 1507 assert(DepMethod && "No template pattern found"); 1508 1509 QualType DepThisType = DepMethod->getThisType(Context); 1510 CheckCXXThisCapture(R.getNameLoc()); 1511 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1512 R.getNameLoc(), DepThisType, false); 1513 TemplateArgumentListInfo TList; 1514 if (ULE->hasExplicitTemplateArgs()) 1515 ULE->copyTemplateArgumentsInto(TList); 1516 1517 CXXScopeSpec SS; 1518 SS.Adopt(ULE->getQualifierLoc()); 1519 CXXDependentScopeMemberExpr *DepExpr = 1520 CXXDependentScopeMemberExpr::Create( 1521 Context, DepThis, DepThisType, true, SourceLocation(), 1522 SS.getWithLocInContext(Context), 1523 ULE->getTemplateKeywordLoc(), 0, 1524 R.getLookupNameInfo(), 1525 ULE->hasExplicitTemplateArgs() ? &TList : 0); 1526 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1527 } else { 1528 Diag(R.getNameLoc(), diagnostic) << Name; 1529 } 1530 1531 // Do we really want to note all of these? 1532 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1533 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1534 1535 // Return true if we are inside a default argument instantiation 1536 // and the found name refers to an instance member function, otherwise 1537 // the function calling DiagnoseEmptyLookup will try to create an 1538 // implicit member call and this is wrong for default argument. 1539 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1540 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1541 return true; 1542 } 1543 1544 // Tell the callee to try to recover. 1545 return false; 1546 } 1547 1548 R.clear(); 1549 } 1550 1551 // In Microsoft mode, if we are performing lookup from within a friend 1552 // function definition declared at class scope then we must set 1553 // DC to the lexical parent to be able to search into the parent 1554 // class. 1555 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) && 1556 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1557 DC->getLexicalParent()->isRecord()) 1558 DC = DC->getLexicalParent(); 1559 else 1560 DC = DC->getParent(); 1561 } 1562 1563 // We didn't find anything, so try to correct for a typo. 1564 TypoCorrection Corrected; 1565 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 1566 S, &SS, CCC))) { 1567 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1568 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts())); 1569 R.setLookupName(Corrected.getCorrection()); 1570 1571 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 1572 if (Corrected.isOverloaded()) { 1573 OverloadCandidateSet OCS(R.getNameLoc()); 1574 OverloadCandidateSet::iterator Best; 1575 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1576 CDEnd = Corrected.end(); 1577 CD != CDEnd; ++CD) { 1578 if (FunctionTemplateDecl *FTD = 1579 dyn_cast<FunctionTemplateDecl>(*CD)) 1580 AddTemplateOverloadCandidate( 1581 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1582 Args, OCS); 1583 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1584 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1585 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1586 Args, OCS); 1587 } 1588 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1589 case OR_Success: 1590 ND = Best->Function; 1591 break; 1592 default: 1593 break; 1594 } 1595 } 1596 R.addDecl(ND); 1597 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 1598 if (SS.isEmpty()) 1599 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr 1600 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1601 else 1602 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1603 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1604 << SS.getRange() 1605 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1606 if (ND) 1607 Diag(ND->getLocation(), diag::note_previous_decl) 1608 << CorrectedQuotedStr; 1609 1610 // Tell the callee to try to recover. 1611 return false; 1612 } 1613 1614 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) { 1615 // FIXME: If we ended up with a typo for a type name or 1616 // Objective-C class name, we're in trouble because the parser 1617 // is in the wrong place to recover. Suggest the typo 1618 // correction, but don't make it a fix-it since we're not going 1619 // to recover well anyway. 1620 if (SS.isEmpty()) 1621 Diag(R.getNameLoc(), diagnostic_suggest) 1622 << Name << CorrectedQuotedStr; 1623 else 1624 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1625 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1626 << SS.getRange(); 1627 1628 // Don't try to recover; it won't work. 1629 return true; 1630 } 1631 } else { 1632 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1633 // because we aren't able to recover. 1634 if (SS.isEmpty()) 1635 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr; 1636 else 1637 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1638 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1639 << SS.getRange(); 1640 return true; 1641 } 1642 } 1643 R.clear(); 1644 1645 // Emit a special diagnostic for failed member lookups. 1646 // FIXME: computing the declaration context might fail here (?) 1647 if (!SS.isEmpty()) { 1648 Diag(R.getNameLoc(), diag::err_no_member) 1649 << Name << computeDeclContext(SS, false) 1650 << SS.getRange(); 1651 return true; 1652 } 1653 1654 // Give up, we can't recover. 1655 Diag(R.getNameLoc(), diagnostic) << Name; 1656 return true; 1657 } 1658 1659 ExprResult Sema::ActOnIdExpression(Scope *S, 1660 CXXScopeSpec &SS, 1661 SourceLocation TemplateKWLoc, 1662 UnqualifiedId &Id, 1663 bool HasTrailingLParen, 1664 bool IsAddressOfOperand, 1665 CorrectionCandidateCallback *CCC) { 1666 assert(!(IsAddressOfOperand && HasTrailingLParen) && 1667 "cannot be direct & operand and have a trailing lparen"); 1668 1669 if (SS.isInvalid()) 1670 return ExprError(); 1671 1672 TemplateArgumentListInfo TemplateArgsBuffer; 1673 1674 // Decompose the UnqualifiedId into the following data. 1675 DeclarationNameInfo NameInfo; 1676 const TemplateArgumentListInfo *TemplateArgs; 1677 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1678 1679 DeclarationName Name = NameInfo.getName(); 1680 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1681 SourceLocation NameLoc = NameInfo.getLoc(); 1682 1683 // C++ [temp.dep.expr]p3: 1684 // An id-expression is type-dependent if it contains: 1685 // -- an identifier that was declared with a dependent type, 1686 // (note: handled after lookup) 1687 // -- a template-id that is dependent, 1688 // (note: handled in BuildTemplateIdExpr) 1689 // -- a conversion-function-id that specifies a dependent type, 1690 // -- a nested-name-specifier that contains a class-name that 1691 // names a dependent type. 1692 // Determine whether this is a member of an unknown specialization; 1693 // we need to handle these differently. 1694 bool DependentID = false; 1695 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1696 Name.getCXXNameType()->isDependentType()) { 1697 DependentID = true; 1698 } else if (SS.isSet()) { 1699 if (DeclContext *DC = computeDeclContext(SS, false)) { 1700 if (RequireCompleteDeclContext(SS, DC)) 1701 return ExprError(); 1702 } else { 1703 DependentID = true; 1704 } 1705 } 1706 1707 if (DependentID) 1708 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1709 IsAddressOfOperand, TemplateArgs); 1710 1711 // Perform the required lookup. 1712 LookupResult R(*this, NameInfo, 1713 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 1714 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 1715 if (TemplateArgs) { 1716 // Lookup the template name again to correctly establish the context in 1717 // which it was found. This is really unfortunate as we already did the 1718 // lookup to determine that it was a template name in the first place. If 1719 // this becomes a performance hit, we can work harder to preserve those 1720 // results until we get here but it's likely not worth it. 1721 bool MemberOfUnknownSpecialization; 1722 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 1723 MemberOfUnknownSpecialization); 1724 1725 if (MemberOfUnknownSpecialization || 1726 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 1727 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1728 IsAddressOfOperand, TemplateArgs); 1729 } else { 1730 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 1731 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 1732 1733 // If the result might be in a dependent base class, this is a dependent 1734 // id-expression. 1735 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 1736 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1737 IsAddressOfOperand, TemplateArgs); 1738 1739 // If this reference is in an Objective-C method, then we need to do 1740 // some special Objective-C lookup, too. 1741 if (IvarLookupFollowUp) { 1742 ExprResult E(LookupInObjCMethod(R, S, II, true)); 1743 if (E.isInvalid()) 1744 return ExprError(); 1745 1746 if (Expr *Ex = E.takeAs<Expr>()) 1747 return Owned(Ex); 1748 } 1749 } 1750 1751 if (R.isAmbiguous()) 1752 return ExprError(); 1753 1754 // Determine whether this name might be a candidate for 1755 // argument-dependent lookup. 1756 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 1757 1758 if (R.empty() && !ADL) { 1759 // Otherwise, this could be an implicitly declared function reference (legal 1760 // in C90, extension in C99, forbidden in C++). 1761 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 1762 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 1763 if (D) R.addDecl(D); 1764 } 1765 1766 // If this name wasn't predeclared and if this is not a function 1767 // call, diagnose the problem. 1768 if (R.empty()) { 1769 1770 // In Microsoft mode, if we are inside a template class member function 1771 // and we can't resolve an identifier then assume the identifier is type 1772 // dependent. The goal is to postpone name lookup to instantiation time 1773 // to be able to search into type dependent base classes. 1774 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 1775 isa<CXXMethodDecl>(CurContext)) 1776 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1777 IsAddressOfOperand, TemplateArgs); 1778 1779 CorrectionCandidateCallback DefaultValidator; 1780 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator)) 1781 return ExprError(); 1782 1783 assert(!R.empty() && 1784 "DiagnoseEmptyLookup returned false but added no results"); 1785 1786 // If we found an Objective-C instance variable, let 1787 // LookupInObjCMethod build the appropriate expression to 1788 // reference the ivar. 1789 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 1790 R.clear(); 1791 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 1792 // In a hopelessly buggy code, Objective-C instance variable 1793 // lookup fails and no expression will be built to reference it. 1794 if (!E.isInvalid() && !E.get()) 1795 return ExprError(); 1796 return move(E); 1797 } 1798 } 1799 } 1800 1801 // This is guaranteed from this point on. 1802 assert(!R.empty() || ADL); 1803 1804 // Check whether this might be a C++ implicit instance member access. 1805 // C++ [class.mfct.non-static]p3: 1806 // When an id-expression that is not part of a class member access 1807 // syntax and not used to form a pointer to member is used in the 1808 // body of a non-static member function of class X, if name lookup 1809 // resolves the name in the id-expression to a non-static non-type 1810 // member of some class C, the id-expression is transformed into a 1811 // class member access expression using (*this) as the 1812 // postfix-expression to the left of the . operator. 1813 // 1814 // But we don't actually need to do this for '&' operands if R 1815 // resolved to a function or overloaded function set, because the 1816 // expression is ill-formed if it actually works out to be a 1817 // non-static member function: 1818 // 1819 // C++ [expr.ref]p4: 1820 // Otherwise, if E1.E2 refers to a non-static member function. . . 1821 // [t]he expression can be used only as the left-hand operand of a 1822 // member function call. 1823 // 1824 // There are other safeguards against such uses, but it's important 1825 // to get this right here so that we don't end up making a 1826 // spuriously dependent expression if we're inside a dependent 1827 // instance method. 1828 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 1829 bool MightBeImplicitMember; 1830 if (!IsAddressOfOperand) 1831 MightBeImplicitMember = true; 1832 else if (!SS.isEmpty()) 1833 MightBeImplicitMember = false; 1834 else if (R.isOverloadedResult()) 1835 MightBeImplicitMember = false; 1836 else if (R.isUnresolvableResult()) 1837 MightBeImplicitMember = true; 1838 else 1839 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 1840 isa<IndirectFieldDecl>(R.getFoundDecl()); 1841 1842 if (MightBeImplicitMember) 1843 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 1844 R, TemplateArgs); 1845 } 1846 1847 if (TemplateArgs || TemplateKWLoc.isValid()) 1848 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 1849 1850 return BuildDeclarationNameExpr(SS, R, ADL); 1851 } 1852 1853 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 1854 /// declaration name, generally during template instantiation. 1855 /// There's a large number of things which don't need to be done along 1856 /// this path. 1857 ExprResult 1858 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 1859 const DeclarationNameInfo &NameInfo) { 1860 DeclContext *DC; 1861 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext()) 1862 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 1863 NameInfo, /*TemplateArgs=*/0); 1864 1865 if (RequireCompleteDeclContext(SS, DC)) 1866 return ExprError(); 1867 1868 LookupResult R(*this, NameInfo, LookupOrdinaryName); 1869 LookupQualifiedName(R, DC); 1870 1871 if (R.isAmbiguous()) 1872 return ExprError(); 1873 1874 if (R.empty()) { 1875 Diag(NameInfo.getLoc(), diag::err_no_member) 1876 << NameInfo.getName() << DC << SS.getRange(); 1877 return ExprError(); 1878 } 1879 1880 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false); 1881 } 1882 1883 /// LookupInObjCMethod - The parser has read a name in, and Sema has 1884 /// detected that we're currently inside an ObjC method. Perform some 1885 /// additional lookup. 1886 /// 1887 /// Ideally, most of this would be done by lookup, but there's 1888 /// actually quite a lot of extra work involved. 1889 /// 1890 /// Returns a null sentinel to indicate trivial success. 1891 ExprResult 1892 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 1893 IdentifierInfo *II, bool AllowBuiltinCreation) { 1894 SourceLocation Loc = Lookup.getNameLoc(); 1895 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 1896 1897 // There are two cases to handle here. 1) scoped lookup could have failed, 1898 // in which case we should look for an ivar. 2) scoped lookup could have 1899 // found a decl, but that decl is outside the current instance method (i.e. 1900 // a global variable). In these two cases, we do a lookup for an ivar with 1901 // this name, if the lookup sucedes, we replace it our current decl. 1902 1903 // If we're in a class method, we don't normally want to look for 1904 // ivars. But if we don't find anything else, and there's an 1905 // ivar, that's an error. 1906 bool IsClassMethod = CurMethod->isClassMethod(); 1907 1908 bool LookForIvars; 1909 if (Lookup.empty()) 1910 LookForIvars = true; 1911 else if (IsClassMethod) 1912 LookForIvars = false; 1913 else 1914 LookForIvars = (Lookup.isSingleResult() && 1915 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 1916 ObjCInterfaceDecl *IFace = 0; 1917 if (LookForIvars) { 1918 IFace = CurMethod->getClassInterface(); 1919 ObjCInterfaceDecl *ClassDeclared; 1920 ObjCIvarDecl *IV = 0; 1921 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 1922 // Diagnose using an ivar in a class method. 1923 if (IsClassMethod) 1924 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 1925 << IV->getDeclName()); 1926 1927 // If we're referencing an invalid decl, just return this as a silent 1928 // error node. The error diagnostic was already emitted on the decl. 1929 if (IV->isInvalidDecl()) 1930 return ExprError(); 1931 1932 // Check if referencing a field with __attribute__((deprecated)). 1933 if (DiagnoseUseOfDecl(IV, Loc)) 1934 return ExprError(); 1935 1936 // Diagnose the use of an ivar outside of the declaring class. 1937 if (IV->getAccessControl() == ObjCIvarDecl::Private && 1938 !declaresSameEntity(ClassDeclared, IFace) && 1939 !getLangOpts().DebuggerSupport) 1940 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 1941 1942 // FIXME: This should use a new expr for a direct reference, don't 1943 // turn this into Self->ivar, just return a BareIVarExpr or something. 1944 IdentifierInfo &II = Context.Idents.get("self"); 1945 UnqualifiedId SelfName; 1946 SelfName.setIdentifier(&II, SourceLocation()); 1947 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 1948 CXXScopeSpec SelfScopeSpec; 1949 SourceLocation TemplateKWLoc; 1950 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 1951 SelfName, false, false); 1952 if (SelfExpr.isInvalid()) 1953 return ExprError(); 1954 1955 SelfExpr = DefaultLvalueConversion(SelfExpr.take()); 1956 if (SelfExpr.isInvalid()) 1957 return ExprError(); 1958 1959 MarkAnyDeclReferenced(Loc, IV); 1960 return Owned(new (Context) 1961 ObjCIvarRefExpr(IV, IV->getType(), Loc, 1962 SelfExpr.take(), true, true)); 1963 } 1964 } else if (CurMethod->isInstanceMethod()) { 1965 // We should warn if a local variable hides an ivar. 1966 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 1967 ObjCInterfaceDecl *ClassDeclared; 1968 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 1969 if (IV->getAccessControl() != ObjCIvarDecl::Private || 1970 declaresSameEntity(IFace, ClassDeclared)) 1971 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 1972 } 1973 } 1974 } else if (Lookup.isSingleResult() && 1975 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 1976 // If accessing a stand-alone ivar in a class method, this is an error. 1977 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 1978 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 1979 << IV->getDeclName()); 1980 } 1981 1982 if (Lookup.empty() && II && AllowBuiltinCreation) { 1983 // FIXME. Consolidate this with similar code in LookupName. 1984 if (unsigned BuiltinID = II->getBuiltinID()) { 1985 if (!(getLangOpts().CPlusPlus && 1986 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 1987 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 1988 S, Lookup.isForRedeclaration(), 1989 Lookup.getNameLoc()); 1990 if (D) Lookup.addDecl(D); 1991 } 1992 } 1993 } 1994 // Sentinel value saying that we didn't do anything special. 1995 return Owned((Expr*) 0); 1996 } 1997 1998 /// \brief Cast a base object to a member's actual type. 1999 /// 2000 /// Logically this happens in three phases: 2001 /// 2002 /// * First we cast from the base type to the naming class. 2003 /// The naming class is the class into which we were looking 2004 /// when we found the member; it's the qualifier type if a 2005 /// qualifier was provided, and otherwise it's the base type. 2006 /// 2007 /// * Next we cast from the naming class to the declaring class. 2008 /// If the member we found was brought into a class's scope by 2009 /// a using declaration, this is that class; otherwise it's 2010 /// the class declaring the member. 2011 /// 2012 /// * Finally we cast from the declaring class to the "true" 2013 /// declaring class of the member. This conversion does not 2014 /// obey access control. 2015 ExprResult 2016 Sema::PerformObjectMemberConversion(Expr *From, 2017 NestedNameSpecifier *Qualifier, 2018 NamedDecl *FoundDecl, 2019 NamedDecl *Member) { 2020 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2021 if (!RD) 2022 return Owned(From); 2023 2024 QualType DestRecordType; 2025 QualType DestType; 2026 QualType FromRecordType; 2027 QualType FromType = From->getType(); 2028 bool PointerConversions = false; 2029 if (isa<FieldDecl>(Member)) { 2030 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2031 2032 if (FromType->getAs<PointerType>()) { 2033 DestType = Context.getPointerType(DestRecordType); 2034 FromRecordType = FromType->getPointeeType(); 2035 PointerConversions = true; 2036 } else { 2037 DestType = DestRecordType; 2038 FromRecordType = FromType; 2039 } 2040 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2041 if (Method->isStatic()) 2042 return Owned(From); 2043 2044 DestType = Method->getThisType(Context); 2045 DestRecordType = DestType->getPointeeType(); 2046 2047 if (FromType->getAs<PointerType>()) { 2048 FromRecordType = FromType->getPointeeType(); 2049 PointerConversions = true; 2050 } else { 2051 FromRecordType = FromType; 2052 DestType = DestRecordType; 2053 } 2054 } else { 2055 // No conversion necessary. 2056 return Owned(From); 2057 } 2058 2059 if (DestType->isDependentType() || FromType->isDependentType()) 2060 return Owned(From); 2061 2062 // If the unqualified types are the same, no conversion is necessary. 2063 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2064 return Owned(From); 2065 2066 SourceRange FromRange = From->getSourceRange(); 2067 SourceLocation FromLoc = FromRange.getBegin(); 2068 2069 ExprValueKind VK = From->getValueKind(); 2070 2071 // C++ [class.member.lookup]p8: 2072 // [...] Ambiguities can often be resolved by qualifying a name with its 2073 // class name. 2074 // 2075 // If the member was a qualified name and the qualified referred to a 2076 // specific base subobject type, we'll cast to that intermediate type 2077 // first and then to the object in which the member is declared. That allows 2078 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2079 // 2080 // class Base { public: int x; }; 2081 // class Derived1 : public Base { }; 2082 // class Derived2 : public Base { }; 2083 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2084 // 2085 // void VeryDerived::f() { 2086 // x = 17; // error: ambiguous base subobjects 2087 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2088 // } 2089 if (Qualifier) { 2090 QualType QType = QualType(Qualifier->getAsType(), 0); 2091 assert(!QType.isNull() && "lookup done with dependent qualifier?"); 2092 assert(QType->isRecordType() && "lookup done with non-record type"); 2093 2094 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2095 2096 // In C++98, the qualifier type doesn't actually have to be a base 2097 // type of the object type, in which case we just ignore it. 2098 // Otherwise build the appropriate casts. 2099 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2100 CXXCastPath BasePath; 2101 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2102 FromLoc, FromRange, &BasePath)) 2103 return ExprError(); 2104 2105 if (PointerConversions) 2106 QType = Context.getPointerType(QType); 2107 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2108 VK, &BasePath).take(); 2109 2110 FromType = QType; 2111 FromRecordType = QRecordType; 2112 2113 // If the qualifier type was the same as the destination type, 2114 // we're done. 2115 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2116 return Owned(From); 2117 } 2118 } 2119 2120 bool IgnoreAccess = false; 2121 2122 // If we actually found the member through a using declaration, cast 2123 // down to the using declaration's type. 2124 // 2125 // Pointer equality is fine here because only one declaration of a 2126 // class ever has member declarations. 2127 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2128 assert(isa<UsingShadowDecl>(FoundDecl)); 2129 QualType URecordType = Context.getTypeDeclType( 2130 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2131 2132 // We only need to do this if the naming-class to declaring-class 2133 // conversion is non-trivial. 2134 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2135 assert(IsDerivedFrom(FromRecordType, URecordType)); 2136 CXXCastPath BasePath; 2137 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2138 FromLoc, FromRange, &BasePath)) 2139 return ExprError(); 2140 2141 QualType UType = URecordType; 2142 if (PointerConversions) 2143 UType = Context.getPointerType(UType); 2144 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2145 VK, &BasePath).take(); 2146 FromType = UType; 2147 FromRecordType = URecordType; 2148 } 2149 2150 // We don't do access control for the conversion from the 2151 // declaring class to the true declaring class. 2152 IgnoreAccess = true; 2153 } 2154 2155 CXXCastPath BasePath; 2156 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2157 FromLoc, FromRange, &BasePath, 2158 IgnoreAccess)) 2159 return ExprError(); 2160 2161 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2162 VK, &BasePath); 2163 } 2164 2165 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2166 const LookupResult &R, 2167 bool HasTrailingLParen) { 2168 // Only when used directly as the postfix-expression of a call. 2169 if (!HasTrailingLParen) 2170 return false; 2171 2172 // Never if a scope specifier was provided. 2173 if (SS.isSet()) 2174 return false; 2175 2176 // Only in C++ or ObjC++. 2177 if (!getLangOpts().CPlusPlus) 2178 return false; 2179 2180 // Turn off ADL when we find certain kinds of declarations during 2181 // normal lookup: 2182 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2183 NamedDecl *D = *I; 2184 2185 // C++0x [basic.lookup.argdep]p3: 2186 // -- a declaration of a class member 2187 // Since using decls preserve this property, we check this on the 2188 // original decl. 2189 if (D->isCXXClassMember()) 2190 return false; 2191 2192 // C++0x [basic.lookup.argdep]p3: 2193 // -- a block-scope function declaration that is not a 2194 // using-declaration 2195 // NOTE: we also trigger this for function templates (in fact, we 2196 // don't check the decl type at all, since all other decl types 2197 // turn off ADL anyway). 2198 if (isa<UsingShadowDecl>(D)) 2199 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2200 else if (D->getDeclContext()->isFunctionOrMethod()) 2201 return false; 2202 2203 // C++0x [basic.lookup.argdep]p3: 2204 // -- a declaration that is neither a function or a function 2205 // template 2206 // And also for builtin functions. 2207 if (isa<FunctionDecl>(D)) { 2208 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2209 2210 // But also builtin functions. 2211 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2212 return false; 2213 } else if (!isa<FunctionTemplateDecl>(D)) 2214 return false; 2215 } 2216 2217 return true; 2218 } 2219 2220 2221 /// Diagnoses obvious problems with the use of the given declaration 2222 /// as an expression. This is only actually called for lookups that 2223 /// were not overloaded, and it doesn't promise that the declaration 2224 /// will in fact be used. 2225 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2226 if (isa<TypedefNameDecl>(D)) { 2227 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2228 return true; 2229 } 2230 2231 if (isa<ObjCInterfaceDecl>(D)) { 2232 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2233 return true; 2234 } 2235 2236 if (isa<NamespaceDecl>(D)) { 2237 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2238 return true; 2239 } 2240 2241 return false; 2242 } 2243 2244 ExprResult 2245 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2246 LookupResult &R, 2247 bool NeedsADL) { 2248 // If this is a single, fully-resolved result and we don't need ADL, 2249 // just build an ordinary singleton decl ref. 2250 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2251 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), 2252 R.getFoundDecl()); 2253 2254 // We only need to check the declaration if there's exactly one 2255 // result, because in the overloaded case the results can only be 2256 // functions and function templates. 2257 if (R.isSingleResult() && 2258 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2259 return ExprError(); 2260 2261 // Otherwise, just build an unresolved lookup expression. Suppress 2262 // any lookup-related diagnostics; we'll hash these out later, when 2263 // we've picked a target. 2264 R.suppressDiagnostics(); 2265 2266 UnresolvedLookupExpr *ULE 2267 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2268 SS.getWithLocInContext(Context), 2269 R.getLookupNameInfo(), 2270 NeedsADL, R.isOverloadedResult(), 2271 R.begin(), R.end()); 2272 2273 return Owned(ULE); 2274 } 2275 2276 /// \brief Complete semantic analysis for a reference to the given declaration. 2277 ExprResult 2278 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2279 const DeclarationNameInfo &NameInfo, 2280 NamedDecl *D) { 2281 assert(D && "Cannot refer to a NULL declaration"); 2282 assert(!isa<FunctionTemplateDecl>(D) && 2283 "Cannot refer unambiguously to a function template"); 2284 2285 SourceLocation Loc = NameInfo.getLoc(); 2286 if (CheckDeclInExpr(*this, Loc, D)) 2287 return ExprError(); 2288 2289 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2290 // Specifically diagnose references to class templates that are missing 2291 // a template argument list. 2292 Diag(Loc, diag::err_template_decl_ref) 2293 << Template << SS.getRange(); 2294 Diag(Template->getLocation(), diag::note_template_decl_here); 2295 return ExprError(); 2296 } 2297 2298 // Make sure that we're referring to a value. 2299 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2300 if (!VD) { 2301 Diag(Loc, diag::err_ref_non_value) 2302 << D << SS.getRange(); 2303 Diag(D->getLocation(), diag::note_declared_at); 2304 return ExprError(); 2305 } 2306 2307 // Check whether this declaration can be used. Note that we suppress 2308 // this check when we're going to perform argument-dependent lookup 2309 // on this function name, because this might not be the function 2310 // that overload resolution actually selects. 2311 if (DiagnoseUseOfDecl(VD, Loc)) 2312 return ExprError(); 2313 2314 // Only create DeclRefExpr's for valid Decl's. 2315 if (VD->isInvalidDecl()) 2316 return ExprError(); 2317 2318 // Handle members of anonymous structs and unions. If we got here, 2319 // and the reference is to a class member indirect field, then this 2320 // must be the subject of a pointer-to-member expression. 2321 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2322 if (!indirectField->isCXXClassMember()) 2323 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2324 indirectField); 2325 2326 { 2327 QualType type = VD->getType(); 2328 ExprValueKind valueKind = VK_RValue; 2329 2330 switch (D->getKind()) { 2331 // Ignore all the non-ValueDecl kinds. 2332 #define ABSTRACT_DECL(kind) 2333 #define VALUE(type, base) 2334 #define DECL(type, base) \ 2335 case Decl::type: 2336 #include "clang/AST/DeclNodes.inc" 2337 llvm_unreachable("invalid value decl kind"); 2338 2339 // These shouldn't make it here. 2340 case Decl::ObjCAtDefsField: 2341 case Decl::ObjCIvar: 2342 llvm_unreachable("forming non-member reference to ivar?"); 2343 2344 // Enum constants are always r-values and never references. 2345 // Unresolved using declarations are dependent. 2346 case Decl::EnumConstant: 2347 case Decl::UnresolvedUsingValue: 2348 valueKind = VK_RValue; 2349 break; 2350 2351 // Fields and indirect fields that got here must be for 2352 // pointer-to-member expressions; we just call them l-values for 2353 // internal consistency, because this subexpression doesn't really 2354 // exist in the high-level semantics. 2355 case Decl::Field: 2356 case Decl::IndirectField: 2357 assert(getLangOpts().CPlusPlus && 2358 "building reference to field in C?"); 2359 2360 // These can't have reference type in well-formed programs, but 2361 // for internal consistency we do this anyway. 2362 type = type.getNonReferenceType(); 2363 valueKind = VK_LValue; 2364 break; 2365 2366 // Non-type template parameters are either l-values or r-values 2367 // depending on the type. 2368 case Decl::NonTypeTemplateParm: { 2369 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2370 type = reftype->getPointeeType(); 2371 valueKind = VK_LValue; // even if the parameter is an r-value reference 2372 break; 2373 } 2374 2375 // For non-references, we need to strip qualifiers just in case 2376 // the template parameter was declared as 'const int' or whatever. 2377 valueKind = VK_RValue; 2378 type = type.getUnqualifiedType(); 2379 break; 2380 } 2381 2382 case Decl::Var: 2383 // In C, "extern void blah;" is valid and is an r-value. 2384 if (!getLangOpts().CPlusPlus && 2385 !type.hasQualifiers() && 2386 type->isVoidType()) { 2387 valueKind = VK_RValue; 2388 break; 2389 } 2390 // fallthrough 2391 2392 case Decl::ImplicitParam: 2393 case Decl::ParmVar: { 2394 // These are always l-values. 2395 valueKind = VK_LValue; 2396 type = type.getNonReferenceType(); 2397 2398 // FIXME: Does the addition of const really only apply in 2399 // potentially-evaluated contexts? Since the variable isn't actually 2400 // captured in an unevaluated context, it seems that the answer is no. 2401 if (ExprEvalContexts.back().Context != Sema::Unevaluated) { 2402 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2403 if (!CapturedType.isNull()) 2404 type = CapturedType; 2405 } 2406 2407 break; 2408 } 2409 2410 case Decl::Function: { 2411 const FunctionType *fty = type->castAs<FunctionType>(); 2412 2413 // If we're referring to a function with an __unknown_anytype 2414 // result type, make the entire expression __unknown_anytype. 2415 if (fty->getResultType() == Context.UnknownAnyTy) { 2416 type = Context.UnknownAnyTy; 2417 valueKind = VK_RValue; 2418 break; 2419 } 2420 2421 // Functions are l-values in C++. 2422 if (getLangOpts().CPlusPlus) { 2423 valueKind = VK_LValue; 2424 break; 2425 } 2426 2427 // C99 DR 316 says that, if a function type comes from a 2428 // function definition (without a prototype), that type is only 2429 // used for checking compatibility. Therefore, when referencing 2430 // the function, we pretend that we don't have the full function 2431 // type. 2432 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2433 isa<FunctionProtoType>(fty)) 2434 type = Context.getFunctionNoProtoType(fty->getResultType(), 2435 fty->getExtInfo()); 2436 2437 // Functions are r-values in C. 2438 valueKind = VK_RValue; 2439 break; 2440 } 2441 2442 case Decl::CXXMethod: 2443 // If we're referring to a method with an __unknown_anytype 2444 // result type, make the entire expression __unknown_anytype. 2445 // This should only be possible with a type written directly. 2446 if (const FunctionProtoType *proto 2447 = dyn_cast<FunctionProtoType>(VD->getType())) 2448 if (proto->getResultType() == Context.UnknownAnyTy) { 2449 type = Context.UnknownAnyTy; 2450 valueKind = VK_RValue; 2451 break; 2452 } 2453 2454 // C++ methods are l-values if static, r-values if non-static. 2455 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2456 valueKind = VK_LValue; 2457 break; 2458 } 2459 // fallthrough 2460 2461 case Decl::CXXConversion: 2462 case Decl::CXXDestructor: 2463 case Decl::CXXConstructor: 2464 valueKind = VK_RValue; 2465 break; 2466 } 2467 2468 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS); 2469 } 2470 } 2471 2472 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2473 PredefinedExpr::IdentType IT; 2474 2475 switch (Kind) { 2476 default: llvm_unreachable("Unknown simple primary expr!"); 2477 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2478 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2479 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 2480 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2481 } 2482 2483 // Pre-defined identifiers are of type char[x], where x is the length of the 2484 // string. 2485 2486 Decl *currentDecl = getCurFunctionOrMethodDecl(); 2487 if (!currentDecl && getCurBlock()) 2488 currentDecl = getCurBlock()->TheDecl; 2489 if (!currentDecl) { 2490 Diag(Loc, diag::ext_predef_outside_function); 2491 currentDecl = Context.getTranslationUnitDecl(); 2492 } 2493 2494 QualType ResTy; 2495 if (cast<DeclContext>(currentDecl)->isDependentContext()) { 2496 ResTy = Context.DependentTy; 2497 } else { 2498 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2499 2500 llvm::APInt LengthI(32, Length + 1); 2501 if (IT == PredefinedExpr::LFunction) 2502 ResTy = Context.WCharTy.withConst(); 2503 else 2504 ResTy = Context.CharTy.withConst(); 2505 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2506 } 2507 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 2508 } 2509 2510 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 2511 SmallString<16> CharBuffer; 2512 bool Invalid = false; 2513 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2514 if (Invalid) 2515 return ExprError(); 2516 2517 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2518 PP, Tok.getKind()); 2519 if (Literal.hadError()) 2520 return ExprError(); 2521 2522 QualType Ty; 2523 if (Literal.isWide()) 2524 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++. 2525 else if (Literal.isUTF16()) 2526 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 2527 else if (Literal.isUTF32()) 2528 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 2529 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 2530 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 2531 else 2532 Ty = Context.CharTy; // 'x' -> char in C++ 2533 2534 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2535 if (Literal.isWide()) 2536 Kind = CharacterLiteral::Wide; 2537 else if (Literal.isUTF16()) 2538 Kind = CharacterLiteral::UTF16; 2539 else if (Literal.isUTF32()) 2540 Kind = CharacterLiteral::UTF32; 2541 2542 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2543 Tok.getLocation()); 2544 2545 if (Literal.getUDSuffix().empty()) 2546 return Owned(Lit); 2547 2548 // We're building a user-defined literal. 2549 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2550 SourceLocation UDSuffixLoc = 2551 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2552 2553 // Make sure we're allowed user-defined literals here. 2554 if (!UDLScope) 2555 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 2556 2557 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 2558 // operator "" X (ch) 2559 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 2560 llvm::makeArrayRef(&Lit, 1), 2561 Tok.getLocation()); 2562 } 2563 2564 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 2565 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2566 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 2567 Context.IntTy, Loc)); 2568 } 2569 2570 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 2571 QualType Ty, SourceLocation Loc) { 2572 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 2573 2574 using llvm::APFloat; 2575 APFloat Val(Format); 2576 2577 APFloat::opStatus result = Literal.GetFloatValue(Val); 2578 2579 // Overflow is always an error, but underflow is only an error if 2580 // we underflowed to zero (APFloat reports denormals as underflow). 2581 if ((result & APFloat::opOverflow) || 2582 ((result & APFloat::opUnderflow) && Val.isZero())) { 2583 unsigned diagnostic; 2584 SmallString<20> buffer; 2585 if (result & APFloat::opOverflow) { 2586 diagnostic = diag::warn_float_overflow; 2587 APFloat::getLargest(Format).toString(buffer); 2588 } else { 2589 diagnostic = diag::warn_float_underflow; 2590 APFloat::getSmallest(Format).toString(buffer); 2591 } 2592 2593 S.Diag(Loc, diagnostic) 2594 << Ty 2595 << StringRef(buffer.data(), buffer.size()); 2596 } 2597 2598 bool isExact = (result == APFloat::opOK); 2599 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 2600 } 2601 2602 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 2603 // Fast path for a single digit (which is quite common). A single digit 2604 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 2605 if (Tok.getLength() == 1) { 2606 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 2607 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 2608 } 2609 2610 SmallString<512> IntegerBuffer; 2611 // Add padding so that NumericLiteralParser can overread by one character. 2612 IntegerBuffer.resize(Tok.getLength()+1); 2613 const char *ThisTokBegin = &IntegerBuffer[0]; 2614 2615 // Get the spelling of the token, which eliminates trigraphs, etc. 2616 bool Invalid = false; 2617 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid); 2618 if (Invalid) 2619 return ExprError(); 2620 2621 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 2622 Tok.getLocation(), PP); 2623 if (Literal.hadError) 2624 return ExprError(); 2625 2626 if (Literal.hasUDSuffix()) { 2627 // We're building a user-defined literal. 2628 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2629 SourceLocation UDSuffixLoc = 2630 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2631 2632 // Make sure we're allowed user-defined literals here. 2633 if (!UDLScope) 2634 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 2635 2636 QualType CookedTy; 2637 if (Literal.isFloatingLiteral()) { 2638 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 2639 // long double, the literal is treated as a call of the form 2640 // operator "" X (f L) 2641 CookedTy = Context.LongDoubleTy; 2642 } else { 2643 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 2644 // unsigned long long, the literal is treated as a call of the form 2645 // operator "" X (n ULL) 2646 CookedTy = Context.UnsignedLongLongTy; 2647 } 2648 2649 DeclarationName OpName = 2650 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 2651 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 2652 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 2653 2654 // Perform literal operator lookup to determine if we're building a raw 2655 // literal or a cooked one. 2656 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 2657 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1), 2658 /*AllowRawAndTemplate*/true)) { 2659 case LOLR_Error: 2660 return ExprError(); 2661 2662 case LOLR_Cooked: { 2663 Expr *Lit; 2664 if (Literal.isFloatingLiteral()) { 2665 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 2666 } else { 2667 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 2668 if (Literal.GetIntegerValue(ResultVal)) 2669 Diag(Tok.getLocation(), diag::warn_integer_too_large); 2670 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 2671 Tok.getLocation()); 2672 } 2673 return BuildLiteralOperatorCall(R, OpNameInfo, 2674 llvm::makeArrayRef(&Lit, 1), 2675 Tok.getLocation()); 2676 } 2677 2678 case LOLR_Raw: { 2679 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 2680 // literal is treated as a call of the form 2681 // operator "" X ("n") 2682 SourceLocation TokLoc = Tok.getLocation(); 2683 unsigned Length = Literal.getUDSuffixOffset(); 2684 QualType StrTy = Context.getConstantArrayType( 2685 Context.CharTy, llvm::APInt(32, Length + 1), 2686 ArrayType::Normal, 0); 2687 Expr *Lit = StringLiteral::Create( 2688 Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii, 2689 /*Pascal*/false, StrTy, &TokLoc, 1); 2690 return BuildLiteralOperatorCall(R, OpNameInfo, 2691 llvm::makeArrayRef(&Lit, 1), TokLoc); 2692 } 2693 2694 case LOLR_Template: 2695 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 2696 // template), L is treated as a call fo the form 2697 // operator "" X <'c1', 'c2', ... 'ck'>() 2698 // where n is the source character sequence c1 c2 ... ck. 2699 TemplateArgumentListInfo ExplicitArgs; 2700 unsigned CharBits = Context.getIntWidth(Context.CharTy); 2701 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 2702 llvm::APSInt Value(CharBits, CharIsUnsigned); 2703 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 2704 Value = ThisTokBegin[I]; 2705 TemplateArgument Arg(Context, Value, Context.CharTy); 2706 TemplateArgumentLocInfo ArgInfo; 2707 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 2708 } 2709 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(), 2710 Tok.getLocation(), &ExplicitArgs); 2711 } 2712 2713 llvm_unreachable("unexpected literal operator lookup result"); 2714 } 2715 2716 Expr *Res; 2717 2718 if (Literal.isFloatingLiteral()) { 2719 QualType Ty; 2720 if (Literal.isFloat) 2721 Ty = Context.FloatTy; 2722 else if (!Literal.isLong) 2723 Ty = Context.DoubleTy; 2724 else 2725 Ty = Context.LongDoubleTy; 2726 2727 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 2728 2729 if (Ty == Context.DoubleTy) { 2730 if (getLangOpts().SinglePrecisionConstants) { 2731 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 2732 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 2733 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 2734 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 2735 } 2736 } 2737 } else if (!Literal.isIntegerLiteral()) { 2738 return ExprError(); 2739 } else { 2740 QualType Ty; 2741 2742 // long long is a C99 feature. 2743 if (!getLangOpts().C99 && Literal.isLongLong) 2744 Diag(Tok.getLocation(), 2745 getLangOpts().CPlusPlus0x ? 2746 diag::warn_cxx98_compat_longlong : diag::ext_longlong); 2747 2748 // Get the value in the widest-possible width. 2749 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 2750 // The microsoft literal suffix extensions support 128-bit literals, which 2751 // may be wider than [u]intmax_t. 2752 if (Literal.isMicrosoftInteger && MaxWidth < 128) 2753 MaxWidth = 128; 2754 llvm::APInt ResultVal(MaxWidth, 0); 2755 2756 if (Literal.GetIntegerValue(ResultVal)) { 2757 // If this value didn't fit into uintmax_t, warn and force to ull. 2758 Diag(Tok.getLocation(), diag::warn_integer_too_large); 2759 Ty = Context.UnsignedLongLongTy; 2760 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 2761 "long long is not intmax_t?"); 2762 } else { 2763 // If this value fits into a ULL, try to figure out what else it fits into 2764 // according to the rules of C99 6.4.4.1p5. 2765 2766 // Octal, Hexadecimal, and integers with a U suffix are allowed to 2767 // be an unsigned int. 2768 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 2769 2770 // Check from smallest to largest, picking the smallest type we can. 2771 unsigned Width = 0; 2772 if (!Literal.isLong && !Literal.isLongLong) { 2773 // Are int/unsigned possibilities? 2774 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2775 2776 // Does it fit in a unsigned int? 2777 if (ResultVal.isIntN(IntSize)) { 2778 // Does it fit in a signed int? 2779 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 2780 Ty = Context.IntTy; 2781 else if (AllowUnsigned) 2782 Ty = Context.UnsignedIntTy; 2783 Width = IntSize; 2784 } 2785 } 2786 2787 // Are long/unsigned long possibilities? 2788 if (Ty.isNull() && !Literal.isLongLong) { 2789 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 2790 2791 // Does it fit in a unsigned long? 2792 if (ResultVal.isIntN(LongSize)) { 2793 // Does it fit in a signed long? 2794 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 2795 Ty = Context.LongTy; 2796 else if (AllowUnsigned) 2797 Ty = Context.UnsignedLongTy; 2798 Width = LongSize; 2799 } 2800 } 2801 2802 // Check long long if needed. 2803 if (Ty.isNull()) { 2804 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 2805 2806 // Does it fit in a unsigned long long? 2807 if (ResultVal.isIntN(LongLongSize)) { 2808 // Does it fit in a signed long long? 2809 // To be compatible with MSVC, hex integer literals ending with the 2810 // LL or i64 suffix are always signed in Microsoft mode. 2811 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 2812 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 2813 Ty = Context.LongLongTy; 2814 else if (AllowUnsigned) 2815 Ty = Context.UnsignedLongLongTy; 2816 Width = LongLongSize; 2817 } 2818 } 2819 2820 // If it doesn't fit in unsigned long long, and we're using Microsoft 2821 // extensions, then its a 128-bit integer literal. 2822 if (Ty.isNull() && Literal.isMicrosoftInteger) { 2823 if (Literal.isUnsigned) 2824 Ty = Context.UnsignedInt128Ty; 2825 else 2826 Ty = Context.Int128Ty; 2827 Width = 128; 2828 } 2829 2830 // If we still couldn't decide a type, we probably have something that 2831 // does not fit in a signed long long, but has no U suffix. 2832 if (Ty.isNull()) { 2833 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 2834 Ty = Context.UnsignedLongLongTy; 2835 Width = Context.getTargetInfo().getLongLongWidth(); 2836 } 2837 2838 if (ResultVal.getBitWidth() != Width) 2839 ResultVal = ResultVal.trunc(Width); 2840 } 2841 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 2842 } 2843 2844 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 2845 if (Literal.isImaginary) 2846 Res = new (Context) ImaginaryLiteral(Res, 2847 Context.getComplexType(Res->getType())); 2848 2849 return Owned(Res); 2850 } 2851 2852 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 2853 assert((E != 0) && "ActOnParenExpr() missing expr"); 2854 return Owned(new (Context) ParenExpr(L, R, E)); 2855 } 2856 2857 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 2858 SourceLocation Loc, 2859 SourceRange ArgRange) { 2860 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 2861 // scalar or vector data type argument..." 2862 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 2863 // type (C99 6.2.5p18) or void. 2864 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 2865 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 2866 << T << ArgRange; 2867 return true; 2868 } 2869 2870 assert((T->isVoidType() || !T->isIncompleteType()) && 2871 "Scalar types should always be complete"); 2872 return false; 2873 } 2874 2875 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 2876 SourceLocation Loc, 2877 SourceRange ArgRange, 2878 UnaryExprOrTypeTrait TraitKind) { 2879 // C99 6.5.3.4p1: 2880 if (T->isFunctionType()) { 2881 // alignof(function) is allowed as an extension. 2882 if (TraitKind == UETT_SizeOf) 2883 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange; 2884 return false; 2885 } 2886 2887 // Allow sizeof(void)/alignof(void) as an extension. 2888 if (T->isVoidType()) { 2889 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange; 2890 return false; 2891 } 2892 2893 return true; 2894 } 2895 2896 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 2897 SourceLocation Loc, 2898 SourceRange ArgRange, 2899 UnaryExprOrTypeTrait TraitKind) { 2900 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode. 2901 if (S.LangOpts.ObjCRuntime.isNonFragile() && T->isObjCObjectType()) { 2902 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 2903 << T << (TraitKind == UETT_SizeOf) 2904 << ArgRange; 2905 return true; 2906 } 2907 2908 return false; 2909 } 2910 2911 /// \brief Check the constrains on expression operands to unary type expression 2912 /// and type traits. 2913 /// 2914 /// Completes any types necessary and validates the constraints on the operand 2915 /// expression. The logic mostly mirrors the type-based overload, but may modify 2916 /// the expression as it completes the type for that expression through template 2917 /// instantiation, etc. 2918 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 2919 UnaryExprOrTypeTrait ExprKind) { 2920 QualType ExprTy = E->getType(); 2921 2922 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 2923 // the result is the size of the referenced type." 2924 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 2925 // result shall be the alignment of the referenced type." 2926 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>()) 2927 ExprTy = Ref->getPointeeType(); 2928 2929 if (ExprKind == UETT_VecStep) 2930 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 2931 E->getSourceRange()); 2932 2933 // Whitelist some types as extensions 2934 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 2935 E->getSourceRange(), ExprKind)) 2936 return false; 2937 2938 if (RequireCompleteExprType(E, 2939 diag::err_sizeof_alignof_incomplete_type, 2940 ExprKind, E->getSourceRange())) 2941 return true; 2942 2943 // Completeing the expression's type may have changed it. 2944 ExprTy = E->getType(); 2945 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>()) 2946 ExprTy = Ref->getPointeeType(); 2947 2948 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 2949 E->getSourceRange(), ExprKind)) 2950 return true; 2951 2952 if (ExprKind == UETT_SizeOf) { 2953 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 2954 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 2955 QualType OType = PVD->getOriginalType(); 2956 QualType Type = PVD->getType(); 2957 if (Type->isPointerType() && OType->isArrayType()) { 2958 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 2959 << Type << OType; 2960 Diag(PVD->getLocation(), diag::note_declared_at); 2961 } 2962 } 2963 } 2964 } 2965 2966 return false; 2967 } 2968 2969 /// \brief Check the constraints on operands to unary expression and type 2970 /// traits. 2971 /// 2972 /// This will complete any types necessary, and validate the various constraints 2973 /// on those operands. 2974 /// 2975 /// The UsualUnaryConversions() function is *not* called by this routine. 2976 /// C99 6.3.2.1p[2-4] all state: 2977 /// Except when it is the operand of the sizeof operator ... 2978 /// 2979 /// C++ [expr.sizeof]p4 2980 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 2981 /// standard conversions are not applied to the operand of sizeof. 2982 /// 2983 /// This policy is followed for all of the unary trait expressions. 2984 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 2985 SourceLocation OpLoc, 2986 SourceRange ExprRange, 2987 UnaryExprOrTypeTrait ExprKind) { 2988 if (ExprType->isDependentType()) 2989 return false; 2990 2991 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 2992 // the result is the size of the referenced type." 2993 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 2994 // result shall be the alignment of the referenced type." 2995 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 2996 ExprType = Ref->getPointeeType(); 2997 2998 if (ExprKind == UETT_VecStep) 2999 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3000 3001 // Whitelist some types as extensions 3002 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3003 ExprKind)) 3004 return false; 3005 3006 if (RequireCompleteType(OpLoc, ExprType, 3007 diag::err_sizeof_alignof_incomplete_type, 3008 ExprKind, ExprRange)) 3009 return true; 3010 3011 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3012 ExprKind)) 3013 return true; 3014 3015 return false; 3016 } 3017 3018 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3019 E = E->IgnoreParens(); 3020 3021 // alignof decl is always ok. 3022 if (isa<DeclRefExpr>(E)) 3023 return false; 3024 3025 // Cannot know anything else if the expression is dependent. 3026 if (E->isTypeDependent()) 3027 return false; 3028 3029 if (E->getBitField()) { 3030 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3031 << 1 << E->getSourceRange(); 3032 return true; 3033 } 3034 3035 // Alignment of a field access is always okay, so long as it isn't a 3036 // bit-field. 3037 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 3038 if (isa<FieldDecl>(ME->getMemberDecl())) 3039 return false; 3040 3041 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3042 } 3043 3044 bool Sema::CheckVecStepExpr(Expr *E) { 3045 E = E->IgnoreParens(); 3046 3047 // Cannot know anything else if the expression is dependent. 3048 if (E->isTypeDependent()) 3049 return false; 3050 3051 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3052 } 3053 3054 /// \brief Build a sizeof or alignof expression given a type operand. 3055 ExprResult 3056 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3057 SourceLocation OpLoc, 3058 UnaryExprOrTypeTrait ExprKind, 3059 SourceRange R) { 3060 if (!TInfo) 3061 return ExprError(); 3062 3063 QualType T = TInfo->getType(); 3064 3065 if (!T->isDependentType() && 3066 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3067 return ExprError(); 3068 3069 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3070 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo, 3071 Context.getSizeType(), 3072 OpLoc, R.getEnd())); 3073 } 3074 3075 /// \brief Build a sizeof or alignof expression given an expression 3076 /// operand. 3077 ExprResult 3078 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3079 UnaryExprOrTypeTrait ExprKind) { 3080 ExprResult PE = CheckPlaceholderExpr(E); 3081 if (PE.isInvalid()) 3082 return ExprError(); 3083 3084 E = PE.get(); 3085 3086 // Verify that the operand is valid. 3087 bool isInvalid = false; 3088 if (E->isTypeDependent()) { 3089 // Delay type-checking for type-dependent expressions. 3090 } else if (ExprKind == UETT_AlignOf) { 3091 isInvalid = CheckAlignOfExpr(*this, E); 3092 } else if (ExprKind == UETT_VecStep) { 3093 isInvalid = CheckVecStepExpr(E); 3094 } else if (E->getBitField()) { // C99 6.5.3.4p1. 3095 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3096 isInvalid = true; 3097 } else { 3098 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3099 } 3100 3101 if (isInvalid) 3102 return ExprError(); 3103 3104 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3105 PE = TranformToPotentiallyEvaluated(E); 3106 if (PE.isInvalid()) return ExprError(); 3107 E = PE.take(); 3108 } 3109 3110 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3111 return Owned(new (Context) UnaryExprOrTypeTraitExpr( 3112 ExprKind, E, Context.getSizeType(), OpLoc, 3113 E->getSourceRange().getEnd())); 3114 } 3115 3116 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3117 /// expr and the same for @c alignof and @c __alignof 3118 /// Note that the ArgRange is invalid if isType is false. 3119 ExprResult 3120 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3121 UnaryExprOrTypeTrait ExprKind, bool IsType, 3122 void *TyOrEx, const SourceRange &ArgRange) { 3123 // If error parsing type, ignore. 3124 if (TyOrEx == 0) return ExprError(); 3125 3126 if (IsType) { 3127 TypeSourceInfo *TInfo; 3128 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3129 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3130 } 3131 3132 Expr *ArgEx = (Expr *)TyOrEx; 3133 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3134 return move(Result); 3135 } 3136 3137 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3138 bool IsReal) { 3139 if (V.get()->isTypeDependent()) 3140 return S.Context.DependentTy; 3141 3142 // _Real and _Imag are only l-values for normal l-values. 3143 if (V.get()->getObjectKind() != OK_Ordinary) { 3144 V = S.DefaultLvalueConversion(V.take()); 3145 if (V.isInvalid()) 3146 return QualType(); 3147 } 3148 3149 // These operators return the element type of a complex type. 3150 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3151 return CT->getElementType(); 3152 3153 // Otherwise they pass through real integer and floating point types here. 3154 if (V.get()->getType()->isArithmeticType()) 3155 return V.get()->getType(); 3156 3157 // Test for placeholders. 3158 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3159 if (PR.isInvalid()) return QualType(); 3160 if (PR.get() != V.get()) { 3161 V = move(PR); 3162 return CheckRealImagOperand(S, V, Loc, IsReal); 3163 } 3164 3165 // Reject anything else. 3166 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3167 << (IsReal ? "__real" : "__imag"); 3168 return QualType(); 3169 } 3170 3171 3172 3173 ExprResult 3174 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3175 tok::TokenKind Kind, Expr *Input) { 3176 UnaryOperatorKind Opc; 3177 switch (Kind) { 3178 default: llvm_unreachable("Unknown unary op!"); 3179 case tok::plusplus: Opc = UO_PostInc; break; 3180 case tok::minusminus: Opc = UO_PostDec; break; 3181 } 3182 3183 // Since this might is a postfix expression, get rid of ParenListExprs. 3184 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3185 if (Result.isInvalid()) return ExprError(); 3186 Input = Result.take(); 3187 3188 return BuildUnaryOp(S, OpLoc, Opc, Input); 3189 } 3190 3191 ExprResult 3192 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 3193 Expr *Idx, SourceLocation RLoc) { 3194 // Since this might be a postfix expression, get rid of ParenListExprs. 3195 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 3196 if (Result.isInvalid()) return ExprError(); 3197 Base = Result.take(); 3198 3199 Expr *LHSExp = Base, *RHSExp = Idx; 3200 3201 if (getLangOpts().CPlusPlus && 3202 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) { 3203 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3204 Context.DependentTy, 3205 VK_LValue, OK_Ordinary, 3206 RLoc)); 3207 } 3208 3209 if (getLangOpts().CPlusPlus && 3210 (LHSExp->getType()->isRecordType() || 3211 LHSExp->getType()->isEnumeralType() || 3212 RHSExp->getType()->isRecordType() || 3213 RHSExp->getType()->isEnumeralType()) && 3214 !LHSExp->getType()->isObjCObjectPointerType()) { 3215 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx); 3216 } 3217 3218 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc); 3219 } 3220 3221 3222 ExprResult 3223 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3224 Expr *Idx, SourceLocation RLoc) { 3225 Expr *LHSExp = Base; 3226 Expr *RHSExp = Idx; 3227 3228 // Perform default conversions. 3229 if (!LHSExp->getType()->getAs<VectorType>()) { 3230 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3231 if (Result.isInvalid()) 3232 return ExprError(); 3233 LHSExp = Result.take(); 3234 } 3235 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3236 if (Result.isInvalid()) 3237 return ExprError(); 3238 RHSExp = Result.take(); 3239 3240 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3241 ExprValueKind VK = VK_LValue; 3242 ExprObjectKind OK = OK_Ordinary; 3243 3244 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3245 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3246 // in the subscript position. As a result, we need to derive the array base 3247 // and index from the expression types. 3248 Expr *BaseExpr, *IndexExpr; 3249 QualType ResultType; 3250 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3251 BaseExpr = LHSExp; 3252 IndexExpr = RHSExp; 3253 ResultType = Context.DependentTy; 3254 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 3255 BaseExpr = LHSExp; 3256 IndexExpr = RHSExp; 3257 ResultType = PTy->getPointeeType(); 3258 } else if (const ObjCObjectPointerType *PTy = 3259 LHSTy->getAs<ObjCObjectPointerType>()) { 3260 BaseExpr = LHSExp; 3261 IndexExpr = RHSExp; 3262 Result = BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0); 3263 if (!Result.isInvalid()) 3264 return Owned(Result.take()); 3265 ResultType = PTy->getPointeeType(); 3266 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 3267 // Handle the uncommon case of "123[Ptr]". 3268 BaseExpr = RHSExp; 3269 IndexExpr = LHSExp; 3270 ResultType = PTy->getPointeeType(); 3271 } else if (const ObjCObjectPointerType *PTy = 3272 RHSTy->getAs<ObjCObjectPointerType>()) { 3273 // Handle the uncommon case of "123[Ptr]". 3274 BaseExpr = RHSExp; 3275 IndexExpr = LHSExp; 3276 ResultType = PTy->getPointeeType(); 3277 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 3278 BaseExpr = LHSExp; // vectors: V[123] 3279 IndexExpr = RHSExp; 3280 VK = LHSExp->getValueKind(); 3281 if (VK != VK_RValue) 3282 OK = OK_VectorComponent; 3283 3284 // FIXME: need to deal with const... 3285 ResultType = VTy->getElementType(); 3286 } else if (LHSTy->isArrayType()) { 3287 // If we see an array that wasn't promoted by 3288 // DefaultFunctionArrayLvalueConversion, it must be an array that 3289 // wasn't promoted because of the C90 rule that doesn't 3290 // allow promoting non-lvalue arrays. Warn, then 3291 // force the promotion here. 3292 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3293 LHSExp->getSourceRange(); 3294 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3295 CK_ArrayToPointerDecay).take(); 3296 LHSTy = LHSExp->getType(); 3297 3298 BaseExpr = LHSExp; 3299 IndexExpr = RHSExp; 3300 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3301 } else if (RHSTy->isArrayType()) { 3302 // Same as previous, except for 123[f().a] case 3303 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3304 RHSExp->getSourceRange(); 3305 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3306 CK_ArrayToPointerDecay).take(); 3307 RHSTy = RHSExp->getType(); 3308 3309 BaseExpr = RHSExp; 3310 IndexExpr = LHSExp; 3311 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3312 } else { 3313 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3314 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3315 } 3316 // C99 6.5.2.1p1 3317 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3318 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3319 << IndexExpr->getSourceRange()); 3320 3321 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3322 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3323 && !IndexExpr->isTypeDependent()) 3324 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3325 3326 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3327 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3328 // type. Note that Functions are not objects, and that (in C99 parlance) 3329 // incomplete types are not object types. 3330 if (ResultType->isFunctionType()) { 3331 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3332 << ResultType << BaseExpr->getSourceRange(); 3333 return ExprError(); 3334 } 3335 3336 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 3337 // GNU extension: subscripting on pointer to void 3338 Diag(LLoc, diag::ext_gnu_subscript_void_type) 3339 << BaseExpr->getSourceRange(); 3340 3341 // C forbids expressions of unqualified void type from being l-values. 3342 // See IsCForbiddenLValueType. 3343 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3344 } else if (!ResultType->isDependentType() && 3345 RequireCompleteType(LLoc, ResultType, 3346 diag::err_subscript_incomplete_type, BaseExpr)) 3347 return ExprError(); 3348 3349 // Diagnose bad cases where we step over interface counts. 3350 if (ResultType->isObjCObjectType() && LangOpts.ObjCRuntime.isNonFragile()) { 3351 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3352 << ResultType << BaseExpr->getSourceRange(); 3353 return ExprError(); 3354 } 3355 3356 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3357 !ResultType.isCForbiddenLValueType()); 3358 3359 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3360 ResultType, VK, OK, RLoc)); 3361 } 3362 3363 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3364 FunctionDecl *FD, 3365 ParmVarDecl *Param) { 3366 if (Param->hasUnparsedDefaultArg()) { 3367 Diag(CallLoc, 3368 diag::err_use_of_default_argument_to_function_declared_later) << 3369 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3370 Diag(UnparsedDefaultArgLocs[Param], 3371 diag::note_default_argument_declared_here); 3372 return ExprError(); 3373 } 3374 3375 if (Param->hasUninstantiatedDefaultArg()) { 3376 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3377 3378 // Instantiate the expression. 3379 MultiLevelTemplateArgumentList ArgList 3380 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true); 3381 3382 std::pair<const TemplateArgument *, unsigned> Innermost 3383 = ArgList.getInnermost(); 3384 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first, 3385 Innermost.second); 3386 3387 ExprResult Result; 3388 { 3389 // C++ [dcl.fct.default]p5: 3390 // The names in the [default argument] expression are bound, and 3391 // the semantic constraints are checked, at the point where the 3392 // default argument expression appears. 3393 ContextRAII SavedContext(*this, FD); 3394 LocalInstantiationScope Local(*this); 3395 Result = SubstExpr(UninstExpr, ArgList); 3396 } 3397 if (Result.isInvalid()) 3398 return ExprError(); 3399 3400 // Check the expression as an initializer for the parameter. 3401 InitializedEntity Entity 3402 = InitializedEntity::InitializeParameter(Context, Param); 3403 InitializationKind Kind 3404 = InitializationKind::CreateCopy(Param->getLocation(), 3405 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 3406 Expr *ResultE = Result.takeAs<Expr>(); 3407 3408 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1); 3409 Result = InitSeq.Perform(*this, Entity, Kind, 3410 MultiExprArg(*this, &ResultE, 1)); 3411 if (Result.isInvalid()) 3412 return ExprError(); 3413 3414 Expr *Arg = Result.takeAs<Expr>(); 3415 CheckImplicitConversions(Arg, Param->getOuterLocStart()); 3416 // Build the default argument expression. 3417 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg)); 3418 } 3419 3420 // If the default expression creates temporaries, we need to 3421 // push them to the current stack of expression temporaries so they'll 3422 // be properly destroyed. 3423 // FIXME: We should really be rebuilding the default argument with new 3424 // bound temporaries; see the comment in PR5810. 3425 // We don't need to do that with block decls, though, because 3426 // blocks in default argument expression can never capture anything. 3427 if (isa<ExprWithCleanups>(Param->getInit())) { 3428 // Set the "needs cleanups" bit regardless of whether there are 3429 // any explicit objects. 3430 ExprNeedsCleanups = true; 3431 3432 // Append all the objects to the cleanup list. Right now, this 3433 // should always be a no-op, because blocks in default argument 3434 // expressions should never be able to capture anything. 3435 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 3436 "default argument expression has capturing blocks?"); 3437 } 3438 3439 // We already type-checked the argument, so we know it works. 3440 // Just mark all of the declarations in this potentially-evaluated expression 3441 // as being "referenced". 3442 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 3443 /*SkipLocalVariables=*/true); 3444 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 3445 } 3446 3447 3448 Sema::VariadicCallType 3449 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 3450 Expr *Fn) { 3451 if (Proto && Proto->isVariadic()) { 3452 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 3453 return VariadicConstructor; 3454 else if (Fn && Fn->getType()->isBlockPointerType()) 3455 return VariadicBlock; 3456 else if (FDecl) { 3457 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 3458 if (Method->isInstance()) 3459 return VariadicMethod; 3460 } 3461 return VariadicFunction; 3462 } 3463 return VariadicDoesNotApply; 3464 } 3465 3466 /// ConvertArgumentsForCall - Converts the arguments specified in 3467 /// Args/NumArgs to the parameter types of the function FDecl with 3468 /// function prototype Proto. Call is the call expression itself, and 3469 /// Fn is the function expression. For a C++ member function, this 3470 /// routine does not attempt to convert the object argument. Returns 3471 /// true if the call is ill-formed. 3472 bool 3473 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 3474 FunctionDecl *FDecl, 3475 const FunctionProtoType *Proto, 3476 Expr **Args, unsigned NumArgs, 3477 SourceLocation RParenLoc, 3478 bool IsExecConfig) { 3479 // Bail out early if calling a builtin with custom typechecking. 3480 // We don't need to do this in the 3481 if (FDecl) 3482 if (unsigned ID = FDecl->getBuiltinID()) 3483 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 3484 return false; 3485 3486 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 3487 // assignment, to the types of the corresponding parameter, ... 3488 unsigned NumArgsInProto = Proto->getNumArgs(); 3489 bool Invalid = false; 3490 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto; 3491 unsigned FnKind = Fn->getType()->isBlockPointerType() 3492 ? 1 /* block */ 3493 : (IsExecConfig ? 3 /* kernel function (exec config) */ 3494 : 0 /* function */); 3495 3496 // If too few arguments are available (and we don't have default 3497 // arguments for the remaining parameters), don't make the call. 3498 if (NumArgs < NumArgsInProto) { 3499 if (NumArgs < MinArgs) { 3500 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 3501 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic() 3502 ? diag::err_typecheck_call_too_few_args_one 3503 : diag::err_typecheck_call_too_few_args_at_least_one) 3504 << FnKind 3505 << FDecl->getParamDecl(0) << Fn->getSourceRange(); 3506 else 3507 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic() 3508 ? diag::err_typecheck_call_too_few_args 3509 : diag::err_typecheck_call_too_few_args_at_least) 3510 << FnKind 3511 << MinArgs << NumArgs << Fn->getSourceRange(); 3512 3513 // Emit the location of the prototype. 3514 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 3515 Diag(FDecl->getLocStart(), diag::note_callee_decl) 3516 << FDecl; 3517 3518 return true; 3519 } 3520 Call->setNumArgs(Context, NumArgsInProto); 3521 } 3522 3523 // If too many are passed and not variadic, error on the extras and drop 3524 // them. 3525 if (NumArgs > NumArgsInProto) { 3526 if (!Proto->isVariadic()) { 3527 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 3528 Diag(Args[NumArgsInProto]->getLocStart(), 3529 MinArgs == NumArgsInProto 3530 ? diag::err_typecheck_call_too_many_args_one 3531 : diag::err_typecheck_call_too_many_args_at_most_one) 3532 << FnKind 3533 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange() 3534 << SourceRange(Args[NumArgsInProto]->getLocStart(), 3535 Args[NumArgs-1]->getLocEnd()); 3536 else 3537 Diag(Args[NumArgsInProto]->getLocStart(), 3538 MinArgs == NumArgsInProto 3539 ? diag::err_typecheck_call_too_many_args 3540 : diag::err_typecheck_call_too_many_args_at_most) 3541 << FnKind 3542 << NumArgsInProto << NumArgs << Fn->getSourceRange() 3543 << SourceRange(Args[NumArgsInProto]->getLocStart(), 3544 Args[NumArgs-1]->getLocEnd()); 3545 3546 // Emit the location of the prototype. 3547 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 3548 Diag(FDecl->getLocStart(), diag::note_callee_decl) 3549 << FDecl; 3550 3551 // This deletes the extra arguments. 3552 Call->setNumArgs(Context, NumArgsInProto); 3553 return true; 3554 } 3555 } 3556 SmallVector<Expr *, 8> AllArgs; 3557 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 3558 3559 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 3560 Proto, 0, Args, NumArgs, AllArgs, CallType); 3561 if (Invalid) 3562 return true; 3563 unsigned TotalNumArgs = AllArgs.size(); 3564 for (unsigned i = 0; i < TotalNumArgs; ++i) 3565 Call->setArg(i, AllArgs[i]); 3566 3567 return false; 3568 } 3569 3570 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, 3571 FunctionDecl *FDecl, 3572 const FunctionProtoType *Proto, 3573 unsigned FirstProtoArg, 3574 Expr **Args, unsigned NumArgs, 3575 SmallVector<Expr *, 8> &AllArgs, 3576 VariadicCallType CallType, 3577 bool AllowExplicit) { 3578 unsigned NumArgsInProto = Proto->getNumArgs(); 3579 unsigned NumArgsToCheck = NumArgs; 3580 bool Invalid = false; 3581 if (NumArgs != NumArgsInProto) 3582 // Use default arguments for missing arguments 3583 NumArgsToCheck = NumArgsInProto; 3584 unsigned ArgIx = 0; 3585 // Continue to check argument types (even if we have too few/many args). 3586 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) { 3587 QualType ProtoArgType = Proto->getArgType(i); 3588 3589 Expr *Arg; 3590 ParmVarDecl *Param; 3591 if (ArgIx < NumArgs) { 3592 Arg = Args[ArgIx++]; 3593 3594 if (RequireCompleteType(Arg->getLocStart(), 3595 ProtoArgType, 3596 diag::err_call_incomplete_argument, Arg)) 3597 return true; 3598 3599 // Pass the argument 3600 Param = 0; 3601 if (FDecl && i < FDecl->getNumParams()) 3602 Param = FDecl->getParamDecl(i); 3603 3604 // Strip the unbridged-cast placeholder expression off, if applicable. 3605 if (Arg->getType() == Context.ARCUnbridgedCastTy && 3606 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 3607 (!Param || !Param->hasAttr<CFConsumedAttr>())) 3608 Arg = stripARCUnbridgedCast(Arg); 3609 3610 InitializedEntity Entity = 3611 Param? InitializedEntity::InitializeParameter(Context, Param) 3612 : InitializedEntity::InitializeParameter(Context, ProtoArgType, 3613 Proto->isArgConsumed(i)); 3614 ExprResult ArgE = PerformCopyInitialization(Entity, 3615 SourceLocation(), 3616 Owned(Arg), 3617 /*TopLevelOfInitList=*/false, 3618 AllowExplicit); 3619 if (ArgE.isInvalid()) 3620 return true; 3621 3622 Arg = ArgE.takeAs<Expr>(); 3623 } else { 3624 Param = FDecl->getParamDecl(i); 3625 3626 ExprResult ArgExpr = 3627 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 3628 if (ArgExpr.isInvalid()) 3629 return true; 3630 3631 Arg = ArgExpr.takeAs<Expr>(); 3632 } 3633 3634 // Check for array bounds violations for each argument to the call. This 3635 // check only triggers warnings when the argument isn't a more complex Expr 3636 // with its own checking, such as a BinaryOperator. 3637 CheckArrayAccess(Arg); 3638 3639 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 3640 CheckStaticArrayArgument(CallLoc, Param, Arg); 3641 3642 AllArgs.push_back(Arg); 3643 } 3644 3645 // If this is a variadic call, handle args passed through "...". 3646 if (CallType != VariadicDoesNotApply) { 3647 // Assume that extern "C" functions with variadic arguments that 3648 // return __unknown_anytype aren't *really* variadic. 3649 if (Proto->getResultType() == Context.UnknownAnyTy && 3650 FDecl && FDecl->isExternC()) { 3651 for (unsigned i = ArgIx; i != NumArgs; ++i) { 3652 ExprResult arg; 3653 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens())) 3654 arg = DefaultFunctionArrayLvalueConversion(Args[i]); 3655 else 3656 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl); 3657 Invalid |= arg.isInvalid(); 3658 AllArgs.push_back(arg.take()); 3659 } 3660 3661 // Otherwise do argument promotion, (C99 6.5.2.2p7). 3662 } else { 3663 for (unsigned i = ArgIx; i != NumArgs; ++i) { 3664 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 3665 FDecl); 3666 Invalid |= Arg.isInvalid(); 3667 AllArgs.push_back(Arg.take()); 3668 } 3669 } 3670 3671 // Check for array bounds violations. 3672 for (unsigned i = ArgIx; i != NumArgs; ++i) 3673 CheckArrayAccess(Args[i]); 3674 } 3675 return Invalid; 3676 } 3677 3678 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 3679 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 3680 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL)) 3681 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 3682 << ATL->getLocalSourceRange(); 3683 } 3684 3685 /// CheckStaticArrayArgument - If the given argument corresponds to a static 3686 /// array parameter, check that it is non-null, and that if it is formed by 3687 /// array-to-pointer decay, the underlying array is sufficiently large. 3688 /// 3689 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 3690 /// array type derivation, then for each call to the function, the value of the 3691 /// corresponding actual argument shall provide access to the first element of 3692 /// an array with at least as many elements as specified by the size expression. 3693 void 3694 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 3695 ParmVarDecl *Param, 3696 const Expr *ArgExpr) { 3697 // Static array parameters are not supported in C++. 3698 if (!Param || getLangOpts().CPlusPlus) 3699 return; 3700 3701 QualType OrigTy = Param->getOriginalType(); 3702 3703 const ArrayType *AT = Context.getAsArrayType(OrigTy); 3704 if (!AT || AT->getSizeModifier() != ArrayType::Static) 3705 return; 3706 3707 if (ArgExpr->isNullPointerConstant(Context, 3708 Expr::NPC_NeverValueDependent)) { 3709 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 3710 DiagnoseCalleeStaticArrayParam(*this, Param); 3711 return; 3712 } 3713 3714 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 3715 if (!CAT) 3716 return; 3717 3718 const ConstantArrayType *ArgCAT = 3719 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 3720 if (!ArgCAT) 3721 return; 3722 3723 if (ArgCAT->getSize().ult(CAT->getSize())) { 3724 Diag(CallLoc, diag::warn_static_array_too_small) 3725 << ArgExpr->getSourceRange() 3726 << (unsigned) ArgCAT->getSize().getZExtValue() 3727 << (unsigned) CAT->getSize().getZExtValue(); 3728 DiagnoseCalleeStaticArrayParam(*this, Param); 3729 } 3730 } 3731 3732 /// Given a function expression of unknown-any type, try to rebuild it 3733 /// to have a function type. 3734 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 3735 3736 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 3737 /// This provides the location of the left/right parens and a list of comma 3738 /// locations. 3739 ExprResult 3740 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 3741 MultiExprArg ArgExprs, SourceLocation RParenLoc, 3742 Expr *ExecConfig, bool IsExecConfig) { 3743 unsigned NumArgs = ArgExprs.size(); 3744 3745 // Since this might be a postfix expression, get rid of ParenListExprs. 3746 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 3747 if (Result.isInvalid()) return ExprError(); 3748 Fn = Result.take(); 3749 3750 Expr **Args = ArgExprs.release(); 3751 3752 if (getLangOpts().CPlusPlus) { 3753 // If this is a pseudo-destructor expression, build the call immediately. 3754 if (isa<CXXPseudoDestructorExpr>(Fn)) { 3755 if (NumArgs > 0) { 3756 // Pseudo-destructor calls should not have any arguments. 3757 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 3758 << FixItHint::CreateRemoval( 3759 SourceRange(Args[0]->getLocStart(), 3760 Args[NumArgs-1]->getLocEnd())); 3761 } 3762 3763 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy, 3764 VK_RValue, RParenLoc)); 3765 } 3766 3767 // Determine whether this is a dependent call inside a C++ template, 3768 // in which case we won't do any semantic analysis now. 3769 // FIXME: Will need to cache the results of name lookup (including ADL) in 3770 // Fn. 3771 bool Dependent = false; 3772 if (Fn->isTypeDependent()) 3773 Dependent = true; 3774 else if (Expr::hasAnyTypeDependentArguments( 3775 llvm::makeArrayRef(Args, NumArgs))) 3776 Dependent = true; 3777 3778 if (Dependent) { 3779 if (ExecConfig) { 3780 return Owned(new (Context) CUDAKernelCallExpr( 3781 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs, 3782 Context.DependentTy, VK_RValue, RParenLoc)); 3783 } else { 3784 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs, 3785 Context.DependentTy, VK_RValue, 3786 RParenLoc)); 3787 } 3788 } 3789 3790 // Determine whether this is a call to an object (C++ [over.call.object]). 3791 if (Fn->getType()->isRecordType()) 3792 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs, 3793 RParenLoc)); 3794 3795 if (Fn->getType() == Context.UnknownAnyTy) { 3796 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 3797 if (result.isInvalid()) return ExprError(); 3798 Fn = result.take(); 3799 } 3800 3801 if (Fn->getType() == Context.BoundMemberTy) { 3802 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 3803 RParenLoc); 3804 } 3805 } 3806 3807 // Check for overloaded calls. This can happen even in C due to extensions. 3808 if (Fn->getType() == Context.OverloadTy) { 3809 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 3810 3811 // We aren't supposed to apply this logic for if there's an '&' involved. 3812 if (!find.HasFormOfMemberPointer) { 3813 OverloadExpr *ovl = find.Expression; 3814 if (isa<UnresolvedLookupExpr>(ovl)) { 3815 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 3816 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs, 3817 RParenLoc, ExecConfig); 3818 } else { 3819 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 3820 RParenLoc); 3821 } 3822 } 3823 } 3824 3825 // If we're directly calling a function, get the appropriate declaration. 3826 if (Fn->getType() == Context.UnknownAnyTy) { 3827 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 3828 if (result.isInvalid()) return ExprError(); 3829 Fn = result.take(); 3830 } 3831 3832 Expr *NakedFn = Fn->IgnoreParens(); 3833 3834 NamedDecl *NDecl = 0; 3835 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 3836 if (UnOp->getOpcode() == UO_AddrOf) 3837 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 3838 3839 if (isa<DeclRefExpr>(NakedFn)) 3840 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 3841 else if (isa<MemberExpr>(NakedFn)) 3842 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 3843 3844 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc, 3845 ExecConfig, IsExecConfig); 3846 } 3847 3848 ExprResult 3849 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 3850 MultiExprArg ExecConfig, SourceLocation GGGLoc) { 3851 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 3852 if (!ConfigDecl) 3853 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 3854 << "cudaConfigureCall"); 3855 QualType ConfigQTy = ConfigDecl->getType(); 3856 3857 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 3858 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc); 3859 MarkFunctionReferenced(LLLLoc, ConfigDecl); 3860 3861 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0, 3862 /*IsExecConfig=*/true); 3863 } 3864 3865 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 3866 /// 3867 /// __builtin_astype( value, dst type ) 3868 /// 3869 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 3870 SourceLocation BuiltinLoc, 3871 SourceLocation RParenLoc) { 3872 ExprValueKind VK = VK_RValue; 3873 ExprObjectKind OK = OK_Ordinary; 3874 QualType DstTy = GetTypeFromParser(ParsedDestTy); 3875 QualType SrcTy = E->getType(); 3876 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 3877 return ExprError(Diag(BuiltinLoc, 3878 diag::err_invalid_astype_of_different_size) 3879 << DstTy 3880 << SrcTy 3881 << E->getSourceRange()); 3882 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, 3883 RParenLoc)); 3884 } 3885 3886 /// BuildResolvedCallExpr - Build a call to a resolved expression, 3887 /// i.e. an expression not of \p OverloadTy. The expression should 3888 /// unary-convert to an expression of function-pointer or 3889 /// block-pointer type. 3890 /// 3891 /// \param NDecl the declaration being called, if available 3892 ExprResult 3893 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 3894 SourceLocation LParenLoc, 3895 Expr **Args, unsigned NumArgs, 3896 SourceLocation RParenLoc, 3897 Expr *Config, bool IsExecConfig) { 3898 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 3899 3900 // Promote the function operand. 3901 ExprResult Result = UsualUnaryConversions(Fn); 3902 if (Result.isInvalid()) 3903 return ExprError(); 3904 Fn = Result.take(); 3905 3906 // Make the call expr early, before semantic checks. This guarantees cleanup 3907 // of arguments and function on error. 3908 CallExpr *TheCall; 3909 if (Config) 3910 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 3911 cast<CallExpr>(Config), 3912 Args, NumArgs, 3913 Context.BoolTy, 3914 VK_RValue, 3915 RParenLoc); 3916 else 3917 TheCall = new (Context) CallExpr(Context, Fn, 3918 Args, NumArgs, 3919 Context.BoolTy, 3920 VK_RValue, 3921 RParenLoc); 3922 3923 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 3924 3925 // Bail out early if calling a builtin with custom typechecking. 3926 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 3927 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 3928 3929 retry: 3930 const FunctionType *FuncT; 3931 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 3932 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 3933 // have type pointer to function". 3934 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 3935 if (FuncT == 0) 3936 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 3937 << Fn->getType() << Fn->getSourceRange()); 3938 } else if (const BlockPointerType *BPT = 3939 Fn->getType()->getAs<BlockPointerType>()) { 3940 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 3941 } else { 3942 // Handle calls to expressions of unknown-any type. 3943 if (Fn->getType() == Context.UnknownAnyTy) { 3944 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 3945 if (rewrite.isInvalid()) return ExprError(); 3946 Fn = rewrite.take(); 3947 TheCall->setCallee(Fn); 3948 goto retry; 3949 } 3950 3951 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 3952 << Fn->getType() << Fn->getSourceRange()); 3953 } 3954 3955 if (getLangOpts().CUDA) { 3956 if (Config) { 3957 // CUDA: Kernel calls must be to global functions 3958 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 3959 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 3960 << FDecl->getName() << Fn->getSourceRange()); 3961 3962 // CUDA: Kernel function must have 'void' return type 3963 if (!FuncT->getResultType()->isVoidType()) 3964 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 3965 << Fn->getType() << Fn->getSourceRange()); 3966 } else { 3967 // CUDA: Calls to global functions must be configured 3968 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 3969 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 3970 << FDecl->getName() << Fn->getSourceRange()); 3971 } 3972 } 3973 3974 // Check for a valid return type 3975 if (CheckCallReturnType(FuncT->getResultType(), 3976 Fn->getLocStart(), TheCall, 3977 FDecl)) 3978 return ExprError(); 3979 3980 // We know the result type of the call, set it. 3981 TheCall->setType(FuncT->getCallResultType(Context)); 3982 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType())); 3983 3984 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 3985 if (Proto) { 3986 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs, 3987 RParenLoc, IsExecConfig)) 3988 return ExprError(); 3989 } else { 3990 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 3991 3992 if (FDecl) { 3993 // Check if we have too few/too many template arguments, based 3994 // on our knowledge of the function definition. 3995 const FunctionDecl *Def = 0; 3996 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) { 3997 Proto = Def->getType()->getAs<FunctionProtoType>(); 3998 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) 3999 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 4000 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange(); 4001 } 4002 4003 // If the function we're calling isn't a function prototype, but we have 4004 // a function prototype from a prior declaratiom, use that prototype. 4005 if (!FDecl->hasPrototype()) 4006 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 4007 } 4008 4009 // Promote the arguments (C99 6.5.2.2p6). 4010 for (unsigned i = 0; i != NumArgs; i++) { 4011 Expr *Arg = Args[i]; 4012 4013 if (Proto && i < Proto->getNumArgs()) { 4014 InitializedEntity Entity 4015 = InitializedEntity::InitializeParameter(Context, 4016 Proto->getArgType(i), 4017 Proto->isArgConsumed(i)); 4018 ExprResult ArgE = PerformCopyInitialization(Entity, 4019 SourceLocation(), 4020 Owned(Arg)); 4021 if (ArgE.isInvalid()) 4022 return true; 4023 4024 Arg = ArgE.takeAs<Expr>(); 4025 4026 } else { 4027 ExprResult ArgE = DefaultArgumentPromotion(Arg); 4028 4029 if (ArgE.isInvalid()) 4030 return true; 4031 4032 Arg = ArgE.takeAs<Expr>(); 4033 } 4034 4035 if (RequireCompleteType(Arg->getLocStart(), 4036 Arg->getType(), 4037 diag::err_call_incomplete_argument, Arg)) 4038 return ExprError(); 4039 4040 TheCall->setArg(i, Arg); 4041 } 4042 } 4043 4044 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4045 if (!Method->isStatic()) 4046 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 4047 << Fn->getSourceRange()); 4048 4049 // Check for sentinels 4050 if (NDecl) 4051 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs); 4052 4053 // Do special checking on direct calls to functions. 4054 if (FDecl) { 4055 if (CheckFunctionCall(FDecl, TheCall, Proto)) 4056 return ExprError(); 4057 4058 if (BuiltinID) 4059 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4060 } else if (NDecl) { 4061 if (CheckBlockCall(NDecl, TheCall, Proto)) 4062 return ExprError(); 4063 } 4064 4065 return MaybeBindToTemporary(TheCall); 4066 } 4067 4068 ExprResult 4069 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 4070 SourceLocation RParenLoc, Expr *InitExpr) { 4071 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 4072 // FIXME: put back this assert when initializers are worked out. 4073 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 4074 4075 TypeSourceInfo *TInfo; 4076 QualType literalType = GetTypeFromParser(Ty, &TInfo); 4077 if (!TInfo) 4078 TInfo = Context.getTrivialTypeSourceInfo(literalType); 4079 4080 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 4081 } 4082 4083 ExprResult 4084 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 4085 SourceLocation RParenLoc, Expr *LiteralExpr) { 4086 QualType literalType = TInfo->getType(); 4087 4088 if (literalType->isArrayType()) { 4089 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 4090 diag::err_illegal_decl_array_incomplete_type, 4091 SourceRange(LParenLoc, 4092 LiteralExpr->getSourceRange().getEnd()))) 4093 return ExprError(); 4094 if (literalType->isVariableArrayType()) 4095 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 4096 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 4097 } else if (!literalType->isDependentType() && 4098 RequireCompleteType(LParenLoc, literalType, 4099 diag::err_typecheck_decl_incomplete_type, 4100 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 4101 return ExprError(); 4102 4103 InitializedEntity Entity 4104 = InitializedEntity::InitializeTemporary(literalType); 4105 InitializationKind Kind 4106 = InitializationKind::CreateCStyleCast(LParenLoc, 4107 SourceRange(LParenLoc, RParenLoc), 4108 /*InitList=*/true); 4109 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1); 4110 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 4111 MultiExprArg(*this, &LiteralExpr, 1), 4112 &literalType); 4113 if (Result.isInvalid()) 4114 return ExprError(); 4115 LiteralExpr = Result.get(); 4116 4117 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 4118 if (isFileScope) { // 6.5.2.5p3 4119 if (CheckForConstantInitializer(LiteralExpr, literalType)) 4120 return ExprError(); 4121 } 4122 4123 // In C, compound literals are l-values for some reason. 4124 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 4125 4126 return MaybeBindToTemporary( 4127 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 4128 VK, LiteralExpr, isFileScope)); 4129 } 4130 4131 ExprResult 4132 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 4133 SourceLocation RBraceLoc) { 4134 unsigned NumInit = InitArgList.size(); 4135 Expr **InitList = InitArgList.release(); 4136 4137 // Immediately handle non-overload placeholders. Overloads can be 4138 // resolved contextually, but everything else here can't. 4139 for (unsigned I = 0; I != NumInit; ++I) { 4140 if (InitList[I]->getType()->isNonOverloadPlaceholderType()) { 4141 ExprResult result = CheckPlaceholderExpr(InitList[I]); 4142 4143 // Ignore failures; dropping the entire initializer list because 4144 // of one failure would be terrible for indexing/etc. 4145 if (result.isInvalid()) continue; 4146 4147 InitList[I] = result.take(); 4148 } 4149 } 4150 4151 // Semantic analysis for initializers is done by ActOnDeclarator() and 4152 // CheckInitializer() - it requires knowledge of the object being intialized. 4153 4154 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList, 4155 NumInit, RBraceLoc); 4156 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 4157 return Owned(E); 4158 } 4159 4160 /// Do an explicit extend of the given block pointer if we're in ARC. 4161 static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 4162 assert(E.get()->getType()->isBlockPointerType()); 4163 assert(E.get()->isRValue()); 4164 4165 // Only do this in an r-value context. 4166 if (!S.getLangOpts().ObjCAutoRefCount) return; 4167 4168 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 4169 CK_ARCExtendBlockObject, E.get(), 4170 /*base path*/ 0, VK_RValue); 4171 S.ExprNeedsCleanups = true; 4172 } 4173 4174 /// Prepare a conversion of the given expression to an ObjC object 4175 /// pointer type. 4176 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 4177 QualType type = E.get()->getType(); 4178 if (type->isObjCObjectPointerType()) { 4179 return CK_BitCast; 4180 } else if (type->isBlockPointerType()) { 4181 maybeExtendBlockObject(*this, E); 4182 return CK_BlockPointerToObjCPointerCast; 4183 } else { 4184 assert(type->isPointerType()); 4185 return CK_CPointerToObjCPointerCast; 4186 } 4187 } 4188 4189 /// Prepares for a scalar cast, performing all the necessary stages 4190 /// except the final cast and returning the kind required. 4191 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 4192 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 4193 // Also, callers should have filtered out the invalid cases with 4194 // pointers. Everything else should be possible. 4195 4196 QualType SrcTy = Src.get()->getType(); 4197 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 4198 return CK_NoOp; 4199 4200 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 4201 case Type::STK_MemberPointer: 4202 llvm_unreachable("member pointer type in C"); 4203 4204 case Type::STK_CPointer: 4205 case Type::STK_BlockPointer: 4206 case Type::STK_ObjCObjectPointer: 4207 switch (DestTy->getScalarTypeKind()) { 4208 case Type::STK_CPointer: 4209 return CK_BitCast; 4210 case Type::STK_BlockPointer: 4211 return (SrcKind == Type::STK_BlockPointer 4212 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 4213 case Type::STK_ObjCObjectPointer: 4214 if (SrcKind == Type::STK_ObjCObjectPointer) 4215 return CK_BitCast; 4216 if (SrcKind == Type::STK_CPointer) 4217 return CK_CPointerToObjCPointerCast; 4218 maybeExtendBlockObject(*this, Src); 4219 return CK_BlockPointerToObjCPointerCast; 4220 case Type::STK_Bool: 4221 return CK_PointerToBoolean; 4222 case Type::STK_Integral: 4223 return CK_PointerToIntegral; 4224 case Type::STK_Floating: 4225 case Type::STK_FloatingComplex: 4226 case Type::STK_IntegralComplex: 4227 case Type::STK_MemberPointer: 4228 llvm_unreachable("illegal cast from pointer"); 4229 } 4230 llvm_unreachable("Should have returned before this"); 4231 4232 case Type::STK_Bool: // casting from bool is like casting from an integer 4233 case Type::STK_Integral: 4234 switch (DestTy->getScalarTypeKind()) { 4235 case Type::STK_CPointer: 4236 case Type::STK_ObjCObjectPointer: 4237 case Type::STK_BlockPointer: 4238 if (Src.get()->isNullPointerConstant(Context, 4239 Expr::NPC_ValueDependentIsNull)) 4240 return CK_NullToPointer; 4241 return CK_IntegralToPointer; 4242 case Type::STK_Bool: 4243 return CK_IntegralToBoolean; 4244 case Type::STK_Integral: 4245 return CK_IntegralCast; 4246 case Type::STK_Floating: 4247 return CK_IntegralToFloating; 4248 case Type::STK_IntegralComplex: 4249 Src = ImpCastExprToType(Src.take(), 4250 DestTy->castAs<ComplexType>()->getElementType(), 4251 CK_IntegralCast); 4252 return CK_IntegralRealToComplex; 4253 case Type::STK_FloatingComplex: 4254 Src = ImpCastExprToType(Src.take(), 4255 DestTy->castAs<ComplexType>()->getElementType(), 4256 CK_IntegralToFloating); 4257 return CK_FloatingRealToComplex; 4258 case Type::STK_MemberPointer: 4259 llvm_unreachable("member pointer type in C"); 4260 } 4261 llvm_unreachable("Should have returned before this"); 4262 4263 case Type::STK_Floating: 4264 switch (DestTy->getScalarTypeKind()) { 4265 case Type::STK_Floating: 4266 return CK_FloatingCast; 4267 case Type::STK_Bool: 4268 return CK_FloatingToBoolean; 4269 case Type::STK_Integral: 4270 return CK_FloatingToIntegral; 4271 case Type::STK_FloatingComplex: 4272 Src = ImpCastExprToType(Src.take(), 4273 DestTy->castAs<ComplexType>()->getElementType(), 4274 CK_FloatingCast); 4275 return CK_FloatingRealToComplex; 4276 case Type::STK_IntegralComplex: 4277 Src = ImpCastExprToType(Src.take(), 4278 DestTy->castAs<ComplexType>()->getElementType(), 4279 CK_FloatingToIntegral); 4280 return CK_IntegralRealToComplex; 4281 case Type::STK_CPointer: 4282 case Type::STK_ObjCObjectPointer: 4283 case Type::STK_BlockPointer: 4284 llvm_unreachable("valid float->pointer cast?"); 4285 case Type::STK_MemberPointer: 4286 llvm_unreachable("member pointer type in C"); 4287 } 4288 llvm_unreachable("Should have returned before this"); 4289 4290 case Type::STK_FloatingComplex: 4291 switch (DestTy->getScalarTypeKind()) { 4292 case Type::STK_FloatingComplex: 4293 return CK_FloatingComplexCast; 4294 case Type::STK_IntegralComplex: 4295 return CK_FloatingComplexToIntegralComplex; 4296 case Type::STK_Floating: { 4297 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4298 if (Context.hasSameType(ET, DestTy)) 4299 return CK_FloatingComplexToReal; 4300 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal); 4301 return CK_FloatingCast; 4302 } 4303 case Type::STK_Bool: 4304 return CK_FloatingComplexToBoolean; 4305 case Type::STK_Integral: 4306 Src = ImpCastExprToType(Src.take(), 4307 SrcTy->castAs<ComplexType>()->getElementType(), 4308 CK_FloatingComplexToReal); 4309 return CK_FloatingToIntegral; 4310 case Type::STK_CPointer: 4311 case Type::STK_ObjCObjectPointer: 4312 case Type::STK_BlockPointer: 4313 llvm_unreachable("valid complex float->pointer cast?"); 4314 case Type::STK_MemberPointer: 4315 llvm_unreachable("member pointer type in C"); 4316 } 4317 llvm_unreachable("Should have returned before this"); 4318 4319 case Type::STK_IntegralComplex: 4320 switch (DestTy->getScalarTypeKind()) { 4321 case Type::STK_FloatingComplex: 4322 return CK_IntegralComplexToFloatingComplex; 4323 case Type::STK_IntegralComplex: 4324 return CK_IntegralComplexCast; 4325 case Type::STK_Integral: { 4326 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4327 if (Context.hasSameType(ET, DestTy)) 4328 return CK_IntegralComplexToReal; 4329 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal); 4330 return CK_IntegralCast; 4331 } 4332 case Type::STK_Bool: 4333 return CK_IntegralComplexToBoolean; 4334 case Type::STK_Floating: 4335 Src = ImpCastExprToType(Src.take(), 4336 SrcTy->castAs<ComplexType>()->getElementType(), 4337 CK_IntegralComplexToReal); 4338 return CK_IntegralToFloating; 4339 case Type::STK_CPointer: 4340 case Type::STK_ObjCObjectPointer: 4341 case Type::STK_BlockPointer: 4342 llvm_unreachable("valid complex int->pointer cast?"); 4343 case Type::STK_MemberPointer: 4344 llvm_unreachable("member pointer type in C"); 4345 } 4346 llvm_unreachable("Should have returned before this"); 4347 } 4348 4349 llvm_unreachable("Unhandled scalar cast"); 4350 } 4351 4352 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 4353 CastKind &Kind) { 4354 assert(VectorTy->isVectorType() && "Not a vector type!"); 4355 4356 if (Ty->isVectorType() || Ty->isIntegerType()) { 4357 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 4358 return Diag(R.getBegin(), 4359 Ty->isVectorType() ? 4360 diag::err_invalid_conversion_between_vectors : 4361 diag::err_invalid_conversion_between_vector_and_integer) 4362 << VectorTy << Ty << R; 4363 } else 4364 return Diag(R.getBegin(), 4365 diag::err_invalid_conversion_between_vector_and_scalar) 4366 << VectorTy << Ty << R; 4367 4368 Kind = CK_BitCast; 4369 return false; 4370 } 4371 4372 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 4373 Expr *CastExpr, CastKind &Kind) { 4374 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 4375 4376 QualType SrcTy = CastExpr->getType(); 4377 4378 // If SrcTy is a VectorType, the total size must match to explicitly cast to 4379 // an ExtVectorType. 4380 // In OpenCL, casts between vectors of different types are not allowed. 4381 // (See OpenCL 6.2). 4382 if (SrcTy->isVectorType()) { 4383 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy) 4384 || (getLangOpts().OpenCL && 4385 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 4386 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 4387 << DestTy << SrcTy << R; 4388 return ExprError(); 4389 } 4390 Kind = CK_BitCast; 4391 return Owned(CastExpr); 4392 } 4393 4394 // All non-pointer scalars can be cast to ExtVector type. The appropriate 4395 // conversion will take place first from scalar to elt type, and then 4396 // splat from elt type to vector. 4397 if (SrcTy->isPointerType()) 4398 return Diag(R.getBegin(), 4399 diag::err_invalid_conversion_between_vector_and_scalar) 4400 << DestTy << SrcTy << R; 4401 4402 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 4403 ExprResult CastExprRes = Owned(CastExpr); 4404 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 4405 if (CastExprRes.isInvalid()) 4406 return ExprError(); 4407 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take(); 4408 4409 Kind = CK_VectorSplat; 4410 return Owned(CastExpr); 4411 } 4412 4413 ExprResult 4414 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 4415 Declarator &D, ParsedType &Ty, 4416 SourceLocation RParenLoc, Expr *CastExpr) { 4417 assert(!D.isInvalidType() && (CastExpr != 0) && 4418 "ActOnCastExpr(): missing type or expr"); 4419 4420 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 4421 if (D.isInvalidType()) 4422 return ExprError(); 4423 4424 if (getLangOpts().CPlusPlus) { 4425 // Check that there are no default arguments (C++ only). 4426 CheckExtraCXXDefaultArguments(D); 4427 } 4428 4429 checkUnusedDeclAttributes(D); 4430 4431 QualType castType = castTInfo->getType(); 4432 Ty = CreateParsedType(castType, castTInfo); 4433 4434 bool isVectorLiteral = false; 4435 4436 // Check for an altivec or OpenCL literal, 4437 // i.e. all the elements are integer constants. 4438 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 4439 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 4440 if ((getLangOpts().AltiVec || getLangOpts().OpenCL) 4441 && castType->isVectorType() && (PE || PLE)) { 4442 if (PLE && PLE->getNumExprs() == 0) { 4443 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 4444 return ExprError(); 4445 } 4446 if (PE || PLE->getNumExprs() == 1) { 4447 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 4448 if (!E->getType()->isVectorType()) 4449 isVectorLiteral = true; 4450 } 4451 else 4452 isVectorLiteral = true; 4453 } 4454 4455 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 4456 // then handle it as such. 4457 if (isVectorLiteral) 4458 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 4459 4460 // If the Expr being casted is a ParenListExpr, handle it specially. 4461 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 4462 // sequence of BinOp comma operators. 4463 if (isa<ParenListExpr>(CastExpr)) { 4464 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 4465 if (Result.isInvalid()) return ExprError(); 4466 CastExpr = Result.take(); 4467 } 4468 4469 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 4470 } 4471 4472 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 4473 SourceLocation RParenLoc, Expr *E, 4474 TypeSourceInfo *TInfo) { 4475 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 4476 "Expected paren or paren list expression"); 4477 4478 Expr **exprs; 4479 unsigned numExprs; 4480 Expr *subExpr; 4481 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 4482 exprs = PE->getExprs(); 4483 numExprs = PE->getNumExprs(); 4484 } else { 4485 subExpr = cast<ParenExpr>(E)->getSubExpr(); 4486 exprs = &subExpr; 4487 numExprs = 1; 4488 } 4489 4490 QualType Ty = TInfo->getType(); 4491 assert(Ty->isVectorType() && "Expected vector type"); 4492 4493 SmallVector<Expr *, 8> initExprs; 4494 const VectorType *VTy = Ty->getAs<VectorType>(); 4495 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 4496 4497 // '(...)' form of vector initialization in AltiVec: the number of 4498 // initializers must be one or must match the size of the vector. 4499 // If a single value is specified in the initializer then it will be 4500 // replicated to all the components of the vector 4501 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 4502 // The number of initializers must be one or must match the size of the 4503 // vector. If a single value is specified in the initializer then it will 4504 // be replicated to all the components of the vector 4505 if (numExprs == 1) { 4506 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 4507 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 4508 if (Literal.isInvalid()) 4509 return ExprError(); 4510 Literal = ImpCastExprToType(Literal.take(), ElemTy, 4511 PrepareScalarCast(Literal, ElemTy)); 4512 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 4513 } 4514 else if (numExprs < numElems) { 4515 Diag(E->getExprLoc(), 4516 diag::err_incorrect_number_of_vector_initializers); 4517 return ExprError(); 4518 } 4519 else 4520 initExprs.append(exprs, exprs + numExprs); 4521 } 4522 else { 4523 // For OpenCL, when the number of initializers is a single value, 4524 // it will be replicated to all components of the vector. 4525 if (getLangOpts().OpenCL && 4526 VTy->getVectorKind() == VectorType::GenericVector && 4527 numExprs == 1) { 4528 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 4529 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 4530 if (Literal.isInvalid()) 4531 return ExprError(); 4532 Literal = ImpCastExprToType(Literal.take(), ElemTy, 4533 PrepareScalarCast(Literal, ElemTy)); 4534 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 4535 } 4536 4537 initExprs.append(exprs, exprs + numExprs); 4538 } 4539 // FIXME: This means that pretty-printing the final AST will produce curly 4540 // braces instead of the original commas. 4541 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc, 4542 &initExprs[0], 4543 initExprs.size(), RParenLoc); 4544 initE->setType(Ty); 4545 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 4546 } 4547 4548 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 4549 /// the ParenListExpr into a sequence of comma binary operators. 4550 ExprResult 4551 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 4552 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 4553 if (!E) 4554 return Owned(OrigExpr); 4555 4556 ExprResult Result(E->getExpr(0)); 4557 4558 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 4559 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 4560 E->getExpr(i)); 4561 4562 if (Result.isInvalid()) return ExprError(); 4563 4564 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 4565 } 4566 4567 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 4568 SourceLocation R, 4569 MultiExprArg Val) { 4570 unsigned nexprs = Val.size(); 4571 Expr **exprs = reinterpret_cast<Expr**>(Val.release()); 4572 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list"); 4573 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R); 4574 return Owned(expr); 4575 } 4576 4577 /// \brief Emit a specialized diagnostic when one expression is a null pointer 4578 /// constant and the other is not a pointer. Returns true if a diagnostic is 4579 /// emitted. 4580 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 4581 SourceLocation QuestionLoc) { 4582 Expr *NullExpr = LHSExpr; 4583 Expr *NonPointerExpr = RHSExpr; 4584 Expr::NullPointerConstantKind NullKind = 4585 NullExpr->isNullPointerConstant(Context, 4586 Expr::NPC_ValueDependentIsNotNull); 4587 4588 if (NullKind == Expr::NPCK_NotNull) { 4589 NullExpr = RHSExpr; 4590 NonPointerExpr = LHSExpr; 4591 NullKind = 4592 NullExpr->isNullPointerConstant(Context, 4593 Expr::NPC_ValueDependentIsNotNull); 4594 } 4595 4596 if (NullKind == Expr::NPCK_NotNull) 4597 return false; 4598 4599 if (NullKind == Expr::NPCK_ZeroInteger) { 4600 // In this case, check to make sure that we got here from a "NULL" 4601 // string in the source code. 4602 NullExpr = NullExpr->IgnoreParenImpCasts(); 4603 SourceLocation loc = NullExpr->getExprLoc(); 4604 if (!findMacroSpelling(loc, "NULL")) 4605 return false; 4606 } 4607 4608 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr); 4609 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 4610 << NonPointerExpr->getType() << DiagType 4611 << NonPointerExpr->getSourceRange(); 4612 return true; 4613 } 4614 4615 /// \brief Return false if the condition expression is valid, true otherwise. 4616 static bool checkCondition(Sema &S, Expr *Cond) { 4617 QualType CondTy = Cond->getType(); 4618 4619 // C99 6.5.15p2 4620 if (CondTy->isScalarType()) return false; 4621 4622 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar. 4623 if (S.getLangOpts().OpenCL && CondTy->isVectorType()) 4624 return false; 4625 4626 // Emit the proper error message. 4627 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ? 4628 diag::err_typecheck_cond_expect_scalar : 4629 diag::err_typecheck_cond_expect_scalar_or_vector) 4630 << CondTy; 4631 return true; 4632 } 4633 4634 /// \brief Return false if the two expressions can be converted to a vector, 4635 /// true otherwise 4636 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 4637 ExprResult &RHS, 4638 QualType CondTy) { 4639 // Both operands should be of scalar type. 4640 if (!LHS.get()->getType()->isScalarType()) { 4641 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 4642 << CondTy; 4643 return true; 4644 } 4645 if (!RHS.get()->getType()->isScalarType()) { 4646 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 4647 << CondTy; 4648 return true; 4649 } 4650 4651 // Implicity convert these scalars to the type of the condition. 4652 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast); 4653 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast); 4654 return false; 4655 } 4656 4657 /// \brief Handle when one or both operands are void type. 4658 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 4659 ExprResult &RHS) { 4660 Expr *LHSExpr = LHS.get(); 4661 Expr *RHSExpr = RHS.get(); 4662 4663 if (!LHSExpr->getType()->isVoidType()) 4664 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 4665 << RHSExpr->getSourceRange(); 4666 if (!RHSExpr->getType()->isVoidType()) 4667 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 4668 << LHSExpr->getSourceRange(); 4669 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid); 4670 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid); 4671 return S.Context.VoidTy; 4672 } 4673 4674 /// \brief Return false if the NullExpr can be promoted to PointerTy, 4675 /// true otherwise. 4676 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 4677 QualType PointerTy) { 4678 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 4679 !NullExpr.get()->isNullPointerConstant(S.Context, 4680 Expr::NPC_ValueDependentIsNull)) 4681 return true; 4682 4683 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer); 4684 return false; 4685 } 4686 4687 /// \brief Checks compatibility between two pointers and return the resulting 4688 /// type. 4689 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 4690 ExprResult &RHS, 4691 SourceLocation Loc) { 4692 QualType LHSTy = LHS.get()->getType(); 4693 QualType RHSTy = RHS.get()->getType(); 4694 4695 if (S.Context.hasSameType(LHSTy, RHSTy)) { 4696 // Two identical pointers types are always compatible. 4697 return LHSTy; 4698 } 4699 4700 QualType lhptee, rhptee; 4701 4702 // Get the pointee types. 4703 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 4704 lhptee = LHSBTy->getPointeeType(); 4705 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 4706 } else { 4707 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 4708 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 4709 } 4710 4711 // C99 6.5.15p6: If both operands are pointers to compatible types or to 4712 // differently qualified versions of compatible types, the result type is 4713 // a pointer to an appropriately qualified version of the composite 4714 // type. 4715 4716 // Only CVR-qualifiers exist in the standard, and the differently-qualified 4717 // clause doesn't make sense for our extensions. E.g. address space 2 should 4718 // be incompatible with address space 3: they may live on different devices or 4719 // anything. 4720 Qualifiers lhQual = lhptee.getQualifiers(); 4721 Qualifiers rhQual = rhptee.getQualifiers(); 4722 4723 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 4724 lhQual.removeCVRQualifiers(); 4725 rhQual.removeCVRQualifiers(); 4726 4727 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 4728 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 4729 4730 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 4731 4732 if (CompositeTy.isNull()) { 4733 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers) 4734 << LHSTy << RHSTy << LHS.get()->getSourceRange() 4735 << RHS.get()->getSourceRange(); 4736 // In this situation, we assume void* type. No especially good 4737 // reason, but this is what gcc does, and we do have to pick 4738 // to get a consistent AST. 4739 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 4740 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 4741 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 4742 return incompatTy; 4743 } 4744 4745 // The pointer types are compatible. 4746 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 4747 ResultTy = S.Context.getPointerType(ResultTy); 4748 4749 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast); 4750 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast); 4751 return ResultTy; 4752 } 4753 4754 /// \brief Return the resulting type when the operands are both block pointers. 4755 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 4756 ExprResult &LHS, 4757 ExprResult &RHS, 4758 SourceLocation Loc) { 4759 QualType LHSTy = LHS.get()->getType(); 4760 QualType RHSTy = RHS.get()->getType(); 4761 4762 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 4763 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 4764 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 4765 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 4766 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 4767 return destType; 4768 } 4769 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 4770 << LHSTy << RHSTy << LHS.get()->getSourceRange() 4771 << RHS.get()->getSourceRange(); 4772 return QualType(); 4773 } 4774 4775 // We have 2 block pointer types. 4776 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 4777 } 4778 4779 /// \brief Return the resulting type when the operands are both pointers. 4780 static QualType 4781 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 4782 ExprResult &RHS, 4783 SourceLocation Loc) { 4784 // get the pointer types 4785 QualType LHSTy = LHS.get()->getType(); 4786 QualType RHSTy = RHS.get()->getType(); 4787 4788 // get the "pointed to" types 4789 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 4790 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 4791 4792 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 4793 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 4794 // Figure out necessary qualifiers (C99 6.5.15p6) 4795 QualType destPointee 4796 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 4797 QualType destType = S.Context.getPointerType(destPointee); 4798 // Add qualifiers if necessary. 4799 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp); 4800 // Promote to void*. 4801 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 4802 return destType; 4803 } 4804 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 4805 QualType destPointee 4806 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 4807 QualType destType = S.Context.getPointerType(destPointee); 4808 // Add qualifiers if necessary. 4809 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp); 4810 // Promote to void*. 4811 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 4812 return destType; 4813 } 4814 4815 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 4816 } 4817 4818 /// \brief Return false if the first expression is not an integer and the second 4819 /// expression is not a pointer, true otherwise. 4820 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 4821 Expr* PointerExpr, SourceLocation Loc, 4822 bool IsIntFirstExpr) { 4823 if (!PointerExpr->getType()->isPointerType() || 4824 !Int.get()->getType()->isIntegerType()) 4825 return false; 4826 4827 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 4828 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 4829 4830 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch) 4831 << Expr1->getType() << Expr2->getType() 4832 << Expr1->getSourceRange() << Expr2->getSourceRange(); 4833 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(), 4834 CK_IntegralToPointer); 4835 return true; 4836 } 4837 4838 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 4839 /// In that case, LHS = cond. 4840 /// C99 6.5.15 4841 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 4842 ExprResult &RHS, ExprValueKind &VK, 4843 ExprObjectKind &OK, 4844 SourceLocation QuestionLoc) { 4845 4846 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 4847 if (!LHSResult.isUsable()) return QualType(); 4848 LHS = move(LHSResult); 4849 4850 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 4851 if (!RHSResult.isUsable()) return QualType(); 4852 RHS = move(RHSResult); 4853 4854 // C++ is sufficiently different to merit its own checker. 4855 if (getLangOpts().CPlusPlus) 4856 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 4857 4858 VK = VK_RValue; 4859 OK = OK_Ordinary; 4860 4861 Cond = UsualUnaryConversions(Cond.take()); 4862 if (Cond.isInvalid()) 4863 return QualType(); 4864 LHS = UsualUnaryConversions(LHS.take()); 4865 if (LHS.isInvalid()) 4866 return QualType(); 4867 RHS = UsualUnaryConversions(RHS.take()); 4868 if (RHS.isInvalid()) 4869 return QualType(); 4870 4871 QualType CondTy = Cond.get()->getType(); 4872 QualType LHSTy = LHS.get()->getType(); 4873 QualType RHSTy = RHS.get()->getType(); 4874 4875 // first, check the condition. 4876 if (checkCondition(*this, Cond.get())) 4877 return QualType(); 4878 4879 // Now check the two expressions. 4880 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 4881 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 4882 4883 // OpenCL: If the condition is a vector, and both operands are scalar, 4884 // attempt to implicity convert them to the vector type to act like the 4885 // built in select. 4886 if (getLangOpts().OpenCL && CondTy->isVectorType()) 4887 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy)) 4888 return QualType(); 4889 4890 // If both operands have arithmetic type, do the usual arithmetic conversions 4891 // to find a common type: C99 6.5.15p3,5. 4892 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 4893 UsualArithmeticConversions(LHS, RHS); 4894 if (LHS.isInvalid() || RHS.isInvalid()) 4895 return QualType(); 4896 return LHS.get()->getType(); 4897 } 4898 4899 // If both operands are the same structure or union type, the result is that 4900 // type. 4901 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 4902 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 4903 if (LHSRT->getDecl() == RHSRT->getDecl()) 4904 // "If both the operands have structure or union type, the result has 4905 // that type." This implies that CV qualifiers are dropped. 4906 return LHSTy.getUnqualifiedType(); 4907 // FIXME: Type of conditional expression must be complete in C mode. 4908 } 4909 4910 // C99 6.5.15p5: "If both operands have void type, the result has void type." 4911 // The following || allows only one side to be void (a GCC-ism). 4912 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 4913 return checkConditionalVoidType(*this, LHS, RHS); 4914 } 4915 4916 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 4917 // the type of the other operand." 4918 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 4919 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 4920 4921 // All objective-c pointer type analysis is done here. 4922 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 4923 QuestionLoc); 4924 if (LHS.isInvalid() || RHS.isInvalid()) 4925 return QualType(); 4926 if (!compositeType.isNull()) 4927 return compositeType; 4928 4929 4930 // Handle block pointer types. 4931 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 4932 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 4933 QuestionLoc); 4934 4935 // Check constraints for C object pointers types (C99 6.5.15p3,6). 4936 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 4937 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 4938 QuestionLoc); 4939 4940 // GCC compatibility: soften pointer/integer mismatch. Note that 4941 // null pointers have been filtered out by this point. 4942 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 4943 /*isIntFirstExpr=*/true)) 4944 return RHSTy; 4945 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 4946 /*isIntFirstExpr=*/false)) 4947 return LHSTy; 4948 4949 // Emit a better diagnostic if one of the expressions is a null pointer 4950 // constant and the other is not a pointer type. In this case, the user most 4951 // likely forgot to take the address of the other expression. 4952 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 4953 return QualType(); 4954 4955 // Otherwise, the operands are not compatible. 4956 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 4957 << LHSTy << RHSTy << LHS.get()->getSourceRange() 4958 << RHS.get()->getSourceRange(); 4959 return QualType(); 4960 } 4961 4962 /// FindCompositeObjCPointerType - Helper method to find composite type of 4963 /// two objective-c pointer types of the two input expressions. 4964 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 4965 SourceLocation QuestionLoc) { 4966 QualType LHSTy = LHS.get()->getType(); 4967 QualType RHSTy = RHS.get()->getType(); 4968 4969 // Handle things like Class and struct objc_class*. Here we case the result 4970 // to the pseudo-builtin, because that will be implicitly cast back to the 4971 // redefinition type if an attempt is made to access its fields. 4972 if (LHSTy->isObjCClassType() && 4973 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 4974 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 4975 return LHSTy; 4976 } 4977 if (RHSTy->isObjCClassType() && 4978 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 4979 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 4980 return RHSTy; 4981 } 4982 // And the same for struct objc_object* / id 4983 if (LHSTy->isObjCIdType() && 4984 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 4985 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 4986 return LHSTy; 4987 } 4988 if (RHSTy->isObjCIdType() && 4989 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 4990 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 4991 return RHSTy; 4992 } 4993 // And the same for struct objc_selector* / SEL 4994 if (Context.isObjCSelType(LHSTy) && 4995 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 4996 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 4997 return LHSTy; 4998 } 4999 if (Context.isObjCSelType(RHSTy) && 5000 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 5001 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast); 5002 return RHSTy; 5003 } 5004 // Check constraints for Objective-C object pointers types. 5005 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 5006 5007 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 5008 // Two identical object pointer types are always compatible. 5009 return LHSTy; 5010 } 5011 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 5012 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 5013 QualType compositeType = LHSTy; 5014 5015 // If both operands are interfaces and either operand can be 5016 // assigned to the other, use that type as the composite 5017 // type. This allows 5018 // xxx ? (A*) a : (B*) b 5019 // where B is a subclass of A. 5020 // 5021 // Additionally, as for assignment, if either type is 'id' 5022 // allow silent coercion. Finally, if the types are 5023 // incompatible then make sure to use 'id' as the composite 5024 // type so the result is acceptable for sending messages to. 5025 5026 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 5027 // It could return the composite type. 5028 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 5029 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 5030 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 5031 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 5032 } else if ((LHSTy->isObjCQualifiedIdType() || 5033 RHSTy->isObjCQualifiedIdType()) && 5034 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 5035 // Need to handle "id<xx>" explicitly. 5036 // GCC allows qualified id and any Objective-C type to devolve to 5037 // id. Currently localizing to here until clear this should be 5038 // part of ObjCQualifiedIdTypesAreCompatible. 5039 compositeType = Context.getObjCIdType(); 5040 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 5041 compositeType = Context.getObjCIdType(); 5042 } else if (!(compositeType = 5043 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 5044 ; 5045 else { 5046 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 5047 << LHSTy << RHSTy 5048 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5049 QualType incompatTy = Context.getObjCIdType(); 5050 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5051 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5052 return incompatTy; 5053 } 5054 // The object pointer types are compatible. 5055 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast); 5056 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast); 5057 return compositeType; 5058 } 5059 // Check Objective-C object pointer types and 'void *' 5060 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 5061 if (getLangOpts().ObjCAutoRefCount) { 5062 // ARC forbids the implicit conversion of object pointers to 'void *', 5063 // so these types are not compatible. 5064 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5065 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5066 LHS = RHS = true; 5067 return QualType(); 5068 } 5069 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5070 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5071 QualType destPointee 5072 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5073 QualType destType = Context.getPointerType(destPointee); 5074 // Add qualifiers if necessary. 5075 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5076 // Promote to void*. 5077 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5078 return destType; 5079 } 5080 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 5081 if (getLangOpts().ObjCAutoRefCount) { 5082 // ARC forbids the implicit conversion of object pointers to 'void *', 5083 // so these types are not compatible. 5084 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5085 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5086 LHS = RHS = true; 5087 return QualType(); 5088 } 5089 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5090 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5091 QualType destPointee 5092 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5093 QualType destType = Context.getPointerType(destPointee); 5094 // Add qualifiers if necessary. 5095 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5096 // Promote to void*. 5097 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5098 return destType; 5099 } 5100 return QualType(); 5101 } 5102 5103 /// SuggestParentheses - Emit a note with a fixit hint that wraps 5104 /// ParenRange in parentheses. 5105 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 5106 const PartialDiagnostic &Note, 5107 SourceRange ParenRange) { 5108 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 5109 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 5110 EndLoc.isValid()) { 5111 Self.Diag(Loc, Note) 5112 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 5113 << FixItHint::CreateInsertion(EndLoc, ")"); 5114 } else { 5115 // We can't display the parentheses, so just show the bare note. 5116 Self.Diag(Loc, Note) << ParenRange; 5117 } 5118 } 5119 5120 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 5121 return Opc >= BO_Mul && Opc <= BO_Shr; 5122 } 5123 5124 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 5125 /// expression, either using a built-in or overloaded operator, 5126 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 5127 /// expression. 5128 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 5129 Expr **RHSExprs) { 5130 // Don't strip parenthesis: we should not warn if E is in parenthesis. 5131 E = E->IgnoreImpCasts(); 5132 E = E->IgnoreConversionOperator(); 5133 E = E->IgnoreImpCasts(); 5134 5135 // Built-in binary operator. 5136 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 5137 if (IsArithmeticOp(OP->getOpcode())) { 5138 *Opcode = OP->getOpcode(); 5139 *RHSExprs = OP->getRHS(); 5140 return true; 5141 } 5142 } 5143 5144 // Overloaded operator. 5145 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 5146 if (Call->getNumArgs() != 2) 5147 return false; 5148 5149 // Make sure this is really a binary operator that is safe to pass into 5150 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 5151 OverloadedOperatorKind OO = Call->getOperator(); 5152 if (OO < OO_Plus || OO > OO_Arrow) 5153 return false; 5154 5155 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 5156 if (IsArithmeticOp(OpKind)) { 5157 *Opcode = OpKind; 5158 *RHSExprs = Call->getArg(1); 5159 return true; 5160 } 5161 } 5162 5163 return false; 5164 } 5165 5166 static bool IsLogicOp(BinaryOperatorKind Opc) { 5167 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 5168 } 5169 5170 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 5171 /// or is a logical expression such as (x==y) which has int type, but is 5172 /// commonly interpreted as boolean. 5173 static bool ExprLooksBoolean(Expr *E) { 5174 E = E->IgnoreParenImpCasts(); 5175 5176 if (E->getType()->isBooleanType()) 5177 return true; 5178 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 5179 return IsLogicOp(OP->getOpcode()); 5180 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 5181 return OP->getOpcode() == UO_LNot; 5182 5183 return false; 5184 } 5185 5186 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 5187 /// and binary operator are mixed in a way that suggests the programmer assumed 5188 /// the conditional operator has higher precedence, for example: 5189 /// "int x = a + someBinaryCondition ? 1 : 2". 5190 static void DiagnoseConditionalPrecedence(Sema &Self, 5191 SourceLocation OpLoc, 5192 Expr *Condition, 5193 Expr *LHSExpr, 5194 Expr *RHSExpr) { 5195 BinaryOperatorKind CondOpcode; 5196 Expr *CondRHS; 5197 5198 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 5199 return; 5200 if (!ExprLooksBoolean(CondRHS)) 5201 return; 5202 5203 // The condition is an arithmetic binary expression, with a right- 5204 // hand side that looks boolean, so warn. 5205 5206 Self.Diag(OpLoc, diag::warn_precedence_conditional) 5207 << Condition->getSourceRange() 5208 << BinaryOperator::getOpcodeStr(CondOpcode); 5209 5210 SuggestParentheses(Self, OpLoc, 5211 Self.PDiag(diag::note_precedence_conditional_silence) 5212 << BinaryOperator::getOpcodeStr(CondOpcode), 5213 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 5214 5215 SuggestParentheses(Self, OpLoc, 5216 Self.PDiag(diag::note_precedence_conditional_first), 5217 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 5218 } 5219 5220 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5221 /// in the case of a the GNU conditional expr extension. 5222 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 5223 SourceLocation ColonLoc, 5224 Expr *CondExpr, Expr *LHSExpr, 5225 Expr *RHSExpr) { 5226 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 5227 // was the condition. 5228 OpaqueValueExpr *opaqueValue = 0; 5229 Expr *commonExpr = 0; 5230 if (LHSExpr == 0) { 5231 commonExpr = CondExpr; 5232 5233 // We usually want to apply unary conversions *before* saving, except 5234 // in the special case of a C++ l-value conditional. 5235 if (!(getLangOpts().CPlusPlus 5236 && !commonExpr->isTypeDependent() 5237 && commonExpr->getValueKind() == RHSExpr->getValueKind() 5238 && commonExpr->isGLValue() 5239 && commonExpr->isOrdinaryOrBitFieldObject() 5240 && RHSExpr->isOrdinaryOrBitFieldObject() 5241 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 5242 ExprResult commonRes = UsualUnaryConversions(commonExpr); 5243 if (commonRes.isInvalid()) 5244 return ExprError(); 5245 commonExpr = commonRes.take(); 5246 } 5247 5248 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 5249 commonExpr->getType(), 5250 commonExpr->getValueKind(), 5251 commonExpr->getObjectKind(), 5252 commonExpr); 5253 LHSExpr = CondExpr = opaqueValue; 5254 } 5255 5256 ExprValueKind VK = VK_RValue; 5257 ExprObjectKind OK = OK_Ordinary; 5258 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 5259 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 5260 VK, OK, QuestionLoc); 5261 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 5262 RHS.isInvalid()) 5263 return ExprError(); 5264 5265 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 5266 RHS.get()); 5267 5268 if (!commonExpr) 5269 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc, 5270 LHS.take(), ColonLoc, 5271 RHS.take(), result, VK, OK)); 5272 5273 return Owned(new (Context) 5274 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(), 5275 RHS.take(), QuestionLoc, ColonLoc, result, VK, 5276 OK)); 5277 } 5278 5279 // checkPointerTypesForAssignment - This is a very tricky routine (despite 5280 // being closely modeled after the C99 spec:-). The odd characteristic of this 5281 // routine is it effectively iqnores the qualifiers on the top level pointee. 5282 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 5283 // FIXME: add a couple examples in this comment. 5284 static Sema::AssignConvertType 5285 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 5286 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5287 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5288 5289 // get the "pointed to" type (ignoring qualifiers at the top level) 5290 const Type *lhptee, *rhptee; 5291 Qualifiers lhq, rhq; 5292 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split(); 5293 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split(); 5294 5295 Sema::AssignConvertType ConvTy = Sema::Compatible; 5296 5297 // C99 6.5.16.1p1: This following citation is common to constraints 5298 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 5299 // qualifiers of the type *pointed to* by the right; 5300 Qualifiers lq; 5301 5302 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 5303 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 5304 lhq.compatiblyIncludesObjCLifetime(rhq)) { 5305 // Ignore lifetime for further calculation. 5306 lhq.removeObjCLifetime(); 5307 rhq.removeObjCLifetime(); 5308 } 5309 5310 if (!lhq.compatiblyIncludes(rhq)) { 5311 // Treat address-space mismatches as fatal. TODO: address subspaces 5312 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 5313 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5314 5315 // It's okay to add or remove GC or lifetime qualifiers when converting to 5316 // and from void*. 5317 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 5318 .compatiblyIncludes( 5319 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 5320 && (lhptee->isVoidType() || rhptee->isVoidType())) 5321 ; // keep old 5322 5323 // Treat lifetime mismatches as fatal. 5324 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 5325 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5326 5327 // For GCC compatibility, other qualifier mismatches are treated 5328 // as still compatible in C. 5329 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5330 } 5331 5332 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 5333 // incomplete type and the other is a pointer to a qualified or unqualified 5334 // version of void... 5335 if (lhptee->isVoidType()) { 5336 if (rhptee->isIncompleteOrObjectType()) 5337 return ConvTy; 5338 5339 // As an extension, we allow cast to/from void* to function pointer. 5340 assert(rhptee->isFunctionType()); 5341 return Sema::FunctionVoidPointer; 5342 } 5343 5344 if (rhptee->isVoidType()) { 5345 if (lhptee->isIncompleteOrObjectType()) 5346 return ConvTy; 5347 5348 // As an extension, we allow cast to/from void* to function pointer. 5349 assert(lhptee->isFunctionType()); 5350 return Sema::FunctionVoidPointer; 5351 } 5352 5353 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 5354 // unqualified versions of compatible types, ... 5355 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 5356 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 5357 // Check if the pointee types are compatible ignoring the sign. 5358 // We explicitly check for char so that we catch "char" vs 5359 // "unsigned char" on systems where "char" is unsigned. 5360 if (lhptee->isCharType()) 5361 ltrans = S.Context.UnsignedCharTy; 5362 else if (lhptee->hasSignedIntegerRepresentation()) 5363 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 5364 5365 if (rhptee->isCharType()) 5366 rtrans = S.Context.UnsignedCharTy; 5367 else if (rhptee->hasSignedIntegerRepresentation()) 5368 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 5369 5370 if (ltrans == rtrans) { 5371 // Types are compatible ignoring the sign. Qualifier incompatibility 5372 // takes priority over sign incompatibility because the sign 5373 // warning can be disabled. 5374 if (ConvTy != Sema::Compatible) 5375 return ConvTy; 5376 5377 return Sema::IncompatiblePointerSign; 5378 } 5379 5380 // If we are a multi-level pointer, it's possible that our issue is simply 5381 // one of qualification - e.g. char ** -> const char ** is not allowed. If 5382 // the eventual target type is the same and the pointers have the same 5383 // level of indirection, this must be the issue. 5384 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 5385 do { 5386 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 5387 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 5388 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 5389 5390 if (lhptee == rhptee) 5391 return Sema::IncompatibleNestedPointerQualifiers; 5392 } 5393 5394 // General pointer incompatibility takes priority over qualifiers. 5395 return Sema::IncompatiblePointer; 5396 } 5397 if (!S.getLangOpts().CPlusPlus && 5398 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 5399 return Sema::IncompatiblePointer; 5400 return ConvTy; 5401 } 5402 5403 /// checkBlockPointerTypesForAssignment - This routine determines whether two 5404 /// block pointer types are compatible or whether a block and normal pointer 5405 /// are compatible. It is more restrict than comparing two function pointer 5406 // types. 5407 static Sema::AssignConvertType 5408 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 5409 QualType RHSType) { 5410 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5411 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5412 5413 QualType lhptee, rhptee; 5414 5415 // get the "pointed to" type (ignoring qualifiers at the top level) 5416 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 5417 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 5418 5419 // In C++, the types have to match exactly. 5420 if (S.getLangOpts().CPlusPlus) 5421 return Sema::IncompatibleBlockPointer; 5422 5423 Sema::AssignConvertType ConvTy = Sema::Compatible; 5424 5425 // For blocks we enforce that qualifiers are identical. 5426 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 5427 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5428 5429 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 5430 return Sema::IncompatibleBlockPointer; 5431 5432 return ConvTy; 5433 } 5434 5435 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 5436 /// for assignment compatibility. 5437 static Sema::AssignConvertType 5438 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 5439 QualType RHSType) { 5440 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 5441 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 5442 5443 if (LHSType->isObjCBuiltinType()) { 5444 // Class is not compatible with ObjC object pointers. 5445 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 5446 !RHSType->isObjCQualifiedClassType()) 5447 return Sema::IncompatiblePointer; 5448 return Sema::Compatible; 5449 } 5450 if (RHSType->isObjCBuiltinType()) { 5451 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 5452 !LHSType->isObjCQualifiedClassType()) 5453 return Sema::IncompatiblePointer; 5454 return Sema::Compatible; 5455 } 5456 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5457 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5458 5459 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 5460 // make an exception for id<P> 5461 !LHSType->isObjCQualifiedIdType()) 5462 return Sema::CompatiblePointerDiscardsQualifiers; 5463 5464 if (S.Context.typesAreCompatible(LHSType, RHSType)) 5465 return Sema::Compatible; 5466 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 5467 return Sema::IncompatibleObjCQualifiedId; 5468 return Sema::IncompatiblePointer; 5469 } 5470 5471 Sema::AssignConvertType 5472 Sema::CheckAssignmentConstraints(SourceLocation Loc, 5473 QualType LHSType, QualType RHSType) { 5474 // Fake up an opaque expression. We don't actually care about what 5475 // cast operations are required, so if CheckAssignmentConstraints 5476 // adds casts to this they'll be wasted, but fortunately that doesn't 5477 // usually happen on valid code. 5478 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 5479 ExprResult RHSPtr = &RHSExpr; 5480 CastKind K = CK_Invalid; 5481 5482 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 5483 } 5484 5485 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 5486 /// has code to accommodate several GCC extensions when type checking 5487 /// pointers. Here are some objectionable examples that GCC considers warnings: 5488 /// 5489 /// int a, *pint; 5490 /// short *pshort; 5491 /// struct foo *pfoo; 5492 /// 5493 /// pint = pshort; // warning: assignment from incompatible pointer type 5494 /// a = pint; // warning: assignment makes integer from pointer without a cast 5495 /// pint = a; // warning: assignment makes pointer from integer without a cast 5496 /// pint = pfoo; // warning: assignment from incompatible pointer type 5497 /// 5498 /// As a result, the code for dealing with pointers is more complex than the 5499 /// C99 spec dictates. 5500 /// 5501 /// Sets 'Kind' for any result kind except Incompatible. 5502 Sema::AssignConvertType 5503 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 5504 CastKind &Kind) { 5505 QualType RHSType = RHS.get()->getType(); 5506 QualType OrigLHSType = LHSType; 5507 5508 // Get canonical types. We're not formatting these types, just comparing 5509 // them. 5510 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 5511 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 5512 5513 5514 // Common case: no conversion required. 5515 if (LHSType == RHSType) { 5516 Kind = CK_NoOp; 5517 return Compatible; 5518 } 5519 5520 // If we have an atomic type, try a non-atomic assignment, then just add an 5521 // atomic qualification step. 5522 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 5523 Sema::AssignConvertType result = 5524 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 5525 if (result != Compatible) 5526 return result; 5527 if (Kind != CK_NoOp) 5528 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind); 5529 Kind = CK_NonAtomicToAtomic; 5530 return Compatible; 5531 } 5532 5533 // If the left-hand side is a reference type, then we are in a 5534 // (rare!) case where we've allowed the use of references in C, 5535 // e.g., as a parameter type in a built-in function. In this case, 5536 // just make sure that the type referenced is compatible with the 5537 // right-hand side type. The caller is responsible for adjusting 5538 // LHSType so that the resulting expression does not have reference 5539 // type. 5540 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 5541 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 5542 Kind = CK_LValueBitCast; 5543 return Compatible; 5544 } 5545 return Incompatible; 5546 } 5547 5548 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 5549 // to the same ExtVector type. 5550 if (LHSType->isExtVectorType()) { 5551 if (RHSType->isExtVectorType()) 5552 return Incompatible; 5553 if (RHSType->isArithmeticType()) { 5554 // CK_VectorSplat does T -> vector T, so first cast to the 5555 // element type. 5556 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 5557 if (elType != RHSType) { 5558 Kind = PrepareScalarCast(RHS, elType); 5559 RHS = ImpCastExprToType(RHS.take(), elType, Kind); 5560 } 5561 Kind = CK_VectorSplat; 5562 return Compatible; 5563 } 5564 } 5565 5566 // Conversions to or from vector type. 5567 if (LHSType->isVectorType() || RHSType->isVectorType()) { 5568 if (LHSType->isVectorType() && RHSType->isVectorType()) { 5569 // Allow assignments of an AltiVec vector type to an equivalent GCC 5570 // vector type and vice versa 5571 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 5572 Kind = CK_BitCast; 5573 return Compatible; 5574 } 5575 5576 // If we are allowing lax vector conversions, and LHS and RHS are both 5577 // vectors, the total size only needs to be the same. This is a bitcast; 5578 // no bits are changed but the result type is different. 5579 if (getLangOpts().LaxVectorConversions && 5580 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) { 5581 Kind = CK_BitCast; 5582 return IncompatibleVectors; 5583 } 5584 } 5585 return Incompatible; 5586 } 5587 5588 // Arithmetic conversions. 5589 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 5590 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 5591 Kind = PrepareScalarCast(RHS, LHSType); 5592 return Compatible; 5593 } 5594 5595 // Conversions to normal pointers. 5596 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 5597 // U* -> T* 5598 if (isa<PointerType>(RHSType)) { 5599 Kind = CK_BitCast; 5600 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 5601 } 5602 5603 // int -> T* 5604 if (RHSType->isIntegerType()) { 5605 Kind = CK_IntegralToPointer; // FIXME: null? 5606 return IntToPointer; 5607 } 5608 5609 // C pointers are not compatible with ObjC object pointers, 5610 // with two exceptions: 5611 if (isa<ObjCObjectPointerType>(RHSType)) { 5612 // - conversions to void* 5613 if (LHSPointer->getPointeeType()->isVoidType()) { 5614 Kind = CK_BitCast; 5615 return Compatible; 5616 } 5617 5618 // - conversions from 'Class' to the redefinition type 5619 if (RHSType->isObjCClassType() && 5620 Context.hasSameType(LHSType, 5621 Context.getObjCClassRedefinitionType())) { 5622 Kind = CK_BitCast; 5623 return Compatible; 5624 } 5625 5626 Kind = CK_BitCast; 5627 return IncompatiblePointer; 5628 } 5629 5630 // U^ -> void* 5631 if (RHSType->getAs<BlockPointerType>()) { 5632 if (LHSPointer->getPointeeType()->isVoidType()) { 5633 Kind = CK_BitCast; 5634 return Compatible; 5635 } 5636 } 5637 5638 return Incompatible; 5639 } 5640 5641 // Conversions to block pointers. 5642 if (isa<BlockPointerType>(LHSType)) { 5643 // U^ -> T^ 5644 if (RHSType->isBlockPointerType()) { 5645 Kind = CK_BitCast; 5646 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 5647 } 5648 5649 // int or null -> T^ 5650 if (RHSType->isIntegerType()) { 5651 Kind = CK_IntegralToPointer; // FIXME: null 5652 return IntToBlockPointer; 5653 } 5654 5655 // id -> T^ 5656 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 5657 Kind = CK_AnyPointerToBlockPointerCast; 5658 return Compatible; 5659 } 5660 5661 // void* -> T^ 5662 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 5663 if (RHSPT->getPointeeType()->isVoidType()) { 5664 Kind = CK_AnyPointerToBlockPointerCast; 5665 return Compatible; 5666 } 5667 5668 return Incompatible; 5669 } 5670 5671 // Conversions to Objective-C pointers. 5672 if (isa<ObjCObjectPointerType>(LHSType)) { 5673 // A* -> B* 5674 if (RHSType->isObjCObjectPointerType()) { 5675 Kind = CK_BitCast; 5676 Sema::AssignConvertType result = 5677 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 5678 if (getLangOpts().ObjCAutoRefCount && 5679 result == Compatible && 5680 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 5681 result = IncompatibleObjCWeakRef; 5682 return result; 5683 } 5684 5685 // int or null -> A* 5686 if (RHSType->isIntegerType()) { 5687 Kind = CK_IntegralToPointer; // FIXME: null 5688 return IntToPointer; 5689 } 5690 5691 // In general, C pointers are not compatible with ObjC object pointers, 5692 // with two exceptions: 5693 if (isa<PointerType>(RHSType)) { 5694 Kind = CK_CPointerToObjCPointerCast; 5695 5696 // - conversions from 'void*' 5697 if (RHSType->isVoidPointerType()) { 5698 return Compatible; 5699 } 5700 5701 // - conversions to 'Class' from its redefinition type 5702 if (LHSType->isObjCClassType() && 5703 Context.hasSameType(RHSType, 5704 Context.getObjCClassRedefinitionType())) { 5705 return Compatible; 5706 } 5707 5708 return IncompatiblePointer; 5709 } 5710 5711 // T^ -> A* 5712 if (RHSType->isBlockPointerType()) { 5713 maybeExtendBlockObject(*this, RHS); 5714 Kind = CK_BlockPointerToObjCPointerCast; 5715 return Compatible; 5716 } 5717 5718 return Incompatible; 5719 } 5720 5721 // Conversions from pointers that are not covered by the above. 5722 if (isa<PointerType>(RHSType)) { 5723 // T* -> _Bool 5724 if (LHSType == Context.BoolTy) { 5725 Kind = CK_PointerToBoolean; 5726 return Compatible; 5727 } 5728 5729 // T* -> int 5730 if (LHSType->isIntegerType()) { 5731 Kind = CK_PointerToIntegral; 5732 return PointerToInt; 5733 } 5734 5735 return Incompatible; 5736 } 5737 5738 // Conversions from Objective-C pointers that are not covered by the above. 5739 if (isa<ObjCObjectPointerType>(RHSType)) { 5740 // T* -> _Bool 5741 if (LHSType == Context.BoolTy) { 5742 Kind = CK_PointerToBoolean; 5743 return Compatible; 5744 } 5745 5746 // T* -> int 5747 if (LHSType->isIntegerType()) { 5748 Kind = CK_PointerToIntegral; 5749 return PointerToInt; 5750 } 5751 5752 return Incompatible; 5753 } 5754 5755 // struct A -> struct B 5756 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 5757 if (Context.typesAreCompatible(LHSType, RHSType)) { 5758 Kind = CK_NoOp; 5759 return Compatible; 5760 } 5761 } 5762 5763 return Incompatible; 5764 } 5765 5766 /// \brief Constructs a transparent union from an expression that is 5767 /// used to initialize the transparent union. 5768 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 5769 ExprResult &EResult, QualType UnionType, 5770 FieldDecl *Field) { 5771 // Build an initializer list that designates the appropriate member 5772 // of the transparent union. 5773 Expr *E = EResult.take(); 5774 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 5775 &E, 1, 5776 SourceLocation()); 5777 Initializer->setType(UnionType); 5778 Initializer->setInitializedFieldInUnion(Field); 5779 5780 // Build a compound literal constructing a value of the transparent 5781 // union type from this initializer list. 5782 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 5783 EResult = S.Owned( 5784 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 5785 VK_RValue, Initializer, false)); 5786 } 5787 5788 Sema::AssignConvertType 5789 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 5790 ExprResult &RHS) { 5791 QualType RHSType = RHS.get()->getType(); 5792 5793 // If the ArgType is a Union type, we want to handle a potential 5794 // transparent_union GCC extension. 5795 const RecordType *UT = ArgType->getAsUnionType(); 5796 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 5797 return Incompatible; 5798 5799 // The field to initialize within the transparent union. 5800 RecordDecl *UD = UT->getDecl(); 5801 FieldDecl *InitField = 0; 5802 // It's compatible if the expression matches any of the fields. 5803 for (RecordDecl::field_iterator it = UD->field_begin(), 5804 itend = UD->field_end(); 5805 it != itend; ++it) { 5806 if (it->getType()->isPointerType()) { 5807 // If the transparent union contains a pointer type, we allow: 5808 // 1) void pointer 5809 // 2) null pointer constant 5810 if (RHSType->isPointerType()) 5811 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 5812 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast); 5813 InitField = *it; 5814 break; 5815 } 5816 5817 if (RHS.get()->isNullPointerConstant(Context, 5818 Expr::NPC_ValueDependentIsNull)) { 5819 RHS = ImpCastExprToType(RHS.take(), it->getType(), 5820 CK_NullToPointer); 5821 InitField = *it; 5822 break; 5823 } 5824 } 5825 5826 CastKind Kind = CK_Invalid; 5827 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 5828 == Compatible) { 5829 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind); 5830 InitField = *it; 5831 break; 5832 } 5833 } 5834 5835 if (!InitField) 5836 return Incompatible; 5837 5838 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 5839 return Compatible; 5840 } 5841 5842 Sema::AssignConvertType 5843 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 5844 bool Diagnose) { 5845 if (getLangOpts().CPlusPlus) { 5846 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 5847 // C++ 5.17p3: If the left operand is not of class type, the 5848 // expression is implicitly converted (C++ 4) to the 5849 // cv-unqualified type of the left operand. 5850 ExprResult Res; 5851 if (Diagnose) { 5852 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 5853 AA_Assigning); 5854 } else { 5855 ImplicitConversionSequence ICS = 5856 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 5857 /*SuppressUserConversions=*/false, 5858 /*AllowExplicit=*/false, 5859 /*InOverloadResolution=*/false, 5860 /*CStyle=*/false, 5861 /*AllowObjCWritebackConversion=*/false); 5862 if (ICS.isFailure()) 5863 return Incompatible; 5864 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 5865 ICS, AA_Assigning); 5866 } 5867 if (Res.isInvalid()) 5868 return Incompatible; 5869 Sema::AssignConvertType result = Compatible; 5870 if (getLangOpts().ObjCAutoRefCount && 5871 !CheckObjCARCUnavailableWeakConversion(LHSType, 5872 RHS.get()->getType())) 5873 result = IncompatibleObjCWeakRef; 5874 RHS = move(Res); 5875 return result; 5876 } 5877 5878 // FIXME: Currently, we fall through and treat C++ classes like C 5879 // structures. 5880 // FIXME: We also fall through for atomics; not sure what should 5881 // happen there, though. 5882 } 5883 5884 // C99 6.5.16.1p1: the left operand is a pointer and the right is 5885 // a null pointer constant. 5886 if ((LHSType->isPointerType() || 5887 LHSType->isObjCObjectPointerType() || 5888 LHSType->isBlockPointerType()) 5889 && RHS.get()->isNullPointerConstant(Context, 5890 Expr::NPC_ValueDependentIsNull)) { 5891 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 5892 return Compatible; 5893 } 5894 5895 // This check seems unnatural, however it is necessary to ensure the proper 5896 // conversion of functions/arrays. If the conversion were done for all 5897 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 5898 // expressions that suppress this implicit conversion (&, sizeof). 5899 // 5900 // Suppress this for references: C++ 8.5.3p5. 5901 if (!LHSType->isReferenceType()) { 5902 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 5903 if (RHS.isInvalid()) 5904 return Incompatible; 5905 } 5906 5907 CastKind Kind = CK_Invalid; 5908 Sema::AssignConvertType result = 5909 CheckAssignmentConstraints(LHSType, RHS, Kind); 5910 5911 // C99 6.5.16.1p2: The value of the right operand is converted to the 5912 // type of the assignment expression. 5913 // CheckAssignmentConstraints allows the left-hand side to be a reference, 5914 // so that we can use references in built-in functions even in C. 5915 // The getNonReferenceType() call makes sure that the resulting expression 5916 // does not have reference type. 5917 if (result != Incompatible && RHS.get()->getType() != LHSType) 5918 RHS = ImpCastExprToType(RHS.take(), 5919 LHSType.getNonLValueExprType(Context), Kind); 5920 return result; 5921 } 5922 5923 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 5924 ExprResult &RHS) { 5925 Diag(Loc, diag::err_typecheck_invalid_operands) 5926 << LHS.get()->getType() << RHS.get()->getType() 5927 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5928 return QualType(); 5929 } 5930 5931 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 5932 SourceLocation Loc, bool IsCompAssign) { 5933 if (!IsCompAssign) { 5934 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 5935 if (LHS.isInvalid()) 5936 return QualType(); 5937 } 5938 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 5939 if (RHS.isInvalid()) 5940 return QualType(); 5941 5942 // For conversion purposes, we ignore any qualifiers. 5943 // For example, "const float" and "float" are equivalent. 5944 QualType LHSType = 5945 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 5946 QualType RHSType = 5947 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 5948 5949 // If the vector types are identical, return. 5950 if (LHSType == RHSType) 5951 return LHSType; 5952 5953 // Handle the case of equivalent AltiVec and GCC vector types 5954 if (LHSType->isVectorType() && RHSType->isVectorType() && 5955 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 5956 if (LHSType->isExtVectorType()) { 5957 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 5958 return LHSType; 5959 } 5960 5961 if (!IsCompAssign) 5962 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 5963 return RHSType; 5964 } 5965 5966 if (getLangOpts().LaxVectorConversions && 5967 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) { 5968 // If we are allowing lax vector conversions, and LHS and RHS are both 5969 // vectors, the total size only needs to be the same. This is a 5970 // bitcast; no bits are changed but the result type is different. 5971 // FIXME: Should we really be allowing this? 5972 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 5973 return LHSType; 5974 } 5975 5976 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can 5977 // swap back (so that we don't reverse the inputs to a subtract, for instance. 5978 bool swapped = false; 5979 if (RHSType->isExtVectorType() && !IsCompAssign) { 5980 swapped = true; 5981 std::swap(RHS, LHS); 5982 std::swap(RHSType, LHSType); 5983 } 5984 5985 // Handle the case of an ext vector and scalar. 5986 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) { 5987 QualType EltTy = LV->getElementType(); 5988 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) { 5989 int order = Context.getIntegerTypeOrder(EltTy, RHSType); 5990 if (order > 0) 5991 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast); 5992 if (order >= 0) { 5993 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 5994 if (swapped) std::swap(RHS, LHS); 5995 return LHSType; 5996 } 5997 } 5998 if (EltTy->isRealFloatingType() && RHSType->isScalarType() && 5999 RHSType->isRealFloatingType()) { 6000 int order = Context.getFloatingTypeOrder(EltTy, RHSType); 6001 if (order > 0) 6002 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast); 6003 if (order >= 0) { 6004 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6005 if (swapped) std::swap(RHS, LHS); 6006 return LHSType; 6007 } 6008 } 6009 } 6010 6011 // Vectors of different size or scalar and non-ext-vector are errors. 6012 if (swapped) std::swap(RHS, LHS); 6013 Diag(Loc, diag::err_typecheck_vector_not_convertable) 6014 << LHS.get()->getType() << RHS.get()->getType() 6015 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6016 return QualType(); 6017 } 6018 6019 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 6020 // expression. These are mainly cases where the null pointer is used as an 6021 // integer instead of a pointer. 6022 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 6023 SourceLocation Loc, bool IsCompare) { 6024 // The canonical way to check for a GNU null is with isNullPointerConstant, 6025 // but we use a bit of a hack here for speed; this is a relatively 6026 // hot path, and isNullPointerConstant is slow. 6027 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 6028 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 6029 6030 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 6031 6032 // Avoid analyzing cases where the result will either be invalid (and 6033 // diagnosed as such) or entirely valid and not something to warn about. 6034 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 6035 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 6036 return; 6037 6038 // Comparison operations would not make sense with a null pointer no matter 6039 // what the other expression is. 6040 if (!IsCompare) { 6041 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 6042 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 6043 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 6044 return; 6045 } 6046 6047 // The rest of the operations only make sense with a null pointer 6048 // if the other expression is a pointer. 6049 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 6050 NonNullType->canDecayToPointerType()) 6051 return; 6052 6053 S.Diag(Loc, diag::warn_null_in_comparison_operation) 6054 << LHSNull /* LHS is NULL */ << NonNullType 6055 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6056 } 6057 6058 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 6059 SourceLocation Loc, 6060 bool IsCompAssign, bool IsDiv) { 6061 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6062 6063 if (LHS.get()->getType()->isVectorType() || 6064 RHS.get()->getType()->isVectorType()) 6065 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6066 6067 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6068 if (LHS.isInvalid() || RHS.isInvalid()) 6069 return QualType(); 6070 6071 6072 if (compType.isNull() || !compType->isArithmeticType()) 6073 return InvalidOperands(Loc, LHS, RHS); 6074 6075 // Check for division by zero. 6076 if (IsDiv && 6077 RHS.get()->isNullPointerConstant(Context, 6078 Expr::NPC_ValueDependentIsNotNull)) 6079 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero) 6080 << RHS.get()->getSourceRange()); 6081 6082 return compType; 6083 } 6084 6085 QualType Sema::CheckRemainderOperands( 6086 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 6087 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6088 6089 if (LHS.get()->getType()->isVectorType() || 6090 RHS.get()->getType()->isVectorType()) { 6091 if (LHS.get()->getType()->hasIntegerRepresentation() && 6092 RHS.get()->getType()->hasIntegerRepresentation()) 6093 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6094 return InvalidOperands(Loc, LHS, RHS); 6095 } 6096 6097 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6098 if (LHS.isInvalid() || RHS.isInvalid()) 6099 return QualType(); 6100 6101 if (compType.isNull() || !compType->isIntegerType()) 6102 return InvalidOperands(Loc, LHS, RHS); 6103 6104 // Check for remainder by zero. 6105 if (RHS.get()->isNullPointerConstant(Context, 6106 Expr::NPC_ValueDependentIsNotNull)) 6107 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero) 6108 << RHS.get()->getSourceRange()); 6109 6110 return compType; 6111 } 6112 6113 /// \brief Diagnose invalid arithmetic on two void pointers. 6114 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 6115 Expr *LHSExpr, Expr *RHSExpr) { 6116 S.Diag(Loc, S.getLangOpts().CPlusPlus 6117 ? diag::err_typecheck_pointer_arith_void_type 6118 : diag::ext_gnu_void_ptr) 6119 << 1 /* two pointers */ << LHSExpr->getSourceRange() 6120 << RHSExpr->getSourceRange(); 6121 } 6122 6123 /// \brief Diagnose invalid arithmetic on a void pointer. 6124 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 6125 Expr *Pointer) { 6126 S.Diag(Loc, S.getLangOpts().CPlusPlus 6127 ? diag::err_typecheck_pointer_arith_void_type 6128 : diag::ext_gnu_void_ptr) 6129 << 0 /* one pointer */ << Pointer->getSourceRange(); 6130 } 6131 6132 /// \brief Diagnose invalid arithmetic on two function pointers. 6133 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 6134 Expr *LHS, Expr *RHS) { 6135 assert(LHS->getType()->isAnyPointerType()); 6136 assert(RHS->getType()->isAnyPointerType()); 6137 S.Diag(Loc, S.getLangOpts().CPlusPlus 6138 ? diag::err_typecheck_pointer_arith_function_type 6139 : diag::ext_gnu_ptr_func_arith) 6140 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 6141 // We only show the second type if it differs from the first. 6142 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 6143 RHS->getType()) 6144 << RHS->getType()->getPointeeType() 6145 << LHS->getSourceRange() << RHS->getSourceRange(); 6146 } 6147 6148 /// \brief Diagnose invalid arithmetic on a function pointer. 6149 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 6150 Expr *Pointer) { 6151 assert(Pointer->getType()->isAnyPointerType()); 6152 S.Diag(Loc, S.getLangOpts().CPlusPlus 6153 ? diag::err_typecheck_pointer_arith_function_type 6154 : diag::ext_gnu_ptr_func_arith) 6155 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 6156 << 0 /* one pointer, so only one type */ 6157 << Pointer->getSourceRange(); 6158 } 6159 6160 /// \brief Emit error if Operand is incomplete pointer type 6161 /// 6162 /// \returns True if pointer has incomplete type 6163 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 6164 Expr *Operand) { 6165 if ((Operand->getType()->isPointerType() && 6166 !Operand->getType()->isDependentType()) || 6167 Operand->getType()->isObjCObjectPointerType()) { 6168 QualType PointeeTy = Operand->getType()->getPointeeType(); 6169 if (S.RequireCompleteType( 6170 Loc, PointeeTy, 6171 diag::err_typecheck_arithmetic_incomplete_type, 6172 PointeeTy, Operand->getSourceRange())) 6173 return true; 6174 } 6175 return false; 6176 } 6177 6178 /// \brief Check the validity of an arithmetic pointer operand. 6179 /// 6180 /// If the operand has pointer type, this code will check for pointer types 6181 /// which are invalid in arithmetic operations. These will be diagnosed 6182 /// appropriately, including whether or not the use is supported as an 6183 /// extension. 6184 /// 6185 /// \returns True when the operand is valid to use (even if as an extension). 6186 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 6187 Expr *Operand) { 6188 if (!Operand->getType()->isAnyPointerType()) return true; 6189 6190 QualType PointeeTy = Operand->getType()->getPointeeType(); 6191 if (PointeeTy->isVoidType()) { 6192 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 6193 return !S.getLangOpts().CPlusPlus; 6194 } 6195 if (PointeeTy->isFunctionType()) { 6196 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 6197 return !S.getLangOpts().CPlusPlus; 6198 } 6199 6200 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 6201 6202 return true; 6203 } 6204 6205 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 6206 /// operands. 6207 /// 6208 /// This routine will diagnose any invalid arithmetic on pointer operands much 6209 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 6210 /// for emitting a single diagnostic even for operations where both LHS and RHS 6211 /// are (potentially problematic) pointers. 6212 /// 6213 /// \returns True when the operand is valid to use (even if as an extension). 6214 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 6215 Expr *LHSExpr, Expr *RHSExpr) { 6216 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 6217 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 6218 if (!isLHSPointer && !isRHSPointer) return true; 6219 6220 QualType LHSPointeeTy, RHSPointeeTy; 6221 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 6222 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 6223 6224 // Check for arithmetic on pointers to incomplete types. 6225 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 6226 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 6227 if (isLHSVoidPtr || isRHSVoidPtr) { 6228 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 6229 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 6230 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 6231 6232 return !S.getLangOpts().CPlusPlus; 6233 } 6234 6235 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 6236 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 6237 if (isLHSFuncPtr || isRHSFuncPtr) { 6238 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 6239 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 6240 RHSExpr); 6241 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 6242 6243 return !S.getLangOpts().CPlusPlus; 6244 } 6245 6246 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false; 6247 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false; 6248 6249 return true; 6250 } 6251 6252 /// \brief Check bad cases where we step over interface counts. 6253 static bool checkArithmethicPointerOnNonFragileABI(Sema &S, 6254 SourceLocation OpLoc, 6255 Expr *Op) { 6256 assert(Op->getType()->isAnyPointerType()); 6257 QualType PointeeTy = Op->getType()->getPointeeType(); 6258 if (!PointeeTy->isObjCObjectType() || S.LangOpts.ObjCRuntime.isFragile()) 6259 return true; 6260 6261 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface) 6262 << PointeeTy << Op->getSourceRange(); 6263 return false; 6264 } 6265 6266 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 6267 /// literal. 6268 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 6269 Expr *LHSExpr, Expr *RHSExpr) { 6270 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 6271 Expr* IndexExpr = RHSExpr; 6272 if (!StrExpr) { 6273 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 6274 IndexExpr = LHSExpr; 6275 } 6276 6277 bool IsStringPlusInt = StrExpr && 6278 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 6279 if (!IsStringPlusInt) 6280 return; 6281 6282 llvm::APSInt index; 6283 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 6284 unsigned StrLenWithNull = StrExpr->getLength() + 1; 6285 if (index.isNonNegative() && 6286 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 6287 index.isUnsigned())) 6288 return; 6289 } 6290 6291 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 6292 Self.Diag(OpLoc, diag::warn_string_plus_int) 6293 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 6294 6295 // Only print a fixit for "str" + int, not for int + "str". 6296 if (IndexExpr == RHSExpr) { 6297 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 6298 Self.Diag(OpLoc, diag::note_string_plus_int_silence) 6299 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 6300 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 6301 << FixItHint::CreateInsertion(EndLoc, "]"); 6302 } else 6303 Self.Diag(OpLoc, diag::note_string_plus_int_silence); 6304 } 6305 6306 /// \brief Emit error when two pointers are incompatible. 6307 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 6308 Expr *LHSExpr, Expr *RHSExpr) { 6309 assert(LHSExpr->getType()->isAnyPointerType()); 6310 assert(RHSExpr->getType()->isAnyPointerType()); 6311 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 6312 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 6313 << RHSExpr->getSourceRange(); 6314 } 6315 6316 QualType Sema::CheckAdditionOperands( // C99 6.5.6 6317 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 6318 QualType* CompLHSTy) { 6319 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6320 6321 if (LHS.get()->getType()->isVectorType() || 6322 RHS.get()->getType()->isVectorType()) { 6323 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 6324 if (CompLHSTy) *CompLHSTy = compType; 6325 return compType; 6326 } 6327 6328 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 6329 if (LHS.isInvalid() || RHS.isInvalid()) 6330 return QualType(); 6331 6332 // Diagnose "string literal" '+' int. 6333 if (Opc == BO_Add) 6334 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 6335 6336 // handle the common case first (both operands are arithmetic). 6337 if (!compType.isNull() && compType->isArithmeticType()) { 6338 if (CompLHSTy) *CompLHSTy = compType; 6339 return compType; 6340 } 6341 6342 // Put any potential pointer into PExp 6343 Expr* PExp = LHS.get(), *IExp = RHS.get(); 6344 if (IExp->getType()->isAnyPointerType()) 6345 std::swap(PExp, IExp); 6346 6347 if (!PExp->getType()->isAnyPointerType()) 6348 return InvalidOperands(Loc, LHS, RHS); 6349 6350 if (!IExp->getType()->isIntegerType()) 6351 return InvalidOperands(Loc, LHS, RHS); 6352 6353 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 6354 return QualType(); 6355 6356 // Diagnose bad cases where we step over interface counts. 6357 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp)) 6358 return QualType(); 6359 6360 // Check array bounds for pointer arithemtic 6361 CheckArrayAccess(PExp, IExp); 6362 6363 if (CompLHSTy) { 6364 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 6365 if (LHSTy.isNull()) { 6366 LHSTy = LHS.get()->getType(); 6367 if (LHSTy->isPromotableIntegerType()) 6368 LHSTy = Context.getPromotedIntegerType(LHSTy); 6369 } 6370 *CompLHSTy = LHSTy; 6371 } 6372 6373 return PExp->getType(); 6374 } 6375 6376 // C99 6.5.6 6377 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 6378 SourceLocation Loc, 6379 QualType* CompLHSTy) { 6380 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6381 6382 if (LHS.get()->getType()->isVectorType() || 6383 RHS.get()->getType()->isVectorType()) { 6384 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 6385 if (CompLHSTy) *CompLHSTy = compType; 6386 return compType; 6387 } 6388 6389 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 6390 if (LHS.isInvalid() || RHS.isInvalid()) 6391 return QualType(); 6392 6393 // Enforce type constraints: C99 6.5.6p3. 6394 6395 // Handle the common case first (both operands are arithmetic). 6396 if (!compType.isNull() && compType->isArithmeticType()) { 6397 if (CompLHSTy) *CompLHSTy = compType; 6398 return compType; 6399 } 6400 6401 // Either ptr - int or ptr - ptr. 6402 if (LHS.get()->getType()->isAnyPointerType()) { 6403 QualType lpointee = LHS.get()->getType()->getPointeeType(); 6404 6405 // Diagnose bad cases where we step over interface counts. 6406 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get())) 6407 return QualType(); 6408 6409 // The result type of a pointer-int computation is the pointer type. 6410 if (RHS.get()->getType()->isIntegerType()) { 6411 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 6412 return QualType(); 6413 6414 // Check array bounds for pointer arithemtic 6415 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0, 6416 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 6417 6418 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 6419 return LHS.get()->getType(); 6420 } 6421 6422 // Handle pointer-pointer subtractions. 6423 if (const PointerType *RHSPTy 6424 = RHS.get()->getType()->getAs<PointerType>()) { 6425 QualType rpointee = RHSPTy->getPointeeType(); 6426 6427 if (getLangOpts().CPlusPlus) { 6428 // Pointee types must be the same: C++ [expr.add] 6429 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 6430 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 6431 } 6432 } else { 6433 // Pointee types must be compatible C99 6.5.6p3 6434 if (!Context.typesAreCompatible( 6435 Context.getCanonicalType(lpointee).getUnqualifiedType(), 6436 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 6437 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 6438 return QualType(); 6439 } 6440 } 6441 6442 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 6443 LHS.get(), RHS.get())) 6444 return QualType(); 6445 6446 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 6447 return Context.getPointerDiffType(); 6448 } 6449 } 6450 6451 return InvalidOperands(Loc, LHS, RHS); 6452 } 6453 6454 static bool isScopedEnumerationType(QualType T) { 6455 if (const EnumType *ET = dyn_cast<EnumType>(T)) 6456 return ET->getDecl()->isScoped(); 6457 return false; 6458 } 6459 6460 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 6461 SourceLocation Loc, unsigned Opc, 6462 QualType LHSType) { 6463 llvm::APSInt Right; 6464 // Check right/shifter operand 6465 if (RHS.get()->isValueDependent() || 6466 !RHS.get()->isIntegerConstantExpr(Right, S.Context)) 6467 return; 6468 6469 if (Right.isNegative()) { 6470 S.DiagRuntimeBehavior(Loc, RHS.get(), 6471 S.PDiag(diag::warn_shift_negative) 6472 << RHS.get()->getSourceRange()); 6473 return; 6474 } 6475 llvm::APInt LeftBits(Right.getBitWidth(), 6476 S.Context.getTypeSize(LHS.get()->getType())); 6477 if (Right.uge(LeftBits)) { 6478 S.DiagRuntimeBehavior(Loc, RHS.get(), 6479 S.PDiag(diag::warn_shift_gt_typewidth) 6480 << RHS.get()->getSourceRange()); 6481 return; 6482 } 6483 if (Opc != BO_Shl) 6484 return; 6485 6486 // When left shifting an ICE which is signed, we can check for overflow which 6487 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 6488 // integers have defined behavior modulo one more than the maximum value 6489 // representable in the result type, so never warn for those. 6490 llvm::APSInt Left; 6491 if (LHS.get()->isValueDependent() || 6492 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 6493 LHSType->hasUnsignedIntegerRepresentation()) 6494 return; 6495 llvm::APInt ResultBits = 6496 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 6497 if (LeftBits.uge(ResultBits)) 6498 return; 6499 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 6500 Result = Result.shl(Right); 6501 6502 // Print the bit representation of the signed integer as an unsigned 6503 // hexadecimal number. 6504 SmallString<40> HexResult; 6505 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 6506 6507 // If we are only missing a sign bit, this is less likely to result in actual 6508 // bugs -- if the result is cast back to an unsigned type, it will have the 6509 // expected value. Thus we place this behind a different warning that can be 6510 // turned off separately if needed. 6511 if (LeftBits == ResultBits - 1) { 6512 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 6513 << HexResult.str() << LHSType 6514 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6515 return; 6516 } 6517 6518 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 6519 << HexResult.str() << Result.getMinSignedBits() << LHSType 6520 << Left.getBitWidth() << LHS.get()->getSourceRange() 6521 << RHS.get()->getSourceRange(); 6522 } 6523 6524 // C99 6.5.7 6525 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 6526 SourceLocation Loc, unsigned Opc, 6527 bool IsCompAssign) { 6528 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6529 6530 // C99 6.5.7p2: Each of the operands shall have integer type. 6531 if (!LHS.get()->getType()->hasIntegerRepresentation() || 6532 !RHS.get()->getType()->hasIntegerRepresentation()) 6533 return InvalidOperands(Loc, LHS, RHS); 6534 6535 // C++0x: Don't allow scoped enums. FIXME: Use something better than 6536 // hasIntegerRepresentation() above instead of this. 6537 if (isScopedEnumerationType(LHS.get()->getType()) || 6538 isScopedEnumerationType(RHS.get()->getType())) { 6539 return InvalidOperands(Loc, LHS, RHS); 6540 } 6541 6542 // Vector shifts promote their scalar inputs to vector type. 6543 if (LHS.get()->getType()->isVectorType() || 6544 RHS.get()->getType()->isVectorType()) 6545 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6546 6547 // Shifts don't perform usual arithmetic conversions, they just do integer 6548 // promotions on each operand. C99 6.5.7p3 6549 6550 // For the LHS, do usual unary conversions, but then reset them away 6551 // if this is a compound assignment. 6552 ExprResult OldLHS = LHS; 6553 LHS = UsualUnaryConversions(LHS.take()); 6554 if (LHS.isInvalid()) 6555 return QualType(); 6556 QualType LHSType = LHS.get()->getType(); 6557 if (IsCompAssign) LHS = OldLHS; 6558 6559 // The RHS is simpler. 6560 RHS = UsualUnaryConversions(RHS.take()); 6561 if (RHS.isInvalid()) 6562 return QualType(); 6563 6564 // Sanity-check shift operands 6565 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 6566 6567 // "The type of the result is that of the promoted left operand." 6568 return LHSType; 6569 } 6570 6571 static bool IsWithinTemplateSpecialization(Decl *D) { 6572 if (DeclContext *DC = D->getDeclContext()) { 6573 if (isa<ClassTemplateSpecializationDecl>(DC)) 6574 return true; 6575 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 6576 return FD->isFunctionTemplateSpecialization(); 6577 } 6578 return false; 6579 } 6580 6581 /// If two different enums are compared, raise a warning. 6582 static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, 6583 ExprResult &RHS) { 6584 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType(); 6585 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType(); 6586 6587 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 6588 if (!LHSEnumType) 6589 return; 6590 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 6591 if (!RHSEnumType) 6592 return; 6593 6594 // Ignore anonymous enums. 6595 if (!LHSEnumType->getDecl()->getIdentifier()) 6596 return; 6597 if (!RHSEnumType->getDecl()->getIdentifier()) 6598 return; 6599 6600 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 6601 return; 6602 6603 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 6604 << LHSStrippedType << RHSStrippedType 6605 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6606 } 6607 6608 /// \brief Diagnose bad pointer comparisons. 6609 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 6610 ExprResult &LHS, ExprResult &RHS, 6611 bool IsError) { 6612 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 6613 : diag::ext_typecheck_comparison_of_distinct_pointers) 6614 << LHS.get()->getType() << RHS.get()->getType() 6615 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6616 } 6617 6618 /// \brief Returns false if the pointers are converted to a composite type, 6619 /// true otherwise. 6620 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 6621 ExprResult &LHS, ExprResult &RHS) { 6622 // C++ [expr.rel]p2: 6623 // [...] Pointer conversions (4.10) and qualification 6624 // conversions (4.4) are performed on pointer operands (or on 6625 // a pointer operand and a null pointer constant) to bring 6626 // them to their composite pointer type. [...] 6627 // 6628 // C++ [expr.eq]p1 uses the same notion for (in)equality 6629 // comparisons of pointers. 6630 6631 // C++ [expr.eq]p2: 6632 // In addition, pointers to members can be compared, or a pointer to 6633 // member and a null pointer constant. Pointer to member conversions 6634 // (4.11) and qualification conversions (4.4) are performed to bring 6635 // them to a common type. If one operand is a null pointer constant, 6636 // the common type is the type of the other operand. Otherwise, the 6637 // common type is a pointer to member type similar (4.4) to the type 6638 // of one of the operands, with a cv-qualification signature (4.4) 6639 // that is the union of the cv-qualification signatures of the operand 6640 // types. 6641 6642 QualType LHSType = LHS.get()->getType(); 6643 QualType RHSType = RHS.get()->getType(); 6644 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 6645 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 6646 6647 bool NonStandardCompositeType = false; 6648 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType; 6649 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 6650 if (T.isNull()) { 6651 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 6652 return true; 6653 } 6654 6655 if (NonStandardCompositeType) 6656 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 6657 << LHSType << RHSType << T << LHS.get()->getSourceRange() 6658 << RHS.get()->getSourceRange(); 6659 6660 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast); 6661 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast); 6662 return false; 6663 } 6664 6665 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 6666 ExprResult &LHS, 6667 ExprResult &RHS, 6668 bool IsError) { 6669 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 6670 : diag::ext_typecheck_comparison_of_fptr_to_void) 6671 << LHS.get()->getType() << RHS.get()->getType() 6672 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6673 } 6674 6675 static bool isObjCObjectLiteral(ExprResult &E) { 6676 switch (E.get()->getStmtClass()) { 6677 case Stmt::ObjCArrayLiteralClass: 6678 case Stmt::ObjCDictionaryLiteralClass: 6679 case Stmt::ObjCStringLiteralClass: 6680 case Stmt::ObjCBoxedExprClass: 6681 return true; 6682 default: 6683 // Note that ObjCBoolLiteral is NOT an object literal! 6684 return false; 6685 } 6686 } 6687 6688 static DiagnosticBuilder diagnoseObjCLiteralComparison(Sema &S, 6689 SourceLocation Loc, 6690 ExprResult &LHS, 6691 ExprResult &RHS, 6692 bool CanFix = false) { 6693 Expr *Literal = (isObjCObjectLiteral(LHS) ? LHS : RHS).get(); 6694 6695 unsigned LiteralKind; 6696 switch (Literal->getStmtClass()) { 6697 case Stmt::ObjCStringLiteralClass: 6698 // "string literal" 6699 LiteralKind = 0; 6700 break; 6701 case Stmt::ObjCArrayLiteralClass: 6702 // "array literal" 6703 LiteralKind = 1; 6704 break; 6705 case Stmt::ObjCDictionaryLiteralClass: 6706 // "dictionary literal" 6707 LiteralKind = 2; 6708 break; 6709 case Stmt::ObjCBoxedExprClass: { 6710 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr(); 6711 switch (Inner->getStmtClass()) { 6712 case Stmt::IntegerLiteralClass: 6713 case Stmt::FloatingLiteralClass: 6714 case Stmt::CharacterLiteralClass: 6715 case Stmt::ObjCBoolLiteralExprClass: 6716 case Stmt::CXXBoolLiteralExprClass: 6717 // "numeric literal" 6718 LiteralKind = 3; 6719 break; 6720 case Stmt::ImplicitCastExprClass: { 6721 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 6722 // Boolean literals can be represented by implicit casts. 6723 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) { 6724 LiteralKind = 3; 6725 break; 6726 } 6727 // FALLTHROUGH 6728 } 6729 default: 6730 // "boxed expression" 6731 LiteralKind = 4; 6732 break; 6733 } 6734 break; 6735 } 6736 default: 6737 llvm_unreachable("Unknown Objective-C object literal kind"); 6738 } 6739 6740 return S.Diag(Loc, diag::err_objc_literal_comparison) 6741 << LiteralKind << CanFix << Literal->getSourceRange(); 6742 } 6743 6744 static ExprResult fixObjCLiteralComparison(Sema &S, SourceLocation OpLoc, 6745 ExprResult &LHS, 6746 ExprResult &RHS, 6747 BinaryOperatorKind Op) { 6748 assert((Op == BO_EQ || Op == BO_NE) && "Cannot fix other operations."); 6749 6750 // Get the LHS object's interface type. 6751 QualType Type = LHS.get()->getType(); 6752 QualType InterfaceType; 6753 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) { 6754 InterfaceType = PTy->getPointeeType(); 6755 if (const ObjCObjectType *iQFaceTy = 6756 InterfaceType->getAsObjCQualifiedInterfaceType()) 6757 InterfaceType = iQFaceTy->getBaseType(); 6758 } else { 6759 // If this is not actually an Objective-C object, bail out. 6760 return ExprEmpty(); 6761 } 6762 6763 // If the RHS isn't an Objective-C object, bail out. 6764 if (!RHS.get()->getType()->isObjCObjectPointerType()) 6765 return ExprEmpty(); 6766 6767 // Try to find the -isEqual: method. 6768 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 6769 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 6770 InterfaceType, 6771 /*instance=*/true); 6772 bool ReceiverIsId = (Type->isObjCIdType() || Type->isObjCQualifiedIdType()); 6773 6774 if (!Method && ReceiverIsId) { 6775 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 6776 /*receiverId=*/true, 6777 /*warn=*/false); 6778 } 6779 6780 if (!Method) 6781 return ExprEmpty(); 6782 6783 QualType T = Method->param_begin()[0]->getType(); 6784 if (!T->isObjCObjectPointerType()) 6785 return ExprEmpty(); 6786 6787 QualType R = Method->getResultType(); 6788 if (!R->isScalarType()) 6789 return ExprEmpty(); 6790 6791 // At this point we know we have a good -isEqual: method. 6792 // Emit the diagnostic and fixit. 6793 DiagnosticBuilder Diag = diagnoseObjCLiteralComparison(S, OpLoc, 6794 LHS, RHS, true); 6795 6796 Expr *LHSExpr = LHS.take(); 6797 Expr *RHSExpr = RHS.take(); 6798 6799 SourceLocation Start = LHSExpr->getLocStart(); 6800 SourceLocation End = S.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 6801 SourceRange OpRange(OpLoc, S.PP.getLocForEndOfToken(OpLoc)); 6802 6803 Diag << FixItHint::CreateInsertion(Start, Op == BO_EQ ? "[" : "![") 6804 << FixItHint::CreateReplacement(OpRange, "isEqual:") 6805 << FixItHint::CreateInsertion(End, "]"); 6806 6807 // Finally, build the call to -isEqual: (and possible logical not). 6808 ExprResult Call = S.BuildInstanceMessage(LHSExpr, LHSExpr->getType(), 6809 /*SuperLoc=*/SourceLocation(), 6810 IsEqualSel, Method, 6811 OpLoc, OpLoc, OpLoc, 6812 MultiExprArg(S, &RHSExpr, 1), 6813 /*isImplicit=*/false); 6814 6815 ExprResult CallCond = S.CheckBooleanCondition(Call.get(), OpLoc); 6816 6817 if (Op == BO_NE) 6818 return S.CreateBuiltinUnaryOp(OpLoc, UO_LNot, CallCond.get()); 6819 return CallCond; 6820 } 6821 6822 // C99 6.5.8, C++ [expr.rel] 6823 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 6824 SourceLocation Loc, unsigned OpaqueOpc, 6825 bool IsRelational) { 6826 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 6827 6828 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 6829 6830 // Handle vector comparisons separately. 6831 if (LHS.get()->getType()->isVectorType() || 6832 RHS.get()->getType()->isVectorType()) 6833 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 6834 6835 QualType LHSType = LHS.get()->getType(); 6836 QualType RHSType = RHS.get()->getType(); 6837 6838 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 6839 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 6840 6841 checkEnumComparison(*this, Loc, LHS, RHS); 6842 6843 if (!LHSType->hasFloatingRepresentation() && 6844 !(LHSType->isBlockPointerType() && IsRelational) && 6845 !LHS.get()->getLocStart().isMacroID() && 6846 !RHS.get()->getLocStart().isMacroID()) { 6847 // For non-floating point types, check for self-comparisons of the form 6848 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 6849 // often indicate logic errors in the program. 6850 // 6851 // NOTE: Don't warn about comparison expressions resulting from macro 6852 // expansion. Also don't warn about comparisons which are only self 6853 // comparisons within a template specialization. The warnings should catch 6854 // obvious cases in the definition of the template anyways. The idea is to 6855 // warn when the typed comparison operator will always evaluate to the same 6856 // result. 6857 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) { 6858 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) { 6859 if (DRL->getDecl() == DRR->getDecl() && 6860 !IsWithinTemplateSpecialization(DRL->getDecl())) { 6861 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 6862 << 0 // self- 6863 << (Opc == BO_EQ 6864 || Opc == BO_LE 6865 || Opc == BO_GE)); 6866 } else if (LHSType->isArrayType() && RHSType->isArrayType() && 6867 !DRL->getDecl()->getType()->isReferenceType() && 6868 !DRR->getDecl()->getType()->isReferenceType()) { 6869 // what is it always going to eval to? 6870 char always_evals_to; 6871 switch(Opc) { 6872 case BO_EQ: // e.g. array1 == array2 6873 always_evals_to = 0; // false 6874 break; 6875 case BO_NE: // e.g. array1 != array2 6876 always_evals_to = 1; // true 6877 break; 6878 default: 6879 // best we can say is 'a constant' 6880 always_evals_to = 2; // e.g. array1 <= array2 6881 break; 6882 } 6883 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 6884 << 1 // array 6885 << always_evals_to); 6886 } 6887 } 6888 } 6889 6890 if (isa<CastExpr>(LHSStripped)) 6891 LHSStripped = LHSStripped->IgnoreParenCasts(); 6892 if (isa<CastExpr>(RHSStripped)) 6893 RHSStripped = RHSStripped->IgnoreParenCasts(); 6894 6895 // Warn about comparisons against a string constant (unless the other 6896 // operand is null), the user probably wants strcmp. 6897 Expr *literalString = 0; 6898 Expr *literalStringStripped = 0; 6899 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 6900 !RHSStripped->isNullPointerConstant(Context, 6901 Expr::NPC_ValueDependentIsNull)) { 6902 literalString = LHS.get(); 6903 literalStringStripped = LHSStripped; 6904 } else if ((isa<StringLiteral>(RHSStripped) || 6905 isa<ObjCEncodeExpr>(RHSStripped)) && 6906 !LHSStripped->isNullPointerConstant(Context, 6907 Expr::NPC_ValueDependentIsNull)) { 6908 literalString = RHS.get(); 6909 literalStringStripped = RHSStripped; 6910 } 6911 6912 if (literalString) { 6913 std::string resultComparison; 6914 switch (Opc) { 6915 case BO_LT: resultComparison = ") < 0"; break; 6916 case BO_GT: resultComparison = ") > 0"; break; 6917 case BO_LE: resultComparison = ") <= 0"; break; 6918 case BO_GE: resultComparison = ") >= 0"; break; 6919 case BO_EQ: resultComparison = ") == 0"; break; 6920 case BO_NE: resultComparison = ") != 0"; break; 6921 default: llvm_unreachable("Invalid comparison operator"); 6922 } 6923 6924 DiagRuntimeBehavior(Loc, 0, 6925 PDiag(diag::warn_stringcompare) 6926 << isa<ObjCEncodeExpr>(literalStringStripped) 6927 << literalString->getSourceRange()); 6928 } 6929 } 6930 6931 // C99 6.5.8p3 / C99 6.5.9p4 6932 if (LHS.get()->getType()->isArithmeticType() && 6933 RHS.get()->getType()->isArithmeticType()) { 6934 UsualArithmeticConversions(LHS, RHS); 6935 if (LHS.isInvalid() || RHS.isInvalid()) 6936 return QualType(); 6937 } 6938 else { 6939 LHS = UsualUnaryConversions(LHS.take()); 6940 if (LHS.isInvalid()) 6941 return QualType(); 6942 6943 RHS = UsualUnaryConversions(RHS.take()); 6944 if (RHS.isInvalid()) 6945 return QualType(); 6946 } 6947 6948 LHSType = LHS.get()->getType(); 6949 RHSType = RHS.get()->getType(); 6950 6951 // The result of comparisons is 'bool' in C++, 'int' in C. 6952 QualType ResultTy = Context.getLogicalOperationType(); 6953 6954 if (IsRelational) { 6955 if (LHSType->isRealType() && RHSType->isRealType()) 6956 return ResultTy; 6957 } else { 6958 // Check for comparisons of floating point operands using != and ==. 6959 if (LHSType->hasFloatingRepresentation()) 6960 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 6961 6962 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 6963 return ResultTy; 6964 } 6965 6966 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context, 6967 Expr::NPC_ValueDependentIsNull); 6968 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context, 6969 Expr::NPC_ValueDependentIsNull); 6970 6971 // All of the following pointer-related warnings are GCC extensions, except 6972 // when handling null pointer constants. 6973 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 6974 QualType LCanPointeeTy = 6975 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 6976 QualType RCanPointeeTy = 6977 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 6978 6979 if (getLangOpts().CPlusPlus) { 6980 if (LCanPointeeTy == RCanPointeeTy) 6981 return ResultTy; 6982 if (!IsRelational && 6983 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 6984 // Valid unless comparison between non-null pointer and function pointer 6985 // This is a gcc extension compatibility comparison. 6986 // In a SFINAE context, we treat this as a hard error to maintain 6987 // conformance with the C++ standard. 6988 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 6989 && !LHSIsNull && !RHSIsNull) { 6990 diagnoseFunctionPointerToVoidComparison( 6991 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext()); 6992 6993 if (isSFINAEContext()) 6994 return QualType(); 6995 6996 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6997 return ResultTy; 6998 } 6999 } 7000 7001 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7002 return QualType(); 7003 else 7004 return ResultTy; 7005 } 7006 // C99 6.5.9p2 and C99 6.5.8p2 7007 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 7008 RCanPointeeTy.getUnqualifiedType())) { 7009 // Valid unless a relational comparison of function pointers 7010 if (IsRelational && LCanPointeeTy->isFunctionType()) { 7011 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 7012 << LHSType << RHSType << LHS.get()->getSourceRange() 7013 << RHS.get()->getSourceRange(); 7014 } 7015 } else if (!IsRelational && 7016 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7017 // Valid unless comparison between non-null pointer and function pointer 7018 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7019 && !LHSIsNull && !RHSIsNull) 7020 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 7021 /*isError*/false); 7022 } else { 7023 // Invalid 7024 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 7025 } 7026 if (LCanPointeeTy != RCanPointeeTy) { 7027 if (LHSIsNull && !RHSIsNull) 7028 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 7029 else 7030 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7031 } 7032 return ResultTy; 7033 } 7034 7035 if (getLangOpts().CPlusPlus) { 7036 // Comparison of nullptr_t with itself. 7037 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 7038 return ResultTy; 7039 7040 // Comparison of pointers with null pointer constants and equality 7041 // comparisons of member pointers to null pointer constants. 7042 if (RHSIsNull && 7043 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 7044 (!IsRelational && 7045 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 7046 RHS = ImpCastExprToType(RHS.take(), LHSType, 7047 LHSType->isMemberPointerType() 7048 ? CK_NullToMemberPointer 7049 : CK_NullToPointer); 7050 return ResultTy; 7051 } 7052 if (LHSIsNull && 7053 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 7054 (!IsRelational && 7055 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 7056 LHS = ImpCastExprToType(LHS.take(), RHSType, 7057 RHSType->isMemberPointerType() 7058 ? CK_NullToMemberPointer 7059 : CK_NullToPointer); 7060 return ResultTy; 7061 } 7062 7063 // Comparison of member pointers. 7064 if (!IsRelational && 7065 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 7066 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7067 return QualType(); 7068 else 7069 return ResultTy; 7070 } 7071 7072 // Handle scoped enumeration types specifically, since they don't promote 7073 // to integers. 7074 if (LHS.get()->getType()->isEnumeralType() && 7075 Context.hasSameUnqualifiedType(LHS.get()->getType(), 7076 RHS.get()->getType())) 7077 return ResultTy; 7078 } 7079 7080 // Handle block pointer types. 7081 if (!IsRelational && LHSType->isBlockPointerType() && 7082 RHSType->isBlockPointerType()) { 7083 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 7084 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 7085 7086 if (!LHSIsNull && !RHSIsNull && 7087 !Context.typesAreCompatible(lpointee, rpointee)) { 7088 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7089 << LHSType << RHSType << LHS.get()->getSourceRange() 7090 << RHS.get()->getSourceRange(); 7091 } 7092 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7093 return ResultTy; 7094 } 7095 7096 // Allow block pointers to be compared with null pointer constants. 7097 if (!IsRelational 7098 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 7099 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 7100 if (!LHSIsNull && !RHSIsNull) { 7101 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 7102 ->getPointeeType()->isVoidType()) 7103 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 7104 ->getPointeeType()->isVoidType()))) 7105 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7106 << LHSType << RHSType << LHS.get()->getSourceRange() 7107 << RHS.get()->getSourceRange(); 7108 } 7109 if (LHSIsNull && !RHSIsNull) 7110 LHS = ImpCastExprToType(LHS.take(), RHSType, 7111 RHSType->isPointerType() ? CK_BitCast 7112 : CK_AnyPointerToBlockPointerCast); 7113 else 7114 RHS = ImpCastExprToType(RHS.take(), LHSType, 7115 LHSType->isPointerType() ? CK_BitCast 7116 : CK_AnyPointerToBlockPointerCast); 7117 return ResultTy; 7118 } 7119 7120 if (LHSType->isObjCObjectPointerType() || 7121 RHSType->isObjCObjectPointerType()) { 7122 const PointerType *LPT = LHSType->getAs<PointerType>(); 7123 const PointerType *RPT = RHSType->getAs<PointerType>(); 7124 if (LPT || RPT) { 7125 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 7126 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 7127 7128 if (!LPtrToVoid && !RPtrToVoid && 7129 !Context.typesAreCompatible(LHSType, RHSType)) { 7130 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 7131 /*isError*/false); 7132 } 7133 if (LHSIsNull && !RHSIsNull) 7134 LHS = ImpCastExprToType(LHS.take(), RHSType, 7135 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 7136 else 7137 RHS = ImpCastExprToType(RHS.take(), LHSType, 7138 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 7139 return ResultTy; 7140 } 7141 if (LHSType->isObjCObjectPointerType() && 7142 RHSType->isObjCObjectPointerType()) { 7143 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 7144 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 7145 /*isError*/false); 7146 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 7147 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS); 7148 7149 if (LHSIsNull && !RHSIsNull) 7150 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 7151 else 7152 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7153 return ResultTy; 7154 } 7155 } 7156 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 7157 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 7158 unsigned DiagID = 0; 7159 bool isError = false; 7160 if ((LHSIsNull && LHSType->isIntegerType()) || 7161 (RHSIsNull && RHSType->isIntegerType())) { 7162 if (IsRelational && !getLangOpts().CPlusPlus) 7163 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 7164 } else if (IsRelational && !getLangOpts().CPlusPlus) 7165 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 7166 else if (getLangOpts().CPlusPlus) { 7167 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 7168 isError = true; 7169 } else 7170 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 7171 7172 if (DiagID) { 7173 Diag(Loc, DiagID) 7174 << LHSType << RHSType << LHS.get()->getSourceRange() 7175 << RHS.get()->getSourceRange(); 7176 if (isError) 7177 return QualType(); 7178 } 7179 7180 if (LHSType->isIntegerType()) 7181 LHS = ImpCastExprToType(LHS.take(), RHSType, 7182 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 7183 else 7184 RHS = ImpCastExprToType(RHS.take(), LHSType, 7185 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 7186 return ResultTy; 7187 } 7188 7189 // Handle block pointers. 7190 if (!IsRelational && RHSIsNull 7191 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 7192 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 7193 return ResultTy; 7194 } 7195 if (!IsRelational && LHSIsNull 7196 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 7197 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer); 7198 return ResultTy; 7199 } 7200 7201 return InvalidOperands(Loc, LHS, RHS); 7202 } 7203 7204 7205 // Return a signed type that is of identical size and number of elements. 7206 // For floating point vectors, return an integer type of identical size 7207 // and number of elements. 7208 QualType Sema::GetSignedVectorType(QualType V) { 7209 const VectorType *VTy = V->getAs<VectorType>(); 7210 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 7211 if (TypeSize == Context.getTypeSize(Context.CharTy)) 7212 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 7213 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 7214 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 7215 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 7216 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 7217 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 7218 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 7219 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 7220 "Unhandled vector element size in vector compare"); 7221 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 7222 } 7223 7224 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 7225 /// operates on extended vector types. Instead of producing an IntTy result, 7226 /// like a scalar comparison, a vector comparison produces a vector of integer 7227 /// types. 7228 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 7229 SourceLocation Loc, 7230 bool IsRelational) { 7231 // Check to make sure we're operating on vectors of the same type and width, 7232 // Allowing one side to be a scalar of element type. 7233 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false); 7234 if (vType.isNull()) 7235 return vType; 7236 7237 QualType LHSType = LHS.get()->getType(); 7238 7239 // If AltiVec, the comparison results in a numeric type, i.e. 7240 // bool for C++, int for C 7241 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 7242 return Context.getLogicalOperationType(); 7243 7244 // For non-floating point types, check for self-comparisons of the form 7245 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7246 // often indicate logic errors in the program. 7247 if (!LHSType->hasFloatingRepresentation()) { 7248 if (DeclRefExpr* DRL 7249 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 7250 if (DeclRefExpr* DRR 7251 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 7252 if (DRL->getDecl() == DRR->getDecl()) 7253 DiagRuntimeBehavior(Loc, 0, 7254 PDiag(diag::warn_comparison_always) 7255 << 0 // self- 7256 << 2 // "a constant" 7257 ); 7258 } 7259 7260 // Check for comparisons of floating point operands using != and ==. 7261 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 7262 assert (RHS.get()->getType()->hasFloatingRepresentation()); 7263 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7264 } 7265 7266 // Return a signed type for the vector. 7267 return GetSignedVectorType(LHSType); 7268 } 7269 7270 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 7271 SourceLocation Loc) { 7272 // Ensure that either both operands are of the same vector type, or 7273 // one operand is of a vector type and the other is of its element type. 7274 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false); 7275 if (vType.isNull() || vType->isFloatingType()) 7276 return InvalidOperands(Loc, LHS, RHS); 7277 7278 return GetSignedVectorType(LHS.get()->getType()); 7279 } 7280 7281 inline QualType Sema::CheckBitwiseOperands( 7282 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 7283 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7284 7285 if (LHS.get()->getType()->isVectorType() || 7286 RHS.get()->getType()->isVectorType()) { 7287 if (LHS.get()->getType()->hasIntegerRepresentation() && 7288 RHS.get()->getType()->hasIntegerRepresentation()) 7289 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 7290 7291 return InvalidOperands(Loc, LHS, RHS); 7292 } 7293 7294 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS); 7295 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 7296 IsCompAssign); 7297 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 7298 return QualType(); 7299 LHS = LHSResult.take(); 7300 RHS = RHSResult.take(); 7301 7302 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 7303 return compType; 7304 return InvalidOperands(Loc, LHS, RHS); 7305 } 7306 7307 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 7308 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 7309 7310 // Check vector operands differently. 7311 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 7312 return CheckVectorLogicalOperands(LHS, RHS, Loc); 7313 7314 // Diagnose cases where the user write a logical and/or but probably meant a 7315 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 7316 // is a constant. 7317 if (LHS.get()->getType()->isIntegerType() && 7318 !LHS.get()->getType()->isBooleanType() && 7319 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 7320 // Don't warn in macros or template instantiations. 7321 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 7322 // If the RHS can be constant folded, and if it constant folds to something 7323 // that isn't 0 or 1 (which indicate a potential logical operation that 7324 // happened to fold to true/false) then warn. 7325 // Parens on the RHS are ignored. 7326 llvm::APSInt Result; 7327 if (RHS.get()->EvaluateAsInt(Result, Context)) 7328 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) || 7329 (Result != 0 && Result != 1)) { 7330 Diag(Loc, diag::warn_logical_instead_of_bitwise) 7331 << RHS.get()->getSourceRange() 7332 << (Opc == BO_LAnd ? "&&" : "||"); 7333 // Suggest replacing the logical operator with the bitwise version 7334 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 7335 << (Opc == BO_LAnd ? "&" : "|") 7336 << FixItHint::CreateReplacement(SourceRange( 7337 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 7338 getLangOpts())), 7339 Opc == BO_LAnd ? "&" : "|"); 7340 if (Opc == BO_LAnd) 7341 // Suggest replacing "Foo() && kNonZero" with "Foo()" 7342 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 7343 << FixItHint::CreateRemoval( 7344 SourceRange( 7345 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 7346 0, getSourceManager(), 7347 getLangOpts()), 7348 RHS.get()->getLocEnd())); 7349 } 7350 } 7351 7352 if (!Context.getLangOpts().CPlusPlus) { 7353 LHS = UsualUnaryConversions(LHS.take()); 7354 if (LHS.isInvalid()) 7355 return QualType(); 7356 7357 RHS = UsualUnaryConversions(RHS.take()); 7358 if (RHS.isInvalid()) 7359 return QualType(); 7360 7361 if (!LHS.get()->getType()->isScalarType() || 7362 !RHS.get()->getType()->isScalarType()) 7363 return InvalidOperands(Loc, LHS, RHS); 7364 7365 return Context.IntTy; 7366 } 7367 7368 // The following is safe because we only use this method for 7369 // non-overloadable operands. 7370 7371 // C++ [expr.log.and]p1 7372 // C++ [expr.log.or]p1 7373 // The operands are both contextually converted to type bool. 7374 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 7375 if (LHSRes.isInvalid()) 7376 return InvalidOperands(Loc, LHS, RHS); 7377 LHS = move(LHSRes); 7378 7379 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 7380 if (RHSRes.isInvalid()) 7381 return InvalidOperands(Loc, LHS, RHS); 7382 RHS = move(RHSRes); 7383 7384 // C++ [expr.log.and]p2 7385 // C++ [expr.log.or]p2 7386 // The result is a bool. 7387 return Context.BoolTy; 7388 } 7389 7390 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression 7391 /// is a read-only property; return true if so. A readonly property expression 7392 /// depends on various declarations and thus must be treated specially. 7393 /// 7394 static bool IsReadonlyProperty(Expr *E, Sema &S) { 7395 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E); 7396 if (!PropExpr) return false; 7397 if (PropExpr->isImplicitProperty()) return false; 7398 7399 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty(); 7400 QualType BaseType = PropExpr->isSuperReceiver() ? 7401 PropExpr->getSuperReceiverType() : 7402 PropExpr->getBase()->getType(); 7403 7404 if (const ObjCObjectPointerType *OPT = 7405 BaseType->getAsObjCInterfacePointerType()) 7406 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl()) 7407 if (S.isPropertyReadonly(PDecl, IFace)) 7408 return true; 7409 return false; 7410 } 7411 7412 static bool IsReadonlyMessage(Expr *E, Sema &S) { 7413 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 7414 if (!ME) return false; 7415 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 7416 ObjCMessageExpr *Base = 7417 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 7418 if (!Base) return false; 7419 return Base->getMethodDecl() != 0; 7420 } 7421 7422 /// Is the given expression (which must be 'const') a reference to a 7423 /// variable which was originally non-const, but which has become 7424 /// 'const' due to being captured within a block? 7425 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 7426 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 7427 assert(E->isLValue() && E->getType().isConstQualified()); 7428 E = E->IgnoreParens(); 7429 7430 // Must be a reference to a declaration from an enclosing scope. 7431 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 7432 if (!DRE) return NCCK_None; 7433 if (!DRE->refersToEnclosingLocal()) return NCCK_None; 7434 7435 // The declaration must be a variable which is not declared 'const'. 7436 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 7437 if (!var) return NCCK_None; 7438 if (var->getType().isConstQualified()) return NCCK_None; 7439 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 7440 7441 // Decide whether the first capture was for a block or a lambda. 7442 DeclContext *DC = S.CurContext; 7443 while (DC->getParent() != var->getDeclContext()) 7444 DC = DC->getParent(); 7445 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 7446 } 7447 7448 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 7449 /// emit an error and return true. If so, return false. 7450 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 7451 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 7452 SourceLocation OrigLoc = Loc; 7453 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 7454 &Loc); 7455 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S)) 7456 IsLV = Expr::MLV_ReadonlyProperty; 7457 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 7458 IsLV = Expr::MLV_InvalidMessageExpression; 7459 if (IsLV == Expr::MLV_Valid) 7460 return false; 7461 7462 unsigned Diag = 0; 7463 bool NeedType = false; 7464 switch (IsLV) { // C99 6.5.16p2 7465 case Expr::MLV_ConstQualified: 7466 Diag = diag::err_typecheck_assign_const; 7467 7468 // Use a specialized diagnostic when we're assigning to an object 7469 // from an enclosing function or block. 7470 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 7471 if (NCCK == NCCK_Block) 7472 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 7473 else 7474 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue; 7475 break; 7476 } 7477 7478 // In ARC, use some specialized diagnostics for occasions where we 7479 // infer 'const'. These are always pseudo-strong variables. 7480 if (S.getLangOpts().ObjCAutoRefCount) { 7481 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 7482 if (declRef && isa<VarDecl>(declRef->getDecl())) { 7483 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 7484 7485 // Use the normal diagnostic if it's pseudo-__strong but the 7486 // user actually wrote 'const'. 7487 if (var->isARCPseudoStrong() && 7488 (!var->getTypeSourceInfo() || 7489 !var->getTypeSourceInfo()->getType().isConstQualified())) { 7490 // There are two pseudo-strong cases: 7491 // - self 7492 ObjCMethodDecl *method = S.getCurMethodDecl(); 7493 if (method && var == method->getSelfDecl()) 7494 Diag = method->isClassMethod() 7495 ? diag::err_typecheck_arc_assign_self_class_method 7496 : diag::err_typecheck_arc_assign_self; 7497 7498 // - fast enumeration variables 7499 else 7500 Diag = diag::err_typecheck_arr_assign_enumeration; 7501 7502 SourceRange Assign; 7503 if (Loc != OrigLoc) 7504 Assign = SourceRange(OrigLoc, OrigLoc); 7505 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 7506 // We need to preserve the AST regardless, so migration tool 7507 // can do its job. 7508 return false; 7509 } 7510 } 7511 } 7512 7513 break; 7514 case Expr::MLV_ArrayType: 7515 case Expr::MLV_ArrayTemporary: 7516 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 7517 NeedType = true; 7518 break; 7519 case Expr::MLV_NotObjectType: 7520 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 7521 NeedType = true; 7522 break; 7523 case Expr::MLV_LValueCast: 7524 Diag = diag::err_typecheck_lvalue_casts_not_supported; 7525 break; 7526 case Expr::MLV_Valid: 7527 llvm_unreachable("did not take early return for MLV_Valid"); 7528 case Expr::MLV_InvalidExpression: 7529 case Expr::MLV_MemberFunction: 7530 case Expr::MLV_ClassTemporary: 7531 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 7532 break; 7533 case Expr::MLV_IncompleteType: 7534 case Expr::MLV_IncompleteVoidType: 7535 return S.RequireCompleteType(Loc, E->getType(), 7536 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 7537 case Expr::MLV_DuplicateVectorComponents: 7538 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 7539 break; 7540 case Expr::MLV_ReadonlyProperty: 7541 case Expr::MLV_NoSetterProperty: 7542 llvm_unreachable("readonly properties should be processed differently"); 7543 case Expr::MLV_InvalidMessageExpression: 7544 Diag = diag::error_readonly_message_assignment; 7545 break; 7546 case Expr::MLV_SubObjCPropertySetting: 7547 Diag = diag::error_no_subobject_property_setting; 7548 break; 7549 } 7550 7551 SourceRange Assign; 7552 if (Loc != OrigLoc) 7553 Assign = SourceRange(OrigLoc, OrigLoc); 7554 if (NeedType) 7555 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 7556 else 7557 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 7558 return true; 7559 } 7560 7561 static void CheckIdentityMemvarAssignment(Expr *LHSExpr, Expr *RHSExpr, 7562 SourceLocation Loc, 7563 Sema &Sema) { 7564 // C / C++ memvars 7565 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 7566 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 7567 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 7568 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 7569 Sema.Diag(Loc, diag::warn_identity_memvar_assign) << 0; 7570 } 7571 7572 // Objective-C memvars 7573 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 7574 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 7575 if (OL && OR && OL->getDecl() == OR->getDecl()) { 7576 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 7577 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 7578 if (RL && RR && RL->getDecl() == RR->getDecl()) 7579 Sema.Diag(Loc, diag::warn_identity_memvar_assign) << 1; 7580 } 7581 } 7582 7583 // C99 6.5.16.1 7584 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 7585 SourceLocation Loc, 7586 QualType CompoundType) { 7587 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 7588 7589 // Verify that LHS is a modifiable lvalue, and emit error if not. 7590 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 7591 return QualType(); 7592 7593 QualType LHSType = LHSExpr->getType(); 7594 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 7595 CompoundType; 7596 AssignConvertType ConvTy; 7597 if (CompoundType.isNull()) { 7598 Expr *RHSCheck = RHS.get(); 7599 7600 CheckIdentityMemvarAssignment(LHSExpr, RHSCheck, Loc, *this); 7601 7602 QualType LHSTy(LHSType); 7603 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 7604 if (RHS.isInvalid()) 7605 return QualType(); 7606 // Special case of NSObject attributes on c-style pointer types. 7607 if (ConvTy == IncompatiblePointer && 7608 ((Context.isObjCNSObjectType(LHSType) && 7609 RHSType->isObjCObjectPointerType()) || 7610 (Context.isObjCNSObjectType(RHSType) && 7611 LHSType->isObjCObjectPointerType()))) 7612 ConvTy = Compatible; 7613 7614 if (ConvTy == Compatible && 7615 LHSType->isObjCObjectType()) 7616 Diag(Loc, diag::err_objc_object_assignment) 7617 << LHSType; 7618 7619 // If the RHS is a unary plus or minus, check to see if they = and + are 7620 // right next to each other. If so, the user may have typo'd "x =+ 4" 7621 // instead of "x += 4". 7622 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 7623 RHSCheck = ICE->getSubExpr(); 7624 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 7625 if ((UO->getOpcode() == UO_Plus || 7626 UO->getOpcode() == UO_Minus) && 7627 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 7628 // Only if the two operators are exactly adjacent. 7629 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 7630 // And there is a space or other character before the subexpr of the 7631 // unary +/-. We don't want to warn on "x=-1". 7632 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 7633 UO->getSubExpr()->getLocStart().isFileID()) { 7634 Diag(Loc, diag::warn_not_compound_assign) 7635 << (UO->getOpcode() == UO_Plus ? "+" : "-") 7636 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 7637 } 7638 } 7639 7640 if (ConvTy == Compatible) { 7641 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) 7642 checkRetainCycles(LHSExpr, RHS.get()); 7643 else if (getLangOpts().ObjCAutoRefCount) 7644 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 7645 } 7646 } else { 7647 // Compound assignment "x += y" 7648 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 7649 } 7650 7651 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 7652 RHS.get(), AA_Assigning)) 7653 return QualType(); 7654 7655 CheckForNullPointerDereference(*this, LHSExpr); 7656 7657 // C99 6.5.16p3: The type of an assignment expression is the type of the 7658 // left operand unless the left operand has qualified type, in which case 7659 // it is the unqualified version of the type of the left operand. 7660 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 7661 // is converted to the type of the assignment expression (above). 7662 // C++ 5.17p1: the type of the assignment expression is that of its left 7663 // operand. 7664 return (getLangOpts().CPlusPlus 7665 ? LHSType : LHSType.getUnqualifiedType()); 7666 } 7667 7668 // C99 6.5.17 7669 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 7670 SourceLocation Loc) { 7671 LHS = S.CheckPlaceholderExpr(LHS.take()); 7672 RHS = S.CheckPlaceholderExpr(RHS.take()); 7673 if (LHS.isInvalid() || RHS.isInvalid()) 7674 return QualType(); 7675 7676 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 7677 // operands, but not unary promotions. 7678 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 7679 7680 // So we treat the LHS as a ignored value, and in C++ we allow the 7681 // containing site to determine what should be done with the RHS. 7682 LHS = S.IgnoredValueConversions(LHS.take()); 7683 if (LHS.isInvalid()) 7684 return QualType(); 7685 7686 S.DiagnoseUnusedExprResult(LHS.get()); 7687 7688 if (!S.getLangOpts().CPlusPlus) { 7689 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take()); 7690 if (RHS.isInvalid()) 7691 return QualType(); 7692 if (!RHS.get()->getType()->isVoidType()) 7693 S.RequireCompleteType(Loc, RHS.get()->getType(), 7694 diag::err_incomplete_type); 7695 } 7696 7697 return RHS.get()->getType(); 7698 } 7699 7700 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 7701 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 7702 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 7703 ExprValueKind &VK, 7704 SourceLocation OpLoc, 7705 bool IsInc, bool IsPrefix) { 7706 if (Op->isTypeDependent()) 7707 return S.Context.DependentTy; 7708 7709 QualType ResType = Op->getType(); 7710 // Atomic types can be used for increment / decrement where the non-atomic 7711 // versions can, so ignore the _Atomic() specifier for the purpose of 7712 // checking. 7713 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7714 ResType = ResAtomicType->getValueType(); 7715 7716 assert(!ResType.isNull() && "no type for increment/decrement expression"); 7717 7718 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 7719 // Decrement of bool is not allowed. 7720 if (!IsInc) { 7721 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 7722 return QualType(); 7723 } 7724 // Increment of bool sets it to true, but is deprecated. 7725 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 7726 } else if (ResType->isRealType()) { 7727 // OK! 7728 } else if (ResType->isAnyPointerType()) { 7729 // C99 6.5.2.4p2, 6.5.6p2 7730 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 7731 return QualType(); 7732 7733 // Diagnose bad cases where we step over interface counts. 7734 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op)) 7735 return QualType(); 7736 } else if (ResType->isAnyComplexType()) { 7737 // C99 does not support ++/-- on complex types, we allow as an extension. 7738 S.Diag(OpLoc, diag::ext_integer_increment_complex) 7739 << ResType << Op->getSourceRange(); 7740 } else if (ResType->isPlaceholderType()) { 7741 ExprResult PR = S.CheckPlaceholderExpr(Op); 7742 if (PR.isInvalid()) return QualType(); 7743 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc, 7744 IsInc, IsPrefix); 7745 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 7746 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 7747 } else { 7748 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 7749 << ResType << int(IsInc) << Op->getSourceRange(); 7750 return QualType(); 7751 } 7752 // At this point, we know we have a real, complex or pointer type. 7753 // Now make sure the operand is a modifiable lvalue. 7754 if (CheckForModifiableLvalue(Op, OpLoc, S)) 7755 return QualType(); 7756 // In C++, a prefix increment is the same type as the operand. Otherwise 7757 // (in C or with postfix), the increment is the unqualified type of the 7758 // operand. 7759 if (IsPrefix && S.getLangOpts().CPlusPlus) { 7760 VK = VK_LValue; 7761 return ResType; 7762 } else { 7763 VK = VK_RValue; 7764 return ResType.getUnqualifiedType(); 7765 } 7766 } 7767 7768 7769 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 7770 /// This routine allows us to typecheck complex/recursive expressions 7771 /// where the declaration is needed for type checking. We only need to 7772 /// handle cases when the expression references a function designator 7773 /// or is an lvalue. Here are some examples: 7774 /// - &(x) => x 7775 /// - &*****f => f for f a function designator. 7776 /// - &s.xx => s 7777 /// - &s.zz[1].yy -> s, if zz is an array 7778 /// - *(x + 1) -> x, if x is an array 7779 /// - &"123"[2] -> 0 7780 /// - & __real__ x -> x 7781 static ValueDecl *getPrimaryDecl(Expr *E) { 7782 switch (E->getStmtClass()) { 7783 case Stmt::DeclRefExprClass: 7784 return cast<DeclRefExpr>(E)->getDecl(); 7785 case Stmt::MemberExprClass: 7786 // If this is an arrow operator, the address is an offset from 7787 // the base's value, so the object the base refers to is 7788 // irrelevant. 7789 if (cast<MemberExpr>(E)->isArrow()) 7790 return 0; 7791 // Otherwise, the expression refers to a part of the base 7792 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 7793 case Stmt::ArraySubscriptExprClass: { 7794 // FIXME: This code shouldn't be necessary! We should catch the implicit 7795 // promotion of register arrays earlier. 7796 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 7797 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 7798 if (ICE->getSubExpr()->getType()->isArrayType()) 7799 return getPrimaryDecl(ICE->getSubExpr()); 7800 } 7801 return 0; 7802 } 7803 case Stmt::UnaryOperatorClass: { 7804 UnaryOperator *UO = cast<UnaryOperator>(E); 7805 7806 switch(UO->getOpcode()) { 7807 case UO_Real: 7808 case UO_Imag: 7809 case UO_Extension: 7810 return getPrimaryDecl(UO->getSubExpr()); 7811 default: 7812 return 0; 7813 } 7814 } 7815 case Stmt::ParenExprClass: 7816 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 7817 case Stmt::ImplicitCastExprClass: 7818 // If the result of an implicit cast is an l-value, we care about 7819 // the sub-expression; otherwise, the result here doesn't matter. 7820 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 7821 default: 7822 return 0; 7823 } 7824 } 7825 7826 namespace { 7827 enum { 7828 AO_Bit_Field = 0, 7829 AO_Vector_Element = 1, 7830 AO_Property_Expansion = 2, 7831 AO_Register_Variable = 3, 7832 AO_No_Error = 4 7833 }; 7834 } 7835 /// \brief Diagnose invalid operand for address of operations. 7836 /// 7837 /// \param Type The type of operand which cannot have its address taken. 7838 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 7839 Expr *E, unsigned Type) { 7840 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 7841 } 7842 7843 /// CheckAddressOfOperand - The operand of & must be either a function 7844 /// designator or an lvalue designating an object. If it is an lvalue, the 7845 /// object cannot be declared with storage class register or be a bit field. 7846 /// Note: The usual conversions are *not* applied to the operand of the & 7847 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 7848 /// In C++, the operand might be an overloaded function name, in which case 7849 /// we allow the '&' but retain the overloaded-function type. 7850 static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp, 7851 SourceLocation OpLoc) { 7852 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 7853 if (PTy->getKind() == BuiltinType::Overload) { 7854 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) { 7855 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 7856 << OrigOp.get()->getSourceRange(); 7857 return QualType(); 7858 } 7859 7860 return S.Context.OverloadTy; 7861 } 7862 7863 if (PTy->getKind() == BuiltinType::UnknownAny) 7864 return S.Context.UnknownAnyTy; 7865 7866 if (PTy->getKind() == BuiltinType::BoundMember) { 7867 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 7868 << OrigOp.get()->getSourceRange(); 7869 return QualType(); 7870 } 7871 7872 OrigOp = S.CheckPlaceholderExpr(OrigOp.take()); 7873 if (OrigOp.isInvalid()) return QualType(); 7874 } 7875 7876 if (OrigOp.get()->isTypeDependent()) 7877 return S.Context.DependentTy; 7878 7879 assert(!OrigOp.get()->getType()->isPlaceholderType()); 7880 7881 // Make sure to ignore parentheses in subsequent checks 7882 Expr *op = OrigOp.get()->IgnoreParens(); 7883 7884 if (S.getLangOpts().C99) { 7885 // Implement C99-only parts of addressof rules. 7886 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 7887 if (uOp->getOpcode() == UO_Deref) 7888 // Per C99 6.5.3.2, the address of a deref always returns a valid result 7889 // (assuming the deref expression is valid). 7890 return uOp->getSubExpr()->getType(); 7891 } 7892 // Technically, there should be a check for array subscript 7893 // expressions here, but the result of one is always an lvalue anyway. 7894 } 7895 ValueDecl *dcl = getPrimaryDecl(op); 7896 Expr::LValueClassification lval = op->ClassifyLValue(S.Context); 7897 unsigned AddressOfError = AO_No_Error; 7898 7899 if (lval == Expr::LV_ClassTemporary) { 7900 bool sfinae = S.isSFINAEContext(); 7901 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary 7902 : diag::ext_typecheck_addrof_class_temporary) 7903 << op->getType() << op->getSourceRange(); 7904 if (sfinae) 7905 return QualType(); 7906 } else if (isa<ObjCSelectorExpr>(op)) { 7907 return S.Context.getPointerType(op->getType()); 7908 } else if (lval == Expr::LV_MemberFunction) { 7909 // If it's an instance method, make a member pointer. 7910 // The expression must have exactly the form &A::foo. 7911 7912 // If the underlying expression isn't a decl ref, give up. 7913 if (!isa<DeclRefExpr>(op)) { 7914 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 7915 << OrigOp.get()->getSourceRange(); 7916 return QualType(); 7917 } 7918 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 7919 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 7920 7921 // The id-expression was parenthesized. 7922 if (OrigOp.get() != DRE) { 7923 S.Diag(OpLoc, diag::err_parens_pointer_member_function) 7924 << OrigOp.get()->getSourceRange(); 7925 7926 // The method was named without a qualifier. 7927 } else if (!DRE->getQualifier()) { 7928 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function) 7929 << op->getSourceRange(); 7930 } 7931 7932 return S.Context.getMemberPointerType(op->getType(), 7933 S.Context.getTypeDeclType(MD->getParent()).getTypePtr()); 7934 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 7935 // C99 6.5.3.2p1 7936 // The operand must be either an l-value or a function designator 7937 if (!op->getType()->isFunctionType()) { 7938 // Use a special diagnostic for loads from property references. 7939 if (isa<PseudoObjectExpr>(op)) { 7940 AddressOfError = AO_Property_Expansion; 7941 } else { 7942 // FIXME: emit more specific diag... 7943 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 7944 << op->getSourceRange(); 7945 return QualType(); 7946 } 7947 } 7948 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 7949 // The operand cannot be a bit-field 7950 AddressOfError = AO_Bit_Field; 7951 } else if (op->getObjectKind() == OK_VectorComponent) { 7952 // The operand cannot be an element of a vector 7953 AddressOfError = AO_Vector_Element; 7954 } else if (dcl) { // C99 6.5.3.2p1 7955 // We have an lvalue with a decl. Make sure the decl is not declared 7956 // with the register storage-class specifier. 7957 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 7958 // in C++ it is not error to take address of a register 7959 // variable (c++03 7.1.1P3) 7960 if (vd->getStorageClass() == SC_Register && 7961 !S.getLangOpts().CPlusPlus) { 7962 AddressOfError = AO_Register_Variable; 7963 } 7964 } else if (isa<FunctionTemplateDecl>(dcl)) { 7965 return S.Context.OverloadTy; 7966 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 7967 // Okay: we can take the address of a field. 7968 // Could be a pointer to member, though, if there is an explicit 7969 // scope qualifier for the class. 7970 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 7971 DeclContext *Ctx = dcl->getDeclContext(); 7972 if (Ctx && Ctx->isRecord()) { 7973 if (dcl->getType()->isReferenceType()) { 7974 S.Diag(OpLoc, 7975 diag::err_cannot_form_pointer_to_member_of_reference_type) 7976 << dcl->getDeclName() << dcl->getType(); 7977 return QualType(); 7978 } 7979 7980 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 7981 Ctx = Ctx->getParent(); 7982 return S.Context.getMemberPointerType(op->getType(), 7983 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 7984 } 7985 } 7986 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 7987 llvm_unreachable("Unknown/unexpected decl type"); 7988 } 7989 7990 if (AddressOfError != AO_No_Error) { 7991 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError); 7992 return QualType(); 7993 } 7994 7995 if (lval == Expr::LV_IncompleteVoidType) { 7996 // Taking the address of a void variable is technically illegal, but we 7997 // allow it in cases which are otherwise valid. 7998 // Example: "extern void x; void* y = &x;". 7999 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 8000 } 8001 8002 // If the operand has type "type", the result has type "pointer to type". 8003 if (op->getType()->isObjCObjectType()) 8004 return S.Context.getObjCObjectPointerType(op->getType()); 8005 return S.Context.getPointerType(op->getType()); 8006 } 8007 8008 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 8009 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 8010 SourceLocation OpLoc) { 8011 if (Op->isTypeDependent()) 8012 return S.Context.DependentTy; 8013 8014 ExprResult ConvResult = S.UsualUnaryConversions(Op); 8015 if (ConvResult.isInvalid()) 8016 return QualType(); 8017 Op = ConvResult.take(); 8018 QualType OpTy = Op->getType(); 8019 QualType Result; 8020 8021 if (isa<CXXReinterpretCastExpr>(Op)) { 8022 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 8023 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 8024 Op->getSourceRange()); 8025 } 8026 8027 // Note that per both C89 and C99, indirection is always legal, even if OpTy 8028 // is an incomplete type or void. It would be possible to warn about 8029 // dereferencing a void pointer, but it's completely well-defined, and such a 8030 // warning is unlikely to catch any mistakes. 8031 if (const PointerType *PT = OpTy->getAs<PointerType>()) 8032 Result = PT->getPointeeType(); 8033 else if (const ObjCObjectPointerType *OPT = 8034 OpTy->getAs<ObjCObjectPointerType>()) 8035 Result = OPT->getPointeeType(); 8036 else { 8037 ExprResult PR = S.CheckPlaceholderExpr(Op); 8038 if (PR.isInvalid()) return QualType(); 8039 if (PR.take() != Op) 8040 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc); 8041 } 8042 8043 if (Result.isNull()) { 8044 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 8045 << OpTy << Op->getSourceRange(); 8046 return QualType(); 8047 } 8048 8049 // Dereferences are usually l-values... 8050 VK = VK_LValue; 8051 8052 // ...except that certain expressions are never l-values in C. 8053 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 8054 VK = VK_RValue; 8055 8056 return Result; 8057 } 8058 8059 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 8060 tok::TokenKind Kind) { 8061 BinaryOperatorKind Opc; 8062 switch (Kind) { 8063 default: llvm_unreachable("Unknown binop!"); 8064 case tok::periodstar: Opc = BO_PtrMemD; break; 8065 case tok::arrowstar: Opc = BO_PtrMemI; break; 8066 case tok::star: Opc = BO_Mul; break; 8067 case tok::slash: Opc = BO_Div; break; 8068 case tok::percent: Opc = BO_Rem; break; 8069 case tok::plus: Opc = BO_Add; break; 8070 case tok::minus: Opc = BO_Sub; break; 8071 case tok::lessless: Opc = BO_Shl; break; 8072 case tok::greatergreater: Opc = BO_Shr; break; 8073 case tok::lessequal: Opc = BO_LE; break; 8074 case tok::less: Opc = BO_LT; break; 8075 case tok::greaterequal: Opc = BO_GE; break; 8076 case tok::greater: Opc = BO_GT; break; 8077 case tok::exclaimequal: Opc = BO_NE; break; 8078 case tok::equalequal: Opc = BO_EQ; break; 8079 case tok::amp: Opc = BO_And; break; 8080 case tok::caret: Opc = BO_Xor; break; 8081 case tok::pipe: Opc = BO_Or; break; 8082 case tok::ampamp: Opc = BO_LAnd; break; 8083 case tok::pipepipe: Opc = BO_LOr; break; 8084 case tok::equal: Opc = BO_Assign; break; 8085 case tok::starequal: Opc = BO_MulAssign; break; 8086 case tok::slashequal: Opc = BO_DivAssign; break; 8087 case tok::percentequal: Opc = BO_RemAssign; break; 8088 case tok::plusequal: Opc = BO_AddAssign; break; 8089 case tok::minusequal: Opc = BO_SubAssign; break; 8090 case tok::lesslessequal: Opc = BO_ShlAssign; break; 8091 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 8092 case tok::ampequal: Opc = BO_AndAssign; break; 8093 case tok::caretequal: Opc = BO_XorAssign; break; 8094 case tok::pipeequal: Opc = BO_OrAssign; break; 8095 case tok::comma: Opc = BO_Comma; break; 8096 } 8097 return Opc; 8098 } 8099 8100 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 8101 tok::TokenKind Kind) { 8102 UnaryOperatorKind Opc; 8103 switch (Kind) { 8104 default: llvm_unreachable("Unknown unary op!"); 8105 case tok::plusplus: Opc = UO_PreInc; break; 8106 case tok::minusminus: Opc = UO_PreDec; break; 8107 case tok::amp: Opc = UO_AddrOf; break; 8108 case tok::star: Opc = UO_Deref; break; 8109 case tok::plus: Opc = UO_Plus; break; 8110 case tok::minus: Opc = UO_Minus; break; 8111 case tok::tilde: Opc = UO_Not; break; 8112 case tok::exclaim: Opc = UO_LNot; break; 8113 case tok::kw___real: Opc = UO_Real; break; 8114 case tok::kw___imag: Opc = UO_Imag; break; 8115 case tok::kw___extension__: Opc = UO_Extension; break; 8116 } 8117 return Opc; 8118 } 8119 8120 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 8121 /// This warning is only emitted for builtin assignment operations. It is also 8122 /// suppressed in the event of macro expansions. 8123 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 8124 SourceLocation OpLoc) { 8125 if (!S.ActiveTemplateInstantiations.empty()) 8126 return; 8127 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 8128 return; 8129 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 8130 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 8131 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 8132 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 8133 if (!LHSDeclRef || !RHSDeclRef || 8134 LHSDeclRef->getLocation().isMacroID() || 8135 RHSDeclRef->getLocation().isMacroID()) 8136 return; 8137 const ValueDecl *LHSDecl = 8138 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 8139 const ValueDecl *RHSDecl = 8140 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 8141 if (LHSDecl != RHSDecl) 8142 return; 8143 if (LHSDecl->getType().isVolatileQualified()) 8144 return; 8145 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 8146 if (RefTy->getPointeeType().isVolatileQualified()) 8147 return; 8148 8149 S.Diag(OpLoc, diag::warn_self_assignment) 8150 << LHSDeclRef->getType() 8151 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8152 } 8153 8154 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 8155 /// operator @p Opc at location @c TokLoc. This routine only supports 8156 /// built-in operations; ActOnBinOp handles overloaded operators. 8157 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 8158 BinaryOperatorKind Opc, 8159 Expr *LHSExpr, Expr *RHSExpr) { 8160 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) { 8161 // The syntax only allows initializer lists on the RHS of assignment, 8162 // so we don't need to worry about accepting invalid code for 8163 // non-assignment operators. 8164 // C++11 5.17p9: 8165 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 8166 // of x = {} is x = T(). 8167 InitializationKind Kind = 8168 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 8169 InitializedEntity Entity = 8170 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 8171 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1); 8172 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, 8173 MultiExprArg(&RHSExpr, 1)); 8174 if (Init.isInvalid()) 8175 return Init; 8176 RHSExpr = Init.take(); 8177 } 8178 8179 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 8180 QualType ResultTy; // Result type of the binary operator. 8181 // The following two variables are used for compound assignment operators 8182 QualType CompLHSTy; // Type of LHS after promotions for computation 8183 QualType CompResultTy; // Type of computation result 8184 ExprValueKind VK = VK_RValue; 8185 ExprObjectKind OK = OK_Ordinary; 8186 8187 switch (Opc) { 8188 case BO_Assign: 8189 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 8190 if (getLangOpts().CPlusPlus && 8191 LHS.get()->getObjectKind() != OK_ObjCProperty) { 8192 VK = LHS.get()->getValueKind(); 8193 OK = LHS.get()->getObjectKind(); 8194 } 8195 if (!ResultTy.isNull()) 8196 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 8197 break; 8198 case BO_PtrMemD: 8199 case BO_PtrMemI: 8200 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 8201 Opc == BO_PtrMemI); 8202 break; 8203 case BO_Mul: 8204 case BO_Div: 8205 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 8206 Opc == BO_Div); 8207 break; 8208 case BO_Rem: 8209 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 8210 break; 8211 case BO_Add: 8212 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 8213 break; 8214 case BO_Sub: 8215 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 8216 break; 8217 case BO_Shl: 8218 case BO_Shr: 8219 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 8220 break; 8221 case BO_LE: 8222 case BO_LT: 8223 case BO_GE: 8224 case BO_GT: 8225 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 8226 break; 8227 case BO_EQ: 8228 case BO_NE: 8229 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) { 8230 ExprResult IsEqualCall = fixObjCLiteralComparison(*this, OpLoc, 8231 LHS, RHS, Opc); 8232 if (IsEqualCall.isUsable()) 8233 return IsEqualCall; 8234 // Otherwise, fall back to the normal diagnostic in CheckCompareOperands. 8235 } 8236 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 8237 break; 8238 case BO_And: 8239 case BO_Xor: 8240 case BO_Or: 8241 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 8242 break; 8243 case BO_LAnd: 8244 case BO_LOr: 8245 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 8246 break; 8247 case BO_MulAssign: 8248 case BO_DivAssign: 8249 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 8250 Opc == BO_DivAssign); 8251 CompLHSTy = CompResultTy; 8252 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8253 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8254 break; 8255 case BO_RemAssign: 8256 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 8257 CompLHSTy = CompResultTy; 8258 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8259 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8260 break; 8261 case BO_AddAssign: 8262 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 8263 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8264 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8265 break; 8266 case BO_SubAssign: 8267 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 8268 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8269 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8270 break; 8271 case BO_ShlAssign: 8272 case BO_ShrAssign: 8273 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 8274 CompLHSTy = CompResultTy; 8275 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8276 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8277 break; 8278 case BO_AndAssign: 8279 case BO_XorAssign: 8280 case BO_OrAssign: 8281 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 8282 CompLHSTy = CompResultTy; 8283 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8284 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8285 break; 8286 case BO_Comma: 8287 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 8288 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 8289 VK = RHS.get()->getValueKind(); 8290 OK = RHS.get()->getObjectKind(); 8291 } 8292 break; 8293 } 8294 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 8295 return ExprError(); 8296 8297 // Check for array bounds violations for both sides of the BinaryOperator 8298 CheckArrayAccess(LHS.get()); 8299 CheckArrayAccess(RHS.get()); 8300 8301 if (CompResultTy.isNull()) 8302 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc, 8303 ResultTy, VK, OK, OpLoc)); 8304 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 8305 OK_ObjCProperty) { 8306 VK = VK_LValue; 8307 OK = LHS.get()->getObjectKind(); 8308 } 8309 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc, 8310 ResultTy, VK, OK, CompLHSTy, 8311 CompResultTy, OpLoc)); 8312 } 8313 8314 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 8315 /// operators are mixed in a way that suggests that the programmer forgot that 8316 /// comparison operators have higher precedence. The most typical example of 8317 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 8318 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 8319 SourceLocation OpLoc, Expr *LHSExpr, 8320 Expr *RHSExpr) { 8321 typedef BinaryOperator BinOp; 8322 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1), 8323 RHSopc = static_cast<BinOp::Opcode>(-1); 8324 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr)) 8325 LHSopc = BO->getOpcode(); 8326 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr)) 8327 RHSopc = BO->getOpcode(); 8328 8329 // Subs are not binary operators. 8330 if (LHSopc == -1 && RHSopc == -1) 8331 return; 8332 8333 // Bitwise operations are sometimes used as eager logical ops. 8334 // Don't diagnose this. 8335 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) && 8336 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc))) 8337 return; 8338 8339 bool isLeftComp = BinOp::isComparisonOp(LHSopc); 8340 bool isRightComp = BinOp::isComparisonOp(RHSopc); 8341 if (!isLeftComp && !isRightComp) return; 8342 8343 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 8344 OpLoc) 8345 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 8346 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc) 8347 : BinOp::getOpcodeStr(RHSopc); 8348 SourceRange ParensRange = isLeftComp ? 8349 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(), 8350 RHSExpr->getLocEnd()) 8351 : SourceRange(LHSExpr->getLocStart(), 8352 cast<BinOp>(RHSExpr)->getLHS()->getLocStart()); 8353 8354 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 8355 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr; 8356 SuggestParentheses(Self, OpLoc, 8357 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr, 8358 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 8359 SuggestParentheses(Self, OpLoc, 8360 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc), 8361 ParensRange); 8362 } 8363 8364 /// \brief It accepts a '&' expr that is inside a '|' one. 8365 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression 8366 /// in parentheses. 8367 static void 8368 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 8369 BinaryOperator *Bop) { 8370 assert(Bop->getOpcode() == BO_And); 8371 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 8372 << Bop->getSourceRange() << OpLoc; 8373 SuggestParentheses(Self, Bop->getOperatorLoc(), 8374 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence), 8375 Bop->getSourceRange()); 8376 } 8377 8378 /// \brief It accepts a '&&' expr that is inside a '||' one. 8379 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 8380 /// in parentheses. 8381 static void 8382 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 8383 BinaryOperator *Bop) { 8384 assert(Bop->getOpcode() == BO_LAnd); 8385 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 8386 << Bop->getSourceRange() << OpLoc; 8387 SuggestParentheses(Self, Bop->getOperatorLoc(), 8388 Self.PDiag(diag::note_logical_and_in_logical_or_silence), 8389 Bop->getSourceRange()); 8390 } 8391 8392 /// \brief Returns true if the given expression can be evaluated as a constant 8393 /// 'true'. 8394 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 8395 bool Res; 8396 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 8397 } 8398 8399 /// \brief Returns true if the given expression can be evaluated as a constant 8400 /// 'false'. 8401 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 8402 bool Res; 8403 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 8404 } 8405 8406 /// \brief Look for '&&' in the left hand of a '||' expr. 8407 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 8408 Expr *LHSExpr, Expr *RHSExpr) { 8409 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 8410 if (Bop->getOpcode() == BO_LAnd) { 8411 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 8412 if (EvaluatesAsFalse(S, RHSExpr)) 8413 return; 8414 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 8415 if (!EvaluatesAsTrue(S, Bop->getLHS())) 8416 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 8417 } else if (Bop->getOpcode() == BO_LOr) { 8418 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 8419 // If it's "a || b && 1 || c" we didn't warn earlier for 8420 // "a || b && 1", but warn now. 8421 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 8422 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 8423 } 8424 } 8425 } 8426 } 8427 8428 /// \brief Look for '&&' in the right hand of a '||' expr. 8429 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 8430 Expr *LHSExpr, Expr *RHSExpr) { 8431 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 8432 if (Bop->getOpcode() == BO_LAnd) { 8433 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 8434 if (EvaluatesAsFalse(S, LHSExpr)) 8435 return; 8436 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 8437 if (!EvaluatesAsTrue(S, Bop->getRHS())) 8438 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 8439 } 8440 } 8441 } 8442 8443 /// \brief Look for '&' in the left or right hand of a '|' expr. 8444 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 8445 Expr *OrArg) { 8446 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 8447 if (Bop->getOpcode() == BO_And) 8448 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 8449 } 8450 } 8451 8452 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 8453 /// precedence. 8454 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 8455 SourceLocation OpLoc, Expr *LHSExpr, 8456 Expr *RHSExpr){ 8457 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 8458 if (BinaryOperator::isBitwiseOp(Opc)) 8459 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 8460 8461 // Diagnose "arg1 & arg2 | arg3" 8462 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 8463 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 8464 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 8465 } 8466 8467 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 8468 // We don't warn for 'assert(a || b && "bad")' since this is safe. 8469 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 8470 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 8471 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 8472 } 8473 } 8474 8475 // Binary Operators. 'Tok' is the token for the operator. 8476 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 8477 tok::TokenKind Kind, 8478 Expr *LHSExpr, Expr *RHSExpr) { 8479 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 8480 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression"); 8481 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression"); 8482 8483 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 8484 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 8485 8486 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 8487 } 8488 8489 /// Build an overloaded binary operator expression in the given scope. 8490 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 8491 BinaryOperatorKind Opc, 8492 Expr *LHS, Expr *RHS) { 8493 // Find all of the overloaded operators visible from this 8494 // point. We perform both an operator-name lookup from the local 8495 // scope and an argument-dependent lookup based on the types of 8496 // the arguments. 8497 UnresolvedSet<16> Functions; 8498 OverloadedOperatorKind OverOp 8499 = BinaryOperator::getOverloadedOperator(Opc); 8500 if (Sc && OverOp != OO_None) 8501 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 8502 RHS->getType(), Functions); 8503 8504 // Build the (potentially-overloaded, potentially-dependent) 8505 // binary operation. 8506 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 8507 } 8508 8509 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 8510 BinaryOperatorKind Opc, 8511 Expr *LHSExpr, Expr *RHSExpr) { 8512 // We want to end up calling one of checkPseudoObjectAssignment 8513 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 8514 // both expressions are overloadable or either is type-dependent), 8515 // or CreateBuiltinBinOp (in any other case). We also want to get 8516 // any placeholder types out of the way. 8517 8518 // Handle pseudo-objects in the LHS. 8519 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 8520 // Assignments with a pseudo-object l-value need special analysis. 8521 if (pty->getKind() == BuiltinType::PseudoObject && 8522 BinaryOperator::isAssignmentOp(Opc)) 8523 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 8524 8525 // Don't resolve overloads if the other type is overloadable. 8526 if (pty->getKind() == BuiltinType::Overload) { 8527 // We can't actually test that if we still have a placeholder, 8528 // though. Fortunately, none of the exceptions we see in that 8529 // code below are valid when the LHS is an overload set. Note 8530 // that an overload set can be dependently-typed, but it never 8531 // instantiates to having an overloadable type. 8532 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 8533 if (resolvedRHS.isInvalid()) return ExprError(); 8534 RHSExpr = resolvedRHS.take(); 8535 8536 if (RHSExpr->isTypeDependent() || 8537 RHSExpr->getType()->isOverloadableType()) 8538 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8539 } 8540 8541 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 8542 if (LHS.isInvalid()) return ExprError(); 8543 LHSExpr = LHS.take(); 8544 } 8545 8546 // Handle pseudo-objects in the RHS. 8547 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 8548 // An overload in the RHS can potentially be resolved by the type 8549 // being assigned to. 8550 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 8551 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 8552 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8553 8554 if (LHSExpr->getType()->isOverloadableType()) 8555 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8556 8557 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 8558 } 8559 8560 // Don't resolve overloads if the other type is overloadable. 8561 if (pty->getKind() == BuiltinType::Overload && 8562 LHSExpr->getType()->isOverloadableType()) 8563 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8564 8565 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 8566 if (!resolvedRHS.isUsable()) return ExprError(); 8567 RHSExpr = resolvedRHS.take(); 8568 } 8569 8570 if (getLangOpts().CPlusPlus) { 8571 // If either expression is type-dependent, always build an 8572 // overloaded op. 8573 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 8574 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8575 8576 // Otherwise, build an overloaded op if either expression has an 8577 // overloadable type. 8578 if (LHSExpr->getType()->isOverloadableType() || 8579 RHSExpr->getType()->isOverloadableType()) 8580 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8581 } 8582 8583 // Build a built-in binary operation. 8584 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 8585 } 8586 8587 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 8588 UnaryOperatorKind Opc, 8589 Expr *InputExpr) { 8590 ExprResult Input = Owned(InputExpr); 8591 ExprValueKind VK = VK_RValue; 8592 ExprObjectKind OK = OK_Ordinary; 8593 QualType resultType; 8594 switch (Opc) { 8595 case UO_PreInc: 8596 case UO_PreDec: 8597 case UO_PostInc: 8598 case UO_PostDec: 8599 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc, 8600 Opc == UO_PreInc || 8601 Opc == UO_PostInc, 8602 Opc == UO_PreInc || 8603 Opc == UO_PreDec); 8604 break; 8605 case UO_AddrOf: 8606 resultType = CheckAddressOfOperand(*this, Input, OpLoc); 8607 break; 8608 case UO_Deref: { 8609 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 8610 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 8611 break; 8612 } 8613 case UO_Plus: 8614 case UO_Minus: 8615 Input = UsualUnaryConversions(Input.take()); 8616 if (Input.isInvalid()) return ExprError(); 8617 resultType = Input.get()->getType(); 8618 if (resultType->isDependentType()) 8619 break; 8620 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 8621 resultType->isVectorType()) 8622 break; 8623 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7 8624 resultType->isEnumeralType()) 8625 break; 8626 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 8627 Opc == UO_Plus && 8628 resultType->isPointerType()) 8629 break; 8630 8631 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8632 << resultType << Input.get()->getSourceRange()); 8633 8634 case UO_Not: // bitwise complement 8635 Input = UsualUnaryConversions(Input.take()); 8636 if (Input.isInvalid()) return ExprError(); 8637 resultType = Input.get()->getType(); 8638 if (resultType->isDependentType()) 8639 break; 8640 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 8641 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 8642 // C99 does not support '~' for complex conjugation. 8643 Diag(OpLoc, diag::ext_integer_complement_complex) 8644 << resultType << Input.get()->getSourceRange(); 8645 else if (resultType->hasIntegerRepresentation()) 8646 break; 8647 else { 8648 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8649 << resultType << Input.get()->getSourceRange()); 8650 } 8651 break; 8652 8653 case UO_LNot: // logical negation 8654 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 8655 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 8656 if (Input.isInvalid()) return ExprError(); 8657 resultType = Input.get()->getType(); 8658 8659 // Though we still have to promote half FP to float... 8660 if (resultType->isHalfType()) { 8661 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take(); 8662 resultType = Context.FloatTy; 8663 } 8664 8665 if (resultType->isDependentType()) 8666 break; 8667 if (resultType->isScalarType()) { 8668 // C99 6.5.3.3p1: ok, fallthrough; 8669 if (Context.getLangOpts().CPlusPlus) { 8670 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 8671 // operand contextually converted to bool. 8672 Input = ImpCastExprToType(Input.take(), Context.BoolTy, 8673 ScalarTypeToBooleanCastKind(resultType)); 8674 } 8675 } else if (resultType->isExtVectorType()) { 8676 // Vector logical not returns the signed variant of the operand type. 8677 resultType = GetSignedVectorType(resultType); 8678 break; 8679 } else { 8680 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8681 << resultType << Input.get()->getSourceRange()); 8682 } 8683 8684 // LNot always has type int. C99 6.5.3.3p5. 8685 // In C++, it's bool. C++ 5.3.1p8 8686 resultType = Context.getLogicalOperationType(); 8687 break; 8688 case UO_Real: 8689 case UO_Imag: 8690 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 8691 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 8692 // complex l-values to ordinary l-values and all other values to r-values. 8693 if (Input.isInvalid()) return ExprError(); 8694 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 8695 if (Input.get()->getValueKind() != VK_RValue && 8696 Input.get()->getObjectKind() == OK_Ordinary) 8697 VK = Input.get()->getValueKind(); 8698 } else if (!getLangOpts().CPlusPlus) { 8699 // In C, a volatile scalar is read by __imag. In C++, it is not. 8700 Input = DefaultLvalueConversion(Input.take()); 8701 } 8702 break; 8703 case UO_Extension: 8704 resultType = Input.get()->getType(); 8705 VK = Input.get()->getValueKind(); 8706 OK = Input.get()->getObjectKind(); 8707 break; 8708 } 8709 if (resultType.isNull() || Input.isInvalid()) 8710 return ExprError(); 8711 8712 // Check for array bounds violations in the operand of the UnaryOperator, 8713 // except for the '*' and '&' operators that have to be handled specially 8714 // by CheckArrayAccess (as there are special cases like &array[arraysize] 8715 // that are explicitly defined as valid by the standard). 8716 if (Opc != UO_AddrOf && Opc != UO_Deref) 8717 CheckArrayAccess(Input.get()); 8718 8719 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType, 8720 VK, OK, OpLoc)); 8721 } 8722 8723 /// \brief Determine whether the given expression is a qualified member 8724 /// access expression, of a form that could be turned into a pointer to member 8725 /// with the address-of operator. 8726 static bool isQualifiedMemberAccess(Expr *E) { 8727 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 8728 if (!DRE->getQualifier()) 8729 return false; 8730 8731 ValueDecl *VD = DRE->getDecl(); 8732 if (!VD->isCXXClassMember()) 8733 return false; 8734 8735 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 8736 return true; 8737 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 8738 return Method->isInstance(); 8739 8740 return false; 8741 } 8742 8743 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 8744 if (!ULE->getQualifier()) 8745 return false; 8746 8747 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 8748 DEnd = ULE->decls_end(); 8749 D != DEnd; ++D) { 8750 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 8751 if (Method->isInstance()) 8752 return true; 8753 } else { 8754 // Overload set does not contain methods. 8755 break; 8756 } 8757 } 8758 8759 return false; 8760 } 8761 8762 return false; 8763 } 8764 8765 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 8766 UnaryOperatorKind Opc, Expr *Input) { 8767 // First things first: handle placeholders so that the 8768 // overloaded-operator check considers the right type. 8769 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 8770 // Increment and decrement of pseudo-object references. 8771 if (pty->getKind() == BuiltinType::PseudoObject && 8772 UnaryOperator::isIncrementDecrementOp(Opc)) 8773 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 8774 8775 // extension is always a builtin operator. 8776 if (Opc == UO_Extension) 8777 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 8778 8779 // & gets special logic for several kinds of placeholder. 8780 // The builtin code knows what to do. 8781 if (Opc == UO_AddrOf && 8782 (pty->getKind() == BuiltinType::Overload || 8783 pty->getKind() == BuiltinType::UnknownAny || 8784 pty->getKind() == BuiltinType::BoundMember)) 8785 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 8786 8787 // Anything else needs to be handled now. 8788 ExprResult Result = CheckPlaceholderExpr(Input); 8789 if (Result.isInvalid()) return ExprError(); 8790 Input = Result.take(); 8791 } 8792 8793 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 8794 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 8795 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 8796 // Find all of the overloaded operators visible from this 8797 // point. We perform both an operator-name lookup from the local 8798 // scope and an argument-dependent lookup based on the types of 8799 // the arguments. 8800 UnresolvedSet<16> Functions; 8801 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 8802 if (S && OverOp != OO_None) 8803 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 8804 Functions); 8805 8806 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 8807 } 8808 8809 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 8810 } 8811 8812 // Unary Operators. 'Tok' is the token for the operator. 8813 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 8814 tok::TokenKind Op, Expr *Input) { 8815 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 8816 } 8817 8818 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 8819 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 8820 LabelDecl *TheDecl) { 8821 TheDecl->setUsed(); 8822 // Create the AST node. The address of a label always has type 'void*'. 8823 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 8824 Context.getPointerType(Context.VoidTy))); 8825 } 8826 8827 /// Given the last statement in a statement-expression, check whether 8828 /// the result is a producing expression (like a call to an 8829 /// ns_returns_retained function) and, if so, rebuild it to hoist the 8830 /// release out of the full-expression. Otherwise, return null. 8831 /// Cannot fail. 8832 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 8833 // Should always be wrapped with one of these. 8834 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 8835 if (!cleanups) return 0; 8836 8837 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 8838 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 8839 return 0; 8840 8841 // Splice out the cast. This shouldn't modify any interesting 8842 // features of the statement. 8843 Expr *producer = cast->getSubExpr(); 8844 assert(producer->getType() == cast->getType()); 8845 assert(producer->getValueKind() == cast->getValueKind()); 8846 cleanups->setSubExpr(producer); 8847 return cleanups; 8848 } 8849 8850 void Sema::ActOnStartStmtExpr() { 8851 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 8852 } 8853 8854 void Sema::ActOnStmtExprError() { 8855 // Note that function is also called by TreeTransform when leaving a 8856 // StmtExpr scope without rebuilding anything. 8857 8858 DiscardCleanupsInEvaluationContext(); 8859 PopExpressionEvaluationContext(); 8860 } 8861 8862 ExprResult 8863 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 8864 SourceLocation RPLoc) { // "({..})" 8865 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 8866 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 8867 8868 if (hasAnyUnrecoverableErrorsInThisFunction()) 8869 DiscardCleanupsInEvaluationContext(); 8870 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 8871 PopExpressionEvaluationContext(); 8872 8873 bool isFileScope 8874 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 8875 if (isFileScope) 8876 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 8877 8878 // FIXME: there are a variety of strange constraints to enforce here, for 8879 // example, it is not possible to goto into a stmt expression apparently. 8880 // More semantic analysis is needed. 8881 8882 // If there are sub stmts in the compound stmt, take the type of the last one 8883 // as the type of the stmtexpr. 8884 QualType Ty = Context.VoidTy; 8885 bool StmtExprMayBindToTemp = false; 8886 if (!Compound->body_empty()) { 8887 Stmt *LastStmt = Compound->body_back(); 8888 LabelStmt *LastLabelStmt = 0; 8889 // If LastStmt is a label, skip down through into the body. 8890 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 8891 LastLabelStmt = Label; 8892 LastStmt = Label->getSubStmt(); 8893 } 8894 8895 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 8896 // Do function/array conversion on the last expression, but not 8897 // lvalue-to-rvalue. However, initialize an unqualified type. 8898 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 8899 if (LastExpr.isInvalid()) 8900 return ExprError(); 8901 Ty = LastExpr.get()->getType().getUnqualifiedType(); 8902 8903 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 8904 // In ARC, if the final expression ends in a consume, splice 8905 // the consume out and bind it later. In the alternate case 8906 // (when dealing with a retainable type), the result 8907 // initialization will create a produce. In both cases the 8908 // result will be +1, and we'll need to balance that out with 8909 // a bind. 8910 if (Expr *rebuiltLastStmt 8911 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 8912 LastExpr = rebuiltLastStmt; 8913 } else { 8914 LastExpr = PerformCopyInitialization( 8915 InitializedEntity::InitializeResult(LPLoc, 8916 Ty, 8917 false), 8918 SourceLocation(), 8919 LastExpr); 8920 } 8921 8922 if (LastExpr.isInvalid()) 8923 return ExprError(); 8924 if (LastExpr.get() != 0) { 8925 if (!LastLabelStmt) 8926 Compound->setLastStmt(LastExpr.take()); 8927 else 8928 LastLabelStmt->setSubStmt(LastExpr.take()); 8929 StmtExprMayBindToTemp = true; 8930 } 8931 } 8932 } 8933 } 8934 8935 // FIXME: Check that expression type is complete/non-abstract; statement 8936 // expressions are not lvalues. 8937 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 8938 if (StmtExprMayBindToTemp) 8939 return MaybeBindToTemporary(ResStmtExpr); 8940 return Owned(ResStmtExpr); 8941 } 8942 8943 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 8944 TypeSourceInfo *TInfo, 8945 OffsetOfComponent *CompPtr, 8946 unsigned NumComponents, 8947 SourceLocation RParenLoc) { 8948 QualType ArgTy = TInfo->getType(); 8949 bool Dependent = ArgTy->isDependentType(); 8950 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 8951 8952 // We must have at least one component that refers to the type, and the first 8953 // one is known to be a field designator. Verify that the ArgTy represents 8954 // a struct/union/class. 8955 if (!Dependent && !ArgTy->isRecordType()) 8956 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 8957 << ArgTy << TypeRange); 8958 8959 // Type must be complete per C99 7.17p3 because a declaring a variable 8960 // with an incomplete type would be ill-formed. 8961 if (!Dependent 8962 && RequireCompleteType(BuiltinLoc, ArgTy, 8963 diag::err_offsetof_incomplete_type, TypeRange)) 8964 return ExprError(); 8965 8966 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 8967 // GCC extension, diagnose them. 8968 // FIXME: This diagnostic isn't actually visible because the location is in 8969 // a system header! 8970 if (NumComponents != 1) 8971 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 8972 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 8973 8974 bool DidWarnAboutNonPOD = false; 8975 QualType CurrentType = ArgTy; 8976 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 8977 SmallVector<OffsetOfNode, 4> Comps; 8978 SmallVector<Expr*, 4> Exprs; 8979 for (unsigned i = 0; i != NumComponents; ++i) { 8980 const OffsetOfComponent &OC = CompPtr[i]; 8981 if (OC.isBrackets) { 8982 // Offset of an array sub-field. TODO: Should we allow vector elements? 8983 if (!CurrentType->isDependentType()) { 8984 const ArrayType *AT = Context.getAsArrayType(CurrentType); 8985 if(!AT) 8986 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 8987 << CurrentType); 8988 CurrentType = AT->getElementType(); 8989 } else 8990 CurrentType = Context.DependentTy; 8991 8992 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 8993 if (IdxRval.isInvalid()) 8994 return ExprError(); 8995 Expr *Idx = IdxRval.take(); 8996 8997 // The expression must be an integral expression. 8998 // FIXME: An integral constant expression? 8999 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 9000 !Idx->getType()->isIntegerType()) 9001 return ExprError(Diag(Idx->getLocStart(), 9002 diag::err_typecheck_subscript_not_integer) 9003 << Idx->getSourceRange()); 9004 9005 // Record this array index. 9006 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 9007 Exprs.push_back(Idx); 9008 continue; 9009 } 9010 9011 // Offset of a field. 9012 if (CurrentType->isDependentType()) { 9013 // We have the offset of a field, but we can't look into the dependent 9014 // type. Just record the identifier of the field. 9015 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 9016 CurrentType = Context.DependentTy; 9017 continue; 9018 } 9019 9020 // We need to have a complete type to look into. 9021 if (RequireCompleteType(OC.LocStart, CurrentType, 9022 diag::err_offsetof_incomplete_type)) 9023 return ExprError(); 9024 9025 // Look for the designated field. 9026 const RecordType *RC = CurrentType->getAs<RecordType>(); 9027 if (!RC) 9028 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 9029 << CurrentType); 9030 RecordDecl *RD = RC->getDecl(); 9031 9032 // C++ [lib.support.types]p5: 9033 // The macro offsetof accepts a restricted set of type arguments in this 9034 // International Standard. type shall be a POD structure or a POD union 9035 // (clause 9). 9036 // C++11 [support.types]p4: 9037 // If type is not a standard-layout class (Clause 9), the results are 9038 // undefined. 9039 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 9040 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD(); 9041 unsigned DiagID = 9042 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type 9043 : diag::warn_offsetof_non_pod_type; 9044 9045 if (!IsSafe && !DidWarnAboutNonPOD && 9046 DiagRuntimeBehavior(BuiltinLoc, 0, 9047 PDiag(DiagID) 9048 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 9049 << CurrentType)) 9050 DidWarnAboutNonPOD = true; 9051 } 9052 9053 // Look for the field. 9054 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 9055 LookupQualifiedName(R, RD); 9056 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 9057 IndirectFieldDecl *IndirectMemberDecl = 0; 9058 if (!MemberDecl) { 9059 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 9060 MemberDecl = IndirectMemberDecl->getAnonField(); 9061 } 9062 9063 if (!MemberDecl) 9064 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 9065 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 9066 OC.LocEnd)); 9067 9068 // C99 7.17p3: 9069 // (If the specified member is a bit-field, the behavior is undefined.) 9070 // 9071 // We diagnose this as an error. 9072 if (MemberDecl->isBitField()) { 9073 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 9074 << MemberDecl->getDeclName() 9075 << SourceRange(BuiltinLoc, RParenLoc); 9076 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 9077 return ExprError(); 9078 } 9079 9080 RecordDecl *Parent = MemberDecl->getParent(); 9081 if (IndirectMemberDecl) 9082 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 9083 9084 // If the member was found in a base class, introduce OffsetOfNodes for 9085 // the base class indirections. 9086 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 9087 /*DetectVirtual=*/false); 9088 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 9089 CXXBasePath &Path = Paths.front(); 9090 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 9091 B != BEnd; ++B) 9092 Comps.push_back(OffsetOfNode(B->Base)); 9093 } 9094 9095 if (IndirectMemberDecl) { 9096 for (IndirectFieldDecl::chain_iterator FI = 9097 IndirectMemberDecl->chain_begin(), 9098 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) { 9099 assert(isa<FieldDecl>(*FI)); 9100 Comps.push_back(OffsetOfNode(OC.LocStart, 9101 cast<FieldDecl>(*FI), OC.LocEnd)); 9102 } 9103 } else 9104 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 9105 9106 CurrentType = MemberDecl->getType().getNonReferenceType(); 9107 } 9108 9109 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 9110 TInfo, Comps.data(), Comps.size(), 9111 Exprs.data(), Exprs.size(), RParenLoc)); 9112 } 9113 9114 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 9115 SourceLocation BuiltinLoc, 9116 SourceLocation TypeLoc, 9117 ParsedType ParsedArgTy, 9118 OffsetOfComponent *CompPtr, 9119 unsigned NumComponents, 9120 SourceLocation RParenLoc) { 9121 9122 TypeSourceInfo *ArgTInfo; 9123 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 9124 if (ArgTy.isNull()) 9125 return ExprError(); 9126 9127 if (!ArgTInfo) 9128 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 9129 9130 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 9131 RParenLoc); 9132 } 9133 9134 9135 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 9136 Expr *CondExpr, 9137 Expr *LHSExpr, Expr *RHSExpr, 9138 SourceLocation RPLoc) { 9139 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 9140 9141 ExprValueKind VK = VK_RValue; 9142 ExprObjectKind OK = OK_Ordinary; 9143 QualType resType; 9144 bool ValueDependent = false; 9145 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 9146 resType = Context.DependentTy; 9147 ValueDependent = true; 9148 } else { 9149 // The conditional expression is required to be a constant expression. 9150 llvm::APSInt condEval(32); 9151 ExprResult CondICE 9152 = VerifyIntegerConstantExpression(CondExpr, &condEval, 9153 diag::err_typecheck_choose_expr_requires_constant, false); 9154 if (CondICE.isInvalid()) 9155 return ExprError(); 9156 CondExpr = CondICE.take(); 9157 9158 // If the condition is > zero, then the AST type is the same as the LSHExpr. 9159 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr; 9160 9161 resType = ActiveExpr->getType(); 9162 ValueDependent = ActiveExpr->isValueDependent(); 9163 VK = ActiveExpr->getValueKind(); 9164 OK = ActiveExpr->getObjectKind(); 9165 } 9166 9167 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 9168 resType, VK, OK, RPLoc, 9169 resType->isDependentType(), 9170 ValueDependent)); 9171 } 9172 9173 //===----------------------------------------------------------------------===// 9174 // Clang Extensions. 9175 //===----------------------------------------------------------------------===// 9176 9177 /// ActOnBlockStart - This callback is invoked when a block literal is started. 9178 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 9179 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 9180 PushBlockScope(CurScope, Block); 9181 CurContext->addDecl(Block); 9182 if (CurScope) 9183 PushDeclContext(CurScope, Block); 9184 else 9185 CurContext = Block; 9186 9187 getCurBlock()->HasImplicitReturnType = true; 9188 9189 // Enter a new evaluation context to insulate the block from any 9190 // cleanups from the enclosing full-expression. 9191 PushExpressionEvaluationContext(PotentiallyEvaluated); 9192 } 9193 9194 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 9195 Scope *CurScope) { 9196 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 9197 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 9198 BlockScopeInfo *CurBlock = getCurBlock(); 9199 9200 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 9201 QualType T = Sig->getType(); 9202 9203 // FIXME: We should allow unexpanded parameter packs here, but that would, 9204 // in turn, make the block expression contain unexpanded parameter packs. 9205 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 9206 // Drop the parameters. 9207 FunctionProtoType::ExtProtoInfo EPI; 9208 EPI.HasTrailingReturn = false; 9209 EPI.TypeQuals |= DeclSpec::TQ_const; 9210 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0, 9211 EPI); 9212 Sig = Context.getTrivialTypeSourceInfo(T); 9213 } 9214 9215 // GetTypeForDeclarator always produces a function type for a block 9216 // literal signature. Furthermore, it is always a FunctionProtoType 9217 // unless the function was written with a typedef. 9218 assert(T->isFunctionType() && 9219 "GetTypeForDeclarator made a non-function block signature"); 9220 9221 // Look for an explicit signature in that function type. 9222 FunctionProtoTypeLoc ExplicitSignature; 9223 9224 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 9225 if (isa<FunctionProtoTypeLoc>(tmp)) { 9226 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp); 9227 9228 // Check whether that explicit signature was synthesized by 9229 // GetTypeForDeclarator. If so, don't save that as part of the 9230 // written signature. 9231 if (ExplicitSignature.getLocalRangeBegin() == 9232 ExplicitSignature.getLocalRangeEnd()) { 9233 // This would be much cheaper if we stored TypeLocs instead of 9234 // TypeSourceInfos. 9235 TypeLoc Result = ExplicitSignature.getResultLoc(); 9236 unsigned Size = Result.getFullDataSize(); 9237 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 9238 Sig->getTypeLoc().initializeFullCopy(Result, Size); 9239 9240 ExplicitSignature = FunctionProtoTypeLoc(); 9241 } 9242 } 9243 9244 CurBlock->TheDecl->setSignatureAsWritten(Sig); 9245 CurBlock->FunctionType = T; 9246 9247 const FunctionType *Fn = T->getAs<FunctionType>(); 9248 QualType RetTy = Fn->getResultType(); 9249 bool isVariadic = 9250 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 9251 9252 CurBlock->TheDecl->setIsVariadic(isVariadic); 9253 9254 // Don't allow returning a objc interface by value. 9255 if (RetTy->isObjCObjectType()) { 9256 Diag(ParamInfo.getLocStart(), 9257 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; 9258 return; 9259 } 9260 9261 // Context.DependentTy is used as a placeholder for a missing block 9262 // return type. TODO: what should we do with declarators like: 9263 // ^ * { ... } 9264 // If the answer is "apply template argument deduction".... 9265 if (RetTy != Context.DependentTy) { 9266 CurBlock->ReturnType = RetTy; 9267 CurBlock->TheDecl->setBlockMissingReturnType(false); 9268 CurBlock->HasImplicitReturnType = false; 9269 } 9270 9271 // Push block parameters from the declarator if we had them. 9272 SmallVector<ParmVarDecl*, 8> Params; 9273 if (ExplicitSignature) { 9274 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) { 9275 ParmVarDecl *Param = ExplicitSignature.getArg(I); 9276 if (Param->getIdentifier() == 0 && 9277 !Param->isImplicit() && 9278 !Param->isInvalidDecl() && 9279 !getLangOpts().CPlusPlus) 9280 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 9281 Params.push_back(Param); 9282 } 9283 9284 // Fake up parameter variables if we have a typedef, like 9285 // ^ fntype { ... } 9286 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 9287 for (FunctionProtoType::arg_type_iterator 9288 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) { 9289 ParmVarDecl *Param = 9290 BuildParmVarDeclForTypedef(CurBlock->TheDecl, 9291 ParamInfo.getLocStart(), 9292 *I); 9293 Params.push_back(Param); 9294 } 9295 } 9296 9297 // Set the parameters on the block decl. 9298 if (!Params.empty()) { 9299 CurBlock->TheDecl->setParams(Params); 9300 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 9301 CurBlock->TheDecl->param_end(), 9302 /*CheckParameterNames=*/false); 9303 } 9304 9305 // Finally we can process decl attributes. 9306 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 9307 9308 // Put the parameter variables in scope. We can bail out immediately 9309 // if we don't have any. 9310 if (Params.empty()) 9311 return; 9312 9313 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 9314 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) { 9315 (*AI)->setOwningFunction(CurBlock->TheDecl); 9316 9317 // If this has an identifier, add it to the scope stack. 9318 if ((*AI)->getIdentifier()) { 9319 CheckShadow(CurBlock->TheScope, *AI); 9320 9321 PushOnScopeChains(*AI, CurBlock->TheScope); 9322 } 9323 } 9324 } 9325 9326 /// ActOnBlockError - If there is an error parsing a block, this callback 9327 /// is invoked to pop the information about the block from the action impl. 9328 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 9329 // Leave the expression-evaluation context. 9330 DiscardCleanupsInEvaluationContext(); 9331 PopExpressionEvaluationContext(); 9332 9333 // Pop off CurBlock, handle nested blocks. 9334 PopDeclContext(); 9335 PopFunctionScopeInfo(); 9336 } 9337 9338 /// ActOnBlockStmtExpr - This is called when the body of a block statement 9339 /// literal was successfully completed. ^(int x){...} 9340 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 9341 Stmt *Body, Scope *CurScope) { 9342 // If blocks are disabled, emit an error. 9343 if (!LangOpts.Blocks) 9344 Diag(CaretLoc, diag::err_blocks_disable); 9345 9346 // Leave the expression-evaluation context. 9347 if (hasAnyUnrecoverableErrorsInThisFunction()) 9348 DiscardCleanupsInEvaluationContext(); 9349 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 9350 PopExpressionEvaluationContext(); 9351 9352 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 9353 9354 PopDeclContext(); 9355 9356 QualType RetTy = Context.VoidTy; 9357 if (!BSI->ReturnType.isNull()) 9358 RetTy = BSI->ReturnType; 9359 9360 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>(); 9361 QualType BlockTy; 9362 9363 // Set the captured variables on the block. 9364 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 9365 SmallVector<BlockDecl::Capture, 4> Captures; 9366 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 9367 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 9368 if (Cap.isThisCapture()) 9369 continue; 9370 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 9371 Cap.isNested(), Cap.getCopyExpr()); 9372 Captures.push_back(NewCap); 9373 } 9374 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(), 9375 BSI->CXXThisCaptureIndex != 0); 9376 9377 // If the user wrote a function type in some form, try to use that. 9378 if (!BSI->FunctionType.isNull()) { 9379 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 9380 9381 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 9382 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 9383 9384 // Turn protoless block types into nullary block types. 9385 if (isa<FunctionNoProtoType>(FTy)) { 9386 FunctionProtoType::ExtProtoInfo EPI; 9387 EPI.ExtInfo = Ext; 9388 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI); 9389 9390 // Otherwise, if we don't need to change anything about the function type, 9391 // preserve its sugar structure. 9392 } else if (FTy->getResultType() == RetTy && 9393 (!NoReturn || FTy->getNoReturnAttr())) { 9394 BlockTy = BSI->FunctionType; 9395 9396 // Otherwise, make the minimal modifications to the function type. 9397 } else { 9398 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 9399 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9400 EPI.TypeQuals = 0; // FIXME: silently? 9401 EPI.ExtInfo = Ext; 9402 BlockTy = Context.getFunctionType(RetTy, 9403 FPT->arg_type_begin(), 9404 FPT->getNumArgs(), 9405 EPI); 9406 } 9407 9408 // If we don't have a function type, just build one from nothing. 9409 } else { 9410 FunctionProtoType::ExtProtoInfo EPI; 9411 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 9412 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI); 9413 } 9414 9415 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 9416 BSI->TheDecl->param_end()); 9417 BlockTy = Context.getBlockPointerType(BlockTy); 9418 9419 // If needed, diagnose invalid gotos and switches in the block. 9420 if (getCurFunction()->NeedsScopeChecking() && 9421 !hasAnyUnrecoverableErrorsInThisFunction()) 9422 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 9423 9424 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 9425 9426 computeNRVO(Body, getCurBlock()); 9427 9428 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 9429 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy(); 9430 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 9431 9432 // If the block isn't obviously global, i.e. it captures anything at 9433 // all, then we need to do a few things in the surrounding context: 9434 if (Result->getBlockDecl()->hasCaptures()) { 9435 // First, this expression has a new cleanup object. 9436 ExprCleanupObjects.push_back(Result->getBlockDecl()); 9437 ExprNeedsCleanups = true; 9438 9439 // It also gets a branch-protected scope if any of the captured 9440 // variables needs destruction. 9441 for (BlockDecl::capture_const_iterator 9442 ci = Result->getBlockDecl()->capture_begin(), 9443 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) { 9444 const VarDecl *var = ci->getVariable(); 9445 if (var->getType().isDestructedType() != QualType::DK_none) { 9446 getCurFunction()->setHasBranchProtectedScope(); 9447 break; 9448 } 9449 } 9450 } 9451 9452 return Owned(Result); 9453 } 9454 9455 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 9456 Expr *E, ParsedType Ty, 9457 SourceLocation RPLoc) { 9458 TypeSourceInfo *TInfo; 9459 GetTypeFromParser(Ty, &TInfo); 9460 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 9461 } 9462 9463 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 9464 Expr *E, TypeSourceInfo *TInfo, 9465 SourceLocation RPLoc) { 9466 Expr *OrigExpr = E; 9467 9468 // Get the va_list type 9469 QualType VaListType = Context.getBuiltinVaListType(); 9470 if (VaListType->isArrayType()) { 9471 // Deal with implicit array decay; for example, on x86-64, 9472 // va_list is an array, but it's supposed to decay to 9473 // a pointer for va_arg. 9474 VaListType = Context.getArrayDecayedType(VaListType); 9475 // Make sure the input expression also decays appropriately. 9476 ExprResult Result = UsualUnaryConversions(E); 9477 if (Result.isInvalid()) 9478 return ExprError(); 9479 E = Result.take(); 9480 } else { 9481 // Otherwise, the va_list argument must be an l-value because 9482 // it is modified by va_arg. 9483 if (!E->isTypeDependent() && 9484 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 9485 return ExprError(); 9486 } 9487 9488 if (!E->isTypeDependent() && 9489 !Context.hasSameType(VaListType, E->getType())) { 9490 return ExprError(Diag(E->getLocStart(), 9491 diag::err_first_argument_to_va_arg_not_of_type_va_list) 9492 << OrigExpr->getType() << E->getSourceRange()); 9493 } 9494 9495 if (!TInfo->getType()->isDependentType()) { 9496 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 9497 diag::err_second_parameter_to_va_arg_incomplete, 9498 TInfo->getTypeLoc())) 9499 return ExprError(); 9500 9501 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 9502 TInfo->getType(), 9503 diag::err_second_parameter_to_va_arg_abstract, 9504 TInfo->getTypeLoc())) 9505 return ExprError(); 9506 9507 if (!TInfo->getType().isPODType(Context)) { 9508 Diag(TInfo->getTypeLoc().getBeginLoc(), 9509 TInfo->getType()->isObjCLifetimeType() 9510 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 9511 : diag::warn_second_parameter_to_va_arg_not_pod) 9512 << TInfo->getType() 9513 << TInfo->getTypeLoc().getSourceRange(); 9514 } 9515 9516 // Check for va_arg where arguments of the given type will be promoted 9517 // (i.e. this va_arg is guaranteed to have undefined behavior). 9518 QualType PromoteType; 9519 if (TInfo->getType()->isPromotableIntegerType()) { 9520 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 9521 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 9522 PromoteType = QualType(); 9523 } 9524 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 9525 PromoteType = Context.DoubleTy; 9526 if (!PromoteType.isNull()) 9527 Diag(TInfo->getTypeLoc().getBeginLoc(), 9528 diag::warn_second_parameter_to_va_arg_never_compatible) 9529 << TInfo->getType() 9530 << PromoteType 9531 << TInfo->getTypeLoc().getSourceRange(); 9532 } 9533 9534 QualType T = TInfo->getType().getNonLValueExprType(Context); 9535 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 9536 } 9537 9538 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 9539 // The type of __null will be int or long, depending on the size of 9540 // pointers on the target. 9541 QualType Ty; 9542 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 9543 if (pw == Context.getTargetInfo().getIntWidth()) 9544 Ty = Context.IntTy; 9545 else if (pw == Context.getTargetInfo().getLongWidth()) 9546 Ty = Context.LongTy; 9547 else if (pw == Context.getTargetInfo().getLongLongWidth()) 9548 Ty = Context.LongLongTy; 9549 else { 9550 llvm_unreachable("I don't know size of pointer!"); 9551 } 9552 9553 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 9554 } 9555 9556 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType, 9557 Expr *SrcExpr, FixItHint &Hint) { 9558 if (!SemaRef.getLangOpts().ObjC1) 9559 return; 9560 9561 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 9562 if (!PT) 9563 return; 9564 9565 // Check if the destination is of type 'id'. 9566 if (!PT->isObjCIdType()) { 9567 // Check if the destination is the 'NSString' interface. 9568 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 9569 if (!ID || !ID->getIdentifier()->isStr("NSString")) 9570 return; 9571 } 9572 9573 // Ignore any parens, implicit casts (should only be 9574 // array-to-pointer decays), and not-so-opaque values. The last is 9575 // important for making this trigger for property assignments. 9576 SrcExpr = SrcExpr->IgnoreParenImpCasts(); 9577 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 9578 if (OV->getSourceExpr()) 9579 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 9580 9581 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 9582 if (!SL || !SL->isAscii()) 9583 return; 9584 9585 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@"); 9586 } 9587 9588 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 9589 SourceLocation Loc, 9590 QualType DstType, QualType SrcType, 9591 Expr *SrcExpr, AssignmentAction Action, 9592 bool *Complained) { 9593 if (Complained) 9594 *Complained = false; 9595 9596 // Decode the result (notice that AST's are still created for extensions). 9597 bool CheckInferredResultType = false; 9598 bool isInvalid = false; 9599 unsigned DiagKind = 0; 9600 FixItHint Hint; 9601 ConversionFixItGenerator ConvHints; 9602 bool MayHaveConvFixit = false; 9603 bool MayHaveFunctionDiff = false; 9604 9605 switch (ConvTy) { 9606 case Compatible: return false; 9607 case PointerToInt: 9608 DiagKind = diag::ext_typecheck_convert_pointer_int; 9609 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9610 MayHaveConvFixit = true; 9611 break; 9612 case IntToPointer: 9613 DiagKind = diag::ext_typecheck_convert_int_pointer; 9614 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9615 MayHaveConvFixit = true; 9616 break; 9617 case IncompatiblePointer: 9618 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint); 9619 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 9620 CheckInferredResultType = DstType->isObjCObjectPointerType() && 9621 SrcType->isObjCObjectPointerType(); 9622 if (Hint.isNull() && !CheckInferredResultType) { 9623 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9624 } 9625 MayHaveConvFixit = true; 9626 break; 9627 case IncompatiblePointerSign: 9628 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 9629 break; 9630 case FunctionVoidPointer: 9631 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 9632 break; 9633 case IncompatiblePointerDiscardsQualifiers: { 9634 // Perform array-to-pointer decay if necessary. 9635 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 9636 9637 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 9638 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 9639 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 9640 DiagKind = diag::err_typecheck_incompatible_address_space; 9641 break; 9642 9643 9644 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 9645 DiagKind = diag::err_typecheck_incompatible_ownership; 9646 break; 9647 } 9648 9649 llvm_unreachable("unknown error case for discarding qualifiers!"); 9650 // fallthrough 9651 } 9652 case CompatiblePointerDiscardsQualifiers: 9653 // If the qualifiers lost were because we were applying the 9654 // (deprecated) C++ conversion from a string literal to a char* 9655 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 9656 // Ideally, this check would be performed in 9657 // checkPointerTypesForAssignment. However, that would require a 9658 // bit of refactoring (so that the second argument is an 9659 // expression, rather than a type), which should be done as part 9660 // of a larger effort to fix checkPointerTypesForAssignment for 9661 // C++ semantics. 9662 if (getLangOpts().CPlusPlus && 9663 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 9664 return false; 9665 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 9666 break; 9667 case IncompatibleNestedPointerQualifiers: 9668 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 9669 break; 9670 case IntToBlockPointer: 9671 DiagKind = diag::err_int_to_block_pointer; 9672 break; 9673 case IncompatibleBlockPointer: 9674 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 9675 break; 9676 case IncompatibleObjCQualifiedId: 9677 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 9678 // it can give a more specific diagnostic. 9679 DiagKind = diag::warn_incompatible_qualified_id; 9680 break; 9681 case IncompatibleVectors: 9682 DiagKind = diag::warn_incompatible_vectors; 9683 break; 9684 case IncompatibleObjCWeakRef: 9685 DiagKind = diag::err_arc_weak_unavailable_assign; 9686 break; 9687 case Incompatible: 9688 DiagKind = diag::err_typecheck_convert_incompatible; 9689 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9690 MayHaveConvFixit = true; 9691 isInvalid = true; 9692 MayHaveFunctionDiff = true; 9693 break; 9694 } 9695 9696 QualType FirstType, SecondType; 9697 switch (Action) { 9698 case AA_Assigning: 9699 case AA_Initializing: 9700 // The destination type comes first. 9701 FirstType = DstType; 9702 SecondType = SrcType; 9703 break; 9704 9705 case AA_Returning: 9706 case AA_Passing: 9707 case AA_Converting: 9708 case AA_Sending: 9709 case AA_Casting: 9710 // The source type comes first. 9711 FirstType = SrcType; 9712 SecondType = DstType; 9713 break; 9714 } 9715 9716 PartialDiagnostic FDiag = PDiag(DiagKind); 9717 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 9718 9719 // If we can fix the conversion, suggest the FixIts. 9720 assert(ConvHints.isNull() || Hint.isNull()); 9721 if (!ConvHints.isNull()) { 9722 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 9723 HE = ConvHints.Hints.end(); HI != HE; ++HI) 9724 FDiag << *HI; 9725 } else { 9726 FDiag << Hint; 9727 } 9728 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 9729 9730 if (MayHaveFunctionDiff) 9731 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 9732 9733 Diag(Loc, FDiag); 9734 9735 if (SecondType == Context.OverloadTy) 9736 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 9737 FirstType); 9738 9739 if (CheckInferredResultType) 9740 EmitRelatedResultTypeNote(SrcExpr); 9741 9742 if (Complained) 9743 *Complained = true; 9744 return isInvalid; 9745 } 9746 9747 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 9748 llvm::APSInt *Result) { 9749 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 9750 public: 9751 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 9752 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 9753 } 9754 } Diagnoser; 9755 9756 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 9757 } 9758 9759 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 9760 llvm::APSInt *Result, 9761 unsigned DiagID, 9762 bool AllowFold) { 9763 class IDDiagnoser : public VerifyICEDiagnoser { 9764 unsigned DiagID; 9765 9766 public: 9767 IDDiagnoser(unsigned DiagID) 9768 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 9769 9770 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 9771 S.Diag(Loc, DiagID) << SR; 9772 } 9773 } Diagnoser(DiagID); 9774 9775 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 9776 } 9777 9778 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 9779 SourceRange SR) { 9780 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 9781 } 9782 9783 ExprResult 9784 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 9785 VerifyICEDiagnoser &Diagnoser, 9786 bool AllowFold) { 9787 SourceLocation DiagLoc = E->getLocStart(); 9788 9789 if (getLangOpts().CPlusPlus0x) { 9790 // C++11 [expr.const]p5: 9791 // If an expression of literal class type is used in a context where an 9792 // integral constant expression is required, then that class type shall 9793 // have a single non-explicit conversion function to an integral or 9794 // unscoped enumeration type 9795 ExprResult Converted; 9796 if (!Diagnoser.Suppress) { 9797 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 9798 public: 9799 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { } 9800 9801 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 9802 QualType T) { 9803 return S.Diag(Loc, diag::err_ice_not_integral) << T; 9804 } 9805 9806 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, 9807 SourceLocation Loc, 9808 QualType T) { 9809 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 9810 } 9811 9812 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, 9813 SourceLocation Loc, 9814 QualType T, 9815 QualType ConvTy) { 9816 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 9817 } 9818 9819 virtual DiagnosticBuilder noteExplicitConv(Sema &S, 9820 CXXConversionDecl *Conv, 9821 QualType ConvTy) { 9822 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 9823 << ConvTy->isEnumeralType() << ConvTy; 9824 } 9825 9826 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 9827 QualType T) { 9828 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 9829 } 9830 9831 virtual DiagnosticBuilder noteAmbiguous(Sema &S, 9832 CXXConversionDecl *Conv, 9833 QualType ConvTy) { 9834 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 9835 << ConvTy->isEnumeralType() << ConvTy; 9836 } 9837 9838 virtual DiagnosticBuilder diagnoseConversion(Sema &S, 9839 SourceLocation Loc, 9840 QualType T, 9841 QualType ConvTy) { 9842 return DiagnosticBuilder::getEmpty(); 9843 } 9844 } ConvertDiagnoser; 9845 9846 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E, 9847 ConvertDiagnoser, 9848 /*AllowScopedEnumerations*/ false); 9849 } else { 9850 // The caller wants to silently enquire whether this is an ICE. Don't 9851 // produce any diagnostics if it isn't. 9852 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser { 9853 public: 9854 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { } 9855 9856 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 9857 QualType T) { 9858 return DiagnosticBuilder::getEmpty(); 9859 } 9860 9861 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, 9862 SourceLocation Loc, 9863 QualType T) { 9864 return DiagnosticBuilder::getEmpty(); 9865 } 9866 9867 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, 9868 SourceLocation Loc, 9869 QualType T, 9870 QualType ConvTy) { 9871 return DiagnosticBuilder::getEmpty(); 9872 } 9873 9874 virtual DiagnosticBuilder noteExplicitConv(Sema &S, 9875 CXXConversionDecl *Conv, 9876 QualType ConvTy) { 9877 return DiagnosticBuilder::getEmpty(); 9878 } 9879 9880 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 9881 QualType T) { 9882 return DiagnosticBuilder::getEmpty(); 9883 } 9884 9885 virtual DiagnosticBuilder noteAmbiguous(Sema &S, 9886 CXXConversionDecl *Conv, 9887 QualType ConvTy) { 9888 return DiagnosticBuilder::getEmpty(); 9889 } 9890 9891 virtual DiagnosticBuilder diagnoseConversion(Sema &S, 9892 SourceLocation Loc, 9893 QualType T, 9894 QualType ConvTy) { 9895 return DiagnosticBuilder::getEmpty(); 9896 } 9897 } ConvertDiagnoser; 9898 9899 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E, 9900 ConvertDiagnoser, false); 9901 } 9902 if (Converted.isInvalid()) 9903 return Converted; 9904 E = Converted.take(); 9905 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 9906 return ExprError(); 9907 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 9908 // An ICE must be of integral or unscoped enumeration type. 9909 if (!Diagnoser.Suppress) 9910 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 9911 return ExprError(); 9912 } 9913 9914 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 9915 // in the non-ICE case. 9916 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) { 9917 if (Result) 9918 *Result = E->EvaluateKnownConstInt(Context); 9919 return Owned(E); 9920 } 9921 9922 Expr::EvalResult EvalResult; 9923 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 9924 EvalResult.Diag = &Notes; 9925 9926 // Try to evaluate the expression, and produce diagnostics explaining why it's 9927 // not a constant expression as a side-effect. 9928 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 9929 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 9930 9931 // In C++11, we can rely on diagnostics being produced for any expression 9932 // which is not a constant expression. If no diagnostics were produced, then 9933 // this is a constant expression. 9934 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) { 9935 if (Result) 9936 *Result = EvalResult.Val.getInt(); 9937 return Owned(E); 9938 } 9939 9940 // If our only note is the usual "invalid subexpression" note, just point 9941 // the caret at its location rather than producing an essentially 9942 // redundant note. 9943 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 9944 diag::note_invalid_subexpr_in_const_expr) { 9945 DiagLoc = Notes[0].first; 9946 Notes.clear(); 9947 } 9948 9949 if (!Folded || !AllowFold) { 9950 if (!Diagnoser.Suppress) { 9951 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 9952 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 9953 Diag(Notes[I].first, Notes[I].second); 9954 } 9955 9956 return ExprError(); 9957 } 9958 9959 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 9960 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 9961 Diag(Notes[I].first, Notes[I].second); 9962 9963 if (Result) 9964 *Result = EvalResult.Val.getInt(); 9965 return Owned(E); 9966 } 9967 9968 namespace { 9969 // Handle the case where we conclude a expression which we speculatively 9970 // considered to be unevaluated is actually evaluated. 9971 class TransformToPE : public TreeTransform<TransformToPE> { 9972 typedef TreeTransform<TransformToPE> BaseTransform; 9973 9974 public: 9975 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 9976 9977 // Make sure we redo semantic analysis 9978 bool AlwaysRebuild() { return true; } 9979 9980 // Make sure we handle LabelStmts correctly. 9981 // FIXME: This does the right thing, but maybe we need a more general 9982 // fix to TreeTransform? 9983 StmtResult TransformLabelStmt(LabelStmt *S) { 9984 S->getDecl()->setStmt(0); 9985 return BaseTransform::TransformLabelStmt(S); 9986 } 9987 9988 // We need to special-case DeclRefExprs referring to FieldDecls which 9989 // are not part of a member pointer formation; normal TreeTransforming 9990 // doesn't catch this case because of the way we represent them in the AST. 9991 // FIXME: This is a bit ugly; is it really the best way to handle this 9992 // case? 9993 // 9994 // Error on DeclRefExprs referring to FieldDecls. 9995 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 9996 if (isa<FieldDecl>(E->getDecl()) && 9997 SemaRef.ExprEvalContexts.back().Context != Sema::Unevaluated) 9998 return SemaRef.Diag(E->getLocation(), 9999 diag::err_invalid_non_static_member_use) 10000 << E->getDecl() << E->getSourceRange(); 10001 10002 return BaseTransform::TransformDeclRefExpr(E); 10003 } 10004 10005 // Exception: filter out member pointer formation 10006 ExprResult TransformUnaryOperator(UnaryOperator *E) { 10007 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 10008 return E; 10009 10010 return BaseTransform::TransformUnaryOperator(E); 10011 } 10012 10013 ExprResult TransformLambdaExpr(LambdaExpr *E) { 10014 // Lambdas never need to be transformed. 10015 return E; 10016 } 10017 }; 10018 } 10019 10020 ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) { 10021 assert(ExprEvalContexts.back().Context == Unevaluated && 10022 "Should only transform unevaluated expressions"); 10023 ExprEvalContexts.back().Context = 10024 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 10025 if (ExprEvalContexts.back().Context == Unevaluated) 10026 return E; 10027 return TransformToPE(*this).TransformExpr(E); 10028 } 10029 10030 void 10031 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 10032 Decl *LambdaContextDecl, 10033 bool IsDecltype) { 10034 ExprEvalContexts.push_back( 10035 ExpressionEvaluationContextRecord(NewContext, 10036 ExprCleanupObjects.size(), 10037 ExprNeedsCleanups, 10038 LambdaContextDecl, 10039 IsDecltype)); 10040 ExprNeedsCleanups = false; 10041 if (!MaybeODRUseExprs.empty()) 10042 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 10043 } 10044 10045 void Sema::PopExpressionEvaluationContext() { 10046 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 10047 10048 if (!Rec.Lambdas.empty()) { 10049 if (Rec.Context == Unevaluated) { 10050 // C++11 [expr.prim.lambda]p2: 10051 // A lambda-expression shall not appear in an unevaluated operand 10052 // (Clause 5). 10053 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) 10054 Diag(Rec.Lambdas[I]->getLocStart(), 10055 diag::err_lambda_unevaluated_operand); 10056 } else { 10057 // Mark the capture expressions odr-used. This was deferred 10058 // during lambda expression creation. 10059 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) { 10060 LambdaExpr *Lambda = Rec.Lambdas[I]; 10061 for (LambdaExpr::capture_init_iterator 10062 C = Lambda->capture_init_begin(), 10063 CEnd = Lambda->capture_init_end(); 10064 C != CEnd; ++C) { 10065 MarkDeclarationsReferencedInExpr(*C); 10066 } 10067 } 10068 } 10069 } 10070 10071 // When are coming out of an unevaluated context, clear out any 10072 // temporaries that we may have created as part of the evaluation of 10073 // the expression in that context: they aren't relevant because they 10074 // will never be constructed. 10075 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) { 10076 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 10077 ExprCleanupObjects.end()); 10078 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 10079 CleanupVarDeclMarking(); 10080 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 10081 // Otherwise, merge the contexts together. 10082 } else { 10083 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 10084 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 10085 Rec.SavedMaybeODRUseExprs.end()); 10086 } 10087 10088 // Pop the current expression evaluation context off the stack. 10089 ExprEvalContexts.pop_back(); 10090 } 10091 10092 void Sema::DiscardCleanupsInEvaluationContext() { 10093 ExprCleanupObjects.erase( 10094 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 10095 ExprCleanupObjects.end()); 10096 ExprNeedsCleanups = false; 10097 MaybeODRUseExprs.clear(); 10098 } 10099 10100 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 10101 if (!E->getType()->isVariablyModifiedType()) 10102 return E; 10103 return TranformToPotentiallyEvaluated(E); 10104 } 10105 10106 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 10107 // Do not mark anything as "used" within a dependent context; wait for 10108 // an instantiation. 10109 if (SemaRef.CurContext->isDependentContext()) 10110 return false; 10111 10112 switch (SemaRef.ExprEvalContexts.back().Context) { 10113 case Sema::Unevaluated: 10114 // We are in an expression that is not potentially evaluated; do nothing. 10115 // (Depending on how you read the standard, we actually do need to do 10116 // something here for null pointer constants, but the standard's 10117 // definition of a null pointer constant is completely crazy.) 10118 return false; 10119 10120 case Sema::ConstantEvaluated: 10121 case Sema::PotentiallyEvaluated: 10122 // We are in a potentially evaluated expression (or a constant-expression 10123 // in C++03); we need to do implicit template instantiation, implicitly 10124 // define class members, and mark most declarations as used. 10125 return true; 10126 10127 case Sema::PotentiallyEvaluatedIfUsed: 10128 // Referenced declarations will only be used if the construct in the 10129 // containing expression is used. 10130 return false; 10131 } 10132 llvm_unreachable("Invalid context"); 10133 } 10134 10135 /// \brief Mark a function referenced, and check whether it is odr-used 10136 /// (C++ [basic.def.odr]p2, C99 6.9p3) 10137 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) { 10138 assert(Func && "No function?"); 10139 10140 Func->setReferenced(); 10141 10142 // Don't mark this function as used multiple times, unless it's a constexpr 10143 // function which we need to instantiate. 10144 if (Func->isUsed(false) && 10145 !(Func->isConstexpr() && !Func->getBody() && 10146 Func->isImplicitlyInstantiable())) 10147 return; 10148 10149 if (!IsPotentiallyEvaluatedContext(*this)) 10150 return; 10151 10152 // Note that this declaration has been used. 10153 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 10154 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 10155 if (Constructor->isDefaultConstructor()) { 10156 if (Constructor->isTrivial()) 10157 return; 10158 if (!Constructor->isUsed(false)) 10159 DefineImplicitDefaultConstructor(Loc, Constructor); 10160 } else if (Constructor->isCopyConstructor()) { 10161 if (!Constructor->isUsed(false)) 10162 DefineImplicitCopyConstructor(Loc, Constructor); 10163 } else if (Constructor->isMoveConstructor()) { 10164 if (!Constructor->isUsed(false)) 10165 DefineImplicitMoveConstructor(Loc, Constructor); 10166 } 10167 } 10168 10169 MarkVTableUsed(Loc, Constructor->getParent()); 10170 } else if (CXXDestructorDecl *Destructor = 10171 dyn_cast<CXXDestructorDecl>(Func)) { 10172 if (Destructor->isDefaulted() && !Destructor->isDeleted() && 10173 !Destructor->isUsed(false)) 10174 DefineImplicitDestructor(Loc, Destructor); 10175 if (Destructor->isVirtual()) 10176 MarkVTableUsed(Loc, Destructor->getParent()); 10177 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 10178 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() && 10179 MethodDecl->isOverloadedOperator() && 10180 MethodDecl->getOverloadedOperator() == OO_Equal) { 10181 if (!MethodDecl->isUsed(false)) { 10182 if (MethodDecl->isCopyAssignmentOperator()) 10183 DefineImplicitCopyAssignment(Loc, MethodDecl); 10184 else 10185 DefineImplicitMoveAssignment(Loc, MethodDecl); 10186 } 10187 } else if (isa<CXXConversionDecl>(MethodDecl) && 10188 MethodDecl->getParent()->isLambda()) { 10189 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl); 10190 if (Conversion->isLambdaToBlockPointerConversion()) 10191 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 10192 else 10193 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 10194 } else if (MethodDecl->isVirtual()) 10195 MarkVTableUsed(Loc, MethodDecl->getParent()); 10196 } 10197 10198 // Recursive functions should be marked when used from another function. 10199 // FIXME: Is this really right? 10200 if (CurContext == Func) return; 10201 10202 // Instantiate the exception specification for any function which is 10203 // used: CodeGen will need it. 10204 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 10205 if (FPT && FPT->getExceptionSpecType() == EST_Uninstantiated) 10206 InstantiateExceptionSpec(Loc, Func); 10207 10208 // Implicit instantiation of function templates and member functions of 10209 // class templates. 10210 if (Func->isImplicitlyInstantiable()) { 10211 bool AlreadyInstantiated = false; 10212 SourceLocation PointOfInstantiation = Loc; 10213 if (FunctionTemplateSpecializationInfo *SpecInfo 10214 = Func->getTemplateSpecializationInfo()) { 10215 if (SpecInfo->getPointOfInstantiation().isInvalid()) 10216 SpecInfo->setPointOfInstantiation(Loc); 10217 else if (SpecInfo->getTemplateSpecializationKind() 10218 == TSK_ImplicitInstantiation) { 10219 AlreadyInstantiated = true; 10220 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 10221 } 10222 } else if (MemberSpecializationInfo *MSInfo 10223 = Func->getMemberSpecializationInfo()) { 10224 if (MSInfo->getPointOfInstantiation().isInvalid()) 10225 MSInfo->setPointOfInstantiation(Loc); 10226 else if (MSInfo->getTemplateSpecializationKind() 10227 == TSK_ImplicitInstantiation) { 10228 AlreadyInstantiated = true; 10229 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 10230 } 10231 } 10232 10233 if (!AlreadyInstantiated || Func->isConstexpr()) { 10234 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 10235 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass()) 10236 PendingLocalImplicitInstantiations.push_back( 10237 std::make_pair(Func, PointOfInstantiation)); 10238 else if (Func->isConstexpr()) 10239 // Do not defer instantiations of constexpr functions, to avoid the 10240 // expression evaluator needing to call back into Sema if it sees a 10241 // call to such a function. 10242 InstantiateFunctionDefinition(PointOfInstantiation, Func); 10243 else { 10244 PendingInstantiations.push_back(std::make_pair(Func, 10245 PointOfInstantiation)); 10246 // Notify the consumer that a function was implicitly instantiated. 10247 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 10248 } 10249 } 10250 } else { 10251 // Walk redefinitions, as some of them may be instantiable. 10252 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()), 10253 e(Func->redecls_end()); i != e; ++i) { 10254 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 10255 MarkFunctionReferenced(Loc, *i); 10256 } 10257 } 10258 10259 // Keep track of used but undefined functions. 10260 if (!Func->isPure() && !Func->hasBody() && 10261 Func->getLinkage() != ExternalLinkage) { 10262 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()]; 10263 if (old.isInvalid()) old = Loc; 10264 } 10265 10266 Func->setUsed(true); 10267 } 10268 10269 static void 10270 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 10271 VarDecl *var, DeclContext *DC) { 10272 DeclContext *VarDC = var->getDeclContext(); 10273 10274 // If the parameter still belongs to the translation unit, then 10275 // we're actually just using one parameter in the declaration of 10276 // the next. 10277 if (isa<ParmVarDecl>(var) && 10278 isa<TranslationUnitDecl>(VarDC)) 10279 return; 10280 10281 // For C code, don't diagnose about capture if we're not actually in code 10282 // right now; it's impossible to write a non-constant expression outside of 10283 // function context, so we'll get other (more useful) diagnostics later. 10284 // 10285 // For C++, things get a bit more nasty... it would be nice to suppress this 10286 // diagnostic for certain cases like using a local variable in an array bound 10287 // for a member of a local class, but the correct predicate is not obvious. 10288 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 10289 return; 10290 10291 if (isa<CXXMethodDecl>(VarDC) && 10292 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 10293 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 10294 << var->getIdentifier(); 10295 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 10296 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 10297 << var->getIdentifier() << fn->getDeclName(); 10298 } else if (isa<BlockDecl>(VarDC)) { 10299 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 10300 << var->getIdentifier(); 10301 } else { 10302 // FIXME: Is there any other context where a local variable can be 10303 // declared? 10304 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 10305 << var->getIdentifier(); 10306 } 10307 10308 S.Diag(var->getLocation(), diag::note_local_variable_declared_here) 10309 << var->getIdentifier(); 10310 10311 // FIXME: Add additional diagnostic info about class etc. which prevents 10312 // capture. 10313 } 10314 10315 /// \brief Capture the given variable in the given lambda expression. 10316 static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI, 10317 VarDecl *Var, QualType FieldType, 10318 QualType DeclRefType, 10319 SourceLocation Loc, 10320 bool RefersToEnclosingLocal) { 10321 CXXRecordDecl *Lambda = LSI->Lambda; 10322 10323 // Build the non-static data member. 10324 FieldDecl *Field 10325 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType, 10326 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 10327 0, false, ICIS_NoInit); 10328 Field->setImplicit(true); 10329 Field->setAccess(AS_private); 10330 Lambda->addDecl(Field); 10331 10332 // C++11 [expr.prim.lambda]p21: 10333 // When the lambda-expression is evaluated, the entities that 10334 // are captured by copy are used to direct-initialize each 10335 // corresponding non-static data member of the resulting closure 10336 // object. (For array members, the array elements are 10337 // direct-initialized in increasing subscript order.) These 10338 // initializations are performed in the (unspecified) order in 10339 // which the non-static data members are declared. 10340 10341 // Introduce a new evaluation context for the initialization, so 10342 // that temporaries introduced as part of the capture are retained 10343 // to be re-"exported" from the lambda expression itself. 10344 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 10345 10346 // C++ [expr.prim.labda]p12: 10347 // An entity captured by a lambda-expression is odr-used (3.2) in 10348 // the scope containing the lambda-expression. 10349 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 10350 DeclRefType, VK_LValue, Loc); 10351 Var->setReferenced(true); 10352 Var->setUsed(true); 10353 10354 // When the field has array type, create index variables for each 10355 // dimension of the array. We use these index variables to subscript 10356 // the source array, and other clients (e.g., CodeGen) will perform 10357 // the necessary iteration with these index variables. 10358 SmallVector<VarDecl *, 4> IndexVariables; 10359 QualType BaseType = FieldType; 10360 QualType SizeType = S.Context.getSizeType(); 10361 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size()); 10362 while (const ConstantArrayType *Array 10363 = S.Context.getAsConstantArrayType(BaseType)) { 10364 // Create the iteration variable for this array index. 10365 IdentifierInfo *IterationVarName = 0; 10366 { 10367 SmallString<8> Str; 10368 llvm::raw_svector_ostream OS(Str); 10369 OS << "__i" << IndexVariables.size(); 10370 IterationVarName = &S.Context.Idents.get(OS.str()); 10371 } 10372 VarDecl *IterationVar 10373 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 10374 IterationVarName, SizeType, 10375 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 10376 SC_None, SC_None); 10377 IndexVariables.push_back(IterationVar); 10378 LSI->ArrayIndexVars.push_back(IterationVar); 10379 10380 // Create a reference to the iteration variable. 10381 ExprResult IterationVarRef 10382 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 10383 assert(!IterationVarRef.isInvalid() && 10384 "Reference to invented variable cannot fail!"); 10385 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take()); 10386 assert(!IterationVarRef.isInvalid() && 10387 "Conversion of invented variable cannot fail!"); 10388 10389 // Subscript the array with this iteration variable. 10390 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr( 10391 Ref, Loc, IterationVarRef.take(), Loc); 10392 if (Subscript.isInvalid()) { 10393 S.CleanupVarDeclMarking(); 10394 S.DiscardCleanupsInEvaluationContext(); 10395 S.PopExpressionEvaluationContext(); 10396 return ExprError(); 10397 } 10398 10399 Ref = Subscript.take(); 10400 BaseType = Array->getElementType(); 10401 } 10402 10403 // Construct the entity that we will be initializing. For an array, this 10404 // will be first element in the array, which may require several levels 10405 // of array-subscript entities. 10406 SmallVector<InitializedEntity, 4> Entities; 10407 Entities.reserve(1 + IndexVariables.size()); 10408 Entities.push_back( 10409 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc)); 10410 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 10411 Entities.push_back(InitializedEntity::InitializeElement(S.Context, 10412 0, 10413 Entities.back())); 10414 10415 InitializationKind InitKind 10416 = InitializationKind::CreateDirect(Loc, Loc, Loc); 10417 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1); 10418 ExprResult Result(true); 10419 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1)) 10420 Result = Init.Perform(S, Entities.back(), InitKind, 10421 MultiExprArg(S, &Ref, 1)); 10422 10423 // If this initialization requires any cleanups (e.g., due to a 10424 // default argument to a copy constructor), note that for the 10425 // lambda. 10426 if (S.ExprNeedsCleanups) 10427 LSI->ExprNeedsCleanups = true; 10428 10429 // Exit the expression evaluation context used for the capture. 10430 S.CleanupVarDeclMarking(); 10431 S.DiscardCleanupsInEvaluationContext(); 10432 S.PopExpressionEvaluationContext(); 10433 return Result; 10434 } 10435 10436 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 10437 TryCaptureKind Kind, SourceLocation EllipsisLoc, 10438 bool BuildAndDiagnose, 10439 QualType &CaptureType, 10440 QualType &DeclRefType) { 10441 bool Nested = false; 10442 10443 DeclContext *DC = CurContext; 10444 if (Var->getDeclContext() == DC) return true; 10445 if (!Var->hasLocalStorage()) return true; 10446 10447 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 10448 10449 // Walk up the stack to determine whether we can capture the variable, 10450 // performing the "simple" checks that don't depend on type. We stop when 10451 // we've either hit the declared scope of the variable or find an existing 10452 // capture of that variable. 10453 CaptureType = Var->getType(); 10454 DeclRefType = CaptureType.getNonReferenceType(); 10455 bool Explicit = (Kind != TryCapture_Implicit); 10456 unsigned FunctionScopesIndex = FunctionScopes.size() - 1; 10457 do { 10458 // Only block literals and lambda expressions can capture; other 10459 // scopes don't work. 10460 DeclContext *ParentDC; 10461 if (isa<BlockDecl>(DC)) 10462 ParentDC = DC->getParent(); 10463 else if (isa<CXXMethodDecl>(DC) && 10464 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call && 10465 cast<CXXRecordDecl>(DC->getParent())->isLambda()) 10466 ParentDC = DC->getParent()->getParent(); 10467 else { 10468 if (BuildAndDiagnose) 10469 diagnoseUncapturableValueReference(*this, Loc, Var, DC); 10470 return true; 10471 } 10472 10473 CapturingScopeInfo *CSI = 10474 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]); 10475 10476 // Check whether we've already captured it. 10477 if (CSI->CaptureMap.count(Var)) { 10478 // If we found a capture, any subcaptures are nested. 10479 Nested = true; 10480 10481 // Retrieve the capture type for this variable. 10482 CaptureType = CSI->getCapture(Var).getCaptureType(); 10483 10484 // Compute the type of an expression that refers to this variable. 10485 DeclRefType = CaptureType.getNonReferenceType(); 10486 10487 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 10488 if (Cap.isCopyCapture() && 10489 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 10490 DeclRefType.addConst(); 10491 break; 10492 } 10493 10494 bool IsBlock = isa<BlockScopeInfo>(CSI); 10495 bool IsLambda = !IsBlock; 10496 10497 // Lambdas are not allowed to capture unnamed variables 10498 // (e.g. anonymous unions). 10499 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 10500 // assuming that's the intent. 10501 if (IsLambda && !Var->getDeclName()) { 10502 if (BuildAndDiagnose) { 10503 Diag(Loc, diag::err_lambda_capture_anonymous_var); 10504 Diag(Var->getLocation(), diag::note_declared_at); 10505 } 10506 return true; 10507 } 10508 10509 // Prohibit variably-modified types; they're difficult to deal with. 10510 if (Var->getType()->isVariablyModifiedType()) { 10511 if (BuildAndDiagnose) { 10512 if (IsBlock) 10513 Diag(Loc, diag::err_ref_vm_type); 10514 else 10515 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName(); 10516 Diag(Var->getLocation(), diag::note_previous_decl) 10517 << Var->getDeclName(); 10518 } 10519 return true; 10520 } 10521 10522 // Lambdas are not allowed to capture __block variables; they don't 10523 // support the expected semantics. 10524 if (IsLambda && HasBlocksAttr) { 10525 if (BuildAndDiagnose) { 10526 Diag(Loc, diag::err_lambda_capture_block) 10527 << Var->getDeclName(); 10528 Diag(Var->getLocation(), diag::note_previous_decl) 10529 << Var->getDeclName(); 10530 } 10531 return true; 10532 } 10533 10534 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 10535 // No capture-default 10536 if (BuildAndDiagnose) { 10537 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName(); 10538 Diag(Var->getLocation(), diag::note_previous_decl) 10539 << Var->getDeclName(); 10540 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 10541 diag::note_lambda_decl); 10542 } 10543 return true; 10544 } 10545 10546 FunctionScopesIndex--; 10547 DC = ParentDC; 10548 Explicit = false; 10549 } while (!Var->getDeclContext()->Equals(DC)); 10550 10551 // Walk back down the scope stack, computing the type of the capture at 10552 // each step, checking type-specific requirements, and adding captures if 10553 // requested. 10554 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N; 10555 ++I) { 10556 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 10557 10558 // Compute the type of the capture and of a reference to the capture within 10559 // this scope. 10560 if (isa<BlockScopeInfo>(CSI)) { 10561 Expr *CopyExpr = 0; 10562 bool ByRef = false; 10563 10564 // Blocks are not allowed to capture arrays. 10565 if (CaptureType->isArrayType()) { 10566 if (BuildAndDiagnose) { 10567 Diag(Loc, diag::err_ref_array_type); 10568 Diag(Var->getLocation(), diag::note_previous_decl) 10569 << Var->getDeclName(); 10570 } 10571 return true; 10572 } 10573 10574 // Forbid the block-capture of autoreleasing variables. 10575 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 10576 if (BuildAndDiagnose) { 10577 Diag(Loc, diag::err_arc_autoreleasing_capture) 10578 << /*block*/ 0; 10579 Diag(Var->getLocation(), diag::note_previous_decl) 10580 << Var->getDeclName(); 10581 } 10582 return true; 10583 } 10584 10585 if (HasBlocksAttr || CaptureType->isReferenceType()) { 10586 // Block capture by reference does not change the capture or 10587 // declaration reference types. 10588 ByRef = true; 10589 } else { 10590 // Block capture by copy introduces 'const'. 10591 CaptureType = CaptureType.getNonReferenceType().withConst(); 10592 DeclRefType = CaptureType; 10593 10594 if (getLangOpts().CPlusPlus && BuildAndDiagnose) { 10595 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 10596 // The capture logic needs the destructor, so make sure we mark it. 10597 // Usually this is unnecessary because most local variables have 10598 // their destructors marked at declaration time, but parameters are 10599 // an exception because it's technically only the call site that 10600 // actually requires the destructor. 10601 if (isa<ParmVarDecl>(Var)) 10602 FinalizeVarWithDestructor(Var, Record); 10603 10604 // According to the blocks spec, the capture of a variable from 10605 // the stack requires a const copy constructor. This is not true 10606 // of the copy/move done to move a __block variable to the heap. 10607 Expr *DeclRef = new (Context) DeclRefExpr(Var, false, 10608 DeclRefType.withConst(), 10609 VK_LValue, Loc); 10610 ExprResult Result 10611 = PerformCopyInitialization( 10612 InitializedEntity::InitializeBlock(Var->getLocation(), 10613 CaptureType, false), 10614 Loc, Owned(DeclRef)); 10615 10616 // Build a full-expression copy expression if initialization 10617 // succeeded and used a non-trivial constructor. Recover from 10618 // errors by pretending that the copy isn't necessary. 10619 if (!Result.isInvalid() && 10620 !cast<CXXConstructExpr>(Result.get())->getConstructor() 10621 ->isTrivial()) { 10622 Result = MaybeCreateExprWithCleanups(Result); 10623 CopyExpr = Result.take(); 10624 } 10625 } 10626 } 10627 } 10628 10629 // Actually capture the variable. 10630 if (BuildAndDiagnose) 10631 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 10632 SourceLocation(), CaptureType, CopyExpr); 10633 Nested = true; 10634 continue; 10635 } 10636 10637 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 10638 10639 // Determine whether we are capturing by reference or by value. 10640 bool ByRef = false; 10641 if (I == N - 1 && Kind != TryCapture_Implicit) { 10642 ByRef = (Kind == TryCapture_ExplicitByRef); 10643 } else { 10644 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 10645 } 10646 10647 // Compute the type of the field that will capture this variable. 10648 if (ByRef) { 10649 // C++11 [expr.prim.lambda]p15: 10650 // An entity is captured by reference if it is implicitly or 10651 // explicitly captured but not captured by copy. It is 10652 // unspecified whether additional unnamed non-static data 10653 // members are declared in the closure type for entities 10654 // captured by reference. 10655 // 10656 // FIXME: It is not clear whether we want to build an lvalue reference 10657 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 10658 // to do the former, while EDG does the latter. Core issue 1249 will 10659 // clarify, but for now we follow GCC because it's a more permissive and 10660 // easily defensible position. 10661 CaptureType = Context.getLValueReferenceType(DeclRefType); 10662 } else { 10663 // C++11 [expr.prim.lambda]p14: 10664 // For each entity captured by copy, an unnamed non-static 10665 // data member is declared in the closure type. The 10666 // declaration order of these members is unspecified. The type 10667 // of such a data member is the type of the corresponding 10668 // captured entity if the entity is not a reference to an 10669 // object, or the referenced type otherwise. [Note: If the 10670 // captured entity is a reference to a function, the 10671 // corresponding data member is also a reference to a 10672 // function. - end note ] 10673 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 10674 if (!RefType->getPointeeType()->isFunctionType()) 10675 CaptureType = RefType->getPointeeType(); 10676 } 10677 10678 // Forbid the lambda copy-capture of autoreleasing variables. 10679 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 10680 if (BuildAndDiagnose) { 10681 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 10682 Diag(Var->getLocation(), diag::note_previous_decl) 10683 << Var->getDeclName(); 10684 } 10685 return true; 10686 } 10687 } 10688 10689 // Capture this variable in the lambda. 10690 Expr *CopyExpr = 0; 10691 if (BuildAndDiagnose) { 10692 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType, 10693 DeclRefType, Loc, 10694 I == N-1); 10695 if (!Result.isInvalid()) 10696 CopyExpr = Result.take(); 10697 } 10698 10699 // Compute the type of a reference to this captured variable. 10700 if (ByRef) 10701 DeclRefType = CaptureType.getNonReferenceType(); 10702 else { 10703 // C++ [expr.prim.lambda]p5: 10704 // The closure type for a lambda-expression has a public inline 10705 // function call operator [...]. This function call operator is 10706 // declared const (9.3.1) if and only if the lambda-expression’s 10707 // parameter-declaration-clause is not followed by mutable. 10708 DeclRefType = CaptureType.getNonReferenceType(); 10709 if (!LSI->Mutable && !CaptureType->isReferenceType()) 10710 DeclRefType.addConst(); 10711 } 10712 10713 // Add the capture. 10714 if (BuildAndDiagnose) 10715 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc, 10716 EllipsisLoc, CaptureType, CopyExpr); 10717 Nested = true; 10718 } 10719 10720 return false; 10721 } 10722 10723 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 10724 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 10725 QualType CaptureType; 10726 QualType DeclRefType; 10727 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 10728 /*BuildAndDiagnose=*/true, CaptureType, 10729 DeclRefType); 10730 } 10731 10732 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 10733 QualType CaptureType; 10734 QualType DeclRefType; 10735 10736 // Determine whether we can capture this variable. 10737 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 10738 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType)) 10739 return QualType(); 10740 10741 return DeclRefType; 10742 } 10743 10744 static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var, 10745 SourceLocation Loc) { 10746 // Keep track of used but undefined variables. 10747 // FIXME: We shouldn't suppress this warning for static data members. 10748 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 10749 Var->getLinkage() != ExternalLinkage && 10750 !(Var->isStaticDataMember() && Var->hasInit())) { 10751 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()]; 10752 if (old.isInvalid()) old = Loc; 10753 } 10754 10755 SemaRef.tryCaptureVariable(Var, Loc); 10756 10757 Var->setUsed(true); 10758 } 10759 10760 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 10761 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 10762 // an object that satisfies the requirements for appearing in a 10763 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 10764 // is immediately applied." This function handles the lvalue-to-rvalue 10765 // conversion part. 10766 MaybeODRUseExprs.erase(E->IgnoreParens()); 10767 } 10768 10769 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 10770 if (!Res.isUsable()) 10771 return Res; 10772 10773 // If a constant-expression is a reference to a variable where we delay 10774 // deciding whether it is an odr-use, just assume we will apply the 10775 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 10776 // (a non-type template argument), we have special handling anyway. 10777 UpdateMarkingForLValueToRValue(Res.get()); 10778 return Res; 10779 } 10780 10781 void Sema::CleanupVarDeclMarking() { 10782 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 10783 e = MaybeODRUseExprs.end(); 10784 i != e; ++i) { 10785 VarDecl *Var; 10786 SourceLocation Loc; 10787 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 10788 Var = cast<VarDecl>(DRE->getDecl()); 10789 Loc = DRE->getLocation(); 10790 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 10791 Var = cast<VarDecl>(ME->getMemberDecl()); 10792 Loc = ME->getMemberLoc(); 10793 } else { 10794 llvm_unreachable("Unexpcted expression"); 10795 } 10796 10797 MarkVarDeclODRUsed(*this, Var, Loc); 10798 } 10799 10800 MaybeODRUseExprs.clear(); 10801 } 10802 10803 // Mark a VarDecl referenced, and perform the necessary handling to compute 10804 // odr-uses. 10805 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 10806 VarDecl *Var, Expr *E) { 10807 Var->setReferenced(); 10808 10809 if (!IsPotentiallyEvaluatedContext(SemaRef)) 10810 return; 10811 10812 // Implicit instantiation of static data members of class templates. 10813 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) { 10814 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 10815 assert(MSInfo && "Missing member specialization information?"); 10816 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid(); 10817 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && 10818 (!AlreadyInstantiated || 10819 Var->isUsableInConstantExpressions(SemaRef.Context))) { 10820 if (!AlreadyInstantiated) { 10821 // This is a modification of an existing AST node. Notify listeners. 10822 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 10823 L->StaticDataMemberInstantiated(Var); 10824 MSInfo->setPointOfInstantiation(Loc); 10825 } 10826 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation(); 10827 if (Var->isUsableInConstantExpressions(SemaRef.Context)) 10828 // Do not defer instantiations of variables which could be used in a 10829 // constant expression. 10830 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var); 10831 else 10832 SemaRef.PendingInstantiations.push_back( 10833 std::make_pair(Var, PointOfInstantiation)); 10834 } 10835 } 10836 10837 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 10838 // an object that satisfies the requirements for appearing in a 10839 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 10840 // is immediately applied." We check the first part here, and 10841 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 10842 // Note that we use the C++11 definition everywhere because nothing in 10843 // C++03 depends on whether we get the C++03 version correct. This does not 10844 // apply to references, since they are not objects. 10845 const VarDecl *DefVD; 10846 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() && 10847 Var->isUsableInConstantExpressions(SemaRef.Context) && 10848 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) 10849 SemaRef.MaybeODRUseExprs.insert(E); 10850 else 10851 MarkVarDeclODRUsed(SemaRef, Var, Loc); 10852 } 10853 10854 /// \brief Mark a variable referenced, and check whether it is odr-used 10855 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 10856 /// used directly for normal expressions referring to VarDecl. 10857 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 10858 DoMarkVarDeclReferenced(*this, Loc, Var, 0); 10859 } 10860 10861 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 10862 Decl *D, Expr *E) { 10863 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 10864 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 10865 return; 10866 } 10867 10868 SemaRef.MarkAnyDeclReferenced(Loc, D); 10869 10870 // If this is a call to a method via a cast, also mark the method in the 10871 // derived class used in case codegen can devirtualize the call. 10872 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10873 if (!ME) 10874 return; 10875 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 10876 if (!MD) 10877 return; 10878 const Expr *Base = ME->getBase(); 10879 if (Base->getType()->isDependentType()) 10880 return; 10881 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 10882 if (!MostDerivedClassDecl) 10883 return; 10884 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 10885 if (!DM) 10886 return; 10887 SemaRef.MarkAnyDeclReferenced(Loc, DM); 10888 } 10889 10890 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 10891 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 10892 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E); 10893 } 10894 10895 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 10896 void Sema::MarkMemberReferenced(MemberExpr *E) { 10897 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E); 10898 } 10899 10900 /// \brief Perform marking for a reference to an arbitrary declaration. It 10901 /// marks the declaration referenced, and performs odr-use checking for functions 10902 /// and variables. This method should not be used when building an normal 10903 /// expression which refers to a variable. 10904 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) { 10905 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 10906 MarkVariableReferenced(Loc, VD); 10907 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 10908 MarkFunctionReferenced(Loc, FD); 10909 else 10910 D->setReferenced(); 10911 } 10912 10913 namespace { 10914 // Mark all of the declarations referenced 10915 // FIXME: Not fully implemented yet! We need to have a better understanding 10916 // of when we're entering 10917 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 10918 Sema &S; 10919 SourceLocation Loc; 10920 10921 public: 10922 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 10923 10924 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 10925 10926 bool TraverseTemplateArgument(const TemplateArgument &Arg); 10927 bool TraverseRecordType(RecordType *T); 10928 }; 10929 } 10930 10931 bool MarkReferencedDecls::TraverseTemplateArgument( 10932 const TemplateArgument &Arg) { 10933 if (Arg.getKind() == TemplateArgument::Declaration) { 10934 if (Decl *D = Arg.getAsDecl()) 10935 S.MarkAnyDeclReferenced(Loc, D); 10936 } 10937 10938 return Inherited::TraverseTemplateArgument(Arg); 10939 } 10940 10941 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 10942 if (ClassTemplateSpecializationDecl *Spec 10943 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 10944 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 10945 return TraverseTemplateArguments(Args.data(), Args.size()); 10946 } 10947 10948 return true; 10949 } 10950 10951 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 10952 MarkReferencedDecls Marker(*this, Loc); 10953 Marker.TraverseType(Context.getCanonicalType(T)); 10954 } 10955 10956 namespace { 10957 /// \brief Helper class that marks all of the declarations referenced by 10958 /// potentially-evaluated subexpressions as "referenced". 10959 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 10960 Sema &S; 10961 bool SkipLocalVariables; 10962 10963 public: 10964 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 10965 10966 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 10967 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 10968 10969 void VisitDeclRefExpr(DeclRefExpr *E) { 10970 // If we were asked not to visit local variables, don't. 10971 if (SkipLocalVariables) { 10972 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 10973 if (VD->hasLocalStorage()) 10974 return; 10975 } 10976 10977 S.MarkDeclRefReferenced(E); 10978 } 10979 10980 void VisitMemberExpr(MemberExpr *E) { 10981 S.MarkMemberReferenced(E); 10982 Inherited::VisitMemberExpr(E); 10983 } 10984 10985 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 10986 S.MarkFunctionReferenced(E->getLocStart(), 10987 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 10988 Visit(E->getSubExpr()); 10989 } 10990 10991 void VisitCXXNewExpr(CXXNewExpr *E) { 10992 if (E->getOperatorNew()) 10993 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 10994 if (E->getOperatorDelete()) 10995 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 10996 Inherited::VisitCXXNewExpr(E); 10997 } 10998 10999 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 11000 if (E->getOperatorDelete()) 11001 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 11002 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 11003 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 11004 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 11005 S.MarkFunctionReferenced(E->getLocStart(), 11006 S.LookupDestructor(Record)); 11007 } 11008 11009 Inherited::VisitCXXDeleteExpr(E); 11010 } 11011 11012 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11013 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 11014 Inherited::VisitCXXConstructExpr(E); 11015 } 11016 11017 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 11018 Visit(E->getExpr()); 11019 } 11020 11021 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11022 Inherited::VisitImplicitCastExpr(E); 11023 11024 if (E->getCastKind() == CK_LValueToRValue) 11025 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 11026 } 11027 }; 11028 } 11029 11030 /// \brief Mark any declarations that appear within this expression or any 11031 /// potentially-evaluated subexpressions as "referenced". 11032 /// 11033 /// \param SkipLocalVariables If true, don't mark local variables as 11034 /// 'referenced'. 11035 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 11036 bool SkipLocalVariables) { 11037 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 11038 } 11039 11040 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 11041 /// of the program being compiled. 11042 /// 11043 /// This routine emits the given diagnostic when the code currently being 11044 /// type-checked is "potentially evaluated", meaning that there is a 11045 /// possibility that the code will actually be executable. Code in sizeof() 11046 /// expressions, code used only during overload resolution, etc., are not 11047 /// potentially evaluated. This routine will suppress such diagnostics or, 11048 /// in the absolutely nutty case of potentially potentially evaluated 11049 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 11050 /// later. 11051 /// 11052 /// This routine should be used for all diagnostics that describe the run-time 11053 /// behavior of a program, such as passing a non-POD value through an ellipsis. 11054 /// Failure to do so will likely result in spurious diagnostics or failures 11055 /// during overload resolution or within sizeof/alignof/typeof/typeid. 11056 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 11057 const PartialDiagnostic &PD) { 11058 switch (ExprEvalContexts.back().Context) { 11059 case Unevaluated: 11060 // The argument will never be evaluated, so don't complain. 11061 break; 11062 11063 case ConstantEvaluated: 11064 // Relevant diagnostics should be produced by constant evaluation. 11065 break; 11066 11067 case PotentiallyEvaluated: 11068 case PotentiallyEvaluatedIfUsed: 11069 if (Statement && getCurFunctionOrMethodDecl()) { 11070 FunctionScopes.back()->PossiblyUnreachableDiags. 11071 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 11072 } 11073 else 11074 Diag(Loc, PD); 11075 11076 return true; 11077 } 11078 11079 return false; 11080 } 11081 11082 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 11083 CallExpr *CE, FunctionDecl *FD) { 11084 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 11085 return false; 11086 11087 // If we're inside a decltype's expression, don't check for a valid return 11088 // type or construct temporaries until we know whether this is the last call. 11089 if (ExprEvalContexts.back().IsDecltype) { 11090 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 11091 return false; 11092 } 11093 11094 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 11095 FunctionDecl *FD; 11096 CallExpr *CE; 11097 11098 public: 11099 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 11100 : FD(FD), CE(CE) { } 11101 11102 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 11103 if (!FD) { 11104 S.Diag(Loc, diag::err_call_incomplete_return) 11105 << T << CE->getSourceRange(); 11106 return; 11107 } 11108 11109 S.Diag(Loc, diag::err_call_function_incomplete_return) 11110 << CE->getSourceRange() << FD->getDeclName() << T; 11111 S.Diag(FD->getLocation(), 11112 diag::note_function_with_incomplete_return_type_declared_here) 11113 << FD->getDeclName(); 11114 } 11115 } Diagnoser(FD, CE); 11116 11117 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 11118 return true; 11119 11120 return false; 11121 } 11122 11123 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 11124 // will prevent this condition from triggering, which is what we want. 11125 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 11126 SourceLocation Loc; 11127 11128 unsigned diagnostic = diag::warn_condition_is_assignment; 11129 bool IsOrAssign = false; 11130 11131 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 11132 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 11133 return; 11134 11135 IsOrAssign = Op->getOpcode() == BO_OrAssign; 11136 11137 // Greylist some idioms by putting them into a warning subcategory. 11138 if (ObjCMessageExpr *ME 11139 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 11140 Selector Sel = ME->getSelector(); 11141 11142 // self = [<foo> init...] 11143 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init")) 11144 diagnostic = diag::warn_condition_is_idiomatic_assignment; 11145 11146 // <foo> = [<bar> nextObject] 11147 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 11148 diagnostic = diag::warn_condition_is_idiomatic_assignment; 11149 } 11150 11151 Loc = Op->getOperatorLoc(); 11152 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 11153 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 11154 return; 11155 11156 IsOrAssign = Op->getOperator() == OO_PipeEqual; 11157 Loc = Op->getOperatorLoc(); 11158 } else { 11159 // Not an assignment. 11160 return; 11161 } 11162 11163 Diag(Loc, diagnostic) << E->getSourceRange(); 11164 11165 SourceLocation Open = E->getLocStart(); 11166 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 11167 Diag(Loc, diag::note_condition_assign_silence) 11168 << FixItHint::CreateInsertion(Open, "(") 11169 << FixItHint::CreateInsertion(Close, ")"); 11170 11171 if (IsOrAssign) 11172 Diag(Loc, diag::note_condition_or_assign_to_comparison) 11173 << FixItHint::CreateReplacement(Loc, "!="); 11174 else 11175 Diag(Loc, diag::note_condition_assign_to_comparison) 11176 << FixItHint::CreateReplacement(Loc, "=="); 11177 } 11178 11179 /// \brief Redundant parentheses over an equality comparison can indicate 11180 /// that the user intended an assignment used as condition. 11181 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 11182 // Don't warn if the parens came from a macro. 11183 SourceLocation parenLoc = ParenE->getLocStart(); 11184 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 11185 return; 11186 // Don't warn for dependent expressions. 11187 if (ParenE->isTypeDependent()) 11188 return; 11189 11190 Expr *E = ParenE->IgnoreParens(); 11191 11192 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 11193 if (opE->getOpcode() == BO_EQ && 11194 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 11195 == Expr::MLV_Valid) { 11196 SourceLocation Loc = opE->getOperatorLoc(); 11197 11198 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 11199 SourceRange ParenERange = ParenE->getSourceRange(); 11200 Diag(Loc, diag::note_equality_comparison_silence) 11201 << FixItHint::CreateRemoval(ParenERange.getBegin()) 11202 << FixItHint::CreateRemoval(ParenERange.getEnd()); 11203 Diag(Loc, diag::note_equality_comparison_to_assign) 11204 << FixItHint::CreateReplacement(Loc, "="); 11205 } 11206 } 11207 11208 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 11209 DiagnoseAssignmentAsCondition(E); 11210 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 11211 DiagnoseEqualityWithExtraParens(parenE); 11212 11213 ExprResult result = CheckPlaceholderExpr(E); 11214 if (result.isInvalid()) return ExprError(); 11215 E = result.take(); 11216 11217 if (!E->isTypeDependent()) { 11218 if (getLangOpts().CPlusPlus) 11219 return CheckCXXBooleanCondition(E); // C++ 6.4p4 11220 11221 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 11222 if (ERes.isInvalid()) 11223 return ExprError(); 11224 E = ERes.take(); 11225 11226 QualType T = E->getType(); 11227 if (!T->isScalarType()) { // C99 6.8.4.1p1 11228 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 11229 << T << E->getSourceRange(); 11230 return ExprError(); 11231 } 11232 } 11233 11234 return Owned(E); 11235 } 11236 11237 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 11238 Expr *SubExpr) { 11239 if (!SubExpr) 11240 return ExprError(); 11241 11242 return CheckBooleanCondition(SubExpr, Loc); 11243 } 11244 11245 namespace { 11246 /// A visitor for rebuilding a call to an __unknown_any expression 11247 /// to have an appropriate type. 11248 struct RebuildUnknownAnyFunction 11249 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 11250 11251 Sema &S; 11252 11253 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 11254 11255 ExprResult VisitStmt(Stmt *S) { 11256 llvm_unreachable("unexpected statement!"); 11257 } 11258 11259 ExprResult VisitExpr(Expr *E) { 11260 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 11261 << E->getSourceRange(); 11262 return ExprError(); 11263 } 11264 11265 /// Rebuild an expression which simply semantically wraps another 11266 /// expression which it shares the type and value kind of. 11267 template <class T> ExprResult rebuildSugarExpr(T *E) { 11268 ExprResult SubResult = Visit(E->getSubExpr()); 11269 if (SubResult.isInvalid()) return ExprError(); 11270 11271 Expr *SubExpr = SubResult.take(); 11272 E->setSubExpr(SubExpr); 11273 E->setType(SubExpr->getType()); 11274 E->setValueKind(SubExpr->getValueKind()); 11275 assert(E->getObjectKind() == OK_Ordinary); 11276 return E; 11277 } 11278 11279 ExprResult VisitParenExpr(ParenExpr *E) { 11280 return rebuildSugarExpr(E); 11281 } 11282 11283 ExprResult VisitUnaryExtension(UnaryOperator *E) { 11284 return rebuildSugarExpr(E); 11285 } 11286 11287 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 11288 ExprResult SubResult = Visit(E->getSubExpr()); 11289 if (SubResult.isInvalid()) return ExprError(); 11290 11291 Expr *SubExpr = SubResult.take(); 11292 E->setSubExpr(SubExpr); 11293 E->setType(S.Context.getPointerType(SubExpr->getType())); 11294 assert(E->getValueKind() == VK_RValue); 11295 assert(E->getObjectKind() == OK_Ordinary); 11296 return E; 11297 } 11298 11299 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 11300 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 11301 11302 E->setType(VD->getType()); 11303 11304 assert(E->getValueKind() == VK_RValue); 11305 if (S.getLangOpts().CPlusPlus && 11306 !(isa<CXXMethodDecl>(VD) && 11307 cast<CXXMethodDecl>(VD)->isInstance())) 11308 E->setValueKind(VK_LValue); 11309 11310 return E; 11311 } 11312 11313 ExprResult VisitMemberExpr(MemberExpr *E) { 11314 return resolveDecl(E, E->getMemberDecl()); 11315 } 11316 11317 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 11318 return resolveDecl(E, E->getDecl()); 11319 } 11320 }; 11321 } 11322 11323 /// Given a function expression of unknown-any type, try to rebuild it 11324 /// to have a function type. 11325 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 11326 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 11327 if (Result.isInvalid()) return ExprError(); 11328 return S.DefaultFunctionArrayConversion(Result.take()); 11329 } 11330 11331 namespace { 11332 /// A visitor for rebuilding an expression of type __unknown_anytype 11333 /// into one which resolves the type directly on the referring 11334 /// expression. Strict preservation of the original source 11335 /// structure is not a goal. 11336 struct RebuildUnknownAnyExpr 11337 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 11338 11339 Sema &S; 11340 11341 /// The current destination type. 11342 QualType DestType; 11343 11344 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 11345 : S(S), DestType(CastType) {} 11346 11347 ExprResult VisitStmt(Stmt *S) { 11348 llvm_unreachable("unexpected statement!"); 11349 } 11350 11351 ExprResult VisitExpr(Expr *E) { 11352 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 11353 << E->getSourceRange(); 11354 return ExprError(); 11355 } 11356 11357 ExprResult VisitCallExpr(CallExpr *E); 11358 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 11359 11360 /// Rebuild an expression which simply semantically wraps another 11361 /// expression which it shares the type and value kind of. 11362 template <class T> ExprResult rebuildSugarExpr(T *E) { 11363 ExprResult SubResult = Visit(E->getSubExpr()); 11364 if (SubResult.isInvalid()) return ExprError(); 11365 Expr *SubExpr = SubResult.take(); 11366 E->setSubExpr(SubExpr); 11367 E->setType(SubExpr->getType()); 11368 E->setValueKind(SubExpr->getValueKind()); 11369 assert(E->getObjectKind() == OK_Ordinary); 11370 return E; 11371 } 11372 11373 ExprResult VisitParenExpr(ParenExpr *E) { 11374 return rebuildSugarExpr(E); 11375 } 11376 11377 ExprResult VisitUnaryExtension(UnaryOperator *E) { 11378 return rebuildSugarExpr(E); 11379 } 11380 11381 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 11382 const PointerType *Ptr = DestType->getAs<PointerType>(); 11383 if (!Ptr) { 11384 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 11385 << E->getSourceRange(); 11386 return ExprError(); 11387 } 11388 assert(E->getValueKind() == VK_RValue); 11389 assert(E->getObjectKind() == OK_Ordinary); 11390 E->setType(DestType); 11391 11392 // Build the sub-expression as if it were an object of the pointee type. 11393 DestType = Ptr->getPointeeType(); 11394 ExprResult SubResult = Visit(E->getSubExpr()); 11395 if (SubResult.isInvalid()) return ExprError(); 11396 E->setSubExpr(SubResult.take()); 11397 return E; 11398 } 11399 11400 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 11401 11402 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 11403 11404 ExprResult VisitMemberExpr(MemberExpr *E) { 11405 return resolveDecl(E, E->getMemberDecl()); 11406 } 11407 11408 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 11409 return resolveDecl(E, E->getDecl()); 11410 } 11411 }; 11412 } 11413 11414 /// Rebuilds a call expression which yielded __unknown_anytype. 11415 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 11416 Expr *CalleeExpr = E->getCallee(); 11417 11418 enum FnKind { 11419 FK_MemberFunction, 11420 FK_FunctionPointer, 11421 FK_BlockPointer 11422 }; 11423 11424 FnKind Kind; 11425 QualType CalleeType = CalleeExpr->getType(); 11426 if (CalleeType == S.Context.BoundMemberTy) { 11427 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 11428 Kind = FK_MemberFunction; 11429 CalleeType = Expr::findBoundMemberType(CalleeExpr); 11430 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 11431 CalleeType = Ptr->getPointeeType(); 11432 Kind = FK_FunctionPointer; 11433 } else { 11434 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 11435 Kind = FK_BlockPointer; 11436 } 11437 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 11438 11439 // Verify that this is a legal result type of a function. 11440 if (DestType->isArrayType() || DestType->isFunctionType()) { 11441 unsigned diagID = diag::err_func_returning_array_function; 11442 if (Kind == FK_BlockPointer) 11443 diagID = diag::err_block_returning_array_function; 11444 11445 S.Diag(E->getExprLoc(), diagID) 11446 << DestType->isFunctionType() << DestType; 11447 return ExprError(); 11448 } 11449 11450 // Otherwise, go ahead and set DestType as the call's result. 11451 E->setType(DestType.getNonLValueExprType(S.Context)); 11452 E->setValueKind(Expr::getValueKindForType(DestType)); 11453 assert(E->getObjectKind() == OK_Ordinary); 11454 11455 // Rebuild the function type, replacing the result type with DestType. 11456 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType)) 11457 DestType = S.Context.getFunctionType(DestType, 11458 Proto->arg_type_begin(), 11459 Proto->getNumArgs(), 11460 Proto->getExtProtoInfo()); 11461 else 11462 DestType = S.Context.getFunctionNoProtoType(DestType, 11463 FnType->getExtInfo()); 11464 11465 // Rebuild the appropriate pointer-to-function type. 11466 switch (Kind) { 11467 case FK_MemberFunction: 11468 // Nothing to do. 11469 break; 11470 11471 case FK_FunctionPointer: 11472 DestType = S.Context.getPointerType(DestType); 11473 break; 11474 11475 case FK_BlockPointer: 11476 DestType = S.Context.getBlockPointerType(DestType); 11477 break; 11478 } 11479 11480 // Finally, we can recurse. 11481 ExprResult CalleeResult = Visit(CalleeExpr); 11482 if (!CalleeResult.isUsable()) return ExprError(); 11483 E->setCallee(CalleeResult.take()); 11484 11485 // Bind a temporary if necessary. 11486 return S.MaybeBindToTemporary(E); 11487 } 11488 11489 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 11490 // Verify that this is a legal result type of a call. 11491 if (DestType->isArrayType() || DestType->isFunctionType()) { 11492 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 11493 << DestType->isFunctionType() << DestType; 11494 return ExprError(); 11495 } 11496 11497 // Rewrite the method result type if available. 11498 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 11499 assert(Method->getResultType() == S.Context.UnknownAnyTy); 11500 Method->setResultType(DestType); 11501 } 11502 11503 // Change the type of the message. 11504 E->setType(DestType.getNonReferenceType()); 11505 E->setValueKind(Expr::getValueKindForType(DestType)); 11506 11507 return S.MaybeBindToTemporary(E); 11508 } 11509 11510 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 11511 // The only case we should ever see here is a function-to-pointer decay. 11512 if (E->getCastKind() == CK_FunctionToPointerDecay) { 11513 assert(E->getValueKind() == VK_RValue); 11514 assert(E->getObjectKind() == OK_Ordinary); 11515 11516 E->setType(DestType); 11517 11518 // Rebuild the sub-expression as the pointee (function) type. 11519 DestType = DestType->castAs<PointerType>()->getPointeeType(); 11520 11521 ExprResult Result = Visit(E->getSubExpr()); 11522 if (!Result.isUsable()) return ExprError(); 11523 11524 E->setSubExpr(Result.take()); 11525 return S.Owned(E); 11526 } else if (E->getCastKind() == CK_LValueToRValue) { 11527 assert(E->getValueKind() == VK_RValue); 11528 assert(E->getObjectKind() == OK_Ordinary); 11529 11530 assert(isa<BlockPointerType>(E->getType())); 11531 11532 E->setType(DestType); 11533 11534 // The sub-expression has to be a lvalue reference, so rebuild it as such. 11535 DestType = S.Context.getLValueReferenceType(DestType); 11536 11537 ExprResult Result = Visit(E->getSubExpr()); 11538 if (!Result.isUsable()) return ExprError(); 11539 11540 E->setSubExpr(Result.take()); 11541 return S.Owned(E); 11542 } else { 11543 llvm_unreachable("Unhandled cast type!"); 11544 } 11545 } 11546 11547 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 11548 ExprValueKind ValueKind = VK_LValue; 11549 QualType Type = DestType; 11550 11551 // We know how to make this work for certain kinds of decls: 11552 11553 // - functions 11554 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 11555 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 11556 DestType = Ptr->getPointeeType(); 11557 ExprResult Result = resolveDecl(E, VD); 11558 if (Result.isInvalid()) return ExprError(); 11559 return S.ImpCastExprToType(Result.take(), Type, 11560 CK_FunctionToPointerDecay, VK_RValue); 11561 } 11562 11563 if (!Type->isFunctionType()) { 11564 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 11565 << VD << E->getSourceRange(); 11566 return ExprError(); 11567 } 11568 11569 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 11570 if (MD->isInstance()) { 11571 ValueKind = VK_RValue; 11572 Type = S.Context.BoundMemberTy; 11573 } 11574 11575 // Function references aren't l-values in C. 11576 if (!S.getLangOpts().CPlusPlus) 11577 ValueKind = VK_RValue; 11578 11579 // - variables 11580 } else if (isa<VarDecl>(VD)) { 11581 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 11582 Type = RefTy->getPointeeType(); 11583 } else if (Type->isFunctionType()) { 11584 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 11585 << VD << E->getSourceRange(); 11586 return ExprError(); 11587 } 11588 11589 // - nothing else 11590 } else { 11591 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 11592 << VD << E->getSourceRange(); 11593 return ExprError(); 11594 } 11595 11596 VD->setType(DestType); 11597 E->setType(Type); 11598 E->setValueKind(ValueKind); 11599 return S.Owned(E); 11600 } 11601 11602 /// Check a cast of an unknown-any type. We intentionally only 11603 /// trigger this for C-style casts. 11604 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 11605 Expr *CastExpr, CastKind &CastKind, 11606 ExprValueKind &VK, CXXCastPath &Path) { 11607 // Rewrite the casted expression from scratch. 11608 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 11609 if (!result.isUsable()) return ExprError(); 11610 11611 CastExpr = result.take(); 11612 VK = CastExpr->getValueKind(); 11613 CastKind = CK_NoOp; 11614 11615 return CastExpr; 11616 } 11617 11618 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 11619 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 11620 } 11621 11622 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 11623 Expr *orig = E; 11624 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 11625 while (true) { 11626 E = E->IgnoreParenImpCasts(); 11627 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 11628 E = call->getCallee(); 11629 diagID = diag::err_uncasted_call_of_unknown_any; 11630 } else { 11631 break; 11632 } 11633 } 11634 11635 SourceLocation loc; 11636 NamedDecl *d; 11637 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 11638 loc = ref->getLocation(); 11639 d = ref->getDecl(); 11640 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 11641 loc = mem->getMemberLoc(); 11642 d = mem->getMemberDecl(); 11643 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 11644 diagID = diag::err_uncasted_call_of_unknown_any; 11645 loc = msg->getSelectorStartLoc(); 11646 d = msg->getMethodDecl(); 11647 if (!d) { 11648 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 11649 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 11650 << orig->getSourceRange(); 11651 return ExprError(); 11652 } 11653 } else { 11654 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 11655 << E->getSourceRange(); 11656 return ExprError(); 11657 } 11658 11659 S.Diag(loc, diagID) << d << orig->getSourceRange(); 11660 11661 // Never recoverable. 11662 return ExprError(); 11663 } 11664 11665 /// Check for operands with placeholder types and complain if found. 11666 /// Returns true if there was an error and no recovery was possible. 11667 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 11668 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 11669 if (!placeholderType) return Owned(E); 11670 11671 switch (placeholderType->getKind()) { 11672 11673 // Overloaded expressions. 11674 case BuiltinType::Overload: { 11675 // Try to resolve a single function template specialization. 11676 // This is obligatory. 11677 ExprResult result = Owned(E); 11678 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 11679 return result; 11680 11681 // If that failed, try to recover with a call. 11682 } else { 11683 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 11684 /*complain*/ true); 11685 return result; 11686 } 11687 } 11688 11689 // Bound member functions. 11690 case BuiltinType::BoundMember: { 11691 ExprResult result = Owned(E); 11692 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function), 11693 /*complain*/ true); 11694 return result; 11695 } 11696 11697 // ARC unbridged casts. 11698 case BuiltinType::ARCUnbridgedCast: { 11699 Expr *realCast = stripARCUnbridgedCast(E); 11700 diagnoseARCUnbridgedCast(realCast); 11701 return Owned(realCast); 11702 } 11703 11704 // Expressions of unknown type. 11705 case BuiltinType::UnknownAny: 11706 return diagnoseUnknownAnyExpr(*this, E); 11707 11708 // Pseudo-objects. 11709 case BuiltinType::PseudoObject: 11710 return checkPseudoObjectRValue(E); 11711 11712 // Everything else should be impossible. 11713 #define BUILTIN_TYPE(Id, SingletonId) \ 11714 case BuiltinType::Id: 11715 #define PLACEHOLDER_TYPE(Id, SingletonId) 11716 #include "clang/AST/BuiltinTypes.def" 11717 break; 11718 } 11719 11720 llvm_unreachable("invalid placeholder type!"); 11721 } 11722 11723 bool Sema::CheckCaseExpression(Expr *E) { 11724 if (E->isTypeDependent()) 11725 return true; 11726 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 11727 return E->getType()->isIntegralOrEnumerationType(); 11728 return false; 11729 } 11730 11731 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 11732 ExprResult 11733 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 11734 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 11735 "Unknown Objective-C Boolean value!"); 11736 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, 11737 Context.ObjCBuiltinBoolTy, OpLoc)); 11738 } 11739