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()) {
606     if (Ty->isObjCObjectType())
607       return VAK_Invalid;
608     return VAK_Valid;
609   }
610 
611   if (Ty.isCXX98PODType(Context))
612     return VAK_Valid;
613 
614   // C++0x [expr.call]p7:
615   //   Passing a potentially-evaluated argument of class type (Clause 9)
616   //   having a non-trivial copy constructor, a non-trivial move constructor,
617   //   or a non-trivial destructor, with no corresponding parameter,
618   //   is conditionally-supported with implementation-defined semantics.
619   if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
620     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
621       if (Record->hasTrivialCopyConstructor() &&
622           Record->hasTrivialMoveConstructor() &&
623           Record->hasTrivialDestructor())
624         return VAK_ValidInCXX11;
625 
626   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
627     return VAK_Valid;
628   return VAK_Invalid;
629 }
630 
631 bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
632   // Don't allow one to pass an Objective-C interface to a vararg.
633   const QualType & Ty = E->getType();
634 
635   // Complain about passing non-POD types through varargs.
636   switch (isValidVarArgType(Ty)) {
637   case VAK_Valid:
638     break;
639   case VAK_ValidInCXX11:
640     DiagRuntimeBehavior(E->getLocStart(), 0,
641         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
642         << E->getType() << CT);
643     break;
644   case VAK_Invalid: {
645     if (Ty->isObjCObjectType())
646       return DiagRuntimeBehavior(E->getLocStart(), 0,
647                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
648                             << Ty << CT);
649 
650     return DiagRuntimeBehavior(E->getLocStart(), 0,
651                    PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
652                    << getLangOpts().CPlusPlus0x << Ty << CT);
653   }
654   }
655   // c++ rules are enforced elsewhere.
656   return false;
657 }
658 
659 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
660 /// will create a trap if the resulting type is not a POD type.
661 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
662                                                   FunctionDecl *FDecl) {
663   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
664     // Strip the unbridged-cast placeholder expression off, if applicable.
665     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
666         (CT == VariadicMethod ||
667          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
668       E = stripARCUnbridgedCast(E);
669 
670     // Otherwise, do normal placeholder checking.
671     } else {
672       ExprResult ExprRes = CheckPlaceholderExpr(E);
673       if (ExprRes.isInvalid())
674         return ExprError();
675       E = ExprRes.take();
676     }
677   }
678 
679   ExprResult ExprRes = DefaultArgumentPromotion(E);
680   if (ExprRes.isInvalid())
681     return ExprError();
682   E = ExprRes.take();
683 
684   // Diagnostics regarding non-POD argument types are
685   // emitted along with format string checking in Sema::CheckFunctionCall().
686   if (isValidVarArgType(E->getType()) == VAK_Invalid) {
687     // Turn this into a trap.
688     CXXScopeSpec SS;
689     SourceLocation TemplateKWLoc;
690     UnqualifiedId Name;
691     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
692                        E->getLocStart());
693     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
694                                           Name, true, false);
695     if (TrapFn.isInvalid())
696       return ExprError();
697 
698     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
699                                     E->getLocStart(), MultiExprArg(),
700                                     E->getLocEnd());
701     if (Call.isInvalid())
702       return ExprError();
703 
704     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
705                                   Call.get(), E);
706     if (Comma.isInvalid())
707       return ExprError();
708     return Comma.get();
709   }
710 
711   if (!getLangOpts().CPlusPlus &&
712       RequireCompleteType(E->getExprLoc(), E->getType(),
713                           diag::err_call_incomplete_argument))
714     return ExprError();
715 
716   return Owned(E);
717 }
718 
719 /// \brief Converts an integer to complex float type.  Helper function of
720 /// UsualArithmeticConversions()
721 ///
722 /// \return false if the integer expression is an integer type and is
723 /// successfully converted to the complex type.
724 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
725                                                   ExprResult &ComplexExpr,
726                                                   QualType IntTy,
727                                                   QualType ComplexTy,
728                                                   bool SkipCast) {
729   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
730   if (SkipCast) return false;
731   if (IntTy->isIntegerType()) {
732     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
733     IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
734     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
735                                   CK_FloatingRealToComplex);
736   } else {
737     assert(IntTy->isComplexIntegerType());
738     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
739                                   CK_IntegralComplexToFloatingComplex);
740   }
741   return false;
742 }
743 
744 /// \brief Takes two complex float types and converts them to the same type.
745 /// Helper function of UsualArithmeticConversions()
746 static QualType
747 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
748                                             ExprResult &RHS, QualType LHSType,
749                                             QualType RHSType,
750                                             bool IsCompAssign) {
751   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
752 
753   if (order < 0) {
754     // _Complex float -> _Complex double
755     if (!IsCompAssign)
756       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
757     return RHSType;
758   }
759   if (order > 0)
760     // _Complex float -> _Complex double
761     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
762   return LHSType;
763 }
764 
765 /// \brief Converts otherExpr to complex float and promotes complexExpr if
766 /// necessary.  Helper function of UsualArithmeticConversions()
767 static QualType handleOtherComplexFloatConversion(Sema &S,
768                                                   ExprResult &ComplexExpr,
769                                                   ExprResult &OtherExpr,
770                                                   QualType ComplexTy,
771                                                   QualType OtherTy,
772                                                   bool ConvertComplexExpr,
773                                                   bool ConvertOtherExpr) {
774   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
775 
776   // If just the complexExpr is complex, the otherExpr needs to be converted,
777   // and the complexExpr might need to be promoted.
778   if (order > 0) { // complexExpr is wider
779     // float -> _Complex double
780     if (ConvertOtherExpr) {
781       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
782       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
783       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
784                                       CK_FloatingRealToComplex);
785     }
786     return ComplexTy;
787   }
788 
789   // otherTy is at least as wide.  Find its corresponding complex type.
790   QualType result = (order == 0 ? ComplexTy :
791                                   S.Context.getComplexType(OtherTy));
792 
793   // double -> _Complex double
794   if (ConvertOtherExpr)
795     OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
796                                     CK_FloatingRealToComplex);
797 
798   // _Complex float -> _Complex double
799   if (ConvertComplexExpr && order < 0)
800     ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
801                                       CK_FloatingComplexCast);
802 
803   return result;
804 }
805 
806 /// \brief Handle arithmetic conversion with complex types.  Helper function of
807 /// UsualArithmeticConversions()
808 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
809                                              ExprResult &RHS, QualType LHSType,
810                                              QualType RHSType,
811                                              bool IsCompAssign) {
812   // if we have an integer operand, the result is the complex type.
813   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
814                                              /*skipCast*/false))
815     return LHSType;
816   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
817                                              /*skipCast*/IsCompAssign))
818     return RHSType;
819 
820   // This handles complex/complex, complex/float, or float/complex.
821   // When both operands are complex, the shorter operand is converted to the
822   // type of the longer, and that is the type of the result. This corresponds
823   // to what is done when combining two real floating-point operands.
824   // The fun begins when size promotion occur across type domains.
825   // From H&S 6.3.4: When one operand is complex and the other is a real
826   // floating-point type, the less precise type is converted, within it's
827   // real or complex domain, to the precision of the other type. For example,
828   // when combining a "long double" with a "double _Complex", the
829   // "double _Complex" is promoted to "long double _Complex".
830 
831   bool LHSComplexFloat = LHSType->isComplexType();
832   bool RHSComplexFloat = RHSType->isComplexType();
833 
834   // If both are complex, just cast to the more precise type.
835   if (LHSComplexFloat && RHSComplexFloat)
836     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
837                                                        LHSType, RHSType,
838                                                        IsCompAssign);
839 
840   // If only one operand is complex, promote it if necessary and convert the
841   // other operand to complex.
842   if (LHSComplexFloat)
843     return handleOtherComplexFloatConversion(
844         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
845         /*convertOtherExpr*/ true);
846 
847   assert(RHSComplexFloat);
848   return handleOtherComplexFloatConversion(
849       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
850       /*convertOtherExpr*/ !IsCompAssign);
851 }
852 
853 /// \brief Hande arithmetic conversion from integer to float.  Helper function
854 /// of UsualArithmeticConversions()
855 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
856                                            ExprResult &IntExpr,
857                                            QualType FloatTy, QualType IntTy,
858                                            bool ConvertFloat, bool ConvertInt) {
859   if (IntTy->isIntegerType()) {
860     if (ConvertInt)
861       // Convert intExpr to the lhs floating point type.
862       IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
863                                     CK_IntegralToFloating);
864     return FloatTy;
865   }
866 
867   // Convert both sides to the appropriate complex float.
868   assert(IntTy->isComplexIntegerType());
869   QualType result = S.Context.getComplexType(FloatTy);
870 
871   // _Complex int -> _Complex float
872   if (ConvertInt)
873     IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
874                                   CK_IntegralComplexToFloatingComplex);
875 
876   // float -> _Complex float
877   if (ConvertFloat)
878     FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
879                                     CK_FloatingRealToComplex);
880 
881   return result;
882 }
883 
884 /// \brief Handle arithmethic conversion with floating point types.  Helper
885 /// function of UsualArithmeticConversions()
886 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
887                                       ExprResult &RHS, QualType LHSType,
888                                       QualType RHSType, bool IsCompAssign) {
889   bool LHSFloat = LHSType->isRealFloatingType();
890   bool RHSFloat = RHSType->isRealFloatingType();
891 
892   // If we have two real floating types, convert the smaller operand
893   // to the bigger result.
894   if (LHSFloat && RHSFloat) {
895     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
896     if (order > 0) {
897       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
898       return LHSType;
899     }
900 
901     assert(order < 0 && "illegal float comparison");
902     if (!IsCompAssign)
903       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
904     return RHSType;
905   }
906 
907   if (LHSFloat)
908     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
909                                       /*convertFloat=*/!IsCompAssign,
910                                       /*convertInt=*/ true);
911   assert(RHSFloat);
912   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
913                                     /*convertInt=*/ true,
914                                     /*convertFloat=*/!IsCompAssign);
915 }
916 
917 /// \brief Handle conversions with GCC complex int extension.  Helper function
918 /// of UsualArithmeticConversions()
919 // FIXME: if the operands are (int, _Complex long), we currently
920 // don't promote the complex.  Also, signedness?
921 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
922                                            ExprResult &RHS, QualType LHSType,
923                                            QualType RHSType,
924                                            bool IsCompAssign) {
925   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
926   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
927 
928   if (LHSComplexInt && RHSComplexInt) {
929     int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
930                                               RHSComplexInt->getElementType());
931     assert(order && "inequal types with equal element ordering");
932     if (order > 0) {
933       // _Complex int -> _Complex long
934       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
935       return LHSType;
936     }
937 
938     if (!IsCompAssign)
939       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
940     return RHSType;
941   }
942 
943   if (LHSComplexInt) {
944     // int -> _Complex int
945     // FIXME: This needs to take integer ranks into account
946     RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
947                               CK_IntegralCast);
948     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
949     return LHSType;
950   }
951 
952   assert(RHSComplexInt);
953   // int -> _Complex int
954   // FIXME: This needs to take integer ranks into account
955   if (!IsCompAssign) {
956     LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
957                               CK_IntegralCast);
958     LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
959   }
960   return RHSType;
961 }
962 
963 /// \brief Handle integer arithmetic conversions.  Helper function of
964 /// UsualArithmeticConversions()
965 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
966                                         ExprResult &RHS, QualType LHSType,
967                                         QualType RHSType, bool IsCompAssign) {
968   // The rules for this case are in C99 6.3.1.8
969   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
970   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
971   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
972   if (LHSSigned == RHSSigned) {
973     // Same signedness; use the higher-ranked type
974     if (order >= 0) {
975       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
976       return LHSType;
977     } else if (!IsCompAssign)
978       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
979     return RHSType;
980   } else if (order != (LHSSigned ? 1 : -1)) {
981     // The unsigned type has greater than or equal rank to the
982     // signed type, so use the unsigned type
983     if (RHSSigned) {
984       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
985       return LHSType;
986     } else if (!IsCompAssign)
987       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
988     return RHSType;
989   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
990     // The two types are different widths; if we are here, that
991     // means the signed type is larger than the unsigned type, so
992     // use the signed type.
993     if (LHSSigned) {
994       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
995       return LHSType;
996     } else if (!IsCompAssign)
997       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
998     return RHSType;
999   } else {
1000     // The signed type is higher-ranked than the unsigned type,
1001     // but isn't actually any bigger (like unsigned int and long
1002     // on most 32-bit systems).  Use the unsigned type corresponding
1003     // to the signed type.
1004     QualType result =
1005       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1006     RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
1007     if (!IsCompAssign)
1008       LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
1009     return result;
1010   }
1011 }
1012 
1013 /// UsualArithmeticConversions - Performs various conversions that are common to
1014 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1015 /// routine returns the first non-arithmetic type found. The client is
1016 /// responsible for emitting appropriate error diagnostics.
1017 /// FIXME: verify the conversion rules for "complex int" are consistent with
1018 /// GCC.
1019 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1020                                           bool IsCompAssign) {
1021   if (!IsCompAssign) {
1022     LHS = UsualUnaryConversions(LHS.take());
1023     if (LHS.isInvalid())
1024       return QualType();
1025   }
1026 
1027   RHS = UsualUnaryConversions(RHS.take());
1028   if (RHS.isInvalid())
1029     return QualType();
1030 
1031   // For conversion purposes, we ignore any qualifiers.
1032   // For example, "const float" and "float" are equivalent.
1033   QualType LHSType =
1034     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1035   QualType RHSType =
1036     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1037 
1038   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1039   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1040     LHSType = AtomicLHS->getValueType();
1041 
1042   // If both types are identical, no conversion is needed.
1043   if (LHSType == RHSType)
1044     return LHSType;
1045 
1046   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1047   // The caller can deal with this (e.g. pointer + int).
1048   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1049     return QualType();
1050 
1051   // Apply unary and bitfield promotions to the LHS's type.
1052   QualType LHSUnpromotedType = LHSType;
1053   if (LHSType->isPromotableIntegerType())
1054     LHSType = Context.getPromotedIntegerType(LHSType);
1055   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1056   if (!LHSBitfieldPromoteTy.isNull())
1057     LHSType = LHSBitfieldPromoteTy;
1058   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1059     LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
1060 
1061   // If both types are identical, no conversion is needed.
1062   if (LHSType == RHSType)
1063     return LHSType;
1064 
1065   // At this point, we have two different arithmetic types.
1066 
1067   // Handle complex types first (C99 6.3.1.8p1).
1068   if (LHSType->isComplexType() || RHSType->isComplexType())
1069     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1070                                         IsCompAssign);
1071 
1072   // Now handle "real" floating types (i.e. float, double, long double).
1073   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1074     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1075                                  IsCompAssign);
1076 
1077   // Handle GCC complex int extension.
1078   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1079     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1080                                       IsCompAssign);
1081 
1082   // Finally, we have two differing integer types.
1083   return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
1084                                  IsCompAssign);
1085 }
1086 
1087 //===----------------------------------------------------------------------===//
1088 //  Semantic Analysis for various Expression Types
1089 //===----------------------------------------------------------------------===//
1090 
1091 
1092 ExprResult
1093 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1094                                 SourceLocation DefaultLoc,
1095                                 SourceLocation RParenLoc,
1096                                 Expr *ControllingExpr,
1097                                 MultiTypeArg ArgTypes,
1098                                 MultiExprArg ArgExprs) {
1099   unsigned NumAssocs = ArgTypes.size();
1100   assert(NumAssocs == ArgExprs.size());
1101 
1102   ParsedType *ParsedTypes = ArgTypes.release();
1103   Expr **Exprs = ArgExprs.release();
1104 
1105   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1106   for (unsigned i = 0; i < NumAssocs; ++i) {
1107     if (ParsedTypes[i])
1108       (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1109     else
1110       Types[i] = 0;
1111   }
1112 
1113   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1114                                              ControllingExpr, Types, Exprs,
1115                                              NumAssocs);
1116   delete [] Types;
1117   return ER;
1118 }
1119 
1120 ExprResult
1121 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1122                                  SourceLocation DefaultLoc,
1123                                  SourceLocation RParenLoc,
1124                                  Expr *ControllingExpr,
1125                                  TypeSourceInfo **Types,
1126                                  Expr **Exprs,
1127                                  unsigned NumAssocs) {
1128   bool TypeErrorFound = false,
1129        IsResultDependent = ControllingExpr->isTypeDependent(),
1130        ContainsUnexpandedParameterPack
1131          = ControllingExpr->containsUnexpandedParameterPack();
1132 
1133   for (unsigned i = 0; i < NumAssocs; ++i) {
1134     if (Exprs[i]->containsUnexpandedParameterPack())
1135       ContainsUnexpandedParameterPack = true;
1136 
1137     if (Types[i]) {
1138       if (Types[i]->getType()->containsUnexpandedParameterPack())
1139         ContainsUnexpandedParameterPack = true;
1140 
1141       if (Types[i]->getType()->isDependentType()) {
1142         IsResultDependent = true;
1143       } else {
1144         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1145         // complete object type other than a variably modified type."
1146         unsigned D = 0;
1147         if (Types[i]->getType()->isIncompleteType())
1148           D = diag::err_assoc_type_incomplete;
1149         else if (!Types[i]->getType()->isObjectType())
1150           D = diag::err_assoc_type_nonobject;
1151         else if (Types[i]->getType()->isVariablyModifiedType())
1152           D = diag::err_assoc_type_variably_modified;
1153 
1154         if (D != 0) {
1155           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1156             << Types[i]->getTypeLoc().getSourceRange()
1157             << Types[i]->getType();
1158           TypeErrorFound = true;
1159         }
1160 
1161         // C11 6.5.1.1p2 "No two generic associations in the same generic
1162         // selection shall specify compatible types."
1163         for (unsigned j = i+1; j < NumAssocs; ++j)
1164           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1165               Context.typesAreCompatible(Types[i]->getType(),
1166                                          Types[j]->getType())) {
1167             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1168                  diag::err_assoc_compatible_types)
1169               << Types[j]->getTypeLoc().getSourceRange()
1170               << Types[j]->getType()
1171               << Types[i]->getType();
1172             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1173                  diag::note_compat_assoc)
1174               << Types[i]->getTypeLoc().getSourceRange()
1175               << Types[i]->getType();
1176             TypeErrorFound = true;
1177           }
1178       }
1179     }
1180   }
1181   if (TypeErrorFound)
1182     return ExprError();
1183 
1184   // If we determined that the generic selection is result-dependent, don't
1185   // try to compute the result expression.
1186   if (IsResultDependent)
1187     return Owned(new (Context) GenericSelectionExpr(
1188                    Context, KeyLoc, ControllingExpr,
1189                    Types, Exprs, NumAssocs, DefaultLoc,
1190                    RParenLoc, ContainsUnexpandedParameterPack));
1191 
1192   SmallVector<unsigned, 1> CompatIndices;
1193   unsigned DefaultIndex = -1U;
1194   for (unsigned i = 0; i < NumAssocs; ++i) {
1195     if (!Types[i])
1196       DefaultIndex = i;
1197     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1198                                         Types[i]->getType()))
1199       CompatIndices.push_back(i);
1200   }
1201 
1202   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1203   // type compatible with at most one of the types named in its generic
1204   // association list."
1205   if (CompatIndices.size() > 1) {
1206     // We strip parens here because the controlling expression is typically
1207     // parenthesized in macro definitions.
1208     ControllingExpr = ControllingExpr->IgnoreParens();
1209     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1210       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1211       << (unsigned) CompatIndices.size();
1212     for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
1213          E = CompatIndices.end(); I != E; ++I) {
1214       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1215            diag::note_compat_assoc)
1216         << Types[*I]->getTypeLoc().getSourceRange()
1217         << Types[*I]->getType();
1218     }
1219     return ExprError();
1220   }
1221 
1222   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1223   // its controlling expression shall have type compatible with exactly one of
1224   // the types named in its generic association list."
1225   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1226     // We strip parens here because the controlling expression is typically
1227     // parenthesized in macro definitions.
1228     ControllingExpr = ControllingExpr->IgnoreParens();
1229     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1230       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1231     return ExprError();
1232   }
1233 
1234   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1235   // type name that is compatible with the type of the controlling expression,
1236   // then the result expression of the generic selection is the expression
1237   // in that generic association. Otherwise, the result expression of the
1238   // generic selection is the expression in the default generic association."
1239   unsigned ResultIndex =
1240     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1241 
1242   return Owned(new (Context) GenericSelectionExpr(
1243                  Context, KeyLoc, ControllingExpr,
1244                  Types, Exprs, NumAssocs, DefaultLoc,
1245                  RParenLoc, ContainsUnexpandedParameterPack,
1246                  ResultIndex));
1247 }
1248 
1249 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1250 /// location of the token and the offset of the ud-suffix within it.
1251 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1252                                      unsigned Offset) {
1253   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1254                                         S.getLangOpts());
1255 }
1256 
1257 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1258 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1259 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1260                                                  IdentifierInfo *UDSuffix,
1261                                                  SourceLocation UDSuffixLoc,
1262                                                  ArrayRef<Expr*> Args,
1263                                                  SourceLocation LitEndLoc) {
1264   assert(Args.size() <= 2 && "too many arguments for literal operator");
1265 
1266   QualType ArgTy[2];
1267   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1268     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1269     if (ArgTy[ArgIdx]->isArrayType())
1270       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1271   }
1272 
1273   DeclarationName OpName =
1274     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1275   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1276   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1277 
1278   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1279   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1280                               /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1281     return ExprError();
1282 
1283   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1284 }
1285 
1286 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1287 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1288 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1289 /// multiple tokens.  However, the common case is that StringToks points to one
1290 /// string.
1291 ///
1292 ExprResult
1293 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1294                          Scope *UDLScope) {
1295   assert(NumStringToks && "Must have at least one string!");
1296 
1297   StringLiteralParser Literal(StringToks, NumStringToks, PP);
1298   if (Literal.hadError)
1299     return ExprError();
1300 
1301   SmallVector<SourceLocation, 4> StringTokLocs;
1302   for (unsigned i = 0; i != NumStringToks; ++i)
1303     StringTokLocs.push_back(StringToks[i].getLocation());
1304 
1305   QualType StrTy = Context.CharTy;
1306   if (Literal.isWide())
1307     StrTy = Context.getWCharType();
1308   else if (Literal.isUTF16())
1309     StrTy = Context.Char16Ty;
1310   else if (Literal.isUTF32())
1311     StrTy = Context.Char32Ty;
1312   else if (Literal.isPascal())
1313     StrTy = Context.UnsignedCharTy;
1314 
1315   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1316   if (Literal.isWide())
1317     Kind = StringLiteral::Wide;
1318   else if (Literal.isUTF8())
1319     Kind = StringLiteral::UTF8;
1320   else if (Literal.isUTF16())
1321     Kind = StringLiteral::UTF16;
1322   else if (Literal.isUTF32())
1323     Kind = StringLiteral::UTF32;
1324 
1325   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1326   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1327     StrTy.addConst();
1328 
1329   // Get an array type for the string, according to C99 6.4.5.  This includes
1330   // the nul terminator character as well as the string length for pascal
1331   // strings.
1332   StrTy = Context.getConstantArrayType(StrTy,
1333                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1334                                        ArrayType::Normal, 0);
1335 
1336   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1337   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1338                                              Kind, Literal.Pascal, StrTy,
1339                                              &StringTokLocs[0],
1340                                              StringTokLocs.size());
1341   if (Literal.getUDSuffix().empty())
1342     return Owned(Lit);
1343 
1344   // We're building a user-defined literal.
1345   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1346   SourceLocation UDSuffixLoc =
1347     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1348                    Literal.getUDSuffixOffset());
1349 
1350   // Make sure we're allowed user-defined literals here.
1351   if (!UDLScope)
1352     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1353 
1354   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1355   //   operator "" X (str, len)
1356   QualType SizeType = Context.getSizeType();
1357   llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1358   IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1359                                                   StringTokLocs[0]);
1360   Expr *Args[] = { Lit, LenArg };
1361   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1362                                         Args, StringTokLocs.back());
1363 }
1364 
1365 ExprResult
1366 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1367                        SourceLocation Loc,
1368                        const CXXScopeSpec *SS) {
1369   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1370   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1371 }
1372 
1373 /// BuildDeclRefExpr - Build an expression that references a
1374 /// declaration that does not require a closure capture.
1375 ExprResult
1376 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1377                        const DeclarationNameInfo &NameInfo,
1378                        const CXXScopeSpec *SS) {
1379   if (getLangOpts().CUDA)
1380     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1381       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1382         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1383                            CalleeTarget = IdentifyCUDATarget(Callee);
1384         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1385           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1386             << CalleeTarget << D->getIdentifier() << CallerTarget;
1387           Diag(D->getLocation(), diag::note_previous_decl)
1388             << D->getIdentifier();
1389           return ExprError();
1390         }
1391       }
1392 
1393   bool refersToEnclosingScope =
1394     (CurContext != D->getDeclContext() &&
1395      D->getDeclContext()->isFunctionOrMethod());
1396 
1397   DeclRefExpr *E = DeclRefExpr::Create(Context,
1398                                        SS ? SS->getWithLocInContext(Context)
1399                                               : NestedNameSpecifierLoc(),
1400                                        SourceLocation(),
1401                                        D, refersToEnclosingScope,
1402                                        NameInfo, Ty, VK);
1403 
1404   MarkDeclRefReferenced(E);
1405 
1406   // Just in case we're building an illegal pointer-to-member.
1407   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1408   if (FD && FD->isBitField())
1409     E->setObjectKind(OK_BitField);
1410 
1411   return Owned(E);
1412 }
1413 
1414 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1415 /// possibly a list of template arguments.
1416 ///
1417 /// If this produces template arguments, it is permitted to call
1418 /// DecomposeTemplateName.
1419 ///
1420 /// This actually loses a lot of source location information for
1421 /// non-standard name kinds; we should consider preserving that in
1422 /// some way.
1423 void
1424 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1425                              TemplateArgumentListInfo &Buffer,
1426                              DeclarationNameInfo &NameInfo,
1427                              const TemplateArgumentListInfo *&TemplateArgs) {
1428   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1429     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1430     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1431 
1432     ASTTemplateArgsPtr TemplateArgsPtr(*this,
1433                                        Id.TemplateId->getTemplateArgs(),
1434                                        Id.TemplateId->NumArgs);
1435     translateTemplateArguments(TemplateArgsPtr, Buffer);
1436     TemplateArgsPtr.release();
1437 
1438     TemplateName TName = Id.TemplateId->Template.get();
1439     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1440     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1441     TemplateArgs = &Buffer;
1442   } else {
1443     NameInfo = GetNameFromUnqualifiedId(Id);
1444     TemplateArgs = 0;
1445   }
1446 }
1447 
1448 /// Diagnose an empty lookup.
1449 ///
1450 /// \return false if new lookup candidates were found
1451 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1452                                CorrectionCandidateCallback &CCC,
1453                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1454                                llvm::ArrayRef<Expr *> Args) {
1455   DeclarationName Name = R.getLookupName();
1456 
1457   unsigned diagnostic = diag::err_undeclared_var_use;
1458   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1459   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1460       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1461       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1462     diagnostic = diag::err_undeclared_use;
1463     diagnostic_suggest = diag::err_undeclared_use_suggest;
1464   }
1465 
1466   // If the original lookup was an unqualified lookup, fake an
1467   // unqualified lookup.  This is useful when (for example) the
1468   // original lookup would not have found something because it was a
1469   // dependent name.
1470   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1471     ? CurContext : 0;
1472   while (DC) {
1473     if (isa<CXXRecordDecl>(DC)) {
1474       LookupQualifiedName(R, DC);
1475 
1476       if (!R.empty()) {
1477         // Don't give errors about ambiguities in this lookup.
1478         R.suppressDiagnostics();
1479 
1480         // During a default argument instantiation the CurContext points
1481         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1482         // function parameter list, hence add an explicit check.
1483         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1484                               ActiveTemplateInstantiations.back().Kind ==
1485             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1486         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1487         bool isInstance = CurMethod &&
1488                           CurMethod->isInstance() &&
1489                           DC == CurMethod->getParent() && !isDefaultArgument;
1490 
1491 
1492         // Give a code modification hint to insert 'this->'.
1493         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1494         // Actually quite difficult!
1495         if (getLangOpts().MicrosoftMode)
1496           diagnostic = diag::warn_found_via_dependent_bases_lookup;
1497         if (isInstance) {
1498           Diag(R.getNameLoc(), diagnostic) << Name
1499             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1500           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1501               CallsUndergoingInstantiation.back()->getCallee());
1502 
1503 
1504           CXXMethodDecl *DepMethod;
1505           if (CurMethod->getTemplatedKind() ==
1506               FunctionDecl::TK_FunctionTemplateSpecialization)
1507             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1508                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1509           else
1510             DepMethod = cast<CXXMethodDecl>(
1511                 CurMethod->getInstantiatedFromMemberFunction());
1512           assert(DepMethod && "No template pattern found");
1513 
1514           QualType DepThisType = DepMethod->getThisType(Context);
1515           CheckCXXThisCapture(R.getNameLoc());
1516           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1517                                      R.getNameLoc(), DepThisType, false);
1518           TemplateArgumentListInfo TList;
1519           if (ULE->hasExplicitTemplateArgs())
1520             ULE->copyTemplateArgumentsInto(TList);
1521 
1522           CXXScopeSpec SS;
1523           SS.Adopt(ULE->getQualifierLoc());
1524           CXXDependentScopeMemberExpr *DepExpr =
1525               CXXDependentScopeMemberExpr::Create(
1526                   Context, DepThis, DepThisType, true, SourceLocation(),
1527                   SS.getWithLocInContext(Context),
1528                   ULE->getTemplateKeywordLoc(), 0,
1529                   R.getLookupNameInfo(),
1530                   ULE->hasExplicitTemplateArgs() ? &TList : 0);
1531           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1532         } else {
1533           Diag(R.getNameLoc(), diagnostic) << Name;
1534         }
1535 
1536         // Do we really want to note all of these?
1537         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1538           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1539 
1540         // Return true if we are inside a default argument instantiation
1541         // and the found name refers to an instance member function, otherwise
1542         // the function calling DiagnoseEmptyLookup will try to create an
1543         // implicit member call and this is wrong for default argument.
1544         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1545           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1546           return true;
1547         }
1548 
1549         // Tell the callee to try to recover.
1550         return false;
1551       }
1552 
1553       R.clear();
1554     }
1555 
1556     // In Microsoft mode, if we are performing lookup from within a friend
1557     // function definition declared at class scope then we must set
1558     // DC to the lexical parent to be able to search into the parent
1559     // class.
1560     if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
1561         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1562         DC->getLexicalParent()->isRecord())
1563       DC = DC->getLexicalParent();
1564     else
1565       DC = DC->getParent();
1566   }
1567 
1568   // We didn't find anything, so try to correct for a typo.
1569   TypoCorrection Corrected;
1570   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1571                                     S, &SS, CCC))) {
1572     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1573     std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
1574     R.setLookupName(Corrected.getCorrection());
1575 
1576     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
1577       if (Corrected.isOverloaded()) {
1578         OverloadCandidateSet OCS(R.getNameLoc());
1579         OverloadCandidateSet::iterator Best;
1580         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1581                                         CDEnd = Corrected.end();
1582              CD != CDEnd; ++CD) {
1583           if (FunctionTemplateDecl *FTD =
1584                    dyn_cast<FunctionTemplateDecl>(*CD))
1585             AddTemplateOverloadCandidate(
1586                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1587                 Args, OCS);
1588           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1589             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1590               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1591                                    Args, OCS);
1592         }
1593         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1594           case OR_Success:
1595             ND = Best->Function;
1596             break;
1597           default:
1598             break;
1599         }
1600       }
1601       R.addDecl(ND);
1602       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
1603         if (SS.isEmpty())
1604           Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1605             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1606         else
1607           Diag(R.getNameLoc(), diag::err_no_member_suggest)
1608             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1609             << SS.getRange()
1610             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1611         if (ND)
1612           Diag(ND->getLocation(), diag::note_previous_decl)
1613             << CorrectedQuotedStr;
1614 
1615         // Tell the callee to try to recover.
1616         return false;
1617       }
1618 
1619       if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
1620         // FIXME: If we ended up with a typo for a type name or
1621         // Objective-C class name, we're in trouble because the parser
1622         // is in the wrong place to recover. Suggest the typo
1623         // correction, but don't make it a fix-it since we're not going
1624         // to recover well anyway.
1625         if (SS.isEmpty())
1626           Diag(R.getNameLoc(), diagnostic_suggest)
1627             << Name << CorrectedQuotedStr;
1628         else
1629           Diag(R.getNameLoc(), diag::err_no_member_suggest)
1630             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1631             << SS.getRange();
1632 
1633         // Don't try to recover; it won't work.
1634         return true;
1635       }
1636     } else {
1637       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1638       // because we aren't able to recover.
1639       if (SS.isEmpty())
1640         Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
1641       else
1642         Diag(R.getNameLoc(), diag::err_no_member_suggest)
1643         << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1644         << SS.getRange();
1645       return true;
1646     }
1647   }
1648   R.clear();
1649 
1650   // Emit a special diagnostic for failed member lookups.
1651   // FIXME: computing the declaration context might fail here (?)
1652   if (!SS.isEmpty()) {
1653     Diag(R.getNameLoc(), diag::err_no_member)
1654       << Name << computeDeclContext(SS, false)
1655       << SS.getRange();
1656     return true;
1657   }
1658 
1659   // Give up, we can't recover.
1660   Diag(R.getNameLoc(), diagnostic) << Name;
1661   return true;
1662 }
1663 
1664 ExprResult Sema::ActOnIdExpression(Scope *S,
1665                                    CXXScopeSpec &SS,
1666                                    SourceLocation TemplateKWLoc,
1667                                    UnqualifiedId &Id,
1668                                    bool HasTrailingLParen,
1669                                    bool IsAddressOfOperand,
1670                                    CorrectionCandidateCallback *CCC) {
1671   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1672          "cannot be direct & operand and have a trailing lparen");
1673 
1674   if (SS.isInvalid())
1675     return ExprError();
1676 
1677   TemplateArgumentListInfo TemplateArgsBuffer;
1678 
1679   // Decompose the UnqualifiedId into the following data.
1680   DeclarationNameInfo NameInfo;
1681   const TemplateArgumentListInfo *TemplateArgs;
1682   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1683 
1684   DeclarationName Name = NameInfo.getName();
1685   IdentifierInfo *II = Name.getAsIdentifierInfo();
1686   SourceLocation NameLoc = NameInfo.getLoc();
1687 
1688   // C++ [temp.dep.expr]p3:
1689   //   An id-expression is type-dependent if it contains:
1690   //     -- an identifier that was declared with a dependent type,
1691   //        (note: handled after lookup)
1692   //     -- a template-id that is dependent,
1693   //        (note: handled in BuildTemplateIdExpr)
1694   //     -- a conversion-function-id that specifies a dependent type,
1695   //     -- a nested-name-specifier that contains a class-name that
1696   //        names a dependent type.
1697   // Determine whether this is a member of an unknown specialization;
1698   // we need to handle these differently.
1699   bool DependentID = false;
1700   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1701       Name.getCXXNameType()->isDependentType()) {
1702     DependentID = true;
1703   } else if (SS.isSet()) {
1704     if (DeclContext *DC = computeDeclContext(SS, false)) {
1705       if (RequireCompleteDeclContext(SS, DC))
1706         return ExprError();
1707     } else {
1708       DependentID = true;
1709     }
1710   }
1711 
1712   if (DependentID)
1713     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1714                                       IsAddressOfOperand, TemplateArgs);
1715 
1716   // Perform the required lookup.
1717   LookupResult R(*this, NameInfo,
1718                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1719                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1720   if (TemplateArgs) {
1721     // Lookup the template name again to correctly establish the context in
1722     // which it was found. This is really unfortunate as we already did the
1723     // lookup to determine that it was a template name in the first place. If
1724     // this becomes a performance hit, we can work harder to preserve those
1725     // results until we get here but it's likely not worth it.
1726     bool MemberOfUnknownSpecialization;
1727     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1728                        MemberOfUnknownSpecialization);
1729 
1730     if (MemberOfUnknownSpecialization ||
1731         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1732       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1733                                         IsAddressOfOperand, TemplateArgs);
1734   } else {
1735     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
1736     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1737 
1738     // If the result might be in a dependent base class, this is a dependent
1739     // id-expression.
1740     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1741       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1742                                         IsAddressOfOperand, TemplateArgs);
1743 
1744     // If this reference is in an Objective-C method, then we need to do
1745     // some special Objective-C lookup, too.
1746     if (IvarLookupFollowUp) {
1747       ExprResult E(LookupInObjCMethod(R, S, II, true));
1748       if (E.isInvalid())
1749         return ExprError();
1750 
1751       if (Expr *Ex = E.takeAs<Expr>())
1752         return Owned(Ex);
1753     }
1754   }
1755 
1756   if (R.isAmbiguous())
1757     return ExprError();
1758 
1759   // Determine whether this name might be a candidate for
1760   // argument-dependent lookup.
1761   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1762 
1763   if (R.empty() && !ADL) {
1764     // Otherwise, this could be an implicitly declared function reference (legal
1765     // in C90, extension in C99, forbidden in C++).
1766     if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
1767       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1768       if (D) R.addDecl(D);
1769     }
1770 
1771     // If this name wasn't predeclared and if this is not a function
1772     // call, diagnose the problem.
1773     if (R.empty()) {
1774 
1775       // In Microsoft mode, if we are inside a template class member function
1776       // and we can't resolve an identifier then assume the identifier is type
1777       // dependent. The goal is to postpone name lookup to instantiation time
1778       // to be able to search into type dependent base classes.
1779       if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
1780           isa<CXXMethodDecl>(CurContext))
1781         return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1782                                           IsAddressOfOperand, TemplateArgs);
1783 
1784       CorrectionCandidateCallback DefaultValidator;
1785       if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
1786         return ExprError();
1787 
1788       assert(!R.empty() &&
1789              "DiagnoseEmptyLookup returned false but added no results");
1790 
1791       // If we found an Objective-C instance variable, let
1792       // LookupInObjCMethod build the appropriate expression to
1793       // reference the ivar.
1794       if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1795         R.clear();
1796         ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1797         // In a hopelessly buggy code, Objective-C instance variable
1798         // lookup fails and no expression will be built to reference it.
1799         if (!E.isInvalid() && !E.get())
1800           return ExprError();
1801         return move(E);
1802       }
1803     }
1804   }
1805 
1806   // This is guaranteed from this point on.
1807   assert(!R.empty() || ADL);
1808 
1809   // Check whether this might be a C++ implicit instance member access.
1810   // C++ [class.mfct.non-static]p3:
1811   //   When an id-expression that is not part of a class member access
1812   //   syntax and not used to form a pointer to member is used in the
1813   //   body of a non-static member function of class X, if name lookup
1814   //   resolves the name in the id-expression to a non-static non-type
1815   //   member of some class C, the id-expression is transformed into a
1816   //   class member access expression using (*this) as the
1817   //   postfix-expression to the left of the . operator.
1818   //
1819   // But we don't actually need to do this for '&' operands if R
1820   // resolved to a function or overloaded function set, because the
1821   // expression is ill-formed if it actually works out to be a
1822   // non-static member function:
1823   //
1824   // C++ [expr.ref]p4:
1825   //   Otherwise, if E1.E2 refers to a non-static member function. . .
1826   //   [t]he expression can be used only as the left-hand operand of a
1827   //   member function call.
1828   //
1829   // There are other safeguards against such uses, but it's important
1830   // to get this right here so that we don't end up making a
1831   // spuriously dependent expression if we're inside a dependent
1832   // instance method.
1833   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1834     bool MightBeImplicitMember;
1835     if (!IsAddressOfOperand)
1836       MightBeImplicitMember = true;
1837     else if (!SS.isEmpty())
1838       MightBeImplicitMember = false;
1839     else if (R.isOverloadedResult())
1840       MightBeImplicitMember = false;
1841     else if (R.isUnresolvableResult())
1842       MightBeImplicitMember = true;
1843     else
1844       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1845                               isa<IndirectFieldDecl>(R.getFoundDecl());
1846 
1847     if (MightBeImplicitMember)
1848       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1849                                              R, TemplateArgs);
1850   }
1851 
1852   if (TemplateArgs || TemplateKWLoc.isValid())
1853     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
1854 
1855   return BuildDeclarationNameExpr(SS, R, ADL);
1856 }
1857 
1858 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1859 /// declaration name, generally during template instantiation.
1860 /// There's a large number of things which don't need to be done along
1861 /// this path.
1862 ExprResult
1863 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
1864                                         const DeclarationNameInfo &NameInfo) {
1865   DeclContext *DC;
1866   if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
1867     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1868                                      NameInfo, /*TemplateArgs=*/0);
1869 
1870   if (RequireCompleteDeclContext(SS, DC))
1871     return ExprError();
1872 
1873   LookupResult R(*this, NameInfo, LookupOrdinaryName);
1874   LookupQualifiedName(R, DC);
1875 
1876   if (R.isAmbiguous())
1877     return ExprError();
1878 
1879   if (R.empty()) {
1880     Diag(NameInfo.getLoc(), diag::err_no_member)
1881       << NameInfo.getName() << DC << SS.getRange();
1882     return ExprError();
1883   }
1884 
1885   return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1886 }
1887 
1888 /// LookupInObjCMethod - The parser has read a name in, and Sema has
1889 /// detected that we're currently inside an ObjC method.  Perform some
1890 /// additional lookup.
1891 ///
1892 /// Ideally, most of this would be done by lookup, but there's
1893 /// actually quite a lot of extra work involved.
1894 ///
1895 /// Returns a null sentinel to indicate trivial success.
1896 ExprResult
1897 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1898                          IdentifierInfo *II, bool AllowBuiltinCreation) {
1899   SourceLocation Loc = Lookup.getNameLoc();
1900   ObjCMethodDecl *CurMethod = getCurMethodDecl();
1901 
1902   // There are two cases to handle here.  1) scoped lookup could have failed,
1903   // in which case we should look for an ivar.  2) scoped lookup could have
1904   // found a decl, but that decl is outside the current instance method (i.e.
1905   // a global variable).  In these two cases, we do a lookup for an ivar with
1906   // this name, if the lookup sucedes, we replace it our current decl.
1907 
1908   // If we're in a class method, we don't normally want to look for
1909   // ivars.  But if we don't find anything else, and there's an
1910   // ivar, that's an error.
1911   bool IsClassMethod = CurMethod->isClassMethod();
1912 
1913   bool LookForIvars;
1914   if (Lookup.empty())
1915     LookForIvars = true;
1916   else if (IsClassMethod)
1917     LookForIvars = false;
1918   else
1919     LookForIvars = (Lookup.isSingleResult() &&
1920                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1921   ObjCInterfaceDecl *IFace = 0;
1922   if (LookForIvars) {
1923     IFace = CurMethod->getClassInterface();
1924     ObjCInterfaceDecl *ClassDeclared;
1925     ObjCIvarDecl *IV = 0;
1926     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
1927       // Diagnose using an ivar in a class method.
1928       if (IsClassMethod)
1929         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1930                          << IV->getDeclName());
1931 
1932       // If we're referencing an invalid decl, just return this as a silent
1933       // error node.  The error diagnostic was already emitted on the decl.
1934       if (IV->isInvalidDecl())
1935         return ExprError();
1936 
1937       // Check if referencing a field with __attribute__((deprecated)).
1938       if (DiagnoseUseOfDecl(IV, Loc))
1939         return ExprError();
1940 
1941       // Diagnose the use of an ivar outside of the declaring class.
1942       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1943           !declaresSameEntity(ClassDeclared, IFace) &&
1944           !getLangOpts().DebuggerSupport)
1945         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1946 
1947       // FIXME: This should use a new expr for a direct reference, don't
1948       // turn this into Self->ivar, just return a BareIVarExpr or something.
1949       IdentifierInfo &II = Context.Idents.get("self");
1950       UnqualifiedId SelfName;
1951       SelfName.setIdentifier(&II, SourceLocation());
1952       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
1953       CXXScopeSpec SelfScopeSpec;
1954       SourceLocation TemplateKWLoc;
1955       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
1956                                               SelfName, false, false);
1957       if (SelfExpr.isInvalid())
1958         return ExprError();
1959 
1960       SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1961       if (SelfExpr.isInvalid())
1962         return ExprError();
1963 
1964       MarkAnyDeclReferenced(Loc, IV);
1965       return Owned(new (Context)
1966                    ObjCIvarRefExpr(IV, IV->getType(), Loc,
1967                                    SelfExpr.take(), true, true));
1968     }
1969   } else if (CurMethod->isInstanceMethod()) {
1970     // We should warn if a local variable hides an ivar.
1971     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1972       ObjCInterfaceDecl *ClassDeclared;
1973       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1974         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1975             declaresSameEntity(IFace, ClassDeclared))
1976           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1977       }
1978     }
1979   } else if (Lookup.isSingleResult() &&
1980              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
1981     // If accessing a stand-alone ivar in a class method, this is an error.
1982     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
1983       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1984                        << IV->getDeclName());
1985   }
1986 
1987   if (Lookup.empty() && II && AllowBuiltinCreation) {
1988     // FIXME. Consolidate this with similar code in LookupName.
1989     if (unsigned BuiltinID = II->getBuiltinID()) {
1990       if (!(getLangOpts().CPlusPlus &&
1991             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1992         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1993                                            S, Lookup.isForRedeclaration(),
1994                                            Lookup.getNameLoc());
1995         if (D) Lookup.addDecl(D);
1996       }
1997     }
1998   }
1999   // Sentinel value saying that we didn't do anything special.
2000   return Owned((Expr*) 0);
2001 }
2002 
2003 /// \brief Cast a base object to a member's actual type.
2004 ///
2005 /// Logically this happens in three phases:
2006 ///
2007 /// * First we cast from the base type to the naming class.
2008 ///   The naming class is the class into which we were looking
2009 ///   when we found the member;  it's the qualifier type if a
2010 ///   qualifier was provided, and otherwise it's the base type.
2011 ///
2012 /// * Next we cast from the naming class to the declaring class.
2013 ///   If the member we found was brought into a class's scope by
2014 ///   a using declaration, this is that class;  otherwise it's
2015 ///   the class declaring the member.
2016 ///
2017 /// * Finally we cast from the declaring class to the "true"
2018 ///   declaring class of the member.  This conversion does not
2019 ///   obey access control.
2020 ExprResult
2021 Sema::PerformObjectMemberConversion(Expr *From,
2022                                     NestedNameSpecifier *Qualifier,
2023                                     NamedDecl *FoundDecl,
2024                                     NamedDecl *Member) {
2025   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2026   if (!RD)
2027     return Owned(From);
2028 
2029   QualType DestRecordType;
2030   QualType DestType;
2031   QualType FromRecordType;
2032   QualType FromType = From->getType();
2033   bool PointerConversions = false;
2034   if (isa<FieldDecl>(Member)) {
2035     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2036 
2037     if (FromType->getAs<PointerType>()) {
2038       DestType = Context.getPointerType(DestRecordType);
2039       FromRecordType = FromType->getPointeeType();
2040       PointerConversions = true;
2041     } else {
2042       DestType = DestRecordType;
2043       FromRecordType = FromType;
2044     }
2045   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2046     if (Method->isStatic())
2047       return Owned(From);
2048 
2049     DestType = Method->getThisType(Context);
2050     DestRecordType = DestType->getPointeeType();
2051 
2052     if (FromType->getAs<PointerType>()) {
2053       FromRecordType = FromType->getPointeeType();
2054       PointerConversions = true;
2055     } else {
2056       FromRecordType = FromType;
2057       DestType = DestRecordType;
2058     }
2059   } else {
2060     // No conversion necessary.
2061     return Owned(From);
2062   }
2063 
2064   if (DestType->isDependentType() || FromType->isDependentType())
2065     return Owned(From);
2066 
2067   // If the unqualified types are the same, no conversion is necessary.
2068   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2069     return Owned(From);
2070 
2071   SourceRange FromRange = From->getSourceRange();
2072   SourceLocation FromLoc = FromRange.getBegin();
2073 
2074   ExprValueKind VK = From->getValueKind();
2075 
2076   // C++ [class.member.lookup]p8:
2077   //   [...] Ambiguities can often be resolved by qualifying a name with its
2078   //   class name.
2079   //
2080   // If the member was a qualified name and the qualified referred to a
2081   // specific base subobject type, we'll cast to that intermediate type
2082   // first and then to the object in which the member is declared. That allows
2083   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2084   //
2085   //   class Base { public: int x; };
2086   //   class Derived1 : public Base { };
2087   //   class Derived2 : public Base { };
2088   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2089   //
2090   //   void VeryDerived::f() {
2091   //     x = 17; // error: ambiguous base subobjects
2092   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2093   //   }
2094   if (Qualifier) {
2095     QualType QType = QualType(Qualifier->getAsType(), 0);
2096     assert(!QType.isNull() && "lookup done with dependent qualifier?");
2097     assert(QType->isRecordType() && "lookup done with non-record type");
2098 
2099     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2100 
2101     // In C++98, the qualifier type doesn't actually have to be a base
2102     // type of the object type, in which case we just ignore it.
2103     // Otherwise build the appropriate casts.
2104     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2105       CXXCastPath BasePath;
2106       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2107                                        FromLoc, FromRange, &BasePath))
2108         return ExprError();
2109 
2110       if (PointerConversions)
2111         QType = Context.getPointerType(QType);
2112       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2113                                VK, &BasePath).take();
2114 
2115       FromType = QType;
2116       FromRecordType = QRecordType;
2117 
2118       // If the qualifier type was the same as the destination type,
2119       // we're done.
2120       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2121         return Owned(From);
2122     }
2123   }
2124 
2125   bool IgnoreAccess = false;
2126 
2127   // If we actually found the member through a using declaration, cast
2128   // down to the using declaration's type.
2129   //
2130   // Pointer equality is fine here because only one declaration of a
2131   // class ever has member declarations.
2132   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2133     assert(isa<UsingShadowDecl>(FoundDecl));
2134     QualType URecordType = Context.getTypeDeclType(
2135                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2136 
2137     // We only need to do this if the naming-class to declaring-class
2138     // conversion is non-trivial.
2139     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2140       assert(IsDerivedFrom(FromRecordType, URecordType));
2141       CXXCastPath BasePath;
2142       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2143                                        FromLoc, FromRange, &BasePath))
2144         return ExprError();
2145 
2146       QualType UType = URecordType;
2147       if (PointerConversions)
2148         UType = Context.getPointerType(UType);
2149       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2150                                VK, &BasePath).take();
2151       FromType = UType;
2152       FromRecordType = URecordType;
2153     }
2154 
2155     // We don't do access control for the conversion from the
2156     // declaring class to the true declaring class.
2157     IgnoreAccess = true;
2158   }
2159 
2160   CXXCastPath BasePath;
2161   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2162                                    FromLoc, FromRange, &BasePath,
2163                                    IgnoreAccess))
2164     return ExprError();
2165 
2166   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2167                            VK, &BasePath);
2168 }
2169 
2170 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2171                                       const LookupResult &R,
2172                                       bool HasTrailingLParen) {
2173   // Only when used directly as the postfix-expression of a call.
2174   if (!HasTrailingLParen)
2175     return false;
2176 
2177   // Never if a scope specifier was provided.
2178   if (SS.isSet())
2179     return false;
2180 
2181   // Only in C++ or ObjC++.
2182   if (!getLangOpts().CPlusPlus)
2183     return false;
2184 
2185   // Turn off ADL when we find certain kinds of declarations during
2186   // normal lookup:
2187   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2188     NamedDecl *D = *I;
2189 
2190     // C++0x [basic.lookup.argdep]p3:
2191     //     -- a declaration of a class member
2192     // Since using decls preserve this property, we check this on the
2193     // original decl.
2194     if (D->isCXXClassMember())
2195       return false;
2196 
2197     // C++0x [basic.lookup.argdep]p3:
2198     //     -- a block-scope function declaration that is not a
2199     //        using-declaration
2200     // NOTE: we also trigger this for function templates (in fact, we
2201     // don't check the decl type at all, since all other decl types
2202     // turn off ADL anyway).
2203     if (isa<UsingShadowDecl>(D))
2204       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2205     else if (D->getDeclContext()->isFunctionOrMethod())
2206       return false;
2207 
2208     // C++0x [basic.lookup.argdep]p3:
2209     //     -- a declaration that is neither a function or a function
2210     //        template
2211     // And also for builtin functions.
2212     if (isa<FunctionDecl>(D)) {
2213       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2214 
2215       // But also builtin functions.
2216       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2217         return false;
2218     } else if (!isa<FunctionTemplateDecl>(D))
2219       return false;
2220   }
2221 
2222   return true;
2223 }
2224 
2225 
2226 /// Diagnoses obvious problems with the use of the given declaration
2227 /// as an expression.  This is only actually called for lookups that
2228 /// were not overloaded, and it doesn't promise that the declaration
2229 /// will in fact be used.
2230 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2231   if (isa<TypedefNameDecl>(D)) {
2232     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2233     return true;
2234   }
2235 
2236   if (isa<ObjCInterfaceDecl>(D)) {
2237     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2238     return true;
2239   }
2240 
2241   if (isa<NamespaceDecl>(D)) {
2242     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2243     return true;
2244   }
2245 
2246   return false;
2247 }
2248 
2249 ExprResult
2250 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2251                                LookupResult &R,
2252                                bool NeedsADL) {
2253   // If this is a single, fully-resolved result and we don't need ADL,
2254   // just build an ordinary singleton decl ref.
2255   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2256     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2257                                     R.getFoundDecl());
2258 
2259   // We only need to check the declaration if there's exactly one
2260   // result, because in the overloaded case the results can only be
2261   // functions and function templates.
2262   if (R.isSingleResult() &&
2263       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2264     return ExprError();
2265 
2266   // Otherwise, just build an unresolved lookup expression.  Suppress
2267   // any lookup-related diagnostics; we'll hash these out later, when
2268   // we've picked a target.
2269   R.suppressDiagnostics();
2270 
2271   UnresolvedLookupExpr *ULE
2272     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2273                                    SS.getWithLocInContext(Context),
2274                                    R.getLookupNameInfo(),
2275                                    NeedsADL, R.isOverloadedResult(),
2276                                    R.begin(), R.end());
2277 
2278   return Owned(ULE);
2279 }
2280 
2281 /// \brief Complete semantic analysis for a reference to the given declaration.
2282 ExprResult
2283 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2284                                const DeclarationNameInfo &NameInfo,
2285                                NamedDecl *D) {
2286   assert(D && "Cannot refer to a NULL declaration");
2287   assert(!isa<FunctionTemplateDecl>(D) &&
2288          "Cannot refer unambiguously to a function template");
2289 
2290   SourceLocation Loc = NameInfo.getLoc();
2291   if (CheckDeclInExpr(*this, Loc, D))
2292     return ExprError();
2293 
2294   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2295     // Specifically diagnose references to class templates that are missing
2296     // a template argument list.
2297     Diag(Loc, diag::err_template_decl_ref)
2298       << Template << SS.getRange();
2299     Diag(Template->getLocation(), diag::note_template_decl_here);
2300     return ExprError();
2301   }
2302 
2303   // Make sure that we're referring to a value.
2304   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2305   if (!VD) {
2306     Diag(Loc, diag::err_ref_non_value)
2307       << D << SS.getRange();
2308     Diag(D->getLocation(), diag::note_declared_at);
2309     return ExprError();
2310   }
2311 
2312   // Check whether this declaration can be used. Note that we suppress
2313   // this check when we're going to perform argument-dependent lookup
2314   // on this function name, because this might not be the function
2315   // that overload resolution actually selects.
2316   if (DiagnoseUseOfDecl(VD, Loc))
2317     return ExprError();
2318 
2319   // Only create DeclRefExpr's for valid Decl's.
2320   if (VD->isInvalidDecl())
2321     return ExprError();
2322 
2323   // Handle members of anonymous structs and unions.  If we got here,
2324   // and the reference is to a class member indirect field, then this
2325   // must be the subject of a pointer-to-member expression.
2326   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2327     if (!indirectField->isCXXClassMember())
2328       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2329                                                       indirectField);
2330 
2331   {
2332     QualType type = VD->getType();
2333     ExprValueKind valueKind = VK_RValue;
2334 
2335     switch (D->getKind()) {
2336     // Ignore all the non-ValueDecl kinds.
2337 #define ABSTRACT_DECL(kind)
2338 #define VALUE(type, base)
2339 #define DECL(type, base) \
2340     case Decl::type:
2341 #include "clang/AST/DeclNodes.inc"
2342       llvm_unreachable("invalid value decl kind");
2343 
2344     // These shouldn't make it here.
2345     case Decl::ObjCAtDefsField:
2346     case Decl::ObjCIvar:
2347       llvm_unreachable("forming non-member reference to ivar?");
2348 
2349     // Enum constants are always r-values and never references.
2350     // Unresolved using declarations are dependent.
2351     case Decl::EnumConstant:
2352     case Decl::UnresolvedUsingValue:
2353       valueKind = VK_RValue;
2354       break;
2355 
2356     // Fields and indirect fields that got here must be for
2357     // pointer-to-member expressions; we just call them l-values for
2358     // internal consistency, because this subexpression doesn't really
2359     // exist in the high-level semantics.
2360     case Decl::Field:
2361     case Decl::IndirectField:
2362       assert(getLangOpts().CPlusPlus &&
2363              "building reference to field in C?");
2364 
2365       // These can't have reference type in well-formed programs, but
2366       // for internal consistency we do this anyway.
2367       type = type.getNonReferenceType();
2368       valueKind = VK_LValue;
2369       break;
2370 
2371     // Non-type template parameters are either l-values or r-values
2372     // depending on the type.
2373     case Decl::NonTypeTemplateParm: {
2374       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2375         type = reftype->getPointeeType();
2376         valueKind = VK_LValue; // even if the parameter is an r-value reference
2377         break;
2378       }
2379 
2380       // For non-references, we need to strip qualifiers just in case
2381       // the template parameter was declared as 'const int' or whatever.
2382       valueKind = VK_RValue;
2383       type = type.getUnqualifiedType();
2384       break;
2385     }
2386 
2387     case Decl::Var:
2388       // In C, "extern void blah;" is valid and is an r-value.
2389       if (!getLangOpts().CPlusPlus &&
2390           !type.hasQualifiers() &&
2391           type->isVoidType()) {
2392         valueKind = VK_RValue;
2393         break;
2394       }
2395       // fallthrough
2396 
2397     case Decl::ImplicitParam:
2398     case Decl::ParmVar: {
2399       // These are always l-values.
2400       valueKind = VK_LValue;
2401       type = type.getNonReferenceType();
2402 
2403       // FIXME: Does the addition of const really only apply in
2404       // potentially-evaluated contexts? Since the variable isn't actually
2405       // captured in an unevaluated context, it seems that the answer is no.
2406       if (ExprEvalContexts.back().Context != Sema::Unevaluated) {
2407         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2408         if (!CapturedType.isNull())
2409           type = CapturedType;
2410       }
2411 
2412       break;
2413     }
2414 
2415     case Decl::Function: {
2416       const FunctionType *fty = type->castAs<FunctionType>();
2417 
2418       // If we're referring to a function with an __unknown_anytype
2419       // result type, make the entire expression __unknown_anytype.
2420       if (fty->getResultType() == Context.UnknownAnyTy) {
2421         type = Context.UnknownAnyTy;
2422         valueKind = VK_RValue;
2423         break;
2424       }
2425 
2426       // Functions are l-values in C++.
2427       if (getLangOpts().CPlusPlus) {
2428         valueKind = VK_LValue;
2429         break;
2430       }
2431 
2432       // C99 DR 316 says that, if a function type comes from a
2433       // function definition (without a prototype), that type is only
2434       // used for checking compatibility. Therefore, when referencing
2435       // the function, we pretend that we don't have the full function
2436       // type.
2437       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2438           isa<FunctionProtoType>(fty))
2439         type = Context.getFunctionNoProtoType(fty->getResultType(),
2440                                               fty->getExtInfo());
2441 
2442       // Functions are r-values in C.
2443       valueKind = VK_RValue;
2444       break;
2445     }
2446 
2447     case Decl::CXXMethod:
2448       // If we're referring to a method with an __unknown_anytype
2449       // result type, make the entire expression __unknown_anytype.
2450       // This should only be possible with a type written directly.
2451       if (const FunctionProtoType *proto
2452             = dyn_cast<FunctionProtoType>(VD->getType()))
2453         if (proto->getResultType() == Context.UnknownAnyTy) {
2454           type = Context.UnknownAnyTy;
2455           valueKind = VK_RValue;
2456           break;
2457         }
2458 
2459       // C++ methods are l-values if static, r-values if non-static.
2460       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2461         valueKind = VK_LValue;
2462         break;
2463       }
2464       // fallthrough
2465 
2466     case Decl::CXXConversion:
2467     case Decl::CXXDestructor:
2468     case Decl::CXXConstructor:
2469       valueKind = VK_RValue;
2470       break;
2471     }
2472 
2473     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2474   }
2475 }
2476 
2477 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2478   PredefinedExpr::IdentType IT;
2479 
2480   switch (Kind) {
2481   default: llvm_unreachable("Unknown simple primary expr!");
2482   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2483   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2484   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2485   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2486   }
2487 
2488   // Pre-defined identifiers are of type char[x], where x is the length of the
2489   // string.
2490 
2491   Decl *currentDecl = getCurFunctionOrMethodDecl();
2492   if (!currentDecl && getCurBlock())
2493     currentDecl = getCurBlock()->TheDecl;
2494   if (!currentDecl) {
2495     Diag(Loc, diag::ext_predef_outside_function);
2496     currentDecl = Context.getTranslationUnitDecl();
2497   }
2498 
2499   QualType ResTy;
2500   if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2501     ResTy = Context.DependentTy;
2502   } else {
2503     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2504 
2505     llvm::APInt LengthI(32, Length + 1);
2506     if (IT == PredefinedExpr::LFunction)
2507       ResTy = Context.WCharTy.withConst();
2508     else
2509       ResTy = Context.CharTy.withConst();
2510     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2511   }
2512   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2513 }
2514 
2515 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2516   SmallString<16> CharBuffer;
2517   bool Invalid = false;
2518   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2519   if (Invalid)
2520     return ExprError();
2521 
2522   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2523                             PP, Tok.getKind());
2524   if (Literal.hadError())
2525     return ExprError();
2526 
2527   QualType Ty;
2528   if (Literal.isWide())
2529     Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
2530   else if (Literal.isUTF16())
2531     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2532   else if (Literal.isUTF32())
2533     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2534   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2535     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2536   else
2537     Ty = Context.CharTy;  // 'x' -> char in C++
2538 
2539   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2540   if (Literal.isWide())
2541     Kind = CharacterLiteral::Wide;
2542   else if (Literal.isUTF16())
2543     Kind = CharacterLiteral::UTF16;
2544   else if (Literal.isUTF32())
2545     Kind = CharacterLiteral::UTF32;
2546 
2547   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2548                                              Tok.getLocation());
2549 
2550   if (Literal.getUDSuffix().empty())
2551     return Owned(Lit);
2552 
2553   // We're building a user-defined literal.
2554   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2555   SourceLocation UDSuffixLoc =
2556     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2557 
2558   // Make sure we're allowed user-defined literals here.
2559   if (!UDLScope)
2560     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2561 
2562   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2563   //   operator "" X (ch)
2564   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2565                                         llvm::makeArrayRef(&Lit, 1),
2566                                         Tok.getLocation());
2567 }
2568 
2569 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2570   unsigned IntSize = Context.getTargetInfo().getIntWidth();
2571   return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2572                                       Context.IntTy, Loc));
2573 }
2574 
2575 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2576                                   QualType Ty, SourceLocation Loc) {
2577   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2578 
2579   using llvm::APFloat;
2580   APFloat Val(Format);
2581 
2582   APFloat::opStatus result = Literal.GetFloatValue(Val);
2583 
2584   // Overflow is always an error, but underflow is only an error if
2585   // we underflowed to zero (APFloat reports denormals as underflow).
2586   if ((result & APFloat::opOverflow) ||
2587       ((result & APFloat::opUnderflow) && Val.isZero())) {
2588     unsigned diagnostic;
2589     SmallString<20> buffer;
2590     if (result & APFloat::opOverflow) {
2591       diagnostic = diag::warn_float_overflow;
2592       APFloat::getLargest(Format).toString(buffer);
2593     } else {
2594       diagnostic = diag::warn_float_underflow;
2595       APFloat::getSmallest(Format).toString(buffer);
2596     }
2597 
2598     S.Diag(Loc, diagnostic)
2599       << Ty
2600       << StringRef(buffer.data(), buffer.size());
2601   }
2602 
2603   bool isExact = (result == APFloat::opOK);
2604   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2605 }
2606 
2607 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
2608   // Fast path for a single digit (which is quite common).  A single digit
2609   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
2610   if (Tok.getLength() == 1) {
2611     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2612     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
2613   }
2614 
2615   SmallString<512> IntegerBuffer;
2616   // Add padding so that NumericLiteralParser can overread by one character.
2617   IntegerBuffer.resize(Tok.getLength()+1);
2618   const char *ThisTokBegin = &IntegerBuffer[0];
2619 
2620   // Get the spelling of the token, which eliminates trigraphs, etc.
2621   bool Invalid = false;
2622   unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2623   if (Invalid)
2624     return ExprError();
2625 
2626   NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
2627                                Tok.getLocation(), PP);
2628   if (Literal.hadError)
2629     return ExprError();
2630 
2631   if (Literal.hasUDSuffix()) {
2632     // We're building a user-defined literal.
2633     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2634     SourceLocation UDSuffixLoc =
2635       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2636 
2637     // Make sure we're allowed user-defined literals here.
2638     if (!UDLScope)
2639       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
2640 
2641     QualType CookedTy;
2642     if (Literal.isFloatingLiteral()) {
2643       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2644       // long double, the literal is treated as a call of the form
2645       //   operator "" X (f L)
2646       CookedTy = Context.LongDoubleTy;
2647     } else {
2648       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2649       // unsigned long long, the literal is treated as a call of the form
2650       //   operator "" X (n ULL)
2651       CookedTy = Context.UnsignedLongLongTy;
2652     }
2653 
2654     DeclarationName OpName =
2655       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2656     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2657     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2658 
2659     // Perform literal operator lookup to determine if we're building a raw
2660     // literal or a cooked one.
2661     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2662     switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2663                                   /*AllowRawAndTemplate*/true)) {
2664     case LOLR_Error:
2665       return ExprError();
2666 
2667     case LOLR_Cooked: {
2668       Expr *Lit;
2669       if (Literal.isFloatingLiteral()) {
2670         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2671       } else {
2672         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2673         if (Literal.GetIntegerValue(ResultVal))
2674           Diag(Tok.getLocation(), diag::warn_integer_too_large);
2675         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2676                                      Tok.getLocation());
2677       }
2678       return BuildLiteralOperatorCall(R, OpNameInfo,
2679                                       llvm::makeArrayRef(&Lit, 1),
2680                                       Tok.getLocation());
2681     }
2682 
2683     case LOLR_Raw: {
2684       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2685       // literal is treated as a call of the form
2686       //   operator "" X ("n")
2687       SourceLocation TokLoc = Tok.getLocation();
2688       unsigned Length = Literal.getUDSuffixOffset();
2689       QualType StrTy = Context.getConstantArrayType(
2690           Context.CharTy, llvm::APInt(32, Length + 1),
2691           ArrayType::Normal, 0);
2692       Expr *Lit = StringLiteral::Create(
2693           Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
2694           /*Pascal*/false, StrTy, &TokLoc, 1);
2695       return BuildLiteralOperatorCall(R, OpNameInfo,
2696                                       llvm::makeArrayRef(&Lit, 1), TokLoc);
2697     }
2698 
2699     case LOLR_Template:
2700       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2701       // template), L is treated as a call fo the form
2702       //   operator "" X <'c1', 'c2', ... 'ck'>()
2703       // where n is the source character sequence c1 c2 ... ck.
2704       TemplateArgumentListInfo ExplicitArgs;
2705       unsigned CharBits = Context.getIntWidth(Context.CharTy);
2706       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2707       llvm::APSInt Value(CharBits, CharIsUnsigned);
2708       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2709         Value = ThisTokBegin[I];
2710         TemplateArgument Arg(Context, Value, Context.CharTy);
2711         TemplateArgumentLocInfo ArgInfo;
2712         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2713       }
2714       return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2715                                       Tok.getLocation(), &ExplicitArgs);
2716     }
2717 
2718     llvm_unreachable("unexpected literal operator lookup result");
2719   }
2720 
2721   Expr *Res;
2722 
2723   if (Literal.isFloatingLiteral()) {
2724     QualType Ty;
2725     if (Literal.isFloat)
2726       Ty = Context.FloatTy;
2727     else if (!Literal.isLong)
2728       Ty = Context.DoubleTy;
2729     else
2730       Ty = Context.LongDoubleTy;
2731 
2732     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
2733 
2734     if (Ty == Context.DoubleTy) {
2735       if (getLangOpts().SinglePrecisionConstants) {
2736         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2737       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2738         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2739         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2740       }
2741     }
2742   } else if (!Literal.isIntegerLiteral()) {
2743     return ExprError();
2744   } else {
2745     QualType Ty;
2746 
2747     // long long is a C99 feature.
2748     if (!getLangOpts().C99 && Literal.isLongLong)
2749       Diag(Tok.getLocation(),
2750            getLangOpts().CPlusPlus0x ?
2751              diag::warn_cxx98_compat_longlong : diag::ext_longlong);
2752 
2753     // Get the value in the widest-possible width.
2754     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2755     // The microsoft literal suffix extensions support 128-bit literals, which
2756     // may be wider than [u]intmax_t.
2757     if (Literal.isMicrosoftInteger && MaxWidth < 128)
2758       MaxWidth = 128;
2759     llvm::APInt ResultVal(MaxWidth, 0);
2760 
2761     if (Literal.GetIntegerValue(ResultVal)) {
2762       // If this value didn't fit into uintmax_t, warn and force to ull.
2763       Diag(Tok.getLocation(), diag::warn_integer_too_large);
2764       Ty = Context.UnsignedLongLongTy;
2765       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
2766              "long long is not intmax_t?");
2767     } else {
2768       // If this value fits into a ULL, try to figure out what else it fits into
2769       // according to the rules of C99 6.4.4.1p5.
2770 
2771       // Octal, Hexadecimal, and integers with a U suffix are allowed to
2772       // be an unsigned int.
2773       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2774 
2775       // Check from smallest to largest, picking the smallest type we can.
2776       unsigned Width = 0;
2777       if (!Literal.isLong && !Literal.isLongLong) {
2778         // Are int/unsigned possibilities?
2779         unsigned IntSize = Context.getTargetInfo().getIntWidth();
2780 
2781         // Does it fit in a unsigned int?
2782         if (ResultVal.isIntN(IntSize)) {
2783           // Does it fit in a signed int?
2784           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
2785             Ty = Context.IntTy;
2786           else if (AllowUnsigned)
2787             Ty = Context.UnsignedIntTy;
2788           Width = IntSize;
2789         }
2790       }
2791 
2792       // Are long/unsigned long possibilities?
2793       if (Ty.isNull() && !Literal.isLongLong) {
2794         unsigned LongSize = Context.getTargetInfo().getLongWidth();
2795 
2796         // Does it fit in a unsigned long?
2797         if (ResultVal.isIntN(LongSize)) {
2798           // Does it fit in a signed long?
2799           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
2800             Ty = Context.LongTy;
2801           else if (AllowUnsigned)
2802             Ty = Context.UnsignedLongTy;
2803           Width = LongSize;
2804         }
2805       }
2806 
2807       // Check long long if needed.
2808       if (Ty.isNull()) {
2809         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
2810 
2811         // Does it fit in a unsigned long long?
2812         if (ResultVal.isIntN(LongLongSize)) {
2813           // Does it fit in a signed long long?
2814           // To be compatible with MSVC, hex integer literals ending with the
2815           // LL or i64 suffix are always signed in Microsoft mode.
2816           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2817               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
2818             Ty = Context.LongLongTy;
2819           else if (AllowUnsigned)
2820             Ty = Context.UnsignedLongLongTy;
2821           Width = LongLongSize;
2822         }
2823       }
2824 
2825       // If it doesn't fit in unsigned long long, and we're using Microsoft
2826       // extensions, then its a 128-bit integer literal.
2827       if (Ty.isNull() && Literal.isMicrosoftInteger) {
2828         if (Literal.isUnsigned)
2829           Ty = Context.UnsignedInt128Ty;
2830         else
2831           Ty = Context.Int128Ty;
2832         Width = 128;
2833       }
2834 
2835       // If we still couldn't decide a type, we probably have something that
2836       // does not fit in a signed long long, but has no U suffix.
2837       if (Ty.isNull()) {
2838         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
2839         Ty = Context.UnsignedLongLongTy;
2840         Width = Context.getTargetInfo().getLongLongWidth();
2841       }
2842 
2843       if (ResultVal.getBitWidth() != Width)
2844         ResultVal = ResultVal.trunc(Width);
2845     }
2846     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
2847   }
2848 
2849   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2850   if (Literal.isImaginary)
2851     Res = new (Context) ImaginaryLiteral(Res,
2852                                         Context.getComplexType(Res->getType()));
2853 
2854   return Owned(Res);
2855 }
2856 
2857 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
2858   assert((E != 0) && "ActOnParenExpr() missing expr");
2859   return Owned(new (Context) ParenExpr(L, R, E));
2860 }
2861 
2862 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2863                                          SourceLocation Loc,
2864                                          SourceRange ArgRange) {
2865   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2866   // scalar or vector data type argument..."
2867   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2868   // type (C99 6.2.5p18) or void.
2869   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2870     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2871       << T << ArgRange;
2872     return true;
2873   }
2874 
2875   assert((T->isVoidType() || !T->isIncompleteType()) &&
2876          "Scalar types should always be complete");
2877   return false;
2878 }
2879 
2880 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2881                                            SourceLocation Loc,
2882                                            SourceRange ArgRange,
2883                                            UnaryExprOrTypeTrait TraitKind) {
2884   // C99 6.5.3.4p1:
2885   if (T->isFunctionType()) {
2886     // alignof(function) is allowed as an extension.
2887     if (TraitKind == UETT_SizeOf)
2888       S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2889     return false;
2890   }
2891 
2892   // Allow sizeof(void)/alignof(void) as an extension.
2893   if (T->isVoidType()) {
2894     S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2895     return false;
2896   }
2897 
2898   return true;
2899 }
2900 
2901 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2902                                              SourceLocation Loc,
2903                                              SourceRange ArgRange,
2904                                              UnaryExprOrTypeTrait TraitKind) {
2905   // Reject sizeof(interface) and sizeof(interface<proto>) if the
2906   // runtime doesn't allow it.
2907   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
2908     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2909       << T << (TraitKind == UETT_SizeOf)
2910       << ArgRange;
2911     return true;
2912   }
2913 
2914   return false;
2915 }
2916 
2917 /// \brief Check the constrains on expression operands to unary type expression
2918 /// and type traits.
2919 ///
2920 /// Completes any types necessary and validates the constraints on the operand
2921 /// expression. The logic mostly mirrors the type-based overload, but may modify
2922 /// the expression as it completes the type for that expression through template
2923 /// instantiation, etc.
2924 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
2925                                             UnaryExprOrTypeTrait ExprKind) {
2926   QualType ExprTy = E->getType();
2927 
2928   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2929   //   the result is the size of the referenced type."
2930   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2931   //   result shall be the alignment of the referenced type."
2932   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2933     ExprTy = Ref->getPointeeType();
2934 
2935   if (ExprKind == UETT_VecStep)
2936     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2937                                         E->getSourceRange());
2938 
2939   // Whitelist some types as extensions
2940   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2941                                       E->getSourceRange(), ExprKind))
2942     return false;
2943 
2944   if (RequireCompleteExprType(E,
2945                               diag::err_sizeof_alignof_incomplete_type,
2946                               ExprKind, E->getSourceRange()))
2947     return true;
2948 
2949   // Completeing the expression's type may have changed it.
2950   ExprTy = E->getType();
2951   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2952     ExprTy = Ref->getPointeeType();
2953 
2954   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2955                                        E->getSourceRange(), ExprKind))
2956     return true;
2957 
2958   if (ExprKind == UETT_SizeOf) {
2959     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
2960       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2961         QualType OType = PVD->getOriginalType();
2962         QualType Type = PVD->getType();
2963         if (Type->isPointerType() && OType->isArrayType()) {
2964           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
2965             << Type << OType;
2966           Diag(PVD->getLocation(), diag::note_declared_at);
2967         }
2968       }
2969     }
2970   }
2971 
2972   return false;
2973 }
2974 
2975 /// \brief Check the constraints on operands to unary expression and type
2976 /// traits.
2977 ///
2978 /// This will complete any types necessary, and validate the various constraints
2979 /// on those operands.
2980 ///
2981 /// The UsualUnaryConversions() function is *not* called by this routine.
2982 /// C99 6.3.2.1p[2-4] all state:
2983 ///   Except when it is the operand of the sizeof operator ...
2984 ///
2985 /// C++ [expr.sizeof]p4
2986 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2987 ///   standard conversions are not applied to the operand of sizeof.
2988 ///
2989 /// This policy is followed for all of the unary trait expressions.
2990 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
2991                                             SourceLocation OpLoc,
2992                                             SourceRange ExprRange,
2993                                             UnaryExprOrTypeTrait ExprKind) {
2994   if (ExprType->isDependentType())
2995     return false;
2996 
2997   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2998   //   the result is the size of the referenced type."
2999   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3000   //   result shall be the alignment of the referenced type."
3001   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3002     ExprType = Ref->getPointeeType();
3003 
3004   if (ExprKind == UETT_VecStep)
3005     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3006 
3007   // Whitelist some types as extensions
3008   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3009                                       ExprKind))
3010     return false;
3011 
3012   if (RequireCompleteType(OpLoc, ExprType,
3013                           diag::err_sizeof_alignof_incomplete_type,
3014                           ExprKind, ExprRange))
3015     return true;
3016 
3017   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3018                                        ExprKind))
3019     return true;
3020 
3021   return false;
3022 }
3023 
3024 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3025   E = E->IgnoreParens();
3026 
3027   // alignof decl is always ok.
3028   if (isa<DeclRefExpr>(E))
3029     return false;
3030 
3031   // Cannot know anything else if the expression is dependent.
3032   if (E->isTypeDependent())
3033     return false;
3034 
3035   if (E->getBitField()) {
3036     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3037        << 1 << E->getSourceRange();
3038     return true;
3039   }
3040 
3041   // Alignment of a field access is always okay, so long as it isn't a
3042   // bit-field.
3043   if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
3044     if (isa<FieldDecl>(ME->getMemberDecl()))
3045       return false;
3046 
3047   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3048 }
3049 
3050 bool Sema::CheckVecStepExpr(Expr *E) {
3051   E = E->IgnoreParens();
3052 
3053   // Cannot know anything else if the expression is dependent.
3054   if (E->isTypeDependent())
3055     return false;
3056 
3057   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3058 }
3059 
3060 /// \brief Build a sizeof or alignof expression given a type operand.
3061 ExprResult
3062 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3063                                      SourceLocation OpLoc,
3064                                      UnaryExprOrTypeTrait ExprKind,
3065                                      SourceRange R) {
3066   if (!TInfo)
3067     return ExprError();
3068 
3069   QualType T = TInfo->getType();
3070 
3071   if (!T->isDependentType() &&
3072       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3073     return ExprError();
3074 
3075   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3076   return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3077                                                       Context.getSizeType(),
3078                                                       OpLoc, R.getEnd()));
3079 }
3080 
3081 /// \brief Build a sizeof or alignof expression given an expression
3082 /// operand.
3083 ExprResult
3084 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3085                                      UnaryExprOrTypeTrait ExprKind) {
3086   ExprResult PE = CheckPlaceholderExpr(E);
3087   if (PE.isInvalid())
3088     return ExprError();
3089 
3090   E = PE.get();
3091 
3092   // Verify that the operand is valid.
3093   bool isInvalid = false;
3094   if (E->isTypeDependent()) {
3095     // Delay type-checking for type-dependent expressions.
3096   } else if (ExprKind == UETT_AlignOf) {
3097     isInvalid = CheckAlignOfExpr(*this, E);
3098   } else if (ExprKind == UETT_VecStep) {
3099     isInvalid = CheckVecStepExpr(E);
3100   } else if (E->getBitField()) {  // C99 6.5.3.4p1.
3101     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3102     isInvalid = true;
3103   } else {
3104     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3105   }
3106 
3107   if (isInvalid)
3108     return ExprError();
3109 
3110   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3111     PE = TranformToPotentiallyEvaluated(E);
3112     if (PE.isInvalid()) return ExprError();
3113     E = PE.take();
3114   }
3115 
3116   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3117   return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3118       ExprKind, E, Context.getSizeType(), OpLoc,
3119       E->getSourceRange().getEnd()));
3120 }
3121 
3122 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3123 /// expr and the same for @c alignof and @c __alignof
3124 /// Note that the ArgRange is invalid if isType is false.
3125 ExprResult
3126 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3127                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3128                                     void *TyOrEx, const SourceRange &ArgRange) {
3129   // If error parsing type, ignore.
3130   if (TyOrEx == 0) return ExprError();
3131 
3132   if (IsType) {
3133     TypeSourceInfo *TInfo;
3134     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3135     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3136   }
3137 
3138   Expr *ArgEx = (Expr *)TyOrEx;
3139   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3140   return move(Result);
3141 }
3142 
3143 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3144                                      bool IsReal) {
3145   if (V.get()->isTypeDependent())
3146     return S.Context.DependentTy;
3147 
3148   // _Real and _Imag are only l-values for normal l-values.
3149   if (V.get()->getObjectKind() != OK_Ordinary) {
3150     V = S.DefaultLvalueConversion(V.take());
3151     if (V.isInvalid())
3152       return QualType();
3153   }
3154 
3155   // These operators return the element type of a complex type.
3156   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3157     return CT->getElementType();
3158 
3159   // Otherwise they pass through real integer and floating point types here.
3160   if (V.get()->getType()->isArithmeticType())
3161     return V.get()->getType();
3162 
3163   // Test for placeholders.
3164   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3165   if (PR.isInvalid()) return QualType();
3166   if (PR.get() != V.get()) {
3167     V = move(PR);
3168     return CheckRealImagOperand(S, V, Loc, IsReal);
3169   }
3170 
3171   // Reject anything else.
3172   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3173     << (IsReal ? "__real" : "__imag");
3174   return QualType();
3175 }
3176 
3177 
3178 
3179 ExprResult
3180 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3181                           tok::TokenKind Kind, Expr *Input) {
3182   UnaryOperatorKind Opc;
3183   switch (Kind) {
3184   default: llvm_unreachable("Unknown unary op!");
3185   case tok::plusplus:   Opc = UO_PostInc; break;
3186   case tok::minusminus: Opc = UO_PostDec; break;
3187   }
3188 
3189   // Since this might is a postfix expression, get rid of ParenListExprs.
3190   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3191   if (Result.isInvalid()) return ExprError();
3192   Input = Result.take();
3193 
3194   return BuildUnaryOp(S, OpLoc, Opc, Input);
3195 }
3196 
3197 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3198 ///
3199 /// \return true on error
3200 static bool checkArithmeticOnObjCPointer(Sema &S,
3201                                          SourceLocation opLoc,
3202                                          Expr *op) {
3203   assert(op->getType()->isObjCObjectPointerType());
3204   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3205     return false;
3206 
3207   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3208     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3209     << op->getSourceRange();
3210   return true;
3211 }
3212 
3213 ExprResult
3214 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3215                               Expr *Idx, SourceLocation RLoc) {
3216   // Since this might be a postfix expression, get rid of ParenListExprs.
3217   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
3218   if (Result.isInvalid()) return ExprError();
3219   Base = Result.take();
3220 
3221   Expr *LHSExp = Base, *RHSExp = Idx;
3222 
3223   if (getLangOpts().CPlusPlus &&
3224       (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
3225     return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3226                                                   Context.DependentTy,
3227                                                   VK_LValue, OK_Ordinary,
3228                                                   RLoc));
3229   }
3230 
3231   if (getLangOpts().CPlusPlus &&
3232       (LHSExp->getType()->isRecordType() ||
3233        LHSExp->getType()->isEnumeralType() ||
3234        RHSExp->getType()->isRecordType() ||
3235        RHSExp->getType()->isEnumeralType()) &&
3236       !LHSExp->getType()->isObjCObjectPointerType()) {
3237     return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
3238   }
3239 
3240   return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
3241 }
3242 
3243 ExprResult
3244 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3245                                       Expr *Idx, SourceLocation RLoc) {
3246   Expr *LHSExp = Base;
3247   Expr *RHSExp = Idx;
3248 
3249   // Perform default conversions.
3250   if (!LHSExp->getType()->getAs<VectorType>()) {
3251     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3252     if (Result.isInvalid())
3253       return ExprError();
3254     LHSExp = Result.take();
3255   }
3256   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3257   if (Result.isInvalid())
3258     return ExprError();
3259   RHSExp = Result.take();
3260 
3261   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3262   ExprValueKind VK = VK_LValue;
3263   ExprObjectKind OK = OK_Ordinary;
3264 
3265   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3266   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3267   // in the subscript position. As a result, we need to derive the array base
3268   // and index from the expression types.
3269   Expr *BaseExpr, *IndexExpr;
3270   QualType ResultType;
3271   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3272     BaseExpr = LHSExp;
3273     IndexExpr = RHSExp;
3274     ResultType = Context.DependentTy;
3275   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3276     BaseExpr = LHSExp;
3277     IndexExpr = RHSExp;
3278     ResultType = PTy->getPointeeType();
3279   } else if (const ObjCObjectPointerType *PTy =
3280                LHSTy->getAs<ObjCObjectPointerType>()) {
3281     BaseExpr = LHSExp;
3282     IndexExpr = RHSExp;
3283 
3284     // Use custom logic if this should be the pseudo-object subscript
3285     // expression.
3286     if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3287       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3288 
3289     ResultType = PTy->getPointeeType();
3290     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3291       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3292         << ResultType << BaseExpr->getSourceRange();
3293       return ExprError();
3294     }
3295   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3296      // Handle the uncommon case of "123[Ptr]".
3297     BaseExpr = RHSExp;
3298     IndexExpr = LHSExp;
3299     ResultType = PTy->getPointeeType();
3300   } else if (const ObjCObjectPointerType *PTy =
3301                RHSTy->getAs<ObjCObjectPointerType>()) {
3302      // Handle the uncommon case of "123[Ptr]".
3303     BaseExpr = RHSExp;
3304     IndexExpr = LHSExp;
3305     ResultType = PTy->getPointeeType();
3306     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3307       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3308         << ResultType << BaseExpr->getSourceRange();
3309       return ExprError();
3310     }
3311   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3312     BaseExpr = LHSExp;    // vectors: V[123]
3313     IndexExpr = RHSExp;
3314     VK = LHSExp->getValueKind();
3315     if (VK != VK_RValue)
3316       OK = OK_VectorComponent;
3317 
3318     // FIXME: need to deal with const...
3319     ResultType = VTy->getElementType();
3320   } else if (LHSTy->isArrayType()) {
3321     // If we see an array that wasn't promoted by
3322     // DefaultFunctionArrayLvalueConversion, it must be an array that
3323     // wasn't promoted because of the C90 rule that doesn't
3324     // allow promoting non-lvalue arrays.  Warn, then
3325     // force the promotion here.
3326     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3327         LHSExp->getSourceRange();
3328     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3329                                CK_ArrayToPointerDecay).take();
3330     LHSTy = LHSExp->getType();
3331 
3332     BaseExpr = LHSExp;
3333     IndexExpr = RHSExp;
3334     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3335   } else if (RHSTy->isArrayType()) {
3336     // Same as previous, except for 123[f().a] case
3337     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3338         RHSExp->getSourceRange();
3339     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3340                                CK_ArrayToPointerDecay).take();
3341     RHSTy = RHSExp->getType();
3342 
3343     BaseExpr = RHSExp;
3344     IndexExpr = LHSExp;
3345     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3346   } else {
3347     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3348        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3349   }
3350   // C99 6.5.2.1p1
3351   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3352     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3353                      << IndexExpr->getSourceRange());
3354 
3355   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3356        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3357          && !IndexExpr->isTypeDependent())
3358     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3359 
3360   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3361   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3362   // type. Note that Functions are not objects, and that (in C99 parlance)
3363   // incomplete types are not object types.
3364   if (ResultType->isFunctionType()) {
3365     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3366       << ResultType << BaseExpr->getSourceRange();
3367     return ExprError();
3368   }
3369 
3370   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3371     // GNU extension: subscripting on pointer to void
3372     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3373       << BaseExpr->getSourceRange();
3374 
3375     // C forbids expressions of unqualified void type from being l-values.
3376     // See IsCForbiddenLValueType.
3377     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3378   } else if (!ResultType->isDependentType() &&
3379       RequireCompleteType(LLoc, ResultType,
3380                           diag::err_subscript_incomplete_type, BaseExpr))
3381     return ExprError();
3382 
3383   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3384          !ResultType.isCForbiddenLValueType());
3385 
3386   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3387                                                 ResultType, VK, OK, RLoc));
3388 }
3389 
3390 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3391                                         FunctionDecl *FD,
3392                                         ParmVarDecl *Param) {
3393   if (Param->hasUnparsedDefaultArg()) {
3394     Diag(CallLoc,
3395          diag::err_use_of_default_argument_to_function_declared_later) <<
3396       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3397     Diag(UnparsedDefaultArgLocs[Param],
3398          diag::note_default_argument_declared_here);
3399     return ExprError();
3400   }
3401 
3402   if (Param->hasUninstantiatedDefaultArg()) {
3403     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3404 
3405     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3406                                                  Param);
3407 
3408     // Instantiate the expression.
3409     MultiLevelTemplateArgumentList ArgList
3410       = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3411 
3412     std::pair<const TemplateArgument *, unsigned> Innermost
3413       = ArgList.getInnermost();
3414     InstantiatingTemplate Inst(*this, CallLoc, Param,
3415                                ArrayRef<TemplateArgument>(Innermost.first,
3416                                                           Innermost.second));
3417     if (Inst)
3418       return ExprError();
3419 
3420     ExprResult Result;
3421     {
3422       // C++ [dcl.fct.default]p5:
3423       //   The names in the [default argument] expression are bound, and
3424       //   the semantic constraints are checked, at the point where the
3425       //   default argument expression appears.
3426       ContextRAII SavedContext(*this, FD);
3427       LocalInstantiationScope Local(*this);
3428       Result = SubstExpr(UninstExpr, ArgList);
3429     }
3430     if (Result.isInvalid())
3431       return ExprError();
3432 
3433     // Check the expression as an initializer for the parameter.
3434     InitializedEntity Entity
3435       = InitializedEntity::InitializeParameter(Context, Param);
3436     InitializationKind Kind
3437       = InitializationKind::CreateCopy(Param->getLocation(),
3438              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3439     Expr *ResultE = Result.takeAs<Expr>();
3440 
3441     InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3442     Result = InitSeq.Perform(*this, Entity, Kind,
3443                              MultiExprArg(*this, &ResultE, 1));
3444     if (Result.isInvalid())
3445       return ExprError();
3446 
3447     Expr *Arg = Result.takeAs<Expr>();
3448     CheckImplicitConversions(Arg, Param->getOuterLocStart());
3449     // Build the default argument expression.
3450     return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
3451   }
3452 
3453   // If the default expression creates temporaries, we need to
3454   // push them to the current stack of expression temporaries so they'll
3455   // be properly destroyed.
3456   // FIXME: We should really be rebuilding the default argument with new
3457   // bound temporaries; see the comment in PR5810.
3458   // We don't need to do that with block decls, though, because
3459   // blocks in default argument expression can never capture anything.
3460   if (isa<ExprWithCleanups>(Param->getInit())) {
3461     // Set the "needs cleanups" bit regardless of whether there are
3462     // any explicit objects.
3463     ExprNeedsCleanups = true;
3464 
3465     // Append all the objects to the cleanup list.  Right now, this
3466     // should always be a no-op, because blocks in default argument
3467     // expressions should never be able to capture anything.
3468     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3469            "default argument expression has capturing blocks?");
3470   }
3471 
3472   // We already type-checked the argument, so we know it works.
3473   // Just mark all of the declarations in this potentially-evaluated expression
3474   // as being "referenced".
3475   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3476                                    /*SkipLocalVariables=*/true);
3477   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3478 }
3479 
3480 
3481 Sema::VariadicCallType
3482 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3483                           Expr *Fn) {
3484   if (Proto && Proto->isVariadic()) {
3485     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3486       return VariadicConstructor;
3487     else if (Fn && Fn->getType()->isBlockPointerType())
3488       return VariadicBlock;
3489     else if (FDecl) {
3490       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3491         if (Method->isInstance())
3492           return VariadicMethod;
3493     }
3494     return VariadicFunction;
3495   }
3496   return VariadicDoesNotApply;
3497 }
3498 
3499 /// ConvertArgumentsForCall - Converts the arguments specified in
3500 /// Args/NumArgs to the parameter types of the function FDecl with
3501 /// function prototype Proto. Call is the call expression itself, and
3502 /// Fn is the function expression. For a C++ member function, this
3503 /// routine does not attempt to convert the object argument. Returns
3504 /// true if the call is ill-formed.
3505 bool
3506 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3507                               FunctionDecl *FDecl,
3508                               const FunctionProtoType *Proto,
3509                               Expr **Args, unsigned NumArgs,
3510                               SourceLocation RParenLoc,
3511                               bool IsExecConfig) {
3512   // Bail out early if calling a builtin with custom typechecking.
3513   // We don't need to do this in the
3514   if (FDecl)
3515     if (unsigned ID = FDecl->getBuiltinID())
3516       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3517         return false;
3518 
3519   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
3520   // assignment, to the types of the corresponding parameter, ...
3521   unsigned NumArgsInProto = Proto->getNumArgs();
3522   bool Invalid = false;
3523   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
3524   unsigned FnKind = Fn->getType()->isBlockPointerType()
3525                        ? 1 /* block */
3526                        : (IsExecConfig ? 3 /* kernel function (exec config) */
3527                                        : 0 /* function */);
3528 
3529   // If too few arguments are available (and we don't have default
3530   // arguments for the remaining parameters), don't make the call.
3531   if (NumArgs < NumArgsInProto) {
3532     if (NumArgs < MinArgs) {
3533       if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3534         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3535                           ? diag::err_typecheck_call_too_few_args_one
3536                           : diag::err_typecheck_call_too_few_args_at_least_one)
3537           << FnKind
3538           << FDecl->getParamDecl(0) << Fn->getSourceRange();
3539       else
3540         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3541                           ? diag::err_typecheck_call_too_few_args
3542                           : diag::err_typecheck_call_too_few_args_at_least)
3543           << FnKind
3544           << MinArgs << NumArgs << Fn->getSourceRange();
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       return true;
3552     }
3553     Call->setNumArgs(Context, NumArgsInProto);
3554   }
3555 
3556   // If too many are passed and not variadic, error on the extras and drop
3557   // them.
3558   if (NumArgs > NumArgsInProto) {
3559     if (!Proto->isVariadic()) {
3560       if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3561         Diag(Args[NumArgsInProto]->getLocStart(),
3562              MinArgs == NumArgsInProto
3563                ? diag::err_typecheck_call_too_many_args_one
3564                : diag::err_typecheck_call_too_many_args_at_most_one)
3565           << FnKind
3566           << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3567           << SourceRange(Args[NumArgsInProto]->getLocStart(),
3568                          Args[NumArgs-1]->getLocEnd());
3569       else
3570         Diag(Args[NumArgsInProto]->getLocStart(),
3571              MinArgs == NumArgsInProto
3572                ? diag::err_typecheck_call_too_many_args
3573                : diag::err_typecheck_call_too_many_args_at_most)
3574           << FnKind
3575           << NumArgsInProto << NumArgs << Fn->getSourceRange()
3576           << SourceRange(Args[NumArgsInProto]->getLocStart(),
3577                          Args[NumArgs-1]->getLocEnd());
3578 
3579       // Emit the location of the prototype.
3580       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3581         Diag(FDecl->getLocStart(), diag::note_callee_decl)
3582           << FDecl;
3583 
3584       // This deletes the extra arguments.
3585       Call->setNumArgs(Context, NumArgsInProto);
3586       return true;
3587     }
3588   }
3589   SmallVector<Expr *, 8> AllArgs;
3590   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3591 
3592   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
3593                                    Proto, 0, Args, NumArgs, AllArgs, CallType);
3594   if (Invalid)
3595     return true;
3596   unsigned TotalNumArgs = AllArgs.size();
3597   for (unsigned i = 0; i < TotalNumArgs; ++i)
3598     Call->setArg(i, AllArgs[i]);
3599 
3600   return false;
3601 }
3602 
3603 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3604                                   FunctionDecl *FDecl,
3605                                   const FunctionProtoType *Proto,
3606                                   unsigned FirstProtoArg,
3607                                   Expr **Args, unsigned NumArgs,
3608                                   SmallVector<Expr *, 8> &AllArgs,
3609                                   VariadicCallType CallType,
3610                                   bool AllowExplicit) {
3611   unsigned NumArgsInProto = Proto->getNumArgs();
3612   unsigned NumArgsToCheck = NumArgs;
3613   bool Invalid = false;
3614   if (NumArgs != NumArgsInProto)
3615     // Use default arguments for missing arguments
3616     NumArgsToCheck = NumArgsInProto;
3617   unsigned ArgIx = 0;
3618   // Continue to check argument types (even if we have too few/many args).
3619   for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
3620     QualType ProtoArgType = Proto->getArgType(i);
3621 
3622     Expr *Arg;
3623     ParmVarDecl *Param;
3624     if (ArgIx < NumArgs) {
3625       Arg = Args[ArgIx++];
3626 
3627       if (RequireCompleteType(Arg->getLocStart(),
3628                               ProtoArgType,
3629                               diag::err_call_incomplete_argument, Arg))
3630         return true;
3631 
3632       // Pass the argument
3633       Param = 0;
3634       if (FDecl && i < FDecl->getNumParams())
3635         Param = FDecl->getParamDecl(i);
3636 
3637       // Strip the unbridged-cast placeholder expression off, if applicable.
3638       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3639           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3640           (!Param || !Param->hasAttr<CFConsumedAttr>()))
3641         Arg = stripARCUnbridgedCast(Arg);
3642 
3643       InitializedEntity Entity =
3644         Param? InitializedEntity::InitializeParameter(Context, Param)
3645              : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3646                                                       Proto->isArgConsumed(i));
3647       ExprResult ArgE = PerformCopyInitialization(Entity,
3648                                                   SourceLocation(),
3649                                                   Owned(Arg),
3650                                                   /*TopLevelOfInitList=*/false,
3651                                                   AllowExplicit);
3652       if (ArgE.isInvalid())
3653         return true;
3654 
3655       Arg = ArgE.takeAs<Expr>();
3656     } else {
3657       Param = FDecl->getParamDecl(i);
3658 
3659       ExprResult ArgExpr =
3660         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
3661       if (ArgExpr.isInvalid())
3662         return true;
3663 
3664       Arg = ArgExpr.takeAs<Expr>();
3665     }
3666 
3667     // Check for array bounds violations for each argument to the call. This
3668     // check only triggers warnings when the argument isn't a more complex Expr
3669     // with its own checking, such as a BinaryOperator.
3670     CheckArrayAccess(Arg);
3671 
3672     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3673     CheckStaticArrayArgument(CallLoc, Param, Arg);
3674 
3675     AllArgs.push_back(Arg);
3676   }
3677 
3678   // If this is a variadic call, handle args passed through "...".
3679   if (CallType != VariadicDoesNotApply) {
3680     // Assume that extern "C" functions with variadic arguments that
3681     // return __unknown_anytype aren't *really* variadic.
3682     if (Proto->getResultType() == Context.UnknownAnyTy &&
3683         FDecl && FDecl->isExternC()) {
3684       for (unsigned i = ArgIx; i != NumArgs; ++i) {
3685         ExprResult arg;
3686         if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3687           arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3688         else
3689           arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3690         Invalid |= arg.isInvalid();
3691         AllArgs.push_back(arg.take());
3692       }
3693 
3694     // Otherwise do argument promotion, (C99 6.5.2.2p7).
3695     } else {
3696       for (unsigned i = ArgIx; i != NumArgs; ++i) {
3697         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3698                                                           FDecl);
3699         Invalid |= Arg.isInvalid();
3700         AllArgs.push_back(Arg.take());
3701       }
3702     }
3703 
3704     // Check for array bounds violations.
3705     for (unsigned i = ArgIx; i != NumArgs; ++i)
3706       CheckArrayAccess(Args[i]);
3707   }
3708   return Invalid;
3709 }
3710 
3711 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3712   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3713   if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3714     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3715       << ATL->getLocalSourceRange();
3716 }
3717 
3718 /// CheckStaticArrayArgument - If the given argument corresponds to a static
3719 /// array parameter, check that it is non-null, and that if it is formed by
3720 /// array-to-pointer decay, the underlying array is sufficiently large.
3721 ///
3722 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3723 /// array type derivation, then for each call to the function, the value of the
3724 /// corresponding actual argument shall provide access to the first element of
3725 /// an array with at least as many elements as specified by the size expression.
3726 void
3727 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3728                                ParmVarDecl *Param,
3729                                const Expr *ArgExpr) {
3730   // Static array parameters are not supported in C++.
3731   if (!Param || getLangOpts().CPlusPlus)
3732     return;
3733 
3734   QualType OrigTy = Param->getOriginalType();
3735 
3736   const ArrayType *AT = Context.getAsArrayType(OrigTy);
3737   if (!AT || AT->getSizeModifier() != ArrayType::Static)
3738     return;
3739 
3740   if (ArgExpr->isNullPointerConstant(Context,
3741                                      Expr::NPC_NeverValueDependent)) {
3742     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3743     DiagnoseCalleeStaticArrayParam(*this, Param);
3744     return;
3745   }
3746 
3747   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3748   if (!CAT)
3749     return;
3750 
3751   const ConstantArrayType *ArgCAT =
3752     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3753   if (!ArgCAT)
3754     return;
3755 
3756   if (ArgCAT->getSize().ult(CAT->getSize())) {
3757     Diag(CallLoc, diag::warn_static_array_too_small)
3758       << ArgExpr->getSourceRange()
3759       << (unsigned) ArgCAT->getSize().getZExtValue()
3760       << (unsigned) CAT->getSize().getZExtValue();
3761     DiagnoseCalleeStaticArrayParam(*this, Param);
3762   }
3763 }
3764 
3765 /// Given a function expression of unknown-any type, try to rebuild it
3766 /// to have a function type.
3767 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3768 
3769 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3770 /// This provides the location of the left/right parens and a list of comma
3771 /// locations.
3772 ExprResult
3773 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3774                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
3775                     Expr *ExecConfig, bool IsExecConfig) {
3776   unsigned NumArgs = ArgExprs.size();
3777 
3778   // Since this might be a postfix expression, get rid of ParenListExprs.
3779   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
3780   if (Result.isInvalid()) return ExprError();
3781   Fn = Result.take();
3782 
3783   Expr **Args = ArgExprs.release();
3784 
3785   if (getLangOpts().CPlusPlus) {
3786     // If this is a pseudo-destructor expression, build the call immediately.
3787     if (isa<CXXPseudoDestructorExpr>(Fn)) {
3788       if (NumArgs > 0) {
3789         // Pseudo-destructor calls should not have any arguments.
3790         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3791           << FixItHint::CreateRemoval(
3792                                     SourceRange(Args[0]->getLocStart(),
3793                                                 Args[NumArgs-1]->getLocEnd()));
3794       }
3795 
3796       return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3797                                           VK_RValue, RParenLoc));
3798     }
3799 
3800     // Determine whether this is a dependent call inside a C++ template,
3801     // in which case we won't do any semantic analysis now.
3802     // FIXME: Will need to cache the results of name lookup (including ADL) in
3803     // Fn.
3804     bool Dependent = false;
3805     if (Fn->isTypeDependent())
3806       Dependent = true;
3807     else if (Expr::hasAnyTypeDependentArguments(
3808         llvm::makeArrayRef(Args, NumArgs)))
3809       Dependent = true;
3810 
3811     if (Dependent) {
3812       if (ExecConfig) {
3813         return Owned(new (Context) CUDAKernelCallExpr(
3814             Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3815             Context.DependentTy, VK_RValue, RParenLoc));
3816       } else {
3817         return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3818                                             Context.DependentTy, VK_RValue,
3819                                             RParenLoc));
3820       }
3821     }
3822 
3823     // Determine whether this is a call to an object (C++ [over.call.object]).
3824     if (Fn->getType()->isRecordType())
3825       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3826                                                 RParenLoc));
3827 
3828     if (Fn->getType() == Context.UnknownAnyTy) {
3829       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3830       if (result.isInvalid()) return ExprError();
3831       Fn = result.take();
3832     }
3833 
3834     if (Fn->getType() == Context.BoundMemberTy) {
3835       return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3836                                        RParenLoc);
3837     }
3838   }
3839 
3840   // Check for overloaded calls.  This can happen even in C due to extensions.
3841   if (Fn->getType() == Context.OverloadTy) {
3842     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3843 
3844     // We aren't supposed to apply this logic for if there's an '&' involved.
3845     if (!find.HasFormOfMemberPointer) {
3846       OverloadExpr *ovl = find.Expression;
3847       if (isa<UnresolvedLookupExpr>(ovl)) {
3848         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3849         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3850                                        RParenLoc, ExecConfig);
3851       } else {
3852         return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3853                                          RParenLoc);
3854       }
3855     }
3856   }
3857 
3858   // If we're directly calling a function, get the appropriate declaration.
3859   if (Fn->getType() == Context.UnknownAnyTy) {
3860     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3861     if (result.isInvalid()) return ExprError();
3862     Fn = result.take();
3863   }
3864 
3865   Expr *NakedFn = Fn->IgnoreParens();
3866 
3867   NamedDecl *NDecl = 0;
3868   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3869     if (UnOp->getOpcode() == UO_AddrOf)
3870       NakedFn = UnOp->getSubExpr()->IgnoreParens();
3871 
3872   if (isa<DeclRefExpr>(NakedFn))
3873     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3874   else if (isa<MemberExpr>(NakedFn))
3875     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
3876 
3877   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3878                                ExecConfig, IsExecConfig);
3879 }
3880 
3881 ExprResult
3882 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3883                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
3884   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3885   if (!ConfigDecl)
3886     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3887                           << "cudaConfigureCall");
3888   QualType ConfigQTy = ConfigDecl->getType();
3889 
3890   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3891       ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
3892   MarkFunctionReferenced(LLLLoc, ConfigDecl);
3893 
3894   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3895                        /*IsExecConfig=*/true);
3896 }
3897 
3898 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3899 ///
3900 /// __builtin_astype( value, dst type )
3901 ///
3902 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
3903                                  SourceLocation BuiltinLoc,
3904                                  SourceLocation RParenLoc) {
3905   ExprValueKind VK = VK_RValue;
3906   ExprObjectKind OK = OK_Ordinary;
3907   QualType DstTy = GetTypeFromParser(ParsedDestTy);
3908   QualType SrcTy = E->getType();
3909   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3910     return ExprError(Diag(BuiltinLoc,
3911                           diag::err_invalid_astype_of_different_size)
3912                      << DstTy
3913                      << SrcTy
3914                      << E->getSourceRange());
3915   return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
3916                RParenLoc));
3917 }
3918 
3919 /// BuildResolvedCallExpr - Build a call to a resolved expression,
3920 /// i.e. an expression not of \p OverloadTy.  The expression should
3921 /// unary-convert to an expression of function-pointer or
3922 /// block-pointer type.
3923 ///
3924 /// \param NDecl the declaration being called, if available
3925 ExprResult
3926 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3927                             SourceLocation LParenLoc,
3928                             Expr **Args, unsigned NumArgs,
3929                             SourceLocation RParenLoc,
3930                             Expr *Config, bool IsExecConfig) {
3931   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3932 
3933   // Promote the function operand.
3934   ExprResult Result = UsualUnaryConversions(Fn);
3935   if (Result.isInvalid())
3936     return ExprError();
3937   Fn = Result.take();
3938 
3939   // Make the call expr early, before semantic checks.  This guarantees cleanup
3940   // of arguments and function on error.
3941   CallExpr *TheCall;
3942   if (Config)
3943     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3944                                                cast<CallExpr>(Config),
3945                                                Args, NumArgs,
3946                                                Context.BoolTy,
3947                                                VK_RValue,
3948                                                RParenLoc);
3949   else
3950     TheCall = new (Context) CallExpr(Context, Fn,
3951                                      Args, NumArgs,
3952                                      Context.BoolTy,
3953                                      VK_RValue,
3954                                      RParenLoc);
3955 
3956   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3957 
3958   // Bail out early if calling a builtin with custom typechecking.
3959   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3960     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3961 
3962  retry:
3963   const FunctionType *FuncT;
3964   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
3965     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3966     // have type pointer to function".
3967     FuncT = PT->getPointeeType()->getAs<FunctionType>();
3968     if (FuncT == 0)
3969       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3970                          << Fn->getType() << Fn->getSourceRange());
3971   } else if (const BlockPointerType *BPT =
3972                Fn->getType()->getAs<BlockPointerType>()) {
3973     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3974   } else {
3975     // Handle calls to expressions of unknown-any type.
3976     if (Fn->getType() == Context.UnknownAnyTy) {
3977       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
3978       if (rewrite.isInvalid()) return ExprError();
3979       Fn = rewrite.take();
3980       TheCall->setCallee(Fn);
3981       goto retry;
3982     }
3983 
3984     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3985       << Fn->getType() << Fn->getSourceRange());
3986   }
3987 
3988   if (getLangOpts().CUDA) {
3989     if (Config) {
3990       // CUDA: Kernel calls must be to global functions
3991       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3992         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3993             << FDecl->getName() << Fn->getSourceRange());
3994 
3995       // CUDA: Kernel function must have 'void' return type
3996       if (!FuncT->getResultType()->isVoidType())
3997         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3998             << Fn->getType() << Fn->getSourceRange());
3999     } else {
4000       // CUDA: Calls to global functions must be configured
4001       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4002         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4003             << FDecl->getName() << Fn->getSourceRange());
4004     }
4005   }
4006 
4007   // Check for a valid return type
4008   if (CheckCallReturnType(FuncT->getResultType(),
4009                           Fn->getLocStart(), TheCall,
4010                           FDecl))
4011     return ExprError();
4012 
4013   // We know the result type of the call, set it.
4014   TheCall->setType(FuncT->getCallResultType(Context));
4015   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
4016 
4017   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4018   if (Proto) {
4019     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
4020                                 RParenLoc, IsExecConfig))
4021       return ExprError();
4022   } else {
4023     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4024 
4025     if (FDecl) {
4026       // Check if we have too few/too many template arguments, based
4027       // on our knowledge of the function definition.
4028       const FunctionDecl *Def = 0;
4029       if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
4030         Proto = Def->getType()->getAs<FunctionProtoType>();
4031         if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
4032           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4033             << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
4034       }
4035 
4036       // If the function we're calling isn't a function prototype, but we have
4037       // a function prototype from a prior declaratiom, use that prototype.
4038       if (!FDecl->hasPrototype())
4039         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4040     }
4041 
4042     // Promote the arguments (C99 6.5.2.2p6).
4043     for (unsigned i = 0; i != NumArgs; i++) {
4044       Expr *Arg = Args[i];
4045 
4046       if (Proto && i < Proto->getNumArgs()) {
4047         InitializedEntity Entity
4048           = InitializedEntity::InitializeParameter(Context,
4049                                                    Proto->getArgType(i),
4050                                                    Proto->isArgConsumed(i));
4051         ExprResult ArgE = PerformCopyInitialization(Entity,
4052                                                     SourceLocation(),
4053                                                     Owned(Arg));
4054         if (ArgE.isInvalid())
4055           return true;
4056 
4057         Arg = ArgE.takeAs<Expr>();
4058 
4059       } else {
4060         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4061 
4062         if (ArgE.isInvalid())
4063           return true;
4064 
4065         Arg = ArgE.takeAs<Expr>();
4066       }
4067 
4068       if (RequireCompleteType(Arg->getLocStart(),
4069                               Arg->getType(),
4070                               diag::err_call_incomplete_argument, Arg))
4071         return ExprError();
4072 
4073       TheCall->setArg(i, Arg);
4074     }
4075   }
4076 
4077   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4078     if (!Method->isStatic())
4079       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4080         << Fn->getSourceRange());
4081 
4082   // Check for sentinels
4083   if (NDecl)
4084     DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
4085 
4086   // Do special checking on direct calls to functions.
4087   if (FDecl) {
4088     if (CheckFunctionCall(FDecl, TheCall, Proto))
4089       return ExprError();
4090 
4091     if (BuiltinID)
4092       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4093   } else if (NDecl) {
4094     if (CheckBlockCall(NDecl, TheCall, Proto))
4095       return ExprError();
4096   }
4097 
4098   return MaybeBindToTemporary(TheCall);
4099 }
4100 
4101 ExprResult
4102 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4103                            SourceLocation RParenLoc, Expr *InitExpr) {
4104   assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
4105   // FIXME: put back this assert when initializers are worked out.
4106   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4107 
4108   TypeSourceInfo *TInfo;
4109   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4110   if (!TInfo)
4111     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4112 
4113   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4114 }
4115 
4116 ExprResult
4117 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4118                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4119   QualType literalType = TInfo->getType();
4120 
4121   if (literalType->isArrayType()) {
4122     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4123           diag::err_illegal_decl_array_incomplete_type,
4124           SourceRange(LParenLoc,
4125                       LiteralExpr->getSourceRange().getEnd())))
4126       return ExprError();
4127     if (literalType->isVariableArrayType())
4128       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4129         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4130   } else if (!literalType->isDependentType() &&
4131              RequireCompleteType(LParenLoc, literalType,
4132                diag::err_typecheck_decl_incomplete_type,
4133                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4134     return ExprError();
4135 
4136   InitializedEntity Entity
4137     = InitializedEntity::InitializeTemporary(literalType);
4138   InitializationKind Kind
4139     = InitializationKind::CreateCStyleCast(LParenLoc,
4140                                            SourceRange(LParenLoc, RParenLoc),
4141                                            /*InitList=*/true);
4142   InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
4143   ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
4144                                        MultiExprArg(*this, &LiteralExpr, 1),
4145                                             &literalType);
4146   if (Result.isInvalid())
4147     return ExprError();
4148   LiteralExpr = Result.get();
4149 
4150   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4151   if (isFileScope) { // 6.5.2.5p3
4152     if (CheckForConstantInitializer(LiteralExpr, literalType))
4153       return ExprError();
4154   }
4155 
4156   // In C, compound literals are l-values for some reason.
4157   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4158 
4159   return MaybeBindToTemporary(
4160            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4161                                              VK, LiteralExpr, isFileScope));
4162 }
4163 
4164 ExprResult
4165 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4166                     SourceLocation RBraceLoc) {
4167   unsigned NumInit = InitArgList.size();
4168   Expr **InitList = InitArgList.release();
4169 
4170   // Immediately handle non-overload placeholders.  Overloads can be
4171   // resolved contextually, but everything else here can't.
4172   for (unsigned I = 0; I != NumInit; ++I) {
4173     if (InitList[I]->getType()->isNonOverloadPlaceholderType()) {
4174       ExprResult result = CheckPlaceholderExpr(InitList[I]);
4175 
4176       // Ignore failures; dropping the entire initializer list because
4177       // of one failure would be terrible for indexing/etc.
4178       if (result.isInvalid()) continue;
4179 
4180       InitList[I] = result.take();
4181     }
4182   }
4183 
4184   // Semantic analysis for initializers is done by ActOnDeclarator() and
4185   // CheckInitializer() - it requires knowledge of the object being intialized.
4186 
4187   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4188                                                NumInit, RBraceLoc);
4189   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4190   return Owned(E);
4191 }
4192 
4193 /// Do an explicit extend of the given block pointer if we're in ARC.
4194 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4195   assert(E.get()->getType()->isBlockPointerType());
4196   assert(E.get()->isRValue());
4197 
4198   // Only do this in an r-value context.
4199   if (!S.getLangOpts().ObjCAutoRefCount) return;
4200 
4201   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4202                                CK_ARCExtendBlockObject, E.get(),
4203                                /*base path*/ 0, VK_RValue);
4204   S.ExprNeedsCleanups = true;
4205 }
4206 
4207 /// Prepare a conversion of the given expression to an ObjC object
4208 /// pointer type.
4209 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4210   QualType type = E.get()->getType();
4211   if (type->isObjCObjectPointerType()) {
4212     return CK_BitCast;
4213   } else if (type->isBlockPointerType()) {
4214     maybeExtendBlockObject(*this, E);
4215     return CK_BlockPointerToObjCPointerCast;
4216   } else {
4217     assert(type->isPointerType());
4218     return CK_CPointerToObjCPointerCast;
4219   }
4220 }
4221 
4222 /// Prepares for a scalar cast, performing all the necessary stages
4223 /// except the final cast and returning the kind required.
4224 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4225   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4226   // Also, callers should have filtered out the invalid cases with
4227   // pointers.  Everything else should be possible.
4228 
4229   QualType SrcTy = Src.get()->getType();
4230   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4231     return CK_NoOp;
4232 
4233   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4234   case Type::STK_MemberPointer:
4235     llvm_unreachable("member pointer type in C");
4236 
4237   case Type::STK_CPointer:
4238   case Type::STK_BlockPointer:
4239   case Type::STK_ObjCObjectPointer:
4240     switch (DestTy->getScalarTypeKind()) {
4241     case Type::STK_CPointer:
4242       return CK_BitCast;
4243     case Type::STK_BlockPointer:
4244       return (SrcKind == Type::STK_BlockPointer
4245                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4246     case Type::STK_ObjCObjectPointer:
4247       if (SrcKind == Type::STK_ObjCObjectPointer)
4248         return CK_BitCast;
4249       if (SrcKind == Type::STK_CPointer)
4250         return CK_CPointerToObjCPointerCast;
4251       maybeExtendBlockObject(*this, Src);
4252       return CK_BlockPointerToObjCPointerCast;
4253     case Type::STK_Bool:
4254       return CK_PointerToBoolean;
4255     case Type::STK_Integral:
4256       return CK_PointerToIntegral;
4257     case Type::STK_Floating:
4258     case Type::STK_FloatingComplex:
4259     case Type::STK_IntegralComplex:
4260     case Type::STK_MemberPointer:
4261       llvm_unreachable("illegal cast from pointer");
4262     }
4263     llvm_unreachable("Should have returned before this");
4264 
4265   case Type::STK_Bool: // casting from bool is like casting from an integer
4266   case Type::STK_Integral:
4267     switch (DestTy->getScalarTypeKind()) {
4268     case Type::STK_CPointer:
4269     case Type::STK_ObjCObjectPointer:
4270     case Type::STK_BlockPointer:
4271       if (Src.get()->isNullPointerConstant(Context,
4272                                            Expr::NPC_ValueDependentIsNull))
4273         return CK_NullToPointer;
4274       return CK_IntegralToPointer;
4275     case Type::STK_Bool:
4276       return CK_IntegralToBoolean;
4277     case Type::STK_Integral:
4278       return CK_IntegralCast;
4279     case Type::STK_Floating:
4280       return CK_IntegralToFloating;
4281     case Type::STK_IntegralComplex:
4282       Src = ImpCastExprToType(Src.take(),
4283                               DestTy->castAs<ComplexType>()->getElementType(),
4284                               CK_IntegralCast);
4285       return CK_IntegralRealToComplex;
4286     case Type::STK_FloatingComplex:
4287       Src = ImpCastExprToType(Src.take(),
4288                               DestTy->castAs<ComplexType>()->getElementType(),
4289                               CK_IntegralToFloating);
4290       return CK_FloatingRealToComplex;
4291     case Type::STK_MemberPointer:
4292       llvm_unreachable("member pointer type in C");
4293     }
4294     llvm_unreachable("Should have returned before this");
4295 
4296   case Type::STK_Floating:
4297     switch (DestTy->getScalarTypeKind()) {
4298     case Type::STK_Floating:
4299       return CK_FloatingCast;
4300     case Type::STK_Bool:
4301       return CK_FloatingToBoolean;
4302     case Type::STK_Integral:
4303       return CK_FloatingToIntegral;
4304     case Type::STK_FloatingComplex:
4305       Src = ImpCastExprToType(Src.take(),
4306                               DestTy->castAs<ComplexType>()->getElementType(),
4307                               CK_FloatingCast);
4308       return CK_FloatingRealToComplex;
4309     case Type::STK_IntegralComplex:
4310       Src = ImpCastExprToType(Src.take(),
4311                               DestTy->castAs<ComplexType>()->getElementType(),
4312                               CK_FloatingToIntegral);
4313       return CK_IntegralRealToComplex;
4314     case Type::STK_CPointer:
4315     case Type::STK_ObjCObjectPointer:
4316     case Type::STK_BlockPointer:
4317       llvm_unreachable("valid float->pointer cast?");
4318     case Type::STK_MemberPointer:
4319       llvm_unreachable("member pointer type in C");
4320     }
4321     llvm_unreachable("Should have returned before this");
4322 
4323   case Type::STK_FloatingComplex:
4324     switch (DestTy->getScalarTypeKind()) {
4325     case Type::STK_FloatingComplex:
4326       return CK_FloatingComplexCast;
4327     case Type::STK_IntegralComplex:
4328       return CK_FloatingComplexToIntegralComplex;
4329     case Type::STK_Floating: {
4330       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4331       if (Context.hasSameType(ET, DestTy))
4332         return CK_FloatingComplexToReal;
4333       Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4334       return CK_FloatingCast;
4335     }
4336     case Type::STK_Bool:
4337       return CK_FloatingComplexToBoolean;
4338     case Type::STK_Integral:
4339       Src = ImpCastExprToType(Src.take(),
4340                               SrcTy->castAs<ComplexType>()->getElementType(),
4341                               CK_FloatingComplexToReal);
4342       return CK_FloatingToIntegral;
4343     case Type::STK_CPointer:
4344     case Type::STK_ObjCObjectPointer:
4345     case Type::STK_BlockPointer:
4346       llvm_unreachable("valid complex float->pointer cast?");
4347     case Type::STK_MemberPointer:
4348       llvm_unreachable("member pointer type in C");
4349     }
4350     llvm_unreachable("Should have returned before this");
4351 
4352   case Type::STK_IntegralComplex:
4353     switch (DestTy->getScalarTypeKind()) {
4354     case Type::STK_FloatingComplex:
4355       return CK_IntegralComplexToFloatingComplex;
4356     case Type::STK_IntegralComplex:
4357       return CK_IntegralComplexCast;
4358     case Type::STK_Integral: {
4359       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4360       if (Context.hasSameType(ET, DestTy))
4361         return CK_IntegralComplexToReal;
4362       Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
4363       return CK_IntegralCast;
4364     }
4365     case Type::STK_Bool:
4366       return CK_IntegralComplexToBoolean;
4367     case Type::STK_Floating:
4368       Src = ImpCastExprToType(Src.take(),
4369                               SrcTy->castAs<ComplexType>()->getElementType(),
4370                               CK_IntegralComplexToReal);
4371       return CK_IntegralToFloating;
4372     case Type::STK_CPointer:
4373     case Type::STK_ObjCObjectPointer:
4374     case Type::STK_BlockPointer:
4375       llvm_unreachable("valid complex int->pointer cast?");
4376     case Type::STK_MemberPointer:
4377       llvm_unreachable("member pointer type in C");
4378     }
4379     llvm_unreachable("Should have returned before this");
4380   }
4381 
4382   llvm_unreachable("Unhandled scalar cast");
4383 }
4384 
4385 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
4386                            CastKind &Kind) {
4387   assert(VectorTy->isVectorType() && "Not a vector type!");
4388 
4389   if (Ty->isVectorType() || Ty->isIntegerType()) {
4390     if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
4391       return Diag(R.getBegin(),
4392                   Ty->isVectorType() ?
4393                   diag::err_invalid_conversion_between_vectors :
4394                   diag::err_invalid_conversion_between_vector_and_integer)
4395         << VectorTy << Ty << R;
4396   } else
4397     return Diag(R.getBegin(),
4398                 diag::err_invalid_conversion_between_vector_and_scalar)
4399       << VectorTy << Ty << R;
4400 
4401   Kind = CK_BitCast;
4402   return false;
4403 }
4404 
4405 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4406                                     Expr *CastExpr, CastKind &Kind) {
4407   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
4408 
4409   QualType SrcTy = CastExpr->getType();
4410 
4411   // If SrcTy is a VectorType, the total size must match to explicitly cast to
4412   // an ExtVectorType.
4413   // In OpenCL, casts between vectors of different types are not allowed.
4414   // (See OpenCL 6.2).
4415   if (SrcTy->isVectorType()) {
4416     if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4417         || (getLangOpts().OpenCL &&
4418             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
4419       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4420         << DestTy << SrcTy << R;
4421       return ExprError();
4422     }
4423     Kind = CK_BitCast;
4424     return Owned(CastExpr);
4425   }
4426 
4427   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
4428   // conversion will take place first from scalar to elt type, and then
4429   // splat from elt type to vector.
4430   if (SrcTy->isPointerType())
4431     return Diag(R.getBegin(),
4432                 diag::err_invalid_conversion_between_vector_and_scalar)
4433       << DestTy << SrcTy << R;
4434 
4435   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4436   ExprResult CastExprRes = Owned(CastExpr);
4437   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
4438   if (CastExprRes.isInvalid())
4439     return ExprError();
4440   CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
4441 
4442   Kind = CK_VectorSplat;
4443   return Owned(CastExpr);
4444 }
4445 
4446 ExprResult
4447 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4448                     Declarator &D, ParsedType &Ty,
4449                     SourceLocation RParenLoc, Expr *CastExpr) {
4450   assert(!D.isInvalidType() && (CastExpr != 0) &&
4451          "ActOnCastExpr(): missing type or expr");
4452 
4453   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
4454   if (D.isInvalidType())
4455     return ExprError();
4456 
4457   if (getLangOpts().CPlusPlus) {
4458     // Check that there are no default arguments (C++ only).
4459     CheckExtraCXXDefaultArguments(D);
4460   }
4461 
4462   checkUnusedDeclAttributes(D);
4463 
4464   QualType castType = castTInfo->getType();
4465   Ty = CreateParsedType(castType, castTInfo);
4466 
4467   bool isVectorLiteral = false;
4468 
4469   // Check for an altivec or OpenCL literal,
4470   // i.e. all the elements are integer constants.
4471   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4472   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
4473   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
4474        && castType->isVectorType() && (PE || PLE)) {
4475     if (PLE && PLE->getNumExprs() == 0) {
4476       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4477       return ExprError();
4478     }
4479     if (PE || PLE->getNumExprs() == 1) {
4480       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4481       if (!E->getType()->isVectorType())
4482         isVectorLiteral = true;
4483     }
4484     else
4485       isVectorLiteral = true;
4486   }
4487 
4488   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4489   // then handle it as such.
4490   if (isVectorLiteral)
4491     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
4492 
4493   // If the Expr being casted is a ParenListExpr, handle it specially.
4494   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4495   // sequence of BinOp comma operators.
4496   if (isa<ParenListExpr>(CastExpr)) {
4497     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
4498     if (Result.isInvalid()) return ExprError();
4499     CastExpr = Result.take();
4500   }
4501 
4502   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
4503 }
4504 
4505 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4506                                     SourceLocation RParenLoc, Expr *E,
4507                                     TypeSourceInfo *TInfo) {
4508   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4509          "Expected paren or paren list expression");
4510 
4511   Expr **exprs;
4512   unsigned numExprs;
4513   Expr *subExpr;
4514   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4515     exprs = PE->getExprs();
4516     numExprs = PE->getNumExprs();
4517   } else {
4518     subExpr = cast<ParenExpr>(E)->getSubExpr();
4519     exprs = &subExpr;
4520     numExprs = 1;
4521   }
4522 
4523   QualType Ty = TInfo->getType();
4524   assert(Ty->isVectorType() && "Expected vector type");
4525 
4526   SmallVector<Expr *, 8> initExprs;
4527   const VectorType *VTy = Ty->getAs<VectorType>();
4528   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4529 
4530   // '(...)' form of vector initialization in AltiVec: the number of
4531   // initializers must be one or must match the size of the vector.
4532   // If a single value is specified in the initializer then it will be
4533   // replicated to all the components of the vector
4534   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
4535     // The number of initializers must be one or must match the size of the
4536     // vector. If a single value is specified in the initializer then it will
4537     // be replicated to all the components of the vector
4538     if (numExprs == 1) {
4539       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4540       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4541       if (Literal.isInvalid())
4542         return ExprError();
4543       Literal = ImpCastExprToType(Literal.take(), ElemTy,
4544                                   PrepareScalarCast(Literal, ElemTy));
4545       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4546     }
4547     else if (numExprs < numElems) {
4548       Diag(E->getExprLoc(),
4549            diag::err_incorrect_number_of_vector_initializers);
4550       return ExprError();
4551     }
4552     else
4553       initExprs.append(exprs, exprs + numExprs);
4554   }
4555   else {
4556     // For OpenCL, when the number of initializers is a single value,
4557     // it will be replicated to all components of the vector.
4558     if (getLangOpts().OpenCL &&
4559         VTy->getVectorKind() == VectorType::GenericVector &&
4560         numExprs == 1) {
4561         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4562         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4563         if (Literal.isInvalid())
4564           return ExprError();
4565         Literal = ImpCastExprToType(Literal.take(), ElemTy,
4566                                     PrepareScalarCast(Literal, ElemTy));
4567         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4568     }
4569 
4570     initExprs.append(exprs, exprs + numExprs);
4571   }
4572   // FIXME: This means that pretty-printing the final AST will produce curly
4573   // braces instead of the original commas.
4574   InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4575                                                    &initExprs[0],
4576                                                    initExprs.size(), RParenLoc);
4577   initE->setType(Ty);
4578   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4579 }
4580 
4581 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4582 /// the ParenListExpr into a sequence of comma binary operators.
4583 ExprResult
4584 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4585   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
4586   if (!E)
4587     return Owned(OrigExpr);
4588 
4589   ExprResult Result(E->getExpr(0));
4590 
4591   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4592     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4593                         E->getExpr(i));
4594 
4595   if (Result.isInvalid()) return ExprError();
4596 
4597   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
4598 }
4599 
4600 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4601                                     SourceLocation R,
4602                                     MultiExprArg Val) {
4603   unsigned nexprs = Val.size();
4604   Expr **exprs = reinterpret_cast<Expr**>(Val.release());
4605   assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4606   Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
4607   return Owned(expr);
4608 }
4609 
4610 /// \brief Emit a specialized diagnostic when one expression is a null pointer
4611 /// constant and the other is not a pointer.  Returns true if a diagnostic is
4612 /// emitted.
4613 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
4614                                       SourceLocation QuestionLoc) {
4615   Expr *NullExpr = LHSExpr;
4616   Expr *NonPointerExpr = RHSExpr;
4617   Expr::NullPointerConstantKind NullKind =
4618       NullExpr->isNullPointerConstant(Context,
4619                                       Expr::NPC_ValueDependentIsNotNull);
4620 
4621   if (NullKind == Expr::NPCK_NotNull) {
4622     NullExpr = RHSExpr;
4623     NonPointerExpr = LHSExpr;
4624     NullKind =
4625         NullExpr->isNullPointerConstant(Context,
4626                                         Expr::NPC_ValueDependentIsNotNull);
4627   }
4628 
4629   if (NullKind == Expr::NPCK_NotNull)
4630     return false;
4631 
4632   if (NullKind == Expr::NPCK_ZeroInteger) {
4633     // In this case, check to make sure that we got here from a "NULL"
4634     // string in the source code.
4635     NullExpr = NullExpr->IgnoreParenImpCasts();
4636     SourceLocation loc = NullExpr->getExprLoc();
4637     if (!findMacroSpelling(loc, "NULL"))
4638       return false;
4639   }
4640 
4641   int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4642   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4643       << NonPointerExpr->getType() << DiagType
4644       << NonPointerExpr->getSourceRange();
4645   return true;
4646 }
4647 
4648 /// \brief Return false if the condition expression is valid, true otherwise.
4649 static bool checkCondition(Sema &S, Expr *Cond) {
4650   QualType CondTy = Cond->getType();
4651 
4652   // C99 6.5.15p2
4653   if (CondTy->isScalarType()) return false;
4654 
4655   // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4656   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
4657     return false;
4658 
4659   // Emit the proper error message.
4660   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
4661                               diag::err_typecheck_cond_expect_scalar :
4662                               diag::err_typecheck_cond_expect_scalar_or_vector)
4663     << CondTy;
4664   return true;
4665 }
4666 
4667 /// \brief Return false if the two expressions can be converted to a vector,
4668 /// true otherwise
4669 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4670                                                     ExprResult &RHS,
4671                                                     QualType CondTy) {
4672   // Both operands should be of scalar type.
4673   if (!LHS.get()->getType()->isScalarType()) {
4674     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4675       << CondTy;
4676     return true;
4677   }
4678   if (!RHS.get()->getType()->isScalarType()) {
4679     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4680       << CondTy;
4681     return true;
4682   }
4683 
4684   // Implicity convert these scalars to the type of the condition.
4685   LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4686   RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4687   return false;
4688 }
4689 
4690 /// \brief Handle when one or both operands are void type.
4691 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4692                                          ExprResult &RHS) {
4693     Expr *LHSExpr = LHS.get();
4694     Expr *RHSExpr = RHS.get();
4695 
4696     if (!LHSExpr->getType()->isVoidType())
4697       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4698         << RHSExpr->getSourceRange();
4699     if (!RHSExpr->getType()->isVoidType())
4700       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4701         << LHSExpr->getSourceRange();
4702     LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4703     RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4704     return S.Context.VoidTy;
4705 }
4706 
4707 /// \brief Return false if the NullExpr can be promoted to PointerTy,
4708 /// true otherwise.
4709 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4710                                         QualType PointerTy) {
4711   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4712       !NullExpr.get()->isNullPointerConstant(S.Context,
4713                                             Expr::NPC_ValueDependentIsNull))
4714     return true;
4715 
4716   NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4717   return false;
4718 }
4719 
4720 /// \brief Checks compatibility between two pointers and return the resulting
4721 /// type.
4722 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4723                                                      ExprResult &RHS,
4724                                                      SourceLocation Loc) {
4725   QualType LHSTy = LHS.get()->getType();
4726   QualType RHSTy = RHS.get()->getType();
4727 
4728   if (S.Context.hasSameType(LHSTy, RHSTy)) {
4729     // Two identical pointers types are always compatible.
4730     return LHSTy;
4731   }
4732 
4733   QualType lhptee, rhptee;
4734 
4735   // Get the pointee types.
4736   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4737     lhptee = LHSBTy->getPointeeType();
4738     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
4739   } else {
4740     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4741     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
4742   }
4743 
4744   // C99 6.5.15p6: If both operands are pointers to compatible types or to
4745   // differently qualified versions of compatible types, the result type is
4746   // a pointer to an appropriately qualified version of the composite
4747   // type.
4748 
4749   // Only CVR-qualifiers exist in the standard, and the differently-qualified
4750   // clause doesn't make sense for our extensions. E.g. address space 2 should
4751   // be incompatible with address space 3: they may live on different devices or
4752   // anything.
4753   Qualifiers lhQual = lhptee.getQualifiers();
4754   Qualifiers rhQual = rhptee.getQualifiers();
4755 
4756   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4757   lhQual.removeCVRQualifiers();
4758   rhQual.removeCVRQualifiers();
4759 
4760   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4761   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4762 
4763   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4764 
4765   if (CompositeTy.isNull()) {
4766     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4767       << LHSTy << RHSTy << LHS.get()->getSourceRange()
4768       << RHS.get()->getSourceRange();
4769     // In this situation, we assume void* type. No especially good
4770     // reason, but this is what gcc does, and we do have to pick
4771     // to get a consistent AST.
4772     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4773     LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4774     RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4775     return incompatTy;
4776   }
4777 
4778   // The pointer types are compatible.
4779   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4780   ResultTy = S.Context.getPointerType(ResultTy);
4781 
4782   LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4783   RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4784   return ResultTy;
4785 }
4786 
4787 /// \brief Return the resulting type when the operands are both block pointers.
4788 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4789                                                           ExprResult &LHS,
4790                                                           ExprResult &RHS,
4791                                                           SourceLocation Loc) {
4792   QualType LHSTy = LHS.get()->getType();
4793   QualType RHSTy = RHS.get()->getType();
4794 
4795   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4796     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4797       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4798       LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4799       RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4800       return destType;
4801     }
4802     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4803       << LHSTy << RHSTy << LHS.get()->getSourceRange()
4804       << RHS.get()->getSourceRange();
4805     return QualType();
4806   }
4807 
4808   // We have 2 block pointer types.
4809   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4810 }
4811 
4812 /// \brief Return the resulting type when the operands are both pointers.
4813 static QualType
4814 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4815                                             ExprResult &RHS,
4816                                             SourceLocation Loc) {
4817   // get the pointer types
4818   QualType LHSTy = LHS.get()->getType();
4819   QualType RHSTy = RHS.get()->getType();
4820 
4821   // get the "pointed to" types
4822   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4823   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4824 
4825   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4826   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4827     // Figure out necessary qualifiers (C99 6.5.15p6)
4828     QualType destPointee
4829       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4830     QualType destType = S.Context.getPointerType(destPointee);
4831     // Add qualifiers if necessary.
4832     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4833     // Promote to void*.
4834     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4835     return destType;
4836   }
4837   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4838     QualType destPointee
4839       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4840     QualType destType = S.Context.getPointerType(destPointee);
4841     // Add qualifiers if necessary.
4842     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4843     // Promote to void*.
4844     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4845     return destType;
4846   }
4847 
4848   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4849 }
4850 
4851 /// \brief Return false if the first expression is not an integer and the second
4852 /// expression is not a pointer, true otherwise.
4853 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4854                                         Expr* PointerExpr, SourceLocation Loc,
4855                                         bool IsIntFirstExpr) {
4856   if (!PointerExpr->getType()->isPointerType() ||
4857       !Int.get()->getType()->isIntegerType())
4858     return false;
4859 
4860   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4861   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
4862 
4863   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4864     << Expr1->getType() << Expr2->getType()
4865     << Expr1->getSourceRange() << Expr2->getSourceRange();
4866   Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4867                             CK_IntegralToPointer);
4868   return true;
4869 }
4870 
4871 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4872 /// In that case, LHS = cond.
4873 /// C99 6.5.15
4874 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4875                                         ExprResult &RHS, ExprValueKind &VK,
4876                                         ExprObjectKind &OK,
4877                                         SourceLocation QuestionLoc) {
4878 
4879   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4880   if (!LHSResult.isUsable()) return QualType();
4881   LHS = move(LHSResult);
4882 
4883   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4884   if (!RHSResult.isUsable()) return QualType();
4885   RHS = move(RHSResult);
4886 
4887   // C++ is sufficiently different to merit its own checker.
4888   if (getLangOpts().CPlusPlus)
4889     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
4890 
4891   VK = VK_RValue;
4892   OK = OK_Ordinary;
4893 
4894   Cond = UsualUnaryConversions(Cond.take());
4895   if (Cond.isInvalid())
4896     return QualType();
4897   LHS = UsualUnaryConversions(LHS.take());
4898   if (LHS.isInvalid())
4899     return QualType();
4900   RHS = UsualUnaryConversions(RHS.take());
4901   if (RHS.isInvalid())
4902     return QualType();
4903 
4904   QualType CondTy = Cond.get()->getType();
4905   QualType LHSTy = LHS.get()->getType();
4906   QualType RHSTy = RHS.get()->getType();
4907 
4908   // first, check the condition.
4909   if (checkCondition(*this, Cond.get()))
4910     return QualType();
4911 
4912   // Now check the two expressions.
4913   if (LHSTy->isVectorType() || RHSTy->isVectorType())
4914     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
4915 
4916   // OpenCL: If the condition is a vector, and both operands are scalar,
4917   // attempt to implicity convert them to the vector type to act like the
4918   // built in select.
4919   if (getLangOpts().OpenCL && CondTy->isVectorType())
4920     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
4921       return QualType();
4922 
4923   // If both operands have arithmetic type, do the usual arithmetic conversions
4924   // to find a common type: C99 6.5.15p3,5.
4925   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4926     UsualArithmeticConversions(LHS, RHS);
4927     if (LHS.isInvalid() || RHS.isInvalid())
4928       return QualType();
4929     return LHS.get()->getType();
4930   }
4931 
4932   // If both operands are the same structure or union type, the result is that
4933   // type.
4934   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
4935     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
4936       if (LHSRT->getDecl() == RHSRT->getDecl())
4937         // "If both the operands have structure or union type, the result has
4938         // that type."  This implies that CV qualifiers are dropped.
4939         return LHSTy.getUnqualifiedType();
4940     // FIXME: Type of conditional expression must be complete in C mode.
4941   }
4942 
4943   // C99 6.5.15p5: "If both operands have void type, the result has void type."
4944   // The following || allows only one side to be void (a GCC-ism).
4945   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4946     return checkConditionalVoidType(*this, LHS, RHS);
4947   }
4948 
4949   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4950   // the type of the other operand."
4951   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4952   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
4953 
4954   // All objective-c pointer type analysis is done here.
4955   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4956                                                         QuestionLoc);
4957   if (LHS.isInvalid() || RHS.isInvalid())
4958     return QualType();
4959   if (!compositeType.isNull())
4960     return compositeType;
4961 
4962 
4963   // Handle block pointer types.
4964   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4965     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4966                                                      QuestionLoc);
4967 
4968   // Check constraints for C object pointers types (C99 6.5.15p3,6).
4969   if (LHSTy->isPointerType() && RHSTy->isPointerType())
4970     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4971                                                        QuestionLoc);
4972 
4973   // GCC compatibility: soften pointer/integer mismatch.  Note that
4974   // null pointers have been filtered out by this point.
4975   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4976       /*isIntFirstExpr=*/true))
4977     return RHSTy;
4978   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4979       /*isIntFirstExpr=*/false))
4980     return LHSTy;
4981 
4982   // Emit a better diagnostic if one of the expressions is a null pointer
4983   // constant and the other is not a pointer type. In this case, the user most
4984   // likely forgot to take the address of the other expression.
4985   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
4986     return QualType();
4987 
4988   // Otherwise, the operands are not compatible.
4989   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4990     << LHSTy << RHSTy << LHS.get()->getSourceRange()
4991     << RHS.get()->getSourceRange();
4992   return QualType();
4993 }
4994 
4995 /// FindCompositeObjCPointerType - Helper method to find composite type of
4996 /// two objective-c pointer types of the two input expressions.
4997 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
4998                                             SourceLocation QuestionLoc) {
4999   QualType LHSTy = LHS.get()->getType();
5000   QualType RHSTy = RHS.get()->getType();
5001 
5002   // Handle things like Class and struct objc_class*.  Here we case the result
5003   // to the pseudo-builtin, because that will be implicitly cast back to the
5004   // redefinition type if an attempt is made to access its fields.
5005   if (LHSTy->isObjCClassType() &&
5006       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5007     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5008     return LHSTy;
5009   }
5010   if (RHSTy->isObjCClassType() &&
5011       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5012     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5013     return RHSTy;
5014   }
5015   // And the same for struct objc_object* / id
5016   if (LHSTy->isObjCIdType() &&
5017       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5018     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5019     return LHSTy;
5020   }
5021   if (RHSTy->isObjCIdType() &&
5022       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5023     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5024     return RHSTy;
5025   }
5026   // And the same for struct objc_selector* / SEL
5027   if (Context.isObjCSelType(LHSTy) &&
5028       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5029     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
5030     return LHSTy;
5031   }
5032   if (Context.isObjCSelType(RHSTy) &&
5033       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5034     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
5035     return RHSTy;
5036   }
5037   // Check constraints for Objective-C object pointers types.
5038   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5039 
5040     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5041       // Two identical object pointer types are always compatible.
5042       return LHSTy;
5043     }
5044     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5045     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5046     QualType compositeType = LHSTy;
5047 
5048     // If both operands are interfaces and either operand can be
5049     // assigned to the other, use that type as the composite
5050     // type. This allows
5051     //   xxx ? (A*) a : (B*) b
5052     // where B is a subclass of A.
5053     //
5054     // Additionally, as for assignment, if either type is 'id'
5055     // allow silent coercion. Finally, if the types are
5056     // incompatible then make sure to use 'id' as the composite
5057     // type so the result is acceptable for sending messages to.
5058 
5059     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5060     // It could return the composite type.
5061     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5062       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5063     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5064       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5065     } else if ((LHSTy->isObjCQualifiedIdType() ||
5066                 RHSTy->isObjCQualifiedIdType()) &&
5067                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5068       // Need to handle "id<xx>" explicitly.
5069       // GCC allows qualified id and any Objective-C type to devolve to
5070       // id. Currently localizing to here until clear this should be
5071       // part of ObjCQualifiedIdTypesAreCompatible.
5072       compositeType = Context.getObjCIdType();
5073     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5074       compositeType = Context.getObjCIdType();
5075     } else if (!(compositeType =
5076                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5077       ;
5078     else {
5079       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5080       << LHSTy << RHSTy
5081       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5082       QualType incompatTy = Context.getObjCIdType();
5083       LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5084       RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5085       return incompatTy;
5086     }
5087     // The object pointer types are compatible.
5088     LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5089     RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
5090     return compositeType;
5091   }
5092   // Check Objective-C object pointer types and 'void *'
5093   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5094     if (getLangOpts().ObjCAutoRefCount) {
5095       // ARC forbids the implicit conversion of object pointers to 'void *',
5096       // so these types are not compatible.
5097       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5098           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5099       LHS = RHS = true;
5100       return QualType();
5101     }
5102     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5103     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5104     QualType destPointee
5105     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5106     QualType destType = Context.getPointerType(destPointee);
5107     // Add qualifiers if necessary.
5108     LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5109     // Promote to void*.
5110     RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5111     return destType;
5112   }
5113   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5114     if (getLangOpts().ObjCAutoRefCount) {
5115       // ARC forbids the implicit conversion of object pointers to 'void *',
5116       // so these types are not compatible.
5117       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5118           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5119       LHS = RHS = true;
5120       return QualType();
5121     }
5122     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5123     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5124     QualType destPointee
5125     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5126     QualType destType = Context.getPointerType(destPointee);
5127     // Add qualifiers if necessary.
5128     RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5129     // Promote to void*.
5130     LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5131     return destType;
5132   }
5133   return QualType();
5134 }
5135 
5136 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5137 /// ParenRange in parentheses.
5138 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5139                                const PartialDiagnostic &Note,
5140                                SourceRange ParenRange) {
5141   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5142   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5143       EndLoc.isValid()) {
5144     Self.Diag(Loc, Note)
5145       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5146       << FixItHint::CreateInsertion(EndLoc, ")");
5147   } else {
5148     // We can't display the parentheses, so just show the bare note.
5149     Self.Diag(Loc, Note) << ParenRange;
5150   }
5151 }
5152 
5153 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5154   return Opc >= BO_Mul && Opc <= BO_Shr;
5155 }
5156 
5157 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5158 /// expression, either using a built-in or overloaded operator,
5159 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5160 /// expression.
5161 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5162                                    Expr **RHSExprs) {
5163   // Don't strip parenthesis: we should not warn if E is in parenthesis.
5164   E = E->IgnoreImpCasts();
5165   E = E->IgnoreConversionOperator();
5166   E = E->IgnoreImpCasts();
5167 
5168   // Built-in binary operator.
5169   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5170     if (IsArithmeticOp(OP->getOpcode())) {
5171       *Opcode = OP->getOpcode();
5172       *RHSExprs = OP->getRHS();
5173       return true;
5174     }
5175   }
5176 
5177   // Overloaded operator.
5178   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5179     if (Call->getNumArgs() != 2)
5180       return false;
5181 
5182     // Make sure this is really a binary operator that is safe to pass into
5183     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5184     OverloadedOperatorKind OO = Call->getOperator();
5185     if (OO < OO_Plus || OO > OO_Arrow)
5186       return false;
5187 
5188     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5189     if (IsArithmeticOp(OpKind)) {
5190       *Opcode = OpKind;
5191       *RHSExprs = Call->getArg(1);
5192       return true;
5193     }
5194   }
5195 
5196   return false;
5197 }
5198 
5199 static bool IsLogicOp(BinaryOperatorKind Opc) {
5200   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5201 }
5202 
5203 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5204 /// or is a logical expression such as (x==y) which has int type, but is
5205 /// commonly interpreted as boolean.
5206 static bool ExprLooksBoolean(Expr *E) {
5207   E = E->IgnoreParenImpCasts();
5208 
5209   if (E->getType()->isBooleanType())
5210     return true;
5211   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5212     return IsLogicOp(OP->getOpcode());
5213   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5214     return OP->getOpcode() == UO_LNot;
5215 
5216   return false;
5217 }
5218 
5219 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5220 /// and binary operator are mixed in a way that suggests the programmer assumed
5221 /// the conditional operator has higher precedence, for example:
5222 /// "int x = a + someBinaryCondition ? 1 : 2".
5223 static void DiagnoseConditionalPrecedence(Sema &Self,
5224                                           SourceLocation OpLoc,
5225                                           Expr *Condition,
5226                                           Expr *LHSExpr,
5227                                           Expr *RHSExpr) {
5228   BinaryOperatorKind CondOpcode;
5229   Expr *CondRHS;
5230 
5231   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5232     return;
5233   if (!ExprLooksBoolean(CondRHS))
5234     return;
5235 
5236   // The condition is an arithmetic binary expression, with a right-
5237   // hand side that looks boolean, so warn.
5238 
5239   Self.Diag(OpLoc, diag::warn_precedence_conditional)
5240       << Condition->getSourceRange()
5241       << BinaryOperator::getOpcodeStr(CondOpcode);
5242 
5243   SuggestParentheses(Self, OpLoc,
5244     Self.PDiag(diag::note_precedence_conditional_silence)
5245       << BinaryOperator::getOpcodeStr(CondOpcode),
5246     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5247 
5248   SuggestParentheses(Self, OpLoc,
5249     Self.PDiag(diag::note_precedence_conditional_first),
5250     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5251 }
5252 
5253 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5254 /// in the case of a the GNU conditional expr extension.
5255 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5256                                     SourceLocation ColonLoc,
5257                                     Expr *CondExpr, Expr *LHSExpr,
5258                                     Expr *RHSExpr) {
5259   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5260   // was the condition.
5261   OpaqueValueExpr *opaqueValue = 0;
5262   Expr *commonExpr = 0;
5263   if (LHSExpr == 0) {
5264     commonExpr = CondExpr;
5265 
5266     // We usually want to apply unary conversions *before* saving, except
5267     // in the special case of a C++ l-value conditional.
5268     if (!(getLangOpts().CPlusPlus
5269           && !commonExpr->isTypeDependent()
5270           && commonExpr->getValueKind() == RHSExpr->getValueKind()
5271           && commonExpr->isGLValue()
5272           && commonExpr->isOrdinaryOrBitFieldObject()
5273           && RHSExpr->isOrdinaryOrBitFieldObject()
5274           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5275       ExprResult commonRes = UsualUnaryConversions(commonExpr);
5276       if (commonRes.isInvalid())
5277         return ExprError();
5278       commonExpr = commonRes.take();
5279     }
5280 
5281     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5282                                                 commonExpr->getType(),
5283                                                 commonExpr->getValueKind(),
5284                                                 commonExpr->getObjectKind(),
5285                                                 commonExpr);
5286     LHSExpr = CondExpr = opaqueValue;
5287   }
5288 
5289   ExprValueKind VK = VK_RValue;
5290   ExprObjectKind OK = OK_Ordinary;
5291   ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5292   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
5293                                              VK, OK, QuestionLoc);
5294   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5295       RHS.isInvalid())
5296     return ExprError();
5297 
5298   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5299                                 RHS.get());
5300 
5301   if (!commonExpr)
5302     return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5303                                                    LHS.take(), ColonLoc,
5304                                                    RHS.take(), result, VK, OK));
5305 
5306   return Owned(new (Context)
5307     BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5308                               RHS.take(), QuestionLoc, ColonLoc, result, VK,
5309                               OK));
5310 }
5311 
5312 // checkPointerTypesForAssignment - This is a very tricky routine (despite
5313 // being closely modeled after the C99 spec:-). The odd characteristic of this
5314 // routine is it effectively iqnores the qualifiers on the top level pointee.
5315 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5316 // FIXME: add a couple examples in this comment.
5317 static Sema::AssignConvertType
5318 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5319   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5320   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5321 
5322   // get the "pointed to" type (ignoring qualifiers at the top level)
5323   const Type *lhptee, *rhptee;
5324   Qualifiers lhq, rhq;
5325   llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5326   llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
5327 
5328   Sema::AssignConvertType ConvTy = Sema::Compatible;
5329 
5330   // C99 6.5.16.1p1: This following citation is common to constraints
5331   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5332   // qualifiers of the type *pointed to* by the right;
5333   Qualifiers lq;
5334 
5335   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5336   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5337       lhq.compatiblyIncludesObjCLifetime(rhq)) {
5338     // Ignore lifetime for further calculation.
5339     lhq.removeObjCLifetime();
5340     rhq.removeObjCLifetime();
5341   }
5342 
5343   if (!lhq.compatiblyIncludes(rhq)) {
5344     // Treat address-space mismatches as fatal.  TODO: address subspaces
5345     if (lhq.getAddressSpace() != rhq.getAddressSpace())
5346       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5347 
5348     // It's okay to add or remove GC or lifetime qualifiers when converting to
5349     // and from void*.
5350     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
5351                         .compatiblyIncludes(
5352                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
5353              && (lhptee->isVoidType() || rhptee->isVoidType()))
5354       ; // keep old
5355 
5356     // Treat lifetime mismatches as fatal.
5357     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5358       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5359 
5360     // For GCC compatibility, other qualifier mismatches are treated
5361     // as still compatible in C.
5362     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5363   }
5364 
5365   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5366   // incomplete type and the other is a pointer to a qualified or unqualified
5367   // version of void...
5368   if (lhptee->isVoidType()) {
5369     if (rhptee->isIncompleteOrObjectType())
5370       return ConvTy;
5371 
5372     // As an extension, we allow cast to/from void* to function pointer.
5373     assert(rhptee->isFunctionType());
5374     return Sema::FunctionVoidPointer;
5375   }
5376 
5377   if (rhptee->isVoidType()) {
5378     if (lhptee->isIncompleteOrObjectType())
5379       return ConvTy;
5380 
5381     // As an extension, we allow cast to/from void* to function pointer.
5382     assert(lhptee->isFunctionType());
5383     return Sema::FunctionVoidPointer;
5384   }
5385 
5386   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
5387   // unqualified versions of compatible types, ...
5388   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5389   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
5390     // Check if the pointee types are compatible ignoring the sign.
5391     // We explicitly check for char so that we catch "char" vs
5392     // "unsigned char" on systems where "char" is unsigned.
5393     if (lhptee->isCharType())
5394       ltrans = S.Context.UnsignedCharTy;
5395     else if (lhptee->hasSignedIntegerRepresentation())
5396       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
5397 
5398     if (rhptee->isCharType())
5399       rtrans = S.Context.UnsignedCharTy;
5400     else if (rhptee->hasSignedIntegerRepresentation())
5401       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
5402 
5403     if (ltrans == rtrans) {
5404       // Types are compatible ignoring the sign. Qualifier incompatibility
5405       // takes priority over sign incompatibility because the sign
5406       // warning can be disabled.
5407       if (ConvTy != Sema::Compatible)
5408         return ConvTy;
5409 
5410       return Sema::IncompatiblePointerSign;
5411     }
5412 
5413     // If we are a multi-level pointer, it's possible that our issue is simply
5414     // one of qualification - e.g. char ** -> const char ** is not allowed. If
5415     // the eventual target type is the same and the pointers have the same
5416     // level of indirection, this must be the issue.
5417     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
5418       do {
5419         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5420         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
5421       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
5422 
5423       if (lhptee == rhptee)
5424         return Sema::IncompatibleNestedPointerQualifiers;
5425     }
5426 
5427     // General pointer incompatibility takes priority over qualifiers.
5428     return Sema::IncompatiblePointer;
5429   }
5430   if (!S.getLangOpts().CPlusPlus &&
5431       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5432     return Sema::IncompatiblePointer;
5433   return ConvTy;
5434 }
5435 
5436 /// checkBlockPointerTypesForAssignment - This routine determines whether two
5437 /// block pointer types are compatible or whether a block and normal pointer
5438 /// are compatible. It is more restrict than comparing two function pointer
5439 // types.
5440 static Sema::AssignConvertType
5441 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5442                                     QualType RHSType) {
5443   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5444   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5445 
5446   QualType lhptee, rhptee;
5447 
5448   // get the "pointed to" type (ignoring qualifiers at the top level)
5449   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5450   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
5451 
5452   // In C++, the types have to match exactly.
5453   if (S.getLangOpts().CPlusPlus)
5454     return Sema::IncompatibleBlockPointer;
5455 
5456   Sema::AssignConvertType ConvTy = Sema::Compatible;
5457 
5458   // For blocks we enforce that qualifiers are identical.
5459   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5460     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5461 
5462   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
5463     return Sema::IncompatibleBlockPointer;
5464 
5465   return ConvTy;
5466 }
5467 
5468 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
5469 /// for assignment compatibility.
5470 static Sema::AssignConvertType
5471 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5472                                    QualType RHSType) {
5473   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5474   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
5475 
5476   if (LHSType->isObjCBuiltinType()) {
5477     // Class is not compatible with ObjC object pointers.
5478     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5479         !RHSType->isObjCQualifiedClassType())
5480       return Sema::IncompatiblePointer;
5481     return Sema::Compatible;
5482   }
5483   if (RHSType->isObjCBuiltinType()) {
5484     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5485         !LHSType->isObjCQualifiedClassType())
5486       return Sema::IncompatiblePointer;
5487     return Sema::Compatible;
5488   }
5489   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5490   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5491 
5492   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5493       // make an exception for id<P>
5494       !LHSType->isObjCQualifiedIdType())
5495     return Sema::CompatiblePointerDiscardsQualifiers;
5496 
5497   if (S.Context.typesAreCompatible(LHSType, RHSType))
5498     return Sema::Compatible;
5499   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
5500     return Sema::IncompatibleObjCQualifiedId;
5501   return Sema::IncompatiblePointer;
5502 }
5503 
5504 Sema::AssignConvertType
5505 Sema::CheckAssignmentConstraints(SourceLocation Loc,
5506                                  QualType LHSType, QualType RHSType) {
5507   // Fake up an opaque expression.  We don't actually care about what
5508   // cast operations are required, so if CheckAssignmentConstraints
5509   // adds casts to this they'll be wasted, but fortunately that doesn't
5510   // usually happen on valid code.
5511   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5512   ExprResult RHSPtr = &RHSExpr;
5513   CastKind K = CK_Invalid;
5514 
5515   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
5516 }
5517 
5518 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5519 /// has code to accommodate several GCC extensions when type checking
5520 /// pointers. Here are some objectionable examples that GCC considers warnings:
5521 ///
5522 ///  int a, *pint;
5523 ///  short *pshort;
5524 ///  struct foo *pfoo;
5525 ///
5526 ///  pint = pshort; // warning: assignment from incompatible pointer type
5527 ///  a = pint; // warning: assignment makes integer from pointer without a cast
5528 ///  pint = a; // warning: assignment makes pointer from integer without a cast
5529 ///  pint = pfoo; // warning: assignment from incompatible pointer type
5530 ///
5531 /// As a result, the code for dealing with pointers is more complex than the
5532 /// C99 spec dictates.
5533 ///
5534 /// Sets 'Kind' for any result kind except Incompatible.
5535 Sema::AssignConvertType
5536 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5537                                  CastKind &Kind) {
5538   QualType RHSType = RHS.get()->getType();
5539   QualType OrigLHSType = LHSType;
5540 
5541   // Get canonical types.  We're not formatting these types, just comparing
5542   // them.
5543   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5544   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
5545 
5546 
5547   // Common case: no conversion required.
5548   if (LHSType == RHSType) {
5549     Kind = CK_NoOp;
5550     return Compatible;
5551   }
5552 
5553   // If we have an atomic type, try a non-atomic assignment, then just add an
5554   // atomic qualification step.
5555   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
5556     Sema::AssignConvertType result =
5557       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5558     if (result != Compatible)
5559       return result;
5560     if (Kind != CK_NoOp)
5561       RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5562     Kind = CK_NonAtomicToAtomic;
5563     return Compatible;
5564   }
5565 
5566   // If the left-hand side is a reference type, then we are in a
5567   // (rare!) case where we've allowed the use of references in C,
5568   // e.g., as a parameter type in a built-in function. In this case,
5569   // just make sure that the type referenced is compatible with the
5570   // right-hand side type. The caller is responsible for adjusting
5571   // LHSType so that the resulting expression does not have reference
5572   // type.
5573   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5574     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
5575       Kind = CK_LValueBitCast;
5576       return Compatible;
5577     }
5578     return Incompatible;
5579   }
5580 
5581   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5582   // to the same ExtVector type.
5583   if (LHSType->isExtVectorType()) {
5584     if (RHSType->isExtVectorType())
5585       return Incompatible;
5586     if (RHSType->isArithmeticType()) {
5587       // CK_VectorSplat does T -> vector T, so first cast to the
5588       // element type.
5589       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5590       if (elType != RHSType) {
5591         Kind = PrepareScalarCast(RHS, elType);
5592         RHS = ImpCastExprToType(RHS.take(), elType, Kind);
5593       }
5594       Kind = CK_VectorSplat;
5595       return Compatible;
5596     }
5597   }
5598 
5599   // Conversions to or from vector type.
5600   if (LHSType->isVectorType() || RHSType->isVectorType()) {
5601     if (LHSType->isVectorType() && RHSType->isVectorType()) {
5602       // Allow assignments of an AltiVec vector type to an equivalent GCC
5603       // vector type and vice versa
5604       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5605         Kind = CK_BitCast;
5606         return Compatible;
5607       }
5608 
5609       // If we are allowing lax vector conversions, and LHS and RHS are both
5610       // vectors, the total size only needs to be the same. This is a bitcast;
5611       // no bits are changed but the result type is different.
5612       if (getLangOpts().LaxVectorConversions &&
5613           (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
5614         Kind = CK_BitCast;
5615         return IncompatibleVectors;
5616       }
5617     }
5618     return Incompatible;
5619   }
5620 
5621   // Arithmetic conversions.
5622   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5623       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
5624     Kind = PrepareScalarCast(RHS, LHSType);
5625     return Compatible;
5626   }
5627 
5628   // Conversions to normal pointers.
5629   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
5630     // U* -> T*
5631     if (isa<PointerType>(RHSType)) {
5632       Kind = CK_BitCast;
5633       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
5634     }
5635 
5636     // int -> T*
5637     if (RHSType->isIntegerType()) {
5638       Kind = CK_IntegralToPointer; // FIXME: null?
5639       return IntToPointer;
5640     }
5641 
5642     // C pointers are not compatible with ObjC object pointers,
5643     // with two exceptions:
5644     if (isa<ObjCObjectPointerType>(RHSType)) {
5645       //  - conversions to void*
5646       if (LHSPointer->getPointeeType()->isVoidType()) {
5647         Kind = CK_BitCast;
5648         return Compatible;
5649       }
5650 
5651       //  - conversions from 'Class' to the redefinition type
5652       if (RHSType->isObjCClassType() &&
5653           Context.hasSameType(LHSType,
5654                               Context.getObjCClassRedefinitionType())) {
5655         Kind = CK_BitCast;
5656         return Compatible;
5657       }
5658 
5659       Kind = CK_BitCast;
5660       return IncompatiblePointer;
5661     }
5662 
5663     // U^ -> void*
5664     if (RHSType->getAs<BlockPointerType>()) {
5665       if (LHSPointer->getPointeeType()->isVoidType()) {
5666         Kind = CK_BitCast;
5667         return Compatible;
5668       }
5669     }
5670 
5671     return Incompatible;
5672   }
5673 
5674   // Conversions to block pointers.
5675   if (isa<BlockPointerType>(LHSType)) {
5676     // U^ -> T^
5677     if (RHSType->isBlockPointerType()) {
5678       Kind = CK_BitCast;
5679       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
5680     }
5681 
5682     // int or null -> T^
5683     if (RHSType->isIntegerType()) {
5684       Kind = CK_IntegralToPointer; // FIXME: null
5685       return IntToBlockPointer;
5686     }
5687 
5688     // id -> T^
5689     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
5690       Kind = CK_AnyPointerToBlockPointerCast;
5691       return Compatible;
5692     }
5693 
5694     // void* -> T^
5695     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
5696       if (RHSPT->getPointeeType()->isVoidType()) {
5697         Kind = CK_AnyPointerToBlockPointerCast;
5698         return Compatible;
5699       }
5700 
5701     return Incompatible;
5702   }
5703 
5704   // Conversions to Objective-C pointers.
5705   if (isa<ObjCObjectPointerType>(LHSType)) {
5706     // A* -> B*
5707     if (RHSType->isObjCObjectPointerType()) {
5708       Kind = CK_BitCast;
5709       Sema::AssignConvertType result =
5710         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
5711       if (getLangOpts().ObjCAutoRefCount &&
5712           result == Compatible &&
5713           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
5714         result = IncompatibleObjCWeakRef;
5715       return result;
5716     }
5717 
5718     // int or null -> A*
5719     if (RHSType->isIntegerType()) {
5720       Kind = CK_IntegralToPointer; // FIXME: null
5721       return IntToPointer;
5722     }
5723 
5724     // In general, C pointers are not compatible with ObjC object pointers,
5725     // with two exceptions:
5726     if (isa<PointerType>(RHSType)) {
5727       Kind = CK_CPointerToObjCPointerCast;
5728 
5729       //  - conversions from 'void*'
5730       if (RHSType->isVoidPointerType()) {
5731         return Compatible;
5732       }
5733 
5734       //  - conversions to 'Class' from its redefinition type
5735       if (LHSType->isObjCClassType() &&
5736           Context.hasSameType(RHSType,
5737                               Context.getObjCClassRedefinitionType())) {
5738         return Compatible;
5739       }
5740 
5741       return IncompatiblePointer;
5742     }
5743 
5744     // T^ -> A*
5745     if (RHSType->isBlockPointerType()) {
5746       maybeExtendBlockObject(*this, RHS);
5747       Kind = CK_BlockPointerToObjCPointerCast;
5748       return Compatible;
5749     }
5750 
5751     return Incompatible;
5752   }
5753 
5754   // Conversions from pointers that are not covered by the above.
5755   if (isa<PointerType>(RHSType)) {
5756     // T* -> _Bool
5757     if (LHSType == Context.BoolTy) {
5758       Kind = CK_PointerToBoolean;
5759       return Compatible;
5760     }
5761 
5762     // T* -> int
5763     if (LHSType->isIntegerType()) {
5764       Kind = CK_PointerToIntegral;
5765       return PointerToInt;
5766     }
5767 
5768     return Incompatible;
5769   }
5770 
5771   // Conversions from Objective-C pointers that are not covered by the above.
5772   if (isa<ObjCObjectPointerType>(RHSType)) {
5773     // T* -> _Bool
5774     if (LHSType == Context.BoolTy) {
5775       Kind = CK_PointerToBoolean;
5776       return Compatible;
5777     }
5778 
5779     // T* -> int
5780     if (LHSType->isIntegerType()) {
5781       Kind = CK_PointerToIntegral;
5782       return PointerToInt;
5783     }
5784 
5785     return Incompatible;
5786   }
5787 
5788   // struct A -> struct B
5789   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5790     if (Context.typesAreCompatible(LHSType, RHSType)) {
5791       Kind = CK_NoOp;
5792       return Compatible;
5793     }
5794   }
5795 
5796   return Incompatible;
5797 }
5798 
5799 /// \brief Constructs a transparent union from an expression that is
5800 /// used to initialize the transparent union.
5801 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5802                                       ExprResult &EResult, QualType UnionType,
5803                                       FieldDecl *Field) {
5804   // Build an initializer list that designates the appropriate member
5805   // of the transparent union.
5806   Expr *E = EResult.take();
5807   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
5808                                                    &E, 1,
5809                                                    SourceLocation());
5810   Initializer->setType(UnionType);
5811   Initializer->setInitializedFieldInUnion(Field);
5812 
5813   // Build a compound literal constructing a value of the transparent
5814   // union type from this initializer list.
5815   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
5816   EResult = S.Owned(
5817     new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5818                                 VK_RValue, Initializer, false));
5819 }
5820 
5821 Sema::AssignConvertType
5822 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
5823                                                ExprResult &RHS) {
5824   QualType RHSType = RHS.get()->getType();
5825 
5826   // If the ArgType is a Union type, we want to handle a potential
5827   // transparent_union GCC extension.
5828   const RecordType *UT = ArgType->getAsUnionType();
5829   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
5830     return Incompatible;
5831 
5832   // The field to initialize within the transparent union.
5833   RecordDecl *UD = UT->getDecl();
5834   FieldDecl *InitField = 0;
5835   // It's compatible if the expression matches any of the fields.
5836   for (RecordDecl::field_iterator it = UD->field_begin(),
5837          itend = UD->field_end();
5838        it != itend; ++it) {
5839     if (it->getType()->isPointerType()) {
5840       // If the transparent union contains a pointer type, we allow:
5841       // 1) void pointer
5842       // 2) null pointer constant
5843       if (RHSType->isPointerType())
5844         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
5845           RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
5846           InitField = *it;
5847           break;
5848         }
5849 
5850       if (RHS.get()->isNullPointerConstant(Context,
5851                                            Expr::NPC_ValueDependentIsNull)) {
5852         RHS = ImpCastExprToType(RHS.take(), it->getType(),
5853                                 CK_NullToPointer);
5854         InitField = *it;
5855         break;
5856       }
5857     }
5858 
5859     CastKind Kind = CK_Invalid;
5860     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
5861           == Compatible) {
5862       RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
5863       InitField = *it;
5864       break;
5865     }
5866   }
5867 
5868   if (!InitField)
5869     return Incompatible;
5870 
5871   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
5872   return Compatible;
5873 }
5874 
5875 Sema::AssignConvertType
5876 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5877                                        bool Diagnose) {
5878   if (getLangOpts().CPlusPlus) {
5879     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
5880       // C++ 5.17p3: If the left operand is not of class type, the
5881       // expression is implicitly converted (C++ 4) to the
5882       // cv-unqualified type of the left operand.
5883       ExprResult Res;
5884       if (Diagnose) {
5885         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5886                                         AA_Assigning);
5887       } else {
5888         ImplicitConversionSequence ICS =
5889             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5890                                   /*SuppressUserConversions=*/false,
5891                                   /*AllowExplicit=*/false,
5892                                   /*InOverloadResolution=*/false,
5893                                   /*CStyle=*/false,
5894                                   /*AllowObjCWritebackConversion=*/false);
5895         if (ICS.isFailure())
5896           return Incompatible;
5897         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5898                                         ICS, AA_Assigning);
5899       }
5900       if (Res.isInvalid())
5901         return Incompatible;
5902       Sema::AssignConvertType result = Compatible;
5903       if (getLangOpts().ObjCAutoRefCount &&
5904           !CheckObjCARCUnavailableWeakConversion(LHSType,
5905                                                  RHS.get()->getType()))
5906         result = IncompatibleObjCWeakRef;
5907       RHS = move(Res);
5908       return result;
5909     }
5910 
5911     // FIXME: Currently, we fall through and treat C++ classes like C
5912     // structures.
5913     // FIXME: We also fall through for atomics; not sure what should
5914     // happen there, though.
5915   }
5916 
5917   // C99 6.5.16.1p1: the left operand is a pointer and the right is
5918   // a null pointer constant.
5919   if ((LHSType->isPointerType() ||
5920        LHSType->isObjCObjectPointerType() ||
5921        LHSType->isBlockPointerType())
5922       && RHS.get()->isNullPointerConstant(Context,
5923                                           Expr::NPC_ValueDependentIsNull)) {
5924     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
5925     return Compatible;
5926   }
5927 
5928   // This check seems unnatural, however it is necessary to ensure the proper
5929   // conversion of functions/arrays. If the conversion were done for all
5930   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
5931   // expressions that suppress this implicit conversion (&, sizeof).
5932   //
5933   // Suppress this for references: C++ 8.5.3p5.
5934   if (!LHSType->isReferenceType()) {
5935     RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5936     if (RHS.isInvalid())
5937       return Incompatible;
5938   }
5939 
5940   CastKind Kind = CK_Invalid;
5941   Sema::AssignConvertType result =
5942     CheckAssignmentConstraints(LHSType, RHS, Kind);
5943 
5944   // C99 6.5.16.1p2: The value of the right operand is converted to the
5945   // type of the assignment expression.
5946   // CheckAssignmentConstraints allows the left-hand side to be a reference,
5947   // so that we can use references in built-in functions even in C.
5948   // The getNonReferenceType() call makes sure that the resulting expression
5949   // does not have reference type.
5950   if (result != Incompatible && RHS.get()->getType() != LHSType)
5951     RHS = ImpCastExprToType(RHS.take(),
5952                             LHSType.getNonLValueExprType(Context), Kind);
5953   return result;
5954 }
5955 
5956 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5957                                ExprResult &RHS) {
5958   Diag(Loc, diag::err_typecheck_invalid_operands)
5959     << LHS.get()->getType() << RHS.get()->getType()
5960     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5961   return QualType();
5962 }
5963 
5964 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
5965                                    SourceLocation Loc, bool IsCompAssign) {
5966   if (!IsCompAssign) {
5967     LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5968     if (LHS.isInvalid())
5969       return QualType();
5970   }
5971   RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5972   if (RHS.isInvalid())
5973     return QualType();
5974 
5975   // For conversion purposes, we ignore any qualifiers.
5976   // For example, "const float" and "float" are equivalent.
5977   QualType LHSType =
5978     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5979   QualType RHSType =
5980     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
5981 
5982   // If the vector types are identical, return.
5983   if (LHSType == RHSType)
5984     return LHSType;
5985 
5986   // Handle the case of equivalent AltiVec and GCC vector types
5987   if (LHSType->isVectorType() && RHSType->isVectorType() &&
5988       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5989     if (LHSType->isExtVectorType()) {
5990       RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5991       return LHSType;
5992     }
5993 
5994     if (!IsCompAssign)
5995       LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5996     return RHSType;
5997   }
5998 
5999   if (getLangOpts().LaxVectorConversions &&
6000       Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
6001     // If we are allowing lax vector conversions, and LHS and RHS are both
6002     // vectors, the total size only needs to be the same. This is a
6003     // bitcast; no bits are changed but the result type is different.
6004     // FIXME: Should we really be allowing this?
6005     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6006     return LHSType;
6007   }
6008 
6009   // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6010   // swap back (so that we don't reverse the inputs to a subtract, for instance.
6011   bool swapped = false;
6012   if (RHSType->isExtVectorType() && !IsCompAssign) {
6013     swapped = true;
6014     std::swap(RHS, LHS);
6015     std::swap(RHSType, LHSType);
6016   }
6017 
6018   // Handle the case of an ext vector and scalar.
6019   if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
6020     QualType EltTy = LV->getElementType();
6021     if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6022       int order = Context.getIntegerTypeOrder(EltTy, RHSType);
6023       if (order > 0)
6024         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
6025       if (order >= 0) {
6026         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6027         if (swapped) std::swap(RHS, LHS);
6028         return LHSType;
6029       }
6030     }
6031     if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6032         RHSType->isRealFloatingType()) {
6033       int order = Context.getFloatingTypeOrder(EltTy, RHSType);
6034       if (order > 0)
6035         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
6036       if (order >= 0) {
6037         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6038         if (swapped) std::swap(RHS, LHS);
6039         return LHSType;
6040       }
6041     }
6042   }
6043 
6044   // Vectors of different size or scalar and non-ext-vector are errors.
6045   if (swapped) std::swap(RHS, LHS);
6046   Diag(Loc, diag::err_typecheck_vector_not_convertable)
6047     << LHS.get()->getType() << RHS.get()->getType()
6048     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6049   return QualType();
6050 }
6051 
6052 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6053 // expression.  These are mainly cases where the null pointer is used as an
6054 // integer instead of a pointer.
6055 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6056                                 SourceLocation Loc, bool IsCompare) {
6057   // The canonical way to check for a GNU null is with isNullPointerConstant,
6058   // but we use a bit of a hack here for speed; this is a relatively
6059   // hot path, and isNullPointerConstant is slow.
6060   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6061   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6062 
6063   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6064 
6065   // Avoid analyzing cases where the result will either be invalid (and
6066   // diagnosed as such) or entirely valid and not something to warn about.
6067   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6068       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6069     return;
6070 
6071   // Comparison operations would not make sense with a null pointer no matter
6072   // what the other expression is.
6073   if (!IsCompare) {
6074     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6075         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6076         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6077     return;
6078   }
6079 
6080   // The rest of the operations only make sense with a null pointer
6081   // if the other expression is a pointer.
6082   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6083       NonNullType->canDecayToPointerType())
6084     return;
6085 
6086   S.Diag(Loc, diag::warn_null_in_comparison_operation)
6087       << LHSNull /* LHS is NULL */ << NonNullType
6088       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6089 }
6090 
6091 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6092                                            SourceLocation Loc,
6093                                            bool IsCompAssign, bool IsDiv) {
6094   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6095 
6096   if (LHS.get()->getType()->isVectorType() ||
6097       RHS.get()->getType()->isVectorType())
6098     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6099 
6100   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6101   if (LHS.isInvalid() || RHS.isInvalid())
6102     return QualType();
6103 
6104 
6105   if (compType.isNull() || !compType->isArithmeticType())
6106     return InvalidOperands(Loc, LHS, RHS);
6107 
6108   // Check for division by zero.
6109   if (IsDiv &&
6110       RHS.get()->isNullPointerConstant(Context,
6111                                        Expr::NPC_ValueDependentIsNotNull))
6112     DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6113                                           << RHS.get()->getSourceRange());
6114 
6115   return compType;
6116 }
6117 
6118 QualType Sema::CheckRemainderOperands(
6119   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6120   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6121 
6122   if (LHS.get()->getType()->isVectorType() ||
6123       RHS.get()->getType()->isVectorType()) {
6124     if (LHS.get()->getType()->hasIntegerRepresentation() &&
6125         RHS.get()->getType()->hasIntegerRepresentation())
6126       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6127     return InvalidOperands(Loc, LHS, RHS);
6128   }
6129 
6130   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6131   if (LHS.isInvalid() || RHS.isInvalid())
6132     return QualType();
6133 
6134   if (compType.isNull() || !compType->isIntegerType())
6135     return InvalidOperands(Loc, LHS, RHS);
6136 
6137   // Check for remainder by zero.
6138   if (RHS.get()->isNullPointerConstant(Context,
6139                                        Expr::NPC_ValueDependentIsNotNull))
6140     DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6141                                  << RHS.get()->getSourceRange());
6142 
6143   return compType;
6144 }
6145 
6146 /// \brief Diagnose invalid arithmetic on two void pointers.
6147 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
6148                                                 Expr *LHSExpr, Expr *RHSExpr) {
6149   S.Diag(Loc, S.getLangOpts().CPlusPlus
6150                 ? diag::err_typecheck_pointer_arith_void_type
6151                 : diag::ext_gnu_void_ptr)
6152     << 1 /* two pointers */ << LHSExpr->getSourceRange()
6153                             << RHSExpr->getSourceRange();
6154 }
6155 
6156 /// \brief Diagnose invalid arithmetic on a void pointer.
6157 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6158                                             Expr *Pointer) {
6159   S.Diag(Loc, S.getLangOpts().CPlusPlus
6160                 ? diag::err_typecheck_pointer_arith_void_type
6161                 : diag::ext_gnu_void_ptr)
6162     << 0 /* one pointer */ << Pointer->getSourceRange();
6163 }
6164 
6165 /// \brief Diagnose invalid arithmetic on two function pointers.
6166 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6167                                                     Expr *LHS, Expr *RHS) {
6168   assert(LHS->getType()->isAnyPointerType());
6169   assert(RHS->getType()->isAnyPointerType());
6170   S.Diag(Loc, S.getLangOpts().CPlusPlus
6171                 ? diag::err_typecheck_pointer_arith_function_type
6172                 : diag::ext_gnu_ptr_func_arith)
6173     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6174     // We only show the second type if it differs from the first.
6175     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6176                                                    RHS->getType())
6177     << RHS->getType()->getPointeeType()
6178     << LHS->getSourceRange() << RHS->getSourceRange();
6179 }
6180 
6181 /// \brief Diagnose invalid arithmetic on a function pointer.
6182 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6183                                                 Expr *Pointer) {
6184   assert(Pointer->getType()->isAnyPointerType());
6185   S.Diag(Loc, S.getLangOpts().CPlusPlus
6186                 ? diag::err_typecheck_pointer_arith_function_type
6187                 : diag::ext_gnu_ptr_func_arith)
6188     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6189     << 0 /* one pointer, so only one type */
6190     << Pointer->getSourceRange();
6191 }
6192 
6193 /// \brief Emit error if Operand is incomplete pointer type
6194 ///
6195 /// \returns True if pointer has incomplete type
6196 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6197                                                  Expr *Operand) {
6198   assert(Operand->getType()->isAnyPointerType() &&
6199          !Operand->getType()->isDependentType());
6200   QualType PointeeTy = Operand->getType()->getPointeeType();
6201   return S.RequireCompleteType(Loc, PointeeTy,
6202                                diag::err_typecheck_arithmetic_incomplete_type,
6203                                PointeeTy, Operand->getSourceRange());
6204 }
6205 
6206 /// \brief Check the validity of an arithmetic pointer operand.
6207 ///
6208 /// If the operand has pointer type, this code will check for pointer types
6209 /// which are invalid in arithmetic operations. These will be diagnosed
6210 /// appropriately, including whether or not the use is supported as an
6211 /// extension.
6212 ///
6213 /// \returns True when the operand is valid to use (even if as an extension).
6214 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6215                                             Expr *Operand) {
6216   if (!Operand->getType()->isAnyPointerType()) return true;
6217 
6218   QualType PointeeTy = Operand->getType()->getPointeeType();
6219   if (PointeeTy->isVoidType()) {
6220     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6221     return !S.getLangOpts().CPlusPlus;
6222   }
6223   if (PointeeTy->isFunctionType()) {
6224     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6225     return !S.getLangOpts().CPlusPlus;
6226   }
6227 
6228   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
6229 
6230   return true;
6231 }
6232 
6233 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6234 /// operands.
6235 ///
6236 /// This routine will diagnose any invalid arithmetic on pointer operands much
6237 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
6238 /// for emitting a single diagnostic even for operations where both LHS and RHS
6239 /// are (potentially problematic) pointers.
6240 ///
6241 /// \returns True when the operand is valid to use (even if as an extension).
6242 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
6243                                                 Expr *LHSExpr, Expr *RHSExpr) {
6244   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6245   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
6246   if (!isLHSPointer && !isRHSPointer) return true;
6247 
6248   QualType LHSPointeeTy, RHSPointeeTy;
6249   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6250   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
6251 
6252   // Check for arithmetic on pointers to incomplete types.
6253   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6254   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6255   if (isLHSVoidPtr || isRHSVoidPtr) {
6256     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6257     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6258     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
6259 
6260     return !S.getLangOpts().CPlusPlus;
6261   }
6262 
6263   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6264   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6265   if (isLHSFuncPtr || isRHSFuncPtr) {
6266     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6267     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6268                                                                 RHSExpr);
6269     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
6270 
6271     return !S.getLangOpts().CPlusPlus;
6272   }
6273 
6274   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6275     return false;
6276   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6277     return false;
6278 
6279   return true;
6280 }
6281 
6282 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6283 /// literal.
6284 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6285                                   Expr *LHSExpr, Expr *RHSExpr) {
6286   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6287   Expr* IndexExpr = RHSExpr;
6288   if (!StrExpr) {
6289     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6290     IndexExpr = LHSExpr;
6291   }
6292 
6293   bool IsStringPlusInt = StrExpr &&
6294       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6295   if (!IsStringPlusInt)
6296     return;
6297 
6298   llvm::APSInt index;
6299   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6300     unsigned StrLenWithNull = StrExpr->getLength() + 1;
6301     if (index.isNonNegative() &&
6302         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6303                               index.isUnsigned()))
6304       return;
6305   }
6306 
6307   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6308   Self.Diag(OpLoc, diag::warn_string_plus_int)
6309       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6310 
6311   // Only print a fixit for "str" + int, not for int + "str".
6312   if (IndexExpr == RHSExpr) {
6313     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6314     Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6315         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6316         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6317         << FixItHint::CreateInsertion(EndLoc, "]");
6318   } else
6319     Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6320 }
6321 
6322 /// \brief Emit error when two pointers are incompatible.
6323 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
6324                                            Expr *LHSExpr, Expr *RHSExpr) {
6325   assert(LHSExpr->getType()->isAnyPointerType());
6326   assert(RHSExpr->getType()->isAnyPointerType());
6327   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6328     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6329     << RHSExpr->getSourceRange();
6330 }
6331 
6332 QualType Sema::CheckAdditionOperands( // C99 6.5.6
6333     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6334     QualType* CompLHSTy) {
6335   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6336 
6337   if (LHS.get()->getType()->isVectorType() ||
6338       RHS.get()->getType()->isVectorType()) {
6339     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6340     if (CompLHSTy) *CompLHSTy = compType;
6341     return compType;
6342   }
6343 
6344   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6345   if (LHS.isInvalid() || RHS.isInvalid())
6346     return QualType();
6347 
6348   // Diagnose "string literal" '+' int.
6349   if (Opc == BO_Add)
6350     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6351 
6352   // handle the common case first (both operands are arithmetic).
6353   if (!compType.isNull() && compType->isArithmeticType()) {
6354     if (CompLHSTy) *CompLHSTy = compType;
6355     return compType;
6356   }
6357 
6358   // Type-checking.  Ultimately the pointer's going to be in PExp;
6359   // note that we bias towards the LHS being the pointer.
6360   Expr *PExp = LHS.get(), *IExp = RHS.get();
6361 
6362   bool isObjCPointer;
6363   if (PExp->getType()->isPointerType()) {
6364     isObjCPointer = false;
6365   } else if (PExp->getType()->isObjCObjectPointerType()) {
6366     isObjCPointer = true;
6367   } else {
6368     std::swap(PExp, IExp);
6369     if (PExp->getType()->isPointerType()) {
6370       isObjCPointer = false;
6371     } else if (PExp->getType()->isObjCObjectPointerType()) {
6372       isObjCPointer = true;
6373     } else {
6374       return InvalidOperands(Loc, LHS, RHS);
6375     }
6376   }
6377   assert(PExp->getType()->isAnyPointerType());
6378 
6379   if (!IExp->getType()->isIntegerType())
6380     return InvalidOperands(Loc, LHS, RHS);
6381 
6382   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6383     return QualType();
6384 
6385   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
6386     return QualType();
6387 
6388   // Check array bounds for pointer arithemtic
6389   CheckArrayAccess(PExp, IExp);
6390 
6391   if (CompLHSTy) {
6392     QualType LHSTy = Context.isPromotableBitField(LHS.get());
6393     if (LHSTy.isNull()) {
6394       LHSTy = LHS.get()->getType();
6395       if (LHSTy->isPromotableIntegerType())
6396         LHSTy = Context.getPromotedIntegerType(LHSTy);
6397     }
6398     *CompLHSTy = LHSTy;
6399   }
6400 
6401   return PExp->getType();
6402 }
6403 
6404 // C99 6.5.6
6405 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
6406                                         SourceLocation Loc,
6407                                         QualType* CompLHSTy) {
6408   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6409 
6410   if (LHS.get()->getType()->isVectorType() ||
6411       RHS.get()->getType()->isVectorType()) {
6412     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6413     if (CompLHSTy) *CompLHSTy = compType;
6414     return compType;
6415   }
6416 
6417   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6418   if (LHS.isInvalid() || RHS.isInvalid())
6419     return QualType();
6420 
6421   // Enforce type constraints: C99 6.5.6p3.
6422 
6423   // Handle the common case first (both operands are arithmetic).
6424   if (!compType.isNull() && compType->isArithmeticType()) {
6425     if (CompLHSTy) *CompLHSTy = compType;
6426     return compType;
6427   }
6428 
6429   // Either ptr - int   or   ptr - ptr.
6430   if (LHS.get()->getType()->isAnyPointerType()) {
6431     QualType lpointee = LHS.get()->getType()->getPointeeType();
6432 
6433     // Diagnose bad cases where we step over interface counts.
6434     if (LHS.get()->getType()->isObjCObjectPointerType() &&
6435         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
6436       return QualType();
6437 
6438     // The result type of a pointer-int computation is the pointer type.
6439     if (RHS.get()->getType()->isIntegerType()) {
6440       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
6441         return QualType();
6442 
6443       // Check array bounds for pointer arithemtic
6444       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6445                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
6446 
6447       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6448       return LHS.get()->getType();
6449     }
6450 
6451     // Handle pointer-pointer subtractions.
6452     if (const PointerType *RHSPTy
6453           = RHS.get()->getType()->getAs<PointerType>()) {
6454       QualType rpointee = RHSPTy->getPointeeType();
6455 
6456       if (getLangOpts().CPlusPlus) {
6457         // Pointee types must be the same: C++ [expr.add]
6458         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6459           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6460         }
6461       } else {
6462         // Pointee types must be compatible C99 6.5.6p3
6463         if (!Context.typesAreCompatible(
6464                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6465                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6466           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6467           return QualType();
6468         }
6469       }
6470 
6471       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6472                                                LHS.get(), RHS.get()))
6473         return QualType();
6474 
6475       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6476       return Context.getPointerDiffType();
6477     }
6478   }
6479 
6480   return InvalidOperands(Loc, LHS, RHS);
6481 }
6482 
6483 static bool isScopedEnumerationType(QualType T) {
6484   if (const EnumType *ET = dyn_cast<EnumType>(T))
6485     return ET->getDecl()->isScoped();
6486   return false;
6487 }
6488 
6489 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
6490                                    SourceLocation Loc, unsigned Opc,
6491                                    QualType LHSType) {
6492   llvm::APSInt Right;
6493   // Check right/shifter operand
6494   if (RHS.get()->isValueDependent() ||
6495       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
6496     return;
6497 
6498   if (Right.isNegative()) {
6499     S.DiagRuntimeBehavior(Loc, RHS.get(),
6500                           S.PDiag(diag::warn_shift_negative)
6501                             << RHS.get()->getSourceRange());
6502     return;
6503   }
6504   llvm::APInt LeftBits(Right.getBitWidth(),
6505                        S.Context.getTypeSize(LHS.get()->getType()));
6506   if (Right.uge(LeftBits)) {
6507     S.DiagRuntimeBehavior(Loc, RHS.get(),
6508                           S.PDiag(diag::warn_shift_gt_typewidth)
6509                             << RHS.get()->getSourceRange());
6510     return;
6511   }
6512   if (Opc != BO_Shl)
6513     return;
6514 
6515   // When left shifting an ICE which is signed, we can check for overflow which
6516   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6517   // integers have defined behavior modulo one more than the maximum value
6518   // representable in the result type, so never warn for those.
6519   llvm::APSInt Left;
6520   if (LHS.get()->isValueDependent() ||
6521       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6522       LHSType->hasUnsignedIntegerRepresentation())
6523     return;
6524   llvm::APInt ResultBits =
6525       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6526   if (LeftBits.uge(ResultBits))
6527     return;
6528   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6529   Result = Result.shl(Right);
6530 
6531   // Print the bit representation of the signed integer as an unsigned
6532   // hexadecimal number.
6533   SmallString<40> HexResult;
6534   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6535 
6536   // If we are only missing a sign bit, this is less likely to result in actual
6537   // bugs -- if the result is cast back to an unsigned type, it will have the
6538   // expected value. Thus we place this behind a different warning that can be
6539   // turned off separately if needed.
6540   if (LeftBits == ResultBits - 1) {
6541     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6542         << HexResult.str() << LHSType
6543         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6544     return;
6545   }
6546 
6547   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6548     << HexResult.str() << Result.getMinSignedBits() << LHSType
6549     << Left.getBitWidth() << LHS.get()->getSourceRange()
6550     << RHS.get()->getSourceRange();
6551 }
6552 
6553 // C99 6.5.7
6554 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
6555                                   SourceLocation Loc, unsigned Opc,
6556                                   bool IsCompAssign) {
6557   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6558 
6559   // C99 6.5.7p2: Each of the operands shall have integer type.
6560   if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6561       !RHS.get()->getType()->hasIntegerRepresentation())
6562     return InvalidOperands(Loc, LHS, RHS);
6563 
6564   // C++0x: Don't allow scoped enums. FIXME: Use something better than
6565   // hasIntegerRepresentation() above instead of this.
6566   if (isScopedEnumerationType(LHS.get()->getType()) ||
6567       isScopedEnumerationType(RHS.get()->getType())) {
6568     return InvalidOperands(Loc, LHS, RHS);
6569   }
6570 
6571   // Vector shifts promote their scalar inputs to vector type.
6572   if (LHS.get()->getType()->isVectorType() ||
6573       RHS.get()->getType()->isVectorType())
6574     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6575 
6576   // Shifts don't perform usual arithmetic conversions, they just do integer
6577   // promotions on each operand. C99 6.5.7p3
6578 
6579   // For the LHS, do usual unary conversions, but then reset them away
6580   // if this is a compound assignment.
6581   ExprResult OldLHS = LHS;
6582   LHS = UsualUnaryConversions(LHS.take());
6583   if (LHS.isInvalid())
6584     return QualType();
6585   QualType LHSType = LHS.get()->getType();
6586   if (IsCompAssign) LHS = OldLHS;
6587 
6588   // The RHS is simpler.
6589   RHS = UsualUnaryConversions(RHS.take());
6590   if (RHS.isInvalid())
6591     return QualType();
6592 
6593   // Sanity-check shift operands
6594   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
6595 
6596   // "The type of the result is that of the promoted left operand."
6597   return LHSType;
6598 }
6599 
6600 static bool IsWithinTemplateSpecialization(Decl *D) {
6601   if (DeclContext *DC = D->getDeclContext()) {
6602     if (isa<ClassTemplateSpecializationDecl>(DC))
6603       return true;
6604     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6605       return FD->isFunctionTemplateSpecialization();
6606   }
6607   return false;
6608 }
6609 
6610 /// If two different enums are compared, raise a warning.
6611 static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6612                                 ExprResult &RHS) {
6613   QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6614   QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
6615 
6616   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6617   if (!LHSEnumType)
6618     return;
6619   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6620   if (!RHSEnumType)
6621     return;
6622 
6623   // Ignore anonymous enums.
6624   if (!LHSEnumType->getDecl()->getIdentifier())
6625     return;
6626   if (!RHSEnumType->getDecl()->getIdentifier())
6627     return;
6628 
6629   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6630     return;
6631 
6632   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6633       << LHSStrippedType << RHSStrippedType
6634       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6635 }
6636 
6637 /// \brief Diagnose bad pointer comparisons.
6638 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
6639                                               ExprResult &LHS, ExprResult &RHS,
6640                                               bool IsError) {
6641   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
6642                       : diag::ext_typecheck_comparison_of_distinct_pointers)
6643     << LHS.get()->getType() << RHS.get()->getType()
6644     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6645 }
6646 
6647 /// \brief Returns false if the pointers are converted to a composite type,
6648 /// true otherwise.
6649 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
6650                                            ExprResult &LHS, ExprResult &RHS) {
6651   // C++ [expr.rel]p2:
6652   //   [...] Pointer conversions (4.10) and qualification
6653   //   conversions (4.4) are performed on pointer operands (or on
6654   //   a pointer operand and a null pointer constant) to bring
6655   //   them to their composite pointer type. [...]
6656   //
6657   // C++ [expr.eq]p1 uses the same notion for (in)equality
6658   // comparisons of pointers.
6659 
6660   // C++ [expr.eq]p2:
6661   //   In addition, pointers to members can be compared, or a pointer to
6662   //   member and a null pointer constant. Pointer to member conversions
6663   //   (4.11) and qualification conversions (4.4) are performed to bring
6664   //   them to a common type. If one operand is a null pointer constant,
6665   //   the common type is the type of the other operand. Otherwise, the
6666   //   common type is a pointer to member type similar (4.4) to the type
6667   //   of one of the operands, with a cv-qualification signature (4.4)
6668   //   that is the union of the cv-qualification signatures of the operand
6669   //   types.
6670 
6671   QualType LHSType = LHS.get()->getType();
6672   QualType RHSType = RHS.get()->getType();
6673   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6674          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
6675 
6676   bool NonStandardCompositeType = false;
6677   bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
6678   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
6679   if (T.isNull()) {
6680     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
6681     return true;
6682   }
6683 
6684   if (NonStandardCompositeType)
6685     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6686       << LHSType << RHSType << T << LHS.get()->getSourceRange()
6687       << RHS.get()->getSourceRange();
6688 
6689   LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6690   RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
6691   return false;
6692 }
6693 
6694 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
6695                                                     ExprResult &LHS,
6696                                                     ExprResult &RHS,
6697                                                     bool IsError) {
6698   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6699                       : diag::ext_typecheck_comparison_of_fptr_to_void)
6700     << LHS.get()->getType() << RHS.get()->getType()
6701     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6702 }
6703 
6704 static bool isObjCObjectLiteral(ExprResult &E) {
6705   switch (E.get()->getStmtClass()) {
6706   case Stmt::ObjCArrayLiteralClass:
6707   case Stmt::ObjCDictionaryLiteralClass:
6708   case Stmt::ObjCStringLiteralClass:
6709   case Stmt::ObjCBoxedExprClass:
6710     return true;
6711   default:
6712     // Note that ObjCBoolLiteral is NOT an object literal!
6713     return false;
6714   }
6715 }
6716 
6717 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6718   // Get the LHS object's interface type.
6719   QualType Type = LHS->getType();
6720   QualType InterfaceType;
6721   if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6722     InterfaceType = PTy->getPointeeType();
6723     if (const ObjCObjectType *iQFaceTy =
6724         InterfaceType->getAsObjCQualifiedInterfaceType())
6725       InterfaceType = iQFaceTy->getBaseType();
6726   } else {
6727     // If this is not actually an Objective-C object, bail out.
6728     return false;
6729   }
6730 
6731   // If the RHS isn't an Objective-C object, bail out.
6732   if (!RHS->getType()->isObjCObjectPointerType())
6733     return false;
6734 
6735   // Try to find the -isEqual: method.
6736   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6737   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6738                                                       InterfaceType,
6739                                                       /*instance=*/true);
6740   if (!Method) {
6741     if (Type->isObjCIdType()) {
6742       // For 'id', just check the global pool.
6743       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6744                                                   /*receiverId=*/true,
6745                                                   /*warn=*/false);
6746     } else {
6747       // Check protocols.
6748       Method = S.LookupMethodInQualifiedType(IsEqualSel,
6749                                              cast<ObjCObjectPointerType>(Type),
6750                                              /*instance=*/true);
6751     }
6752   }
6753 
6754   if (!Method)
6755     return false;
6756 
6757   QualType T = Method->param_begin()[0]->getType();
6758   if (!T->isObjCObjectPointerType())
6759     return false;
6760 
6761   QualType R = Method->getResultType();
6762   if (!R->isScalarType())
6763     return false;
6764 
6765   return true;
6766 }
6767 
6768 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6769                                           ExprResult &LHS, ExprResult &RHS,
6770                                           BinaryOperator::Opcode Opc){
6771   Expr *Literal;
6772   Expr *Other;
6773   if (isObjCObjectLiteral(LHS)) {
6774     Literal = LHS.get();
6775     Other = RHS.get();
6776   } else {
6777     Literal = RHS.get();
6778     Other = LHS.get();
6779   }
6780 
6781   // Don't warn on comparisons against nil.
6782   Other = Other->IgnoreParenCasts();
6783   if (Other->isNullPointerConstant(S.getASTContext(),
6784                                    Expr::NPC_ValueDependentIsNotNull))
6785     return;
6786 
6787   // This should be kept in sync with warn_objc_literal_comparison.
6788   // LK_String should always be last, since it has its own warning flag.
6789   enum {
6790     LK_Array,
6791     LK_Dictionary,
6792     LK_Numeric,
6793     LK_Boxed,
6794     LK_String
6795   } LiteralKind;
6796 
6797   switch (Literal->getStmtClass()) {
6798   case Stmt::ObjCStringLiteralClass:
6799     // "string literal"
6800     LiteralKind = LK_String;
6801     break;
6802   case Stmt::ObjCArrayLiteralClass:
6803     // "array literal"
6804     LiteralKind = LK_Array;
6805     break;
6806   case Stmt::ObjCDictionaryLiteralClass:
6807     // "dictionary literal"
6808     LiteralKind = LK_Dictionary;
6809     break;
6810   case Stmt::ObjCBoxedExprClass: {
6811     Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6812     switch (Inner->getStmtClass()) {
6813     case Stmt::IntegerLiteralClass:
6814     case Stmt::FloatingLiteralClass:
6815     case Stmt::CharacterLiteralClass:
6816     case Stmt::ObjCBoolLiteralExprClass:
6817     case Stmt::CXXBoolLiteralExprClass:
6818       // "numeric literal"
6819       LiteralKind = LK_Numeric;
6820       break;
6821     case Stmt::ImplicitCastExprClass: {
6822       CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6823       // Boolean literals can be represented by implicit casts.
6824       if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
6825         LiteralKind = LK_Numeric;
6826         break;
6827       }
6828       // FALLTHROUGH
6829     }
6830     default:
6831       // "boxed expression"
6832       LiteralKind = LK_Boxed;
6833       break;
6834     }
6835     break;
6836   }
6837   default:
6838     llvm_unreachable("Unknown Objective-C object literal kind");
6839   }
6840 
6841   if (LiteralKind == LK_String)
6842     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6843       << Literal->getSourceRange();
6844   else
6845     S.Diag(Loc, diag::warn_objc_literal_comparison)
6846       << LiteralKind << Literal->getSourceRange();
6847 
6848   if (BinaryOperator::isEqualityOp(Opc) &&
6849       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6850     SourceLocation Start = LHS.get()->getLocStart();
6851     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6852     SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
6853 
6854     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6855       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6856       << FixItHint::CreateReplacement(OpRange, "isEqual:")
6857       << FixItHint::CreateInsertion(End, "]");
6858   }
6859 }
6860 
6861 // C99 6.5.8, C++ [expr.rel]
6862 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
6863                                     SourceLocation Loc, unsigned OpaqueOpc,
6864                                     bool IsRelational) {
6865   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6866 
6867   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
6868 
6869   // Handle vector comparisons separately.
6870   if (LHS.get()->getType()->isVectorType() ||
6871       RHS.get()->getType()->isVectorType())
6872     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
6873 
6874   QualType LHSType = LHS.get()->getType();
6875   QualType RHSType = RHS.get()->getType();
6876 
6877   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6878   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
6879 
6880   checkEnumComparison(*this, Loc, LHS, RHS);
6881 
6882   if (!LHSType->hasFloatingRepresentation() &&
6883       !(LHSType->isBlockPointerType() && IsRelational) &&
6884       !LHS.get()->getLocStart().isMacroID() &&
6885       !RHS.get()->getLocStart().isMacroID()) {
6886     // For non-floating point types, check for self-comparisons of the form
6887     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
6888     // often indicate logic errors in the program.
6889     //
6890     // NOTE: Don't warn about comparison expressions resulting from macro
6891     // expansion. Also don't warn about comparisons which are only self
6892     // comparisons within a template specialization. The warnings should catch
6893     // obvious cases in the definition of the template anyways. The idea is to
6894     // warn when the typed comparison operator will always evaluate to the same
6895     // result.
6896     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
6897       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
6898         if (DRL->getDecl() == DRR->getDecl() &&
6899             !IsWithinTemplateSpecialization(DRL->getDecl())) {
6900           DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
6901                               << 0 // self-
6902                               << (Opc == BO_EQ
6903                                   || Opc == BO_LE
6904                                   || Opc == BO_GE));
6905         } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
6906                    !DRL->getDecl()->getType()->isReferenceType() &&
6907                    !DRR->getDecl()->getType()->isReferenceType()) {
6908             // what is it always going to eval to?
6909             char always_evals_to;
6910             switch(Opc) {
6911             case BO_EQ: // e.g. array1 == array2
6912               always_evals_to = 0; // false
6913               break;
6914             case BO_NE: // e.g. array1 != array2
6915               always_evals_to = 1; // true
6916               break;
6917             default:
6918               // best we can say is 'a constant'
6919               always_evals_to = 2; // e.g. array1 <= array2
6920               break;
6921             }
6922             DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
6923                                 << 1 // array
6924                                 << always_evals_to);
6925         }
6926       }
6927     }
6928 
6929     if (isa<CastExpr>(LHSStripped))
6930       LHSStripped = LHSStripped->IgnoreParenCasts();
6931     if (isa<CastExpr>(RHSStripped))
6932       RHSStripped = RHSStripped->IgnoreParenCasts();
6933 
6934     // Warn about comparisons against a string constant (unless the other
6935     // operand is null), the user probably wants strcmp.
6936     Expr *literalString = 0;
6937     Expr *literalStringStripped = 0;
6938     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
6939         !RHSStripped->isNullPointerConstant(Context,
6940                                             Expr::NPC_ValueDependentIsNull)) {
6941       literalString = LHS.get();
6942       literalStringStripped = LHSStripped;
6943     } else if ((isa<StringLiteral>(RHSStripped) ||
6944                 isa<ObjCEncodeExpr>(RHSStripped)) &&
6945                !LHSStripped->isNullPointerConstant(Context,
6946                                             Expr::NPC_ValueDependentIsNull)) {
6947       literalString = RHS.get();
6948       literalStringStripped = RHSStripped;
6949     }
6950 
6951     if (literalString) {
6952       std::string resultComparison;
6953       switch (Opc) {
6954       case BO_LT: resultComparison = ") < 0"; break;
6955       case BO_GT: resultComparison = ") > 0"; break;
6956       case BO_LE: resultComparison = ") <= 0"; break;
6957       case BO_GE: resultComparison = ") >= 0"; break;
6958       case BO_EQ: resultComparison = ") == 0"; break;
6959       case BO_NE: resultComparison = ") != 0"; break;
6960       default: llvm_unreachable("Invalid comparison operator");
6961       }
6962 
6963       DiagRuntimeBehavior(Loc, 0,
6964         PDiag(diag::warn_stringcompare)
6965           << isa<ObjCEncodeExpr>(literalStringStripped)
6966           << literalString->getSourceRange());
6967     }
6968   }
6969 
6970   // C99 6.5.8p3 / C99 6.5.9p4
6971   if (LHS.get()->getType()->isArithmeticType() &&
6972       RHS.get()->getType()->isArithmeticType()) {
6973     UsualArithmeticConversions(LHS, RHS);
6974     if (LHS.isInvalid() || RHS.isInvalid())
6975       return QualType();
6976   }
6977   else {
6978     LHS = UsualUnaryConversions(LHS.take());
6979     if (LHS.isInvalid())
6980       return QualType();
6981 
6982     RHS = UsualUnaryConversions(RHS.take());
6983     if (RHS.isInvalid())
6984       return QualType();
6985   }
6986 
6987   LHSType = LHS.get()->getType();
6988   RHSType = RHS.get()->getType();
6989 
6990   // The result of comparisons is 'bool' in C++, 'int' in C.
6991   QualType ResultTy = Context.getLogicalOperationType();
6992 
6993   if (IsRelational) {
6994     if (LHSType->isRealType() && RHSType->isRealType())
6995       return ResultTy;
6996   } else {
6997     // Check for comparisons of floating point operands using != and ==.
6998     if (LHSType->hasFloatingRepresentation())
6999       CheckFloatComparison(Loc, LHS.get(), RHS.get());
7000 
7001     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7002       return ResultTy;
7003   }
7004 
7005   bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
7006                                               Expr::NPC_ValueDependentIsNull);
7007   bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
7008                                               Expr::NPC_ValueDependentIsNull);
7009 
7010   // All of the following pointer-related warnings are GCC extensions, except
7011   // when handling null pointer constants.
7012   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7013     QualType LCanPointeeTy =
7014       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7015     QualType RCanPointeeTy =
7016       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7017 
7018     if (getLangOpts().CPlusPlus) {
7019       if (LCanPointeeTy == RCanPointeeTy)
7020         return ResultTy;
7021       if (!IsRelational &&
7022           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7023         // Valid unless comparison between non-null pointer and function pointer
7024         // This is a gcc extension compatibility comparison.
7025         // In a SFINAE context, we treat this as a hard error to maintain
7026         // conformance with the C++ standard.
7027         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7028             && !LHSIsNull && !RHSIsNull) {
7029           diagnoseFunctionPointerToVoidComparison(
7030               *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
7031 
7032           if (isSFINAEContext())
7033             return QualType();
7034 
7035           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7036           return ResultTy;
7037         }
7038       }
7039 
7040       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7041         return QualType();
7042       else
7043         return ResultTy;
7044     }
7045     // C99 6.5.9p2 and C99 6.5.8p2
7046     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7047                                    RCanPointeeTy.getUnqualifiedType())) {
7048       // Valid unless a relational comparison of function pointers
7049       if (IsRelational && LCanPointeeTy->isFunctionType()) {
7050         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7051           << LHSType << RHSType << LHS.get()->getSourceRange()
7052           << RHS.get()->getSourceRange();
7053       }
7054     } else if (!IsRelational &&
7055                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7056       // Valid unless comparison between non-null pointer and function pointer
7057       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7058           && !LHSIsNull && !RHSIsNull)
7059         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
7060                                                 /*isError*/false);
7061     } else {
7062       // Invalid
7063       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
7064     }
7065     if (LCanPointeeTy != RCanPointeeTy) {
7066       if (LHSIsNull && !RHSIsNull)
7067         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7068       else
7069         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7070     }
7071     return ResultTy;
7072   }
7073 
7074   if (getLangOpts().CPlusPlus) {
7075     // Comparison of nullptr_t with itself.
7076     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
7077       return ResultTy;
7078 
7079     // Comparison of pointers with null pointer constants and equality
7080     // comparisons of member pointers to null pointer constants.
7081     if (RHSIsNull &&
7082         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
7083          (!IsRelational &&
7084           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7085       RHS = ImpCastExprToType(RHS.take(), LHSType,
7086                         LHSType->isMemberPointerType()
7087                           ? CK_NullToMemberPointer
7088                           : CK_NullToPointer);
7089       return ResultTy;
7090     }
7091     if (LHSIsNull &&
7092         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
7093          (!IsRelational &&
7094           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7095       LHS = ImpCastExprToType(LHS.take(), RHSType,
7096                         RHSType->isMemberPointerType()
7097                           ? CK_NullToMemberPointer
7098                           : CK_NullToPointer);
7099       return ResultTy;
7100     }
7101 
7102     // Comparison of member pointers.
7103     if (!IsRelational &&
7104         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7105       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7106         return QualType();
7107       else
7108         return ResultTy;
7109     }
7110 
7111     // Handle scoped enumeration types specifically, since they don't promote
7112     // to integers.
7113     if (LHS.get()->getType()->isEnumeralType() &&
7114         Context.hasSameUnqualifiedType(LHS.get()->getType(),
7115                                        RHS.get()->getType()))
7116       return ResultTy;
7117   }
7118 
7119   // Handle block pointer types.
7120   if (!IsRelational && LHSType->isBlockPointerType() &&
7121       RHSType->isBlockPointerType()) {
7122     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7123     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
7124 
7125     if (!LHSIsNull && !RHSIsNull &&
7126         !Context.typesAreCompatible(lpointee, rpointee)) {
7127       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7128         << LHSType << RHSType << LHS.get()->getSourceRange()
7129         << RHS.get()->getSourceRange();
7130     }
7131     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7132     return ResultTy;
7133   }
7134 
7135   // Allow block pointers to be compared with null pointer constants.
7136   if (!IsRelational
7137       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7138           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
7139     if (!LHSIsNull && !RHSIsNull) {
7140       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
7141              ->getPointeeType()->isVoidType())
7142             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
7143                 ->getPointeeType()->isVoidType())))
7144         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7145           << LHSType << RHSType << LHS.get()->getSourceRange()
7146           << RHS.get()->getSourceRange();
7147     }
7148     if (LHSIsNull && !RHSIsNull)
7149       LHS = ImpCastExprToType(LHS.take(), RHSType,
7150                               RHSType->isPointerType() ? CK_BitCast
7151                                 : CK_AnyPointerToBlockPointerCast);
7152     else
7153       RHS = ImpCastExprToType(RHS.take(), LHSType,
7154                               LHSType->isPointerType() ? CK_BitCast
7155                                 : CK_AnyPointerToBlockPointerCast);
7156     return ResultTy;
7157   }
7158 
7159   if (LHSType->isObjCObjectPointerType() ||
7160       RHSType->isObjCObjectPointerType()) {
7161     const PointerType *LPT = LHSType->getAs<PointerType>();
7162     const PointerType *RPT = RHSType->getAs<PointerType>();
7163     if (LPT || RPT) {
7164       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7165       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
7166 
7167       if (!LPtrToVoid && !RPtrToVoid &&
7168           !Context.typesAreCompatible(LHSType, RHSType)) {
7169         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7170                                           /*isError*/false);
7171       }
7172       if (LHSIsNull && !RHSIsNull)
7173         LHS = ImpCastExprToType(LHS.take(), RHSType,
7174                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7175       else
7176         RHS = ImpCastExprToType(RHS.take(), LHSType,
7177                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7178       return ResultTy;
7179     }
7180     if (LHSType->isObjCObjectPointerType() &&
7181         RHSType->isObjCObjectPointerType()) {
7182       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7183         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7184                                           /*isError*/false);
7185       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7186         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
7187 
7188       if (LHSIsNull && !RHSIsNull)
7189         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7190       else
7191         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7192       return ResultTy;
7193     }
7194   }
7195   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7196       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
7197     unsigned DiagID = 0;
7198     bool isError = false;
7199     if ((LHSIsNull && LHSType->isIntegerType()) ||
7200         (RHSIsNull && RHSType->isIntegerType())) {
7201       if (IsRelational && !getLangOpts().CPlusPlus)
7202         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
7203     } else if (IsRelational && !getLangOpts().CPlusPlus)
7204       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
7205     else if (getLangOpts().CPlusPlus) {
7206       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7207       isError = true;
7208     } else
7209       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
7210 
7211     if (DiagID) {
7212       Diag(Loc, DiagID)
7213         << LHSType << RHSType << LHS.get()->getSourceRange()
7214         << RHS.get()->getSourceRange();
7215       if (isError)
7216         return QualType();
7217     }
7218 
7219     if (LHSType->isIntegerType())
7220       LHS = ImpCastExprToType(LHS.take(), RHSType,
7221                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7222     else
7223       RHS = ImpCastExprToType(RHS.take(), LHSType,
7224                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7225     return ResultTy;
7226   }
7227 
7228   // Handle block pointers.
7229   if (!IsRelational && RHSIsNull
7230       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7231     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
7232     return ResultTy;
7233   }
7234   if (!IsRelational && LHSIsNull
7235       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7236     LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
7237     return ResultTy;
7238   }
7239 
7240   return InvalidOperands(Loc, LHS, RHS);
7241 }
7242 
7243 
7244 // Return a signed type that is of identical size and number of elements.
7245 // For floating point vectors, return an integer type of identical size
7246 // and number of elements.
7247 QualType Sema::GetSignedVectorType(QualType V) {
7248   const VectorType *VTy = V->getAs<VectorType>();
7249   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7250   if (TypeSize == Context.getTypeSize(Context.CharTy))
7251     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7252   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7253     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7254   else if (TypeSize == Context.getTypeSize(Context.IntTy))
7255     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7256   else if (TypeSize == Context.getTypeSize(Context.LongTy))
7257     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7258   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7259          "Unhandled vector element size in vector compare");
7260   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7261 }
7262 
7263 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7264 /// operates on extended vector types.  Instead of producing an IntTy result,
7265 /// like a scalar comparison, a vector comparison produces a vector of integer
7266 /// types.
7267 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7268                                           SourceLocation Loc,
7269                                           bool IsRelational) {
7270   // Check to make sure we're operating on vectors of the same type and width,
7271   // Allowing one side to be a scalar of element type.
7272   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
7273   if (vType.isNull())
7274     return vType;
7275 
7276   QualType LHSType = LHS.get()->getType();
7277 
7278   // If AltiVec, the comparison results in a numeric type, i.e.
7279   // bool for C++, int for C
7280   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
7281     return Context.getLogicalOperationType();
7282 
7283   // For non-floating point types, check for self-comparisons of the form
7284   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7285   // often indicate logic errors in the program.
7286   if (!LHSType->hasFloatingRepresentation()) {
7287     if (DeclRefExpr* DRL
7288           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7289       if (DeclRefExpr* DRR
7290             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
7291         if (DRL->getDecl() == DRR->getDecl())
7292           DiagRuntimeBehavior(Loc, 0,
7293                               PDiag(diag::warn_comparison_always)
7294                                 << 0 // self-
7295                                 << 2 // "a constant"
7296                               );
7297   }
7298 
7299   // Check for comparisons of floating point operands using != and ==.
7300   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
7301     assert (RHS.get()->getType()->hasFloatingRepresentation());
7302     CheckFloatComparison(Loc, LHS.get(), RHS.get());
7303   }
7304 
7305   // Return a signed type for the vector.
7306   return GetSignedVectorType(LHSType);
7307 }
7308 
7309 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7310                                           SourceLocation Loc) {
7311   // Ensure that either both operands are of the same vector type, or
7312   // one operand is of a vector type and the other is of its element type.
7313   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7314   if (vType.isNull() || vType->isFloatingType())
7315     return InvalidOperands(Loc, LHS, RHS);
7316 
7317   return GetSignedVectorType(LHS.get()->getType());
7318 }
7319 
7320 inline QualType Sema::CheckBitwiseOperands(
7321   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7322   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7323 
7324   if (LHS.get()->getType()->isVectorType() ||
7325       RHS.get()->getType()->isVectorType()) {
7326     if (LHS.get()->getType()->hasIntegerRepresentation() &&
7327         RHS.get()->getType()->hasIntegerRepresentation())
7328       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7329 
7330     return InvalidOperands(Loc, LHS, RHS);
7331   }
7332 
7333   ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7334   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
7335                                                  IsCompAssign);
7336   if (LHSResult.isInvalid() || RHSResult.isInvalid())
7337     return QualType();
7338   LHS = LHSResult.take();
7339   RHS = RHSResult.take();
7340 
7341   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
7342     return compType;
7343   return InvalidOperands(Loc, LHS, RHS);
7344 }
7345 
7346 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
7347   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
7348 
7349   // Check vector operands differently.
7350   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7351     return CheckVectorLogicalOperands(LHS, RHS, Loc);
7352 
7353   // Diagnose cases where the user write a logical and/or but probably meant a
7354   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
7355   // is a constant.
7356   if (LHS.get()->getType()->isIntegerType() &&
7357       !LHS.get()->getType()->isBooleanType() &&
7358       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
7359       // Don't warn in macros or template instantiations.
7360       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
7361     // If the RHS can be constant folded, and if it constant folds to something
7362     // that isn't 0 or 1 (which indicate a potential logical operation that
7363     // happened to fold to true/false) then warn.
7364     // Parens on the RHS are ignored.
7365     llvm::APSInt Result;
7366     if (RHS.get()->EvaluateAsInt(Result, Context))
7367       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
7368           (Result != 0 && Result != 1)) {
7369         Diag(Loc, diag::warn_logical_instead_of_bitwise)
7370           << RHS.get()->getSourceRange()
7371           << (Opc == BO_LAnd ? "&&" : "||");
7372         // Suggest replacing the logical operator with the bitwise version
7373         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7374             << (Opc == BO_LAnd ? "&" : "|")
7375             << FixItHint::CreateReplacement(SourceRange(
7376                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
7377                                                 getLangOpts())),
7378                                             Opc == BO_LAnd ? "&" : "|");
7379         if (Opc == BO_LAnd)
7380           // Suggest replacing "Foo() && kNonZero" with "Foo()"
7381           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7382               << FixItHint::CreateRemoval(
7383                   SourceRange(
7384                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
7385                                                  0, getSourceManager(),
7386                                                  getLangOpts()),
7387                       RHS.get()->getLocEnd()));
7388       }
7389   }
7390 
7391   if (!Context.getLangOpts().CPlusPlus) {
7392     LHS = UsualUnaryConversions(LHS.take());
7393     if (LHS.isInvalid())
7394       return QualType();
7395 
7396     RHS = UsualUnaryConversions(RHS.take());
7397     if (RHS.isInvalid())
7398       return QualType();
7399 
7400     if (!LHS.get()->getType()->isScalarType() ||
7401         !RHS.get()->getType()->isScalarType())
7402       return InvalidOperands(Loc, LHS, RHS);
7403 
7404     return Context.IntTy;
7405   }
7406 
7407   // The following is safe because we only use this method for
7408   // non-overloadable operands.
7409 
7410   // C++ [expr.log.and]p1
7411   // C++ [expr.log.or]p1
7412   // The operands are both contextually converted to type bool.
7413   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7414   if (LHSRes.isInvalid())
7415     return InvalidOperands(Loc, LHS, RHS);
7416   LHS = move(LHSRes);
7417 
7418   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7419   if (RHSRes.isInvalid())
7420     return InvalidOperands(Loc, LHS, RHS);
7421   RHS = move(RHSRes);
7422 
7423   // C++ [expr.log.and]p2
7424   // C++ [expr.log.or]p2
7425   // The result is a bool.
7426   return Context.BoolTy;
7427 }
7428 
7429 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7430 /// is a read-only property; return true if so. A readonly property expression
7431 /// depends on various declarations and thus must be treated specially.
7432 ///
7433 static bool IsReadonlyProperty(Expr *E, Sema &S) {
7434   const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7435   if (!PropExpr) return false;
7436   if (PropExpr->isImplicitProperty()) return false;
7437 
7438   ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7439   QualType BaseType = PropExpr->isSuperReceiver() ?
7440                             PropExpr->getSuperReceiverType() :
7441                             PropExpr->getBase()->getType();
7442 
7443   if (const ObjCObjectPointerType *OPT =
7444       BaseType->getAsObjCInterfacePointerType())
7445     if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7446       if (S.isPropertyReadonly(PDecl, IFace))
7447         return true;
7448   return false;
7449 }
7450 
7451 static bool IsReadonlyMessage(Expr *E, Sema &S) {
7452   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7453   if (!ME) return false;
7454   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7455   ObjCMessageExpr *Base =
7456     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7457   if (!Base) return false;
7458   return Base->getMethodDecl() != 0;
7459 }
7460 
7461 /// Is the given expression (which must be 'const') a reference to a
7462 /// variable which was originally non-const, but which has become
7463 /// 'const' due to being captured within a block?
7464 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7465 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7466   assert(E->isLValue() && E->getType().isConstQualified());
7467   E = E->IgnoreParens();
7468 
7469   // Must be a reference to a declaration from an enclosing scope.
7470   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7471   if (!DRE) return NCCK_None;
7472   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7473 
7474   // The declaration must be a variable which is not declared 'const'.
7475   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7476   if (!var) return NCCK_None;
7477   if (var->getType().isConstQualified()) return NCCK_None;
7478   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7479 
7480   // Decide whether the first capture was for a block or a lambda.
7481   DeclContext *DC = S.CurContext;
7482   while (DC->getParent() != var->getDeclContext())
7483     DC = DC->getParent();
7484   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7485 }
7486 
7487 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
7488 /// emit an error and return true.  If so, return false.
7489 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
7490   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
7491   SourceLocation OrigLoc = Loc;
7492   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
7493                                                               &Loc);
7494   if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7495     IsLV = Expr::MLV_ReadonlyProperty;
7496   else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7497     IsLV = Expr::MLV_InvalidMessageExpression;
7498   if (IsLV == Expr::MLV_Valid)
7499     return false;
7500 
7501   unsigned Diag = 0;
7502   bool NeedType = false;
7503   switch (IsLV) { // C99 6.5.16p2
7504   case Expr::MLV_ConstQualified:
7505     Diag = diag::err_typecheck_assign_const;
7506 
7507     // Use a specialized diagnostic when we're assigning to an object
7508     // from an enclosing function or block.
7509     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7510       if (NCCK == NCCK_Block)
7511         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7512       else
7513         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7514       break;
7515     }
7516 
7517     // In ARC, use some specialized diagnostics for occasions where we
7518     // infer 'const'.  These are always pseudo-strong variables.
7519     if (S.getLangOpts().ObjCAutoRefCount) {
7520       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7521       if (declRef && isa<VarDecl>(declRef->getDecl())) {
7522         VarDecl *var = cast<VarDecl>(declRef->getDecl());
7523 
7524         // Use the normal diagnostic if it's pseudo-__strong but the
7525         // user actually wrote 'const'.
7526         if (var->isARCPseudoStrong() &&
7527             (!var->getTypeSourceInfo() ||
7528              !var->getTypeSourceInfo()->getType().isConstQualified())) {
7529           // There are two pseudo-strong cases:
7530           //  - self
7531           ObjCMethodDecl *method = S.getCurMethodDecl();
7532           if (method && var == method->getSelfDecl())
7533             Diag = method->isClassMethod()
7534               ? diag::err_typecheck_arc_assign_self_class_method
7535               : diag::err_typecheck_arc_assign_self;
7536 
7537           //  - fast enumeration variables
7538           else
7539             Diag = diag::err_typecheck_arr_assign_enumeration;
7540 
7541           SourceRange Assign;
7542           if (Loc != OrigLoc)
7543             Assign = SourceRange(OrigLoc, OrigLoc);
7544           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7545           // We need to preserve the AST regardless, so migration tool
7546           // can do its job.
7547           return false;
7548         }
7549       }
7550     }
7551 
7552     break;
7553   case Expr::MLV_ArrayType:
7554   case Expr::MLV_ArrayTemporary:
7555     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7556     NeedType = true;
7557     break;
7558   case Expr::MLV_NotObjectType:
7559     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7560     NeedType = true;
7561     break;
7562   case Expr::MLV_LValueCast:
7563     Diag = diag::err_typecheck_lvalue_casts_not_supported;
7564     break;
7565   case Expr::MLV_Valid:
7566     llvm_unreachable("did not take early return for MLV_Valid");
7567   case Expr::MLV_InvalidExpression:
7568   case Expr::MLV_MemberFunction:
7569   case Expr::MLV_ClassTemporary:
7570     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7571     break;
7572   case Expr::MLV_IncompleteType:
7573   case Expr::MLV_IncompleteVoidType:
7574     return S.RequireCompleteType(Loc, E->getType(),
7575              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
7576   case Expr::MLV_DuplicateVectorComponents:
7577     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7578     break;
7579   case Expr::MLV_ReadonlyProperty:
7580   case Expr::MLV_NoSetterProperty:
7581     llvm_unreachable("readonly properties should be processed differently");
7582   case Expr::MLV_InvalidMessageExpression:
7583     Diag = diag::error_readonly_message_assignment;
7584     break;
7585   case Expr::MLV_SubObjCPropertySetting:
7586     Diag = diag::error_no_subobject_property_setting;
7587     break;
7588   }
7589 
7590   SourceRange Assign;
7591   if (Loc != OrigLoc)
7592     Assign = SourceRange(OrigLoc, OrigLoc);
7593   if (NeedType)
7594     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
7595   else
7596     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7597   return true;
7598 }
7599 
7600 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7601                                          SourceLocation Loc,
7602                                          Sema &Sema) {
7603   // C / C++ fields
7604   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7605   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7606   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7607     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
7608       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
7609   }
7610 
7611   // Objective-C instance variables
7612   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7613   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7614   if (OL && OR && OL->getDecl() == OR->getDecl()) {
7615     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7616     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7617     if (RL && RR && RL->getDecl() == RR->getDecl())
7618       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
7619   }
7620 }
7621 
7622 // C99 6.5.16.1
7623 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
7624                                        SourceLocation Loc,
7625                                        QualType CompoundType) {
7626   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7627 
7628   // Verify that LHS is a modifiable lvalue, and emit error if not.
7629   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
7630     return QualType();
7631 
7632   QualType LHSType = LHSExpr->getType();
7633   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7634                                              CompoundType;
7635   AssignConvertType ConvTy;
7636   if (CompoundType.isNull()) {
7637     Expr *RHSCheck = RHS.get();
7638 
7639     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
7640 
7641     QualType LHSTy(LHSType);
7642     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
7643     if (RHS.isInvalid())
7644       return QualType();
7645     // Special case of NSObject attributes on c-style pointer types.
7646     if (ConvTy == IncompatiblePointer &&
7647         ((Context.isObjCNSObjectType(LHSType) &&
7648           RHSType->isObjCObjectPointerType()) ||
7649          (Context.isObjCNSObjectType(RHSType) &&
7650           LHSType->isObjCObjectPointerType())))
7651       ConvTy = Compatible;
7652 
7653     if (ConvTy == Compatible &&
7654         LHSType->isObjCObjectType())
7655         Diag(Loc, diag::err_objc_object_assignment)
7656           << LHSType;
7657 
7658     // If the RHS is a unary plus or minus, check to see if they = and + are
7659     // right next to each other.  If so, the user may have typo'd "x =+ 4"
7660     // instead of "x += 4".
7661     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7662       RHSCheck = ICE->getSubExpr();
7663     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
7664       if ((UO->getOpcode() == UO_Plus ||
7665            UO->getOpcode() == UO_Minus) &&
7666           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
7667           // Only if the two operators are exactly adjacent.
7668           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
7669           // And there is a space or other character before the subexpr of the
7670           // unary +/-.  We don't want to warn on "x=-1".
7671           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7672           UO->getSubExpr()->getLocStart().isFileID()) {
7673         Diag(Loc, diag::warn_not_compound_assign)
7674           << (UO->getOpcode() == UO_Plus ? "+" : "-")
7675           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
7676       }
7677     }
7678 
7679     if (ConvTy == Compatible) {
7680       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
7681         checkRetainCycles(LHSExpr, RHS.get());
7682       else if (getLangOpts().ObjCAutoRefCount)
7683         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
7684     }
7685   } else {
7686     // Compound assignment "x += y"
7687     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
7688   }
7689 
7690   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
7691                                RHS.get(), AA_Assigning))
7692     return QualType();
7693 
7694   CheckForNullPointerDereference(*this, LHSExpr);
7695 
7696   // C99 6.5.16p3: The type of an assignment expression is the type of the
7697   // left operand unless the left operand has qualified type, in which case
7698   // it is the unqualified version of the type of the left operand.
7699   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7700   // is converted to the type of the assignment expression (above).
7701   // C++ 5.17p1: the type of the assignment expression is that of its left
7702   // operand.
7703   return (getLangOpts().CPlusPlus
7704           ? LHSType : LHSType.getUnqualifiedType());
7705 }
7706 
7707 // C99 6.5.17
7708 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
7709                                    SourceLocation Loc) {
7710   LHS = S.CheckPlaceholderExpr(LHS.take());
7711   RHS = S.CheckPlaceholderExpr(RHS.take());
7712   if (LHS.isInvalid() || RHS.isInvalid())
7713     return QualType();
7714 
7715   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7716   // operands, but not unary promotions.
7717   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
7718 
7719   // So we treat the LHS as a ignored value, and in C++ we allow the
7720   // containing site to determine what should be done with the RHS.
7721   LHS = S.IgnoredValueConversions(LHS.take());
7722   if (LHS.isInvalid())
7723     return QualType();
7724 
7725   S.DiagnoseUnusedExprResult(LHS.get());
7726 
7727   if (!S.getLangOpts().CPlusPlus) {
7728     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7729     if (RHS.isInvalid())
7730       return QualType();
7731     if (!RHS.get()->getType()->isVoidType())
7732       S.RequireCompleteType(Loc, RHS.get()->getType(),
7733                             diag::err_incomplete_type);
7734   }
7735 
7736   return RHS.get()->getType();
7737 }
7738 
7739 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7740 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
7741 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7742                                                ExprValueKind &VK,
7743                                                SourceLocation OpLoc,
7744                                                bool IsInc, bool IsPrefix) {
7745   if (Op->isTypeDependent())
7746     return S.Context.DependentTy;
7747 
7748   QualType ResType = Op->getType();
7749   // Atomic types can be used for increment / decrement where the non-atomic
7750   // versions can, so ignore the _Atomic() specifier for the purpose of
7751   // checking.
7752   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7753     ResType = ResAtomicType->getValueType();
7754 
7755   assert(!ResType.isNull() && "no type for increment/decrement expression");
7756 
7757   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
7758     // Decrement of bool is not allowed.
7759     if (!IsInc) {
7760       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
7761       return QualType();
7762     }
7763     // Increment of bool sets it to true, but is deprecated.
7764     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
7765   } else if (ResType->isRealType()) {
7766     // OK!
7767   } else if (ResType->isPointerType()) {
7768     // C99 6.5.2.4p2, 6.5.6p2
7769     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
7770       return QualType();
7771   } else if (ResType->isObjCObjectPointerType()) {
7772     // On modern runtimes, ObjC pointer arithmetic is forbidden.
7773     // Otherwise, we just need a complete type.
7774     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7775         checkArithmeticOnObjCPointer(S, OpLoc, Op))
7776       return QualType();
7777   } else if (ResType->isAnyComplexType()) {
7778     // C99 does not support ++/-- on complex types, we allow as an extension.
7779     S.Diag(OpLoc, diag::ext_integer_increment_complex)
7780       << ResType << Op->getSourceRange();
7781   } else if (ResType->isPlaceholderType()) {
7782     ExprResult PR = S.CheckPlaceholderExpr(Op);
7783     if (PR.isInvalid()) return QualType();
7784     return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7785                                           IsInc, IsPrefix);
7786   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
7787     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
7788   } else {
7789     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
7790       << ResType << int(IsInc) << Op->getSourceRange();
7791     return QualType();
7792   }
7793   // At this point, we know we have a real, complex or pointer type.
7794   // Now make sure the operand is a modifiable lvalue.
7795   if (CheckForModifiableLvalue(Op, OpLoc, S))
7796     return QualType();
7797   // In C++, a prefix increment is the same type as the operand. Otherwise
7798   // (in C or with postfix), the increment is the unqualified type of the
7799   // operand.
7800   if (IsPrefix && S.getLangOpts().CPlusPlus) {
7801     VK = VK_LValue;
7802     return ResType;
7803   } else {
7804     VK = VK_RValue;
7805     return ResType.getUnqualifiedType();
7806   }
7807 }
7808 
7809 
7810 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
7811 /// This routine allows us to typecheck complex/recursive expressions
7812 /// where the declaration is needed for type checking. We only need to
7813 /// handle cases when the expression references a function designator
7814 /// or is an lvalue. Here are some examples:
7815 ///  - &(x) => x
7816 ///  - &*****f => f for f a function designator.
7817 ///  - &s.xx => s
7818 ///  - &s.zz[1].yy -> s, if zz is an array
7819 ///  - *(x + 1) -> x, if x is an array
7820 ///  - &"123"[2] -> 0
7821 ///  - & __real__ x -> x
7822 static ValueDecl *getPrimaryDecl(Expr *E) {
7823   switch (E->getStmtClass()) {
7824   case Stmt::DeclRefExprClass:
7825     return cast<DeclRefExpr>(E)->getDecl();
7826   case Stmt::MemberExprClass:
7827     // If this is an arrow operator, the address is an offset from
7828     // the base's value, so the object the base refers to is
7829     // irrelevant.
7830     if (cast<MemberExpr>(E)->isArrow())
7831       return 0;
7832     // Otherwise, the expression refers to a part of the base
7833     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
7834   case Stmt::ArraySubscriptExprClass: {
7835     // FIXME: This code shouldn't be necessary!  We should catch the implicit
7836     // promotion of register arrays earlier.
7837     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7838     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7839       if (ICE->getSubExpr()->getType()->isArrayType())
7840         return getPrimaryDecl(ICE->getSubExpr());
7841     }
7842     return 0;
7843   }
7844   case Stmt::UnaryOperatorClass: {
7845     UnaryOperator *UO = cast<UnaryOperator>(E);
7846 
7847     switch(UO->getOpcode()) {
7848     case UO_Real:
7849     case UO_Imag:
7850     case UO_Extension:
7851       return getPrimaryDecl(UO->getSubExpr());
7852     default:
7853       return 0;
7854     }
7855   }
7856   case Stmt::ParenExprClass:
7857     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
7858   case Stmt::ImplicitCastExprClass:
7859     // If the result of an implicit cast is an l-value, we care about
7860     // the sub-expression; otherwise, the result here doesn't matter.
7861     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
7862   default:
7863     return 0;
7864   }
7865 }
7866 
7867 namespace {
7868   enum {
7869     AO_Bit_Field = 0,
7870     AO_Vector_Element = 1,
7871     AO_Property_Expansion = 2,
7872     AO_Register_Variable = 3,
7873     AO_No_Error = 4
7874   };
7875 }
7876 /// \brief Diagnose invalid operand for address of operations.
7877 ///
7878 /// \param Type The type of operand which cannot have its address taken.
7879 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7880                                          Expr *E, unsigned Type) {
7881   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7882 }
7883 
7884 /// CheckAddressOfOperand - The operand of & must be either a function
7885 /// designator or an lvalue designating an object. If it is an lvalue, the
7886 /// object cannot be declared with storage class register or be a bit field.
7887 /// Note: The usual conversions are *not* applied to the operand of the &
7888 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7889 /// In C++, the operand might be an overloaded function name, in which case
7890 /// we allow the '&' but retain the overloaded-function type.
7891 static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
7892                                       SourceLocation OpLoc) {
7893   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7894     if (PTy->getKind() == BuiltinType::Overload) {
7895       if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7896         S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7897           << OrigOp.get()->getSourceRange();
7898         return QualType();
7899       }
7900 
7901       return S.Context.OverloadTy;
7902     }
7903 
7904     if (PTy->getKind() == BuiltinType::UnknownAny)
7905       return S.Context.UnknownAnyTy;
7906 
7907     if (PTy->getKind() == BuiltinType::BoundMember) {
7908       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7909         << OrigOp.get()->getSourceRange();
7910       return QualType();
7911     }
7912 
7913     OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7914     if (OrigOp.isInvalid()) return QualType();
7915   }
7916 
7917   if (OrigOp.get()->isTypeDependent())
7918     return S.Context.DependentTy;
7919 
7920   assert(!OrigOp.get()->getType()->isPlaceholderType());
7921 
7922   // Make sure to ignore parentheses in subsequent checks
7923   Expr *op = OrigOp.get()->IgnoreParens();
7924 
7925   if (S.getLangOpts().C99) {
7926     // Implement C99-only parts of addressof rules.
7927     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
7928       if (uOp->getOpcode() == UO_Deref)
7929         // Per C99 6.5.3.2, the address of a deref always returns a valid result
7930         // (assuming the deref expression is valid).
7931         return uOp->getSubExpr()->getType();
7932     }
7933     // Technically, there should be a check for array subscript
7934     // expressions here, but the result of one is always an lvalue anyway.
7935   }
7936   ValueDecl *dcl = getPrimaryDecl(op);
7937   Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
7938   unsigned AddressOfError = AO_No_Error;
7939 
7940   if (lval == Expr::LV_ClassTemporary) {
7941     bool sfinae = S.isSFINAEContext();
7942     S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7943                          : diag::ext_typecheck_addrof_class_temporary)
7944       << op->getType() << op->getSourceRange();
7945     if (sfinae)
7946       return QualType();
7947   } else if (isa<ObjCSelectorExpr>(op)) {
7948     return S.Context.getPointerType(op->getType());
7949   } else if (lval == Expr::LV_MemberFunction) {
7950     // If it's an instance method, make a member pointer.
7951     // The expression must have exactly the form &A::foo.
7952 
7953     // If the underlying expression isn't a decl ref, give up.
7954     if (!isa<DeclRefExpr>(op)) {
7955       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7956         << OrigOp.get()->getSourceRange();
7957       return QualType();
7958     }
7959     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7960     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7961 
7962     // The id-expression was parenthesized.
7963     if (OrigOp.get() != DRE) {
7964       S.Diag(OpLoc, diag::err_parens_pointer_member_function)
7965         << OrigOp.get()->getSourceRange();
7966 
7967     // The method was named without a qualifier.
7968     } else if (!DRE->getQualifier()) {
7969       S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
7970         << op->getSourceRange();
7971     }
7972 
7973     return S.Context.getMemberPointerType(op->getType(),
7974               S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
7975   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
7976     // C99 6.5.3.2p1
7977     // The operand must be either an l-value or a function designator
7978     if (!op->getType()->isFunctionType()) {
7979       // Use a special diagnostic for loads from property references.
7980       if (isa<PseudoObjectExpr>(op)) {
7981         AddressOfError = AO_Property_Expansion;
7982       } else {
7983         // FIXME: emit more specific diag...
7984         S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7985           << op->getSourceRange();
7986         return QualType();
7987       }
7988     }
7989   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
7990     // The operand cannot be a bit-field
7991     AddressOfError = AO_Bit_Field;
7992   } else if (op->getObjectKind() == OK_VectorComponent) {
7993     // The operand cannot be an element of a vector
7994     AddressOfError = AO_Vector_Element;
7995   } else if (dcl) { // C99 6.5.3.2p1
7996     // We have an lvalue with a decl. Make sure the decl is not declared
7997     // with the register storage-class specifier.
7998     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
7999       // in C++ it is not error to take address of a register
8000       // variable (c++03 7.1.1P3)
8001       if (vd->getStorageClass() == SC_Register &&
8002           !S.getLangOpts().CPlusPlus) {
8003         AddressOfError = AO_Register_Variable;
8004       }
8005     } else if (isa<FunctionTemplateDecl>(dcl)) {
8006       return S.Context.OverloadTy;
8007     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8008       // Okay: we can take the address of a field.
8009       // Could be a pointer to member, though, if there is an explicit
8010       // scope qualifier for the class.
8011       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8012         DeclContext *Ctx = dcl->getDeclContext();
8013         if (Ctx && Ctx->isRecord()) {
8014           if (dcl->getType()->isReferenceType()) {
8015             S.Diag(OpLoc,
8016                    diag::err_cannot_form_pointer_to_member_of_reference_type)
8017               << dcl->getDeclName() << dcl->getType();
8018             return QualType();
8019           }
8020 
8021           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8022             Ctx = Ctx->getParent();
8023           return S.Context.getMemberPointerType(op->getType(),
8024                 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8025         }
8026       }
8027     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
8028       llvm_unreachable("Unknown/unexpected decl type");
8029   }
8030 
8031   if (AddressOfError != AO_No_Error) {
8032     diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8033     return QualType();
8034   }
8035 
8036   if (lval == Expr::LV_IncompleteVoidType) {
8037     // Taking the address of a void variable is technically illegal, but we
8038     // allow it in cases which are otherwise valid.
8039     // Example: "extern void x; void* y = &x;".
8040     S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
8041   }
8042 
8043   // If the operand has type "type", the result has type "pointer to type".
8044   if (op->getType()->isObjCObjectType())
8045     return S.Context.getObjCObjectPointerType(op->getType());
8046   return S.Context.getPointerType(op->getType());
8047 }
8048 
8049 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
8050 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8051                                         SourceLocation OpLoc) {
8052   if (Op->isTypeDependent())
8053     return S.Context.DependentTy;
8054 
8055   ExprResult ConvResult = S.UsualUnaryConversions(Op);
8056   if (ConvResult.isInvalid())
8057     return QualType();
8058   Op = ConvResult.take();
8059   QualType OpTy = Op->getType();
8060   QualType Result;
8061 
8062   if (isa<CXXReinterpretCastExpr>(Op)) {
8063     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8064     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8065                                      Op->getSourceRange());
8066   }
8067 
8068   // Note that per both C89 and C99, indirection is always legal, even if OpTy
8069   // is an incomplete type or void.  It would be possible to warn about
8070   // dereferencing a void pointer, but it's completely well-defined, and such a
8071   // warning is unlikely to catch any mistakes.
8072   if (const PointerType *PT = OpTy->getAs<PointerType>())
8073     Result = PT->getPointeeType();
8074   else if (const ObjCObjectPointerType *OPT =
8075              OpTy->getAs<ObjCObjectPointerType>())
8076     Result = OPT->getPointeeType();
8077   else {
8078     ExprResult PR = S.CheckPlaceholderExpr(Op);
8079     if (PR.isInvalid()) return QualType();
8080     if (PR.take() != Op)
8081       return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
8082   }
8083 
8084   if (Result.isNull()) {
8085     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
8086       << OpTy << Op->getSourceRange();
8087     return QualType();
8088   }
8089 
8090   // Dereferences are usually l-values...
8091   VK = VK_LValue;
8092 
8093   // ...except that certain expressions are never l-values in C.
8094   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
8095     VK = VK_RValue;
8096 
8097   return Result;
8098 }
8099 
8100 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
8101   tok::TokenKind Kind) {
8102   BinaryOperatorKind Opc;
8103   switch (Kind) {
8104   default: llvm_unreachable("Unknown binop!");
8105   case tok::periodstar:           Opc = BO_PtrMemD; break;
8106   case tok::arrowstar:            Opc = BO_PtrMemI; break;
8107   case tok::star:                 Opc = BO_Mul; break;
8108   case tok::slash:                Opc = BO_Div; break;
8109   case tok::percent:              Opc = BO_Rem; break;
8110   case tok::plus:                 Opc = BO_Add; break;
8111   case tok::minus:                Opc = BO_Sub; break;
8112   case tok::lessless:             Opc = BO_Shl; break;
8113   case tok::greatergreater:       Opc = BO_Shr; break;
8114   case tok::lessequal:            Opc = BO_LE; break;
8115   case tok::less:                 Opc = BO_LT; break;
8116   case tok::greaterequal:         Opc = BO_GE; break;
8117   case tok::greater:              Opc = BO_GT; break;
8118   case tok::exclaimequal:         Opc = BO_NE; break;
8119   case tok::equalequal:           Opc = BO_EQ; break;
8120   case tok::amp:                  Opc = BO_And; break;
8121   case tok::caret:                Opc = BO_Xor; break;
8122   case tok::pipe:                 Opc = BO_Or; break;
8123   case tok::ampamp:               Opc = BO_LAnd; break;
8124   case tok::pipepipe:             Opc = BO_LOr; break;
8125   case tok::equal:                Opc = BO_Assign; break;
8126   case tok::starequal:            Opc = BO_MulAssign; break;
8127   case tok::slashequal:           Opc = BO_DivAssign; break;
8128   case tok::percentequal:         Opc = BO_RemAssign; break;
8129   case tok::plusequal:            Opc = BO_AddAssign; break;
8130   case tok::minusequal:           Opc = BO_SubAssign; break;
8131   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
8132   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
8133   case tok::ampequal:             Opc = BO_AndAssign; break;
8134   case tok::caretequal:           Opc = BO_XorAssign; break;
8135   case tok::pipeequal:            Opc = BO_OrAssign; break;
8136   case tok::comma:                Opc = BO_Comma; break;
8137   }
8138   return Opc;
8139 }
8140 
8141 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
8142   tok::TokenKind Kind) {
8143   UnaryOperatorKind Opc;
8144   switch (Kind) {
8145   default: llvm_unreachable("Unknown unary op!");
8146   case tok::plusplus:     Opc = UO_PreInc; break;
8147   case tok::minusminus:   Opc = UO_PreDec; break;
8148   case tok::amp:          Opc = UO_AddrOf; break;
8149   case tok::star:         Opc = UO_Deref; break;
8150   case tok::plus:         Opc = UO_Plus; break;
8151   case tok::minus:        Opc = UO_Minus; break;
8152   case tok::tilde:        Opc = UO_Not; break;
8153   case tok::exclaim:      Opc = UO_LNot; break;
8154   case tok::kw___real:    Opc = UO_Real; break;
8155   case tok::kw___imag:    Opc = UO_Imag; break;
8156   case tok::kw___extension__: Opc = UO_Extension; break;
8157   }
8158   return Opc;
8159 }
8160 
8161 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8162 /// This warning is only emitted for builtin assignment operations. It is also
8163 /// suppressed in the event of macro expansions.
8164 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
8165                                    SourceLocation OpLoc) {
8166   if (!S.ActiveTemplateInstantiations.empty())
8167     return;
8168   if (OpLoc.isInvalid() || OpLoc.isMacroID())
8169     return;
8170   LHSExpr = LHSExpr->IgnoreParenImpCasts();
8171   RHSExpr = RHSExpr->IgnoreParenImpCasts();
8172   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8173   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8174   if (!LHSDeclRef || !RHSDeclRef ||
8175       LHSDeclRef->getLocation().isMacroID() ||
8176       RHSDeclRef->getLocation().isMacroID())
8177     return;
8178   const ValueDecl *LHSDecl =
8179     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8180   const ValueDecl *RHSDecl =
8181     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8182   if (LHSDecl != RHSDecl)
8183     return;
8184   if (LHSDecl->getType().isVolatileQualified())
8185     return;
8186   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
8187     if (RefTy->getPointeeType().isVolatileQualified())
8188       return;
8189 
8190   S.Diag(OpLoc, diag::warn_self_assignment)
8191       << LHSDeclRef->getType()
8192       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8193 }
8194 
8195 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
8196 /// operator @p Opc at location @c TokLoc. This routine only supports
8197 /// built-in operations; ActOnBinOp handles overloaded operators.
8198 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
8199                                     BinaryOperatorKind Opc,
8200                                     Expr *LHSExpr, Expr *RHSExpr) {
8201   if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
8202     // The syntax only allows initializer lists on the RHS of assignment,
8203     // so we don't need to worry about accepting invalid code for
8204     // non-assignment operators.
8205     // C++11 5.17p9:
8206     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8207     //   of x = {} is x = T().
8208     InitializationKind Kind =
8209         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8210     InitializedEntity Entity =
8211         InitializedEntity::InitializeTemporary(LHSExpr->getType());
8212     InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
8213     ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
8214                                       MultiExprArg(&RHSExpr, 1));
8215     if (Init.isInvalid())
8216       return Init;
8217     RHSExpr = Init.take();
8218   }
8219 
8220   ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
8221   QualType ResultTy;     // Result type of the binary operator.
8222   // The following two variables are used for compound assignment operators
8223   QualType CompLHSTy;    // Type of LHS after promotions for computation
8224   QualType CompResultTy; // Type of computation result
8225   ExprValueKind VK = VK_RValue;
8226   ExprObjectKind OK = OK_Ordinary;
8227 
8228   switch (Opc) {
8229   case BO_Assign:
8230     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
8231     if (getLangOpts().CPlusPlus &&
8232         LHS.get()->getObjectKind() != OK_ObjCProperty) {
8233       VK = LHS.get()->getValueKind();
8234       OK = LHS.get()->getObjectKind();
8235     }
8236     if (!ResultTy.isNull())
8237       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
8238     break;
8239   case BO_PtrMemD:
8240   case BO_PtrMemI:
8241     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
8242                                             Opc == BO_PtrMemI);
8243     break;
8244   case BO_Mul:
8245   case BO_Div:
8246     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
8247                                            Opc == BO_Div);
8248     break;
8249   case BO_Rem:
8250     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
8251     break;
8252   case BO_Add:
8253     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
8254     break;
8255   case BO_Sub:
8256     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
8257     break;
8258   case BO_Shl:
8259   case BO_Shr:
8260     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
8261     break;
8262   case BO_LE:
8263   case BO_LT:
8264   case BO_GE:
8265   case BO_GT:
8266     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
8267     break;
8268   case BO_EQ:
8269   case BO_NE:
8270     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
8271     break;
8272   case BO_And:
8273   case BO_Xor:
8274   case BO_Or:
8275     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
8276     break;
8277   case BO_LAnd:
8278   case BO_LOr:
8279     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
8280     break;
8281   case BO_MulAssign:
8282   case BO_DivAssign:
8283     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
8284                                                Opc == BO_DivAssign);
8285     CompLHSTy = CompResultTy;
8286     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8287       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8288     break;
8289   case BO_RemAssign:
8290     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
8291     CompLHSTy = CompResultTy;
8292     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8293       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8294     break;
8295   case BO_AddAssign:
8296     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
8297     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8298       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8299     break;
8300   case BO_SubAssign:
8301     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8302     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8303       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8304     break;
8305   case BO_ShlAssign:
8306   case BO_ShrAssign:
8307     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
8308     CompLHSTy = CompResultTy;
8309     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8310       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8311     break;
8312   case BO_AndAssign:
8313   case BO_XorAssign:
8314   case BO_OrAssign:
8315     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
8316     CompLHSTy = CompResultTy;
8317     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8318       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8319     break;
8320   case BO_Comma:
8321     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
8322     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
8323       VK = RHS.get()->getValueKind();
8324       OK = RHS.get()->getObjectKind();
8325     }
8326     break;
8327   }
8328   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
8329     return ExprError();
8330 
8331   // Check for array bounds violations for both sides of the BinaryOperator
8332   CheckArrayAccess(LHS.get());
8333   CheckArrayAccess(RHS.get());
8334 
8335   if (CompResultTy.isNull())
8336     return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
8337                                               ResultTy, VK, OK, OpLoc));
8338   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
8339       OK_ObjCProperty) {
8340     VK = VK_LValue;
8341     OK = LHS.get()->getObjectKind();
8342   }
8343   return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
8344                                                     ResultTy, VK, OK, CompLHSTy,
8345                                                     CompResultTy, OpLoc));
8346 }
8347 
8348 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8349 /// operators are mixed in a way that suggests that the programmer forgot that
8350 /// comparison operators have higher precedence. The most typical example of
8351 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
8352 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
8353                                       SourceLocation OpLoc, Expr *LHSExpr,
8354                                       Expr *RHSExpr) {
8355   typedef BinaryOperator BinOp;
8356   BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8357                 RHSopc = static_cast<BinOp::Opcode>(-1);
8358   if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8359     LHSopc = BO->getOpcode();
8360   if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8361     RHSopc = BO->getOpcode();
8362 
8363   // Subs are not binary operators.
8364   if (LHSopc == -1 && RHSopc == -1)
8365     return;
8366 
8367   // Bitwise operations are sometimes used as eager logical ops.
8368   // Don't diagnose this.
8369   if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8370       (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
8371     return;
8372 
8373   bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8374   bool isRightComp = BinOp::isComparisonOp(RHSopc);
8375   if (!isLeftComp && !isRightComp) return;
8376 
8377   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8378                                                    OpLoc)
8379                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
8380   std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8381                                  : BinOp::getOpcodeStr(RHSopc);
8382   SourceRange ParensRange = isLeftComp ?
8383       SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8384                   RHSExpr->getLocEnd())
8385     : SourceRange(LHSExpr->getLocStart(),
8386                   cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
8387 
8388   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8389     << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8390   SuggestParentheses(Self, OpLoc,
8391     Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
8392     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
8393   SuggestParentheses(Self, OpLoc,
8394     Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8395     ParensRange);
8396 }
8397 
8398 /// \brief It accepts a '&' expr that is inside a '|' one.
8399 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8400 /// in parentheses.
8401 static void
8402 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8403                                        BinaryOperator *Bop) {
8404   assert(Bop->getOpcode() == BO_And);
8405   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8406       << Bop->getSourceRange() << OpLoc;
8407   SuggestParentheses(Self, Bop->getOperatorLoc(),
8408     Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8409     Bop->getSourceRange());
8410 }
8411 
8412 /// \brief It accepts a '&&' expr that is inside a '||' one.
8413 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8414 /// in parentheses.
8415 static void
8416 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8417                                        BinaryOperator *Bop) {
8418   assert(Bop->getOpcode() == BO_LAnd);
8419   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8420       << Bop->getSourceRange() << OpLoc;
8421   SuggestParentheses(Self, Bop->getOperatorLoc(),
8422     Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8423     Bop->getSourceRange());
8424 }
8425 
8426 /// \brief Returns true if the given expression can be evaluated as a constant
8427 /// 'true'.
8428 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8429   bool Res;
8430   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8431 }
8432 
8433 /// \brief Returns true if the given expression can be evaluated as a constant
8434 /// 'false'.
8435 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8436   bool Res;
8437   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8438 }
8439 
8440 /// \brief Look for '&&' in the left hand of a '||' expr.
8441 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
8442                                              Expr *LHSExpr, Expr *RHSExpr) {
8443   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
8444     if (Bop->getOpcode() == BO_LAnd) {
8445       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8446       if (EvaluatesAsFalse(S, RHSExpr))
8447         return;
8448       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8449       if (!EvaluatesAsTrue(S, Bop->getLHS()))
8450         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8451     } else if (Bop->getOpcode() == BO_LOr) {
8452       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8453         // If it's "a || b && 1 || c" we didn't warn earlier for
8454         // "a || b && 1", but warn now.
8455         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8456           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8457       }
8458     }
8459   }
8460 }
8461 
8462 /// \brief Look for '&&' in the right hand of a '||' expr.
8463 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
8464                                              Expr *LHSExpr, Expr *RHSExpr) {
8465   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
8466     if (Bop->getOpcode() == BO_LAnd) {
8467       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8468       if (EvaluatesAsFalse(S, LHSExpr))
8469         return;
8470       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8471       if (!EvaluatesAsTrue(S, Bop->getRHS()))
8472         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8473     }
8474   }
8475 }
8476 
8477 /// \brief Look for '&' in the left or right hand of a '|' expr.
8478 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8479                                              Expr *OrArg) {
8480   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8481     if (Bop->getOpcode() == BO_And)
8482       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8483   }
8484 }
8485 
8486 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
8487 /// precedence.
8488 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
8489                                     SourceLocation OpLoc, Expr *LHSExpr,
8490                                     Expr *RHSExpr){
8491   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
8492   if (BinaryOperator::isBitwiseOp(Opc))
8493     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
8494 
8495   // Diagnose "arg1 & arg2 | arg3"
8496   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8497     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8498     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
8499   }
8500 
8501   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8502   // We don't warn for 'assert(a || b && "bad")' since this is safe.
8503   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8504     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8505     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
8506   }
8507 }
8508 
8509 // Binary Operators.  'Tok' is the token for the operator.
8510 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
8511                             tok::TokenKind Kind,
8512                             Expr *LHSExpr, Expr *RHSExpr) {
8513   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
8514   assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8515   assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
8516 
8517   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8518   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
8519 
8520   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
8521 }
8522 
8523 /// Build an overloaded binary operator expression in the given scope.
8524 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8525                                        BinaryOperatorKind Opc,
8526                                        Expr *LHS, Expr *RHS) {
8527   // Find all of the overloaded operators visible from this
8528   // point. We perform both an operator-name lookup from the local
8529   // scope and an argument-dependent lookup based on the types of
8530   // the arguments.
8531   UnresolvedSet<16> Functions;
8532   OverloadedOperatorKind OverOp
8533     = BinaryOperator::getOverloadedOperator(Opc);
8534   if (Sc && OverOp != OO_None)
8535     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8536                                    RHS->getType(), Functions);
8537 
8538   // Build the (potentially-overloaded, potentially-dependent)
8539   // binary operation.
8540   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8541 }
8542 
8543 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
8544                             BinaryOperatorKind Opc,
8545                             Expr *LHSExpr, Expr *RHSExpr) {
8546   // We want to end up calling one of checkPseudoObjectAssignment
8547   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8548   // both expressions are overloadable or either is type-dependent),
8549   // or CreateBuiltinBinOp (in any other case).  We also want to get
8550   // any placeholder types out of the way.
8551 
8552   // Handle pseudo-objects in the LHS.
8553   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8554     // Assignments with a pseudo-object l-value need special analysis.
8555     if (pty->getKind() == BuiltinType::PseudoObject &&
8556         BinaryOperator::isAssignmentOp(Opc))
8557       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8558 
8559     // Don't resolve overloads if the other type is overloadable.
8560     if (pty->getKind() == BuiltinType::Overload) {
8561       // We can't actually test that if we still have a placeholder,
8562       // though.  Fortunately, none of the exceptions we see in that
8563       // code below are valid when the LHS is an overload set.  Note
8564       // that an overload set can be dependently-typed, but it never
8565       // instantiates to having an overloadable type.
8566       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8567       if (resolvedRHS.isInvalid()) return ExprError();
8568       RHSExpr = resolvedRHS.take();
8569 
8570       if (RHSExpr->isTypeDependent() ||
8571           RHSExpr->getType()->isOverloadableType())
8572         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8573     }
8574 
8575     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8576     if (LHS.isInvalid()) return ExprError();
8577     LHSExpr = LHS.take();
8578   }
8579 
8580   // Handle pseudo-objects in the RHS.
8581   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8582     // An overload in the RHS can potentially be resolved by the type
8583     // being assigned to.
8584     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8585       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8586         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8587 
8588       if (LHSExpr->getType()->isOverloadableType())
8589         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8590 
8591       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8592     }
8593 
8594     // Don't resolve overloads if the other type is overloadable.
8595     if (pty->getKind() == BuiltinType::Overload &&
8596         LHSExpr->getType()->isOverloadableType())
8597       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8598 
8599     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8600     if (!resolvedRHS.isUsable()) return ExprError();
8601     RHSExpr = resolvedRHS.take();
8602   }
8603 
8604   if (getLangOpts().CPlusPlus) {
8605     // If either expression is type-dependent, always build an
8606     // overloaded op.
8607     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8608       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8609 
8610     // Otherwise, build an overloaded op if either expression has an
8611     // overloadable type.
8612     if (LHSExpr->getType()->isOverloadableType() ||
8613         RHSExpr->getType()->isOverloadableType())
8614       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8615   }
8616 
8617   // Build a built-in binary operation.
8618   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8619 }
8620 
8621 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
8622                                       UnaryOperatorKind Opc,
8623                                       Expr *InputExpr) {
8624   ExprResult Input = Owned(InputExpr);
8625   ExprValueKind VK = VK_RValue;
8626   ExprObjectKind OK = OK_Ordinary;
8627   QualType resultType;
8628   switch (Opc) {
8629   case UO_PreInc:
8630   case UO_PreDec:
8631   case UO_PostInc:
8632   case UO_PostDec:
8633     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
8634                                                 Opc == UO_PreInc ||
8635                                                 Opc == UO_PostInc,
8636                                                 Opc == UO_PreInc ||
8637                                                 Opc == UO_PreDec);
8638     break;
8639   case UO_AddrOf:
8640     resultType = CheckAddressOfOperand(*this, Input, OpLoc);
8641     break;
8642   case UO_Deref: {
8643     Input = DefaultFunctionArrayLvalueConversion(Input.take());
8644     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
8645     break;
8646   }
8647   case UO_Plus:
8648   case UO_Minus:
8649     Input = UsualUnaryConversions(Input.take());
8650     if (Input.isInvalid()) return ExprError();
8651     resultType = Input.get()->getType();
8652     if (resultType->isDependentType())
8653       break;
8654     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8655         resultType->isVectorType())
8656       break;
8657     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
8658              resultType->isEnumeralType())
8659       break;
8660     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
8661              Opc == UO_Plus &&
8662              resultType->isPointerType())
8663       break;
8664 
8665     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8666       << resultType << Input.get()->getSourceRange());
8667 
8668   case UO_Not: // bitwise complement
8669     Input = UsualUnaryConversions(Input.take());
8670     if (Input.isInvalid()) return ExprError();
8671     resultType = Input.get()->getType();
8672     if (resultType->isDependentType())
8673       break;
8674     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8675     if (resultType->isComplexType() || resultType->isComplexIntegerType())
8676       // C99 does not support '~' for complex conjugation.
8677       Diag(OpLoc, diag::ext_integer_complement_complex)
8678         << resultType << Input.get()->getSourceRange();
8679     else if (resultType->hasIntegerRepresentation())
8680       break;
8681     else {
8682       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8683         << resultType << Input.get()->getSourceRange());
8684     }
8685     break;
8686 
8687   case UO_LNot: // logical negation
8688     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
8689     Input = DefaultFunctionArrayLvalueConversion(Input.take());
8690     if (Input.isInvalid()) return ExprError();
8691     resultType = Input.get()->getType();
8692 
8693     // Though we still have to promote half FP to float...
8694     if (resultType->isHalfType()) {
8695       Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8696       resultType = Context.FloatTy;
8697     }
8698 
8699     if (resultType->isDependentType())
8700       break;
8701     if (resultType->isScalarType()) {
8702       // C99 6.5.3.3p1: ok, fallthrough;
8703       if (Context.getLangOpts().CPlusPlus) {
8704         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8705         // operand contextually converted to bool.
8706         Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8707                                   ScalarTypeToBooleanCastKind(resultType));
8708       }
8709     } else if (resultType->isExtVectorType()) {
8710       // Vector logical not returns the signed variant of the operand type.
8711       resultType = GetSignedVectorType(resultType);
8712       break;
8713     } else {
8714       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8715         << resultType << Input.get()->getSourceRange());
8716     }
8717 
8718     // LNot always has type int. C99 6.5.3.3p5.
8719     // In C++, it's bool. C++ 5.3.1p8
8720     resultType = Context.getLogicalOperationType();
8721     break;
8722   case UO_Real:
8723   case UO_Imag:
8724     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
8725     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8726     // complex l-values to ordinary l-values and all other values to r-values.
8727     if (Input.isInvalid()) return ExprError();
8728     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8729       if (Input.get()->getValueKind() != VK_RValue &&
8730           Input.get()->getObjectKind() == OK_Ordinary)
8731         VK = Input.get()->getValueKind();
8732     } else if (!getLangOpts().CPlusPlus) {
8733       // In C, a volatile scalar is read by __imag. In C++, it is not.
8734       Input = DefaultLvalueConversion(Input.take());
8735     }
8736     break;
8737   case UO_Extension:
8738     resultType = Input.get()->getType();
8739     VK = Input.get()->getValueKind();
8740     OK = Input.get()->getObjectKind();
8741     break;
8742   }
8743   if (resultType.isNull() || Input.isInvalid())
8744     return ExprError();
8745 
8746   // Check for array bounds violations in the operand of the UnaryOperator,
8747   // except for the '*' and '&' operators that have to be handled specially
8748   // by CheckArrayAccess (as there are special cases like &array[arraysize]
8749   // that are explicitly defined as valid by the standard).
8750   if (Opc != UO_AddrOf && Opc != UO_Deref)
8751     CheckArrayAccess(Input.get());
8752 
8753   return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
8754                                            VK, OK, OpLoc));
8755 }
8756 
8757 /// \brief Determine whether the given expression is a qualified member
8758 /// access expression, of a form that could be turned into a pointer to member
8759 /// with the address-of operator.
8760 static bool isQualifiedMemberAccess(Expr *E) {
8761   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8762     if (!DRE->getQualifier())
8763       return false;
8764 
8765     ValueDecl *VD = DRE->getDecl();
8766     if (!VD->isCXXClassMember())
8767       return false;
8768 
8769     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8770       return true;
8771     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8772       return Method->isInstance();
8773 
8774     return false;
8775   }
8776 
8777   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8778     if (!ULE->getQualifier())
8779       return false;
8780 
8781     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8782                                            DEnd = ULE->decls_end();
8783          D != DEnd; ++D) {
8784       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8785         if (Method->isInstance())
8786           return true;
8787       } else {
8788         // Overload set does not contain methods.
8789         break;
8790       }
8791     }
8792 
8793     return false;
8794   }
8795 
8796   return false;
8797 }
8798 
8799 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
8800                               UnaryOperatorKind Opc, Expr *Input) {
8801   // First things first: handle placeholders so that the
8802   // overloaded-operator check considers the right type.
8803   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8804     // Increment and decrement of pseudo-object references.
8805     if (pty->getKind() == BuiltinType::PseudoObject &&
8806         UnaryOperator::isIncrementDecrementOp(Opc))
8807       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8808 
8809     // extension is always a builtin operator.
8810     if (Opc == UO_Extension)
8811       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8812 
8813     // & gets special logic for several kinds of placeholder.
8814     // The builtin code knows what to do.
8815     if (Opc == UO_AddrOf &&
8816         (pty->getKind() == BuiltinType::Overload ||
8817          pty->getKind() == BuiltinType::UnknownAny ||
8818          pty->getKind() == BuiltinType::BoundMember))
8819       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8820 
8821     // Anything else needs to be handled now.
8822     ExprResult Result = CheckPlaceholderExpr(Input);
8823     if (Result.isInvalid()) return ExprError();
8824     Input = Result.take();
8825   }
8826 
8827   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
8828       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8829       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
8830     // Find all of the overloaded operators visible from this
8831     // point. We perform both an operator-name lookup from the local
8832     // scope and an argument-dependent lookup based on the types of
8833     // the arguments.
8834     UnresolvedSet<16> Functions;
8835     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
8836     if (S && OverOp != OO_None)
8837       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8838                                    Functions);
8839 
8840     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
8841   }
8842 
8843   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8844 }
8845 
8846 // Unary Operators.  'Tok' is the token for the operator.
8847 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
8848                               tok::TokenKind Op, Expr *Input) {
8849   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
8850 }
8851 
8852 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
8853 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
8854                                 LabelDecl *TheDecl) {
8855   TheDecl->setUsed();
8856   // Create the AST node.  The address of a label always has type 'void*'.
8857   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
8858                                        Context.getPointerType(Context.VoidTy)));
8859 }
8860 
8861 /// Given the last statement in a statement-expression, check whether
8862 /// the result is a producing expression (like a call to an
8863 /// ns_returns_retained function) and, if so, rebuild it to hoist the
8864 /// release out of the full-expression.  Otherwise, return null.
8865 /// Cannot fail.
8866 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
8867   // Should always be wrapped with one of these.
8868   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
8869   if (!cleanups) return 0;
8870 
8871   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
8872   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
8873     return 0;
8874 
8875   // Splice out the cast.  This shouldn't modify any interesting
8876   // features of the statement.
8877   Expr *producer = cast->getSubExpr();
8878   assert(producer->getType() == cast->getType());
8879   assert(producer->getValueKind() == cast->getValueKind());
8880   cleanups->setSubExpr(producer);
8881   return cleanups;
8882 }
8883 
8884 void Sema::ActOnStartStmtExpr() {
8885   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8886 }
8887 
8888 void Sema::ActOnStmtExprError() {
8889   // Note that function is also called by TreeTransform when leaving a
8890   // StmtExpr scope without rebuilding anything.
8891 
8892   DiscardCleanupsInEvaluationContext();
8893   PopExpressionEvaluationContext();
8894 }
8895 
8896 ExprResult
8897 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
8898                     SourceLocation RPLoc) { // "({..})"
8899   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8900   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8901 
8902   if (hasAnyUnrecoverableErrorsInThisFunction())
8903     DiscardCleanupsInEvaluationContext();
8904   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8905   PopExpressionEvaluationContext();
8906 
8907   bool isFileScope
8908     = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
8909   if (isFileScope)
8910     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
8911 
8912   // FIXME: there are a variety of strange constraints to enforce here, for
8913   // example, it is not possible to goto into a stmt expression apparently.
8914   // More semantic analysis is needed.
8915 
8916   // If there are sub stmts in the compound stmt, take the type of the last one
8917   // as the type of the stmtexpr.
8918   QualType Ty = Context.VoidTy;
8919   bool StmtExprMayBindToTemp = false;
8920   if (!Compound->body_empty()) {
8921     Stmt *LastStmt = Compound->body_back();
8922     LabelStmt *LastLabelStmt = 0;
8923     // If LastStmt is a label, skip down through into the body.
8924     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8925       LastLabelStmt = Label;
8926       LastStmt = Label->getSubStmt();
8927     }
8928 
8929     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
8930       // Do function/array conversion on the last expression, but not
8931       // lvalue-to-rvalue.  However, initialize an unqualified type.
8932       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8933       if (LastExpr.isInvalid())
8934         return ExprError();
8935       Ty = LastExpr.get()->getType().getUnqualifiedType();
8936 
8937       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
8938         // In ARC, if the final expression ends in a consume, splice
8939         // the consume out and bind it later.  In the alternate case
8940         // (when dealing with a retainable type), the result
8941         // initialization will create a produce.  In both cases the
8942         // result will be +1, and we'll need to balance that out with
8943         // a bind.
8944         if (Expr *rebuiltLastStmt
8945               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8946           LastExpr = rebuiltLastStmt;
8947         } else {
8948           LastExpr = PerformCopyInitialization(
8949                             InitializedEntity::InitializeResult(LPLoc,
8950                                                                 Ty,
8951                                                                 false),
8952                                                    SourceLocation(),
8953                                                LastExpr);
8954         }
8955 
8956         if (LastExpr.isInvalid())
8957           return ExprError();
8958         if (LastExpr.get() != 0) {
8959           if (!LastLabelStmt)
8960             Compound->setLastStmt(LastExpr.take());
8961           else
8962             LastLabelStmt->setSubStmt(LastExpr.take());
8963           StmtExprMayBindToTemp = true;
8964         }
8965       }
8966     }
8967   }
8968 
8969   // FIXME: Check that expression type is complete/non-abstract; statement
8970   // expressions are not lvalues.
8971   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8972   if (StmtExprMayBindToTemp)
8973     return MaybeBindToTemporary(ResStmtExpr);
8974   return Owned(ResStmtExpr);
8975 }
8976 
8977 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
8978                                       TypeSourceInfo *TInfo,
8979                                       OffsetOfComponent *CompPtr,
8980                                       unsigned NumComponents,
8981                                       SourceLocation RParenLoc) {
8982   QualType ArgTy = TInfo->getType();
8983   bool Dependent = ArgTy->isDependentType();
8984   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
8985 
8986   // We must have at least one component that refers to the type, and the first
8987   // one is known to be a field designator.  Verify that the ArgTy represents
8988   // a struct/union/class.
8989   if (!Dependent && !ArgTy->isRecordType())
8990     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8991                        << ArgTy << TypeRange);
8992 
8993   // Type must be complete per C99 7.17p3 because a declaring a variable
8994   // with an incomplete type would be ill-formed.
8995   if (!Dependent
8996       && RequireCompleteType(BuiltinLoc, ArgTy,
8997                              diag::err_offsetof_incomplete_type, TypeRange))
8998     return ExprError();
8999 
9000   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9001   // GCC extension, diagnose them.
9002   // FIXME: This diagnostic isn't actually visible because the location is in
9003   // a system header!
9004   if (NumComponents != 1)
9005     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9006       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
9007 
9008   bool DidWarnAboutNonPOD = false;
9009   QualType CurrentType = ArgTy;
9010   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9011   SmallVector<OffsetOfNode, 4> Comps;
9012   SmallVector<Expr*, 4> Exprs;
9013   for (unsigned i = 0; i != NumComponents; ++i) {
9014     const OffsetOfComponent &OC = CompPtr[i];
9015     if (OC.isBrackets) {
9016       // Offset of an array sub-field.  TODO: Should we allow vector elements?
9017       if (!CurrentType->isDependentType()) {
9018         const ArrayType *AT = Context.getAsArrayType(CurrentType);
9019         if(!AT)
9020           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9021                            << CurrentType);
9022         CurrentType = AT->getElementType();
9023       } else
9024         CurrentType = Context.DependentTy;
9025 
9026       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9027       if (IdxRval.isInvalid())
9028         return ExprError();
9029       Expr *Idx = IdxRval.take();
9030 
9031       // The expression must be an integral expression.
9032       // FIXME: An integral constant expression?
9033       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9034           !Idx->getType()->isIntegerType())
9035         return ExprError(Diag(Idx->getLocStart(),
9036                               diag::err_typecheck_subscript_not_integer)
9037                          << Idx->getSourceRange());
9038 
9039       // Record this array index.
9040       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9041       Exprs.push_back(Idx);
9042       continue;
9043     }
9044 
9045     // Offset of a field.
9046     if (CurrentType->isDependentType()) {
9047       // We have the offset of a field, but we can't look into the dependent
9048       // type. Just record the identifier of the field.
9049       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9050       CurrentType = Context.DependentTy;
9051       continue;
9052     }
9053 
9054     // We need to have a complete type to look into.
9055     if (RequireCompleteType(OC.LocStart, CurrentType,
9056                             diag::err_offsetof_incomplete_type))
9057       return ExprError();
9058 
9059     // Look for the designated field.
9060     const RecordType *RC = CurrentType->getAs<RecordType>();
9061     if (!RC)
9062       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9063                        << CurrentType);
9064     RecordDecl *RD = RC->getDecl();
9065 
9066     // C++ [lib.support.types]p5:
9067     //   The macro offsetof accepts a restricted set of type arguments in this
9068     //   International Standard. type shall be a POD structure or a POD union
9069     //   (clause 9).
9070     // C++11 [support.types]p4:
9071     //   If type is not a standard-layout class (Clause 9), the results are
9072     //   undefined.
9073     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9074       bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9075       unsigned DiagID =
9076         LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9077                             : diag::warn_offsetof_non_pod_type;
9078 
9079       if (!IsSafe && !DidWarnAboutNonPOD &&
9080           DiagRuntimeBehavior(BuiltinLoc, 0,
9081                               PDiag(DiagID)
9082                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9083                               << CurrentType))
9084         DidWarnAboutNonPOD = true;
9085     }
9086 
9087     // Look for the field.
9088     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9089     LookupQualifiedName(R, RD);
9090     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
9091     IndirectFieldDecl *IndirectMemberDecl = 0;
9092     if (!MemberDecl) {
9093       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
9094         MemberDecl = IndirectMemberDecl->getAnonField();
9095     }
9096 
9097     if (!MemberDecl)
9098       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9099                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9100                                                               OC.LocEnd));
9101 
9102     // C99 7.17p3:
9103     //   (If the specified member is a bit-field, the behavior is undefined.)
9104     //
9105     // We diagnose this as an error.
9106     if (MemberDecl->isBitField()) {
9107       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9108         << MemberDecl->getDeclName()
9109         << SourceRange(BuiltinLoc, RParenLoc);
9110       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9111       return ExprError();
9112     }
9113 
9114     RecordDecl *Parent = MemberDecl->getParent();
9115     if (IndirectMemberDecl)
9116       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
9117 
9118     // If the member was found in a base class, introduce OffsetOfNodes for
9119     // the base class indirections.
9120     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9121                        /*DetectVirtual=*/false);
9122     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
9123       CXXBasePath &Path = Paths.front();
9124       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9125            B != BEnd; ++B)
9126         Comps.push_back(OffsetOfNode(B->Base));
9127     }
9128 
9129     if (IndirectMemberDecl) {
9130       for (IndirectFieldDecl::chain_iterator FI =
9131            IndirectMemberDecl->chain_begin(),
9132            FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9133         assert(isa<FieldDecl>(*FI));
9134         Comps.push_back(OffsetOfNode(OC.LocStart,
9135                                      cast<FieldDecl>(*FI), OC.LocEnd));
9136       }
9137     } else
9138       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
9139 
9140     CurrentType = MemberDecl->getType().getNonReferenceType();
9141   }
9142 
9143   return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9144                                     TInfo, Comps.data(), Comps.size(),
9145                                     Exprs.data(), Exprs.size(), RParenLoc));
9146 }
9147 
9148 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
9149                                       SourceLocation BuiltinLoc,
9150                                       SourceLocation TypeLoc,
9151                                       ParsedType ParsedArgTy,
9152                                       OffsetOfComponent *CompPtr,
9153                                       unsigned NumComponents,
9154                                       SourceLocation RParenLoc) {
9155 
9156   TypeSourceInfo *ArgTInfo;
9157   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
9158   if (ArgTy.isNull())
9159     return ExprError();
9160 
9161   if (!ArgTInfo)
9162     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9163 
9164   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9165                               RParenLoc);
9166 }
9167 
9168 
9169 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
9170                                  Expr *CondExpr,
9171                                  Expr *LHSExpr, Expr *RHSExpr,
9172                                  SourceLocation RPLoc) {
9173   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9174 
9175   ExprValueKind VK = VK_RValue;
9176   ExprObjectKind OK = OK_Ordinary;
9177   QualType resType;
9178   bool ValueDependent = false;
9179   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
9180     resType = Context.DependentTy;
9181     ValueDependent = true;
9182   } else {
9183     // The conditional expression is required to be a constant expression.
9184     llvm::APSInt condEval(32);
9185     ExprResult CondICE
9186       = VerifyIntegerConstantExpression(CondExpr, &condEval,
9187           diag::err_typecheck_choose_expr_requires_constant, false);
9188     if (CondICE.isInvalid())
9189       return ExprError();
9190     CondExpr = CondICE.take();
9191 
9192     // If the condition is > zero, then the AST type is the same as the LSHExpr.
9193     Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9194 
9195     resType = ActiveExpr->getType();
9196     ValueDependent = ActiveExpr->isValueDependent();
9197     VK = ActiveExpr->getValueKind();
9198     OK = ActiveExpr->getObjectKind();
9199   }
9200 
9201   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
9202                                         resType, VK, OK, RPLoc,
9203                                         resType->isDependentType(),
9204                                         ValueDependent));
9205 }
9206 
9207 //===----------------------------------------------------------------------===//
9208 // Clang Extensions.
9209 //===----------------------------------------------------------------------===//
9210 
9211 /// ActOnBlockStart - This callback is invoked when a block literal is started.
9212 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
9213   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9214   PushBlockScope(CurScope, Block);
9215   CurContext->addDecl(Block);
9216   if (CurScope)
9217     PushDeclContext(CurScope, Block);
9218   else
9219     CurContext = Block;
9220 
9221   getCurBlock()->HasImplicitReturnType = true;
9222 
9223   // Enter a new evaluation context to insulate the block from any
9224   // cleanups from the enclosing full-expression.
9225   PushExpressionEvaluationContext(PotentiallyEvaluated);
9226 }
9227 
9228 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9229                                Scope *CurScope) {
9230   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
9231   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
9232   BlockScopeInfo *CurBlock = getCurBlock();
9233 
9234   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
9235   QualType T = Sig->getType();
9236 
9237   // FIXME: We should allow unexpanded parameter packs here, but that would,
9238   // in turn, make the block expression contain unexpanded parameter packs.
9239   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9240     // Drop the parameters.
9241     FunctionProtoType::ExtProtoInfo EPI;
9242     EPI.HasTrailingReturn = false;
9243     EPI.TypeQuals |= DeclSpec::TQ_const;
9244     T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9245                                 EPI);
9246     Sig = Context.getTrivialTypeSourceInfo(T);
9247   }
9248 
9249   // GetTypeForDeclarator always produces a function type for a block
9250   // literal signature.  Furthermore, it is always a FunctionProtoType
9251   // unless the function was written with a typedef.
9252   assert(T->isFunctionType() &&
9253          "GetTypeForDeclarator made a non-function block signature");
9254 
9255   // Look for an explicit signature in that function type.
9256   FunctionProtoTypeLoc ExplicitSignature;
9257 
9258   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9259   if (isa<FunctionProtoTypeLoc>(tmp)) {
9260     ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9261 
9262     // Check whether that explicit signature was synthesized by
9263     // GetTypeForDeclarator.  If so, don't save that as part of the
9264     // written signature.
9265     if (ExplicitSignature.getLocalRangeBegin() ==
9266         ExplicitSignature.getLocalRangeEnd()) {
9267       // This would be much cheaper if we stored TypeLocs instead of
9268       // TypeSourceInfos.
9269       TypeLoc Result = ExplicitSignature.getResultLoc();
9270       unsigned Size = Result.getFullDataSize();
9271       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9272       Sig->getTypeLoc().initializeFullCopy(Result, Size);
9273 
9274       ExplicitSignature = FunctionProtoTypeLoc();
9275     }
9276   }
9277 
9278   CurBlock->TheDecl->setSignatureAsWritten(Sig);
9279   CurBlock->FunctionType = T;
9280 
9281   const FunctionType *Fn = T->getAs<FunctionType>();
9282   QualType RetTy = Fn->getResultType();
9283   bool isVariadic =
9284     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9285 
9286   CurBlock->TheDecl->setIsVariadic(isVariadic);
9287 
9288   // Don't allow returning a objc interface by value.
9289   if (RetTy->isObjCObjectType()) {
9290     Diag(ParamInfo.getLocStart(),
9291          diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9292     return;
9293   }
9294 
9295   // Context.DependentTy is used as a placeholder for a missing block
9296   // return type.  TODO:  what should we do with declarators like:
9297   //   ^ * { ... }
9298   // If the answer is "apply template argument deduction"....
9299   if (RetTy != Context.DependentTy) {
9300     CurBlock->ReturnType = RetTy;
9301     CurBlock->TheDecl->setBlockMissingReturnType(false);
9302     CurBlock->HasImplicitReturnType = false;
9303   }
9304 
9305   // Push block parameters from the declarator if we had them.
9306   SmallVector<ParmVarDecl*, 8> Params;
9307   if (ExplicitSignature) {
9308     for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9309       ParmVarDecl *Param = ExplicitSignature.getArg(I);
9310       if (Param->getIdentifier() == 0 &&
9311           !Param->isImplicit() &&
9312           !Param->isInvalidDecl() &&
9313           !getLangOpts().CPlusPlus)
9314         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
9315       Params.push_back(Param);
9316     }
9317 
9318   // Fake up parameter variables if we have a typedef, like
9319   //   ^ fntype { ... }
9320   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9321     for (FunctionProtoType::arg_type_iterator
9322            I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9323       ParmVarDecl *Param =
9324         BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9325                                    ParamInfo.getLocStart(),
9326                                    *I);
9327       Params.push_back(Param);
9328     }
9329   }
9330 
9331   // Set the parameters on the block decl.
9332   if (!Params.empty()) {
9333     CurBlock->TheDecl->setParams(Params);
9334     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9335                              CurBlock->TheDecl->param_end(),
9336                              /*CheckParameterNames=*/false);
9337   }
9338 
9339   // Finally we can process decl attributes.
9340   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
9341 
9342   // Put the parameter variables in scope.  We can bail out immediately
9343   // if we don't have any.
9344   if (Params.empty())
9345     return;
9346 
9347   for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
9348          E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9349     (*AI)->setOwningFunction(CurBlock->TheDecl);
9350 
9351     // If this has an identifier, add it to the scope stack.
9352     if ((*AI)->getIdentifier()) {
9353       CheckShadow(CurBlock->TheScope, *AI);
9354 
9355       PushOnScopeChains(*AI, CurBlock->TheScope);
9356     }
9357   }
9358 }
9359 
9360 /// ActOnBlockError - If there is an error parsing a block, this callback
9361 /// is invoked to pop the information about the block from the action impl.
9362 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
9363   // Leave the expression-evaluation context.
9364   DiscardCleanupsInEvaluationContext();
9365   PopExpressionEvaluationContext();
9366 
9367   // Pop off CurBlock, handle nested blocks.
9368   PopDeclContext();
9369   PopFunctionScopeInfo();
9370 }
9371 
9372 /// ActOnBlockStmtExpr - This is called when the body of a block statement
9373 /// literal was successfully completed.  ^(int x){...}
9374 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
9375                                     Stmt *Body, Scope *CurScope) {
9376   // If blocks are disabled, emit an error.
9377   if (!LangOpts.Blocks)
9378     Diag(CaretLoc, diag::err_blocks_disable);
9379 
9380   // Leave the expression-evaluation context.
9381   if (hasAnyUnrecoverableErrorsInThisFunction())
9382     DiscardCleanupsInEvaluationContext();
9383   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9384   PopExpressionEvaluationContext();
9385 
9386   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
9387 
9388   if (BSI->HasImplicitReturnType)
9389     deduceClosureReturnType(*BSI);
9390 
9391   PopDeclContext();
9392 
9393   QualType RetTy = Context.VoidTy;
9394   if (!BSI->ReturnType.isNull())
9395     RetTy = BSI->ReturnType;
9396 
9397   bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
9398   QualType BlockTy;
9399 
9400   // Set the captured variables on the block.
9401   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9402   SmallVector<BlockDecl::Capture, 4> Captures;
9403   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9404     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9405     if (Cap.isThisCapture())
9406       continue;
9407     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
9408                               Cap.isNested(), Cap.getCopyExpr());
9409     Captures.push_back(NewCap);
9410   }
9411   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9412                             BSI->CXXThisCaptureIndex != 0);
9413 
9414   // If the user wrote a function type in some form, try to use that.
9415   if (!BSI->FunctionType.isNull()) {
9416     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9417 
9418     FunctionType::ExtInfo Ext = FTy->getExtInfo();
9419     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9420 
9421     // Turn protoless block types into nullary block types.
9422     if (isa<FunctionNoProtoType>(FTy)) {
9423       FunctionProtoType::ExtProtoInfo EPI;
9424       EPI.ExtInfo = Ext;
9425       BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
9426 
9427     // Otherwise, if we don't need to change anything about the function type,
9428     // preserve its sugar structure.
9429     } else if (FTy->getResultType() == RetTy &&
9430                (!NoReturn || FTy->getNoReturnAttr())) {
9431       BlockTy = BSI->FunctionType;
9432 
9433     // Otherwise, make the minimal modifications to the function type.
9434     } else {
9435       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
9436       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9437       EPI.TypeQuals = 0; // FIXME: silently?
9438       EPI.ExtInfo = Ext;
9439       BlockTy = Context.getFunctionType(RetTy,
9440                                         FPT->arg_type_begin(),
9441                                         FPT->getNumArgs(),
9442                                         EPI);
9443     }
9444 
9445   // If we don't have a function type, just build one from nothing.
9446   } else {
9447     FunctionProtoType::ExtProtoInfo EPI;
9448     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
9449     BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
9450   }
9451 
9452   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9453                            BSI->TheDecl->param_end());
9454   BlockTy = Context.getBlockPointerType(BlockTy);
9455 
9456   // If needed, diagnose invalid gotos and switches in the block.
9457   if (getCurFunction()->NeedsScopeChecking() &&
9458       !hasAnyUnrecoverableErrorsInThisFunction())
9459     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
9460 
9461   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
9462 
9463   // Try to apply the named return value optimization. We have to check again
9464   // if we can do this, though, because blocks keep return statements around
9465   // to deduce an implicit return type.
9466   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9467       !BSI->TheDecl->isDependentContext())
9468     computeNRVO(Body, getCurBlock());
9469 
9470   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9471   const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9472   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
9473 
9474   // If the block isn't obviously global, i.e. it captures anything at
9475   // all, then we need to do a few things in the surrounding context:
9476   if (Result->getBlockDecl()->hasCaptures()) {
9477     // First, this expression has a new cleanup object.
9478     ExprCleanupObjects.push_back(Result->getBlockDecl());
9479     ExprNeedsCleanups = true;
9480 
9481     // It also gets a branch-protected scope if any of the captured
9482     // variables needs destruction.
9483     for (BlockDecl::capture_const_iterator
9484            ci = Result->getBlockDecl()->capture_begin(),
9485            ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9486       const VarDecl *var = ci->getVariable();
9487       if (var->getType().isDestructedType() != QualType::DK_none) {
9488         getCurFunction()->setHasBranchProtectedScope();
9489         break;
9490       }
9491     }
9492   }
9493 
9494   return Owned(Result);
9495 }
9496 
9497 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
9498                                         Expr *E, ParsedType Ty,
9499                                         SourceLocation RPLoc) {
9500   TypeSourceInfo *TInfo;
9501   GetTypeFromParser(Ty, &TInfo);
9502   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
9503 }
9504 
9505 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
9506                                 Expr *E, TypeSourceInfo *TInfo,
9507                                 SourceLocation RPLoc) {
9508   Expr *OrigExpr = E;
9509 
9510   // Get the va_list type
9511   QualType VaListType = Context.getBuiltinVaListType();
9512   if (VaListType->isArrayType()) {
9513     // Deal with implicit array decay; for example, on x86-64,
9514     // va_list is an array, but it's supposed to decay to
9515     // a pointer for va_arg.
9516     VaListType = Context.getArrayDecayedType(VaListType);
9517     // Make sure the input expression also decays appropriately.
9518     ExprResult Result = UsualUnaryConversions(E);
9519     if (Result.isInvalid())
9520       return ExprError();
9521     E = Result.take();
9522   } else {
9523     // Otherwise, the va_list argument must be an l-value because
9524     // it is modified by va_arg.
9525     if (!E->isTypeDependent() &&
9526         CheckForModifiableLvalue(E, BuiltinLoc, *this))
9527       return ExprError();
9528   }
9529 
9530   if (!E->isTypeDependent() &&
9531       !Context.hasSameType(VaListType, E->getType())) {
9532     return ExprError(Diag(E->getLocStart(),
9533                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
9534       << OrigExpr->getType() << E->getSourceRange());
9535   }
9536 
9537   if (!TInfo->getType()->isDependentType()) {
9538     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
9539                             diag::err_second_parameter_to_va_arg_incomplete,
9540                             TInfo->getTypeLoc()))
9541       return ExprError();
9542 
9543     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
9544                                TInfo->getType(),
9545                                diag::err_second_parameter_to_va_arg_abstract,
9546                                TInfo->getTypeLoc()))
9547       return ExprError();
9548 
9549     if (!TInfo->getType().isPODType(Context)) {
9550       Diag(TInfo->getTypeLoc().getBeginLoc(),
9551            TInfo->getType()->isObjCLifetimeType()
9552              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9553              : diag::warn_second_parameter_to_va_arg_not_pod)
9554         << TInfo->getType()
9555         << TInfo->getTypeLoc().getSourceRange();
9556     }
9557 
9558     // Check for va_arg where arguments of the given type will be promoted
9559     // (i.e. this va_arg is guaranteed to have undefined behavior).
9560     QualType PromoteType;
9561     if (TInfo->getType()->isPromotableIntegerType()) {
9562       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9563       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9564         PromoteType = QualType();
9565     }
9566     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9567       PromoteType = Context.DoubleTy;
9568     if (!PromoteType.isNull())
9569       Diag(TInfo->getTypeLoc().getBeginLoc(),
9570           diag::warn_second_parameter_to_va_arg_never_compatible)
9571         << TInfo->getType()
9572         << PromoteType
9573         << TInfo->getTypeLoc().getSourceRange();
9574   }
9575 
9576   QualType T = TInfo->getType().getNonLValueExprType(Context);
9577   return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
9578 }
9579 
9580 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
9581   // The type of __null will be int or long, depending on the size of
9582   // pointers on the target.
9583   QualType Ty;
9584   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9585   if (pw == Context.getTargetInfo().getIntWidth())
9586     Ty = Context.IntTy;
9587   else if (pw == Context.getTargetInfo().getLongWidth())
9588     Ty = Context.LongTy;
9589   else if (pw == Context.getTargetInfo().getLongLongWidth())
9590     Ty = Context.LongLongTy;
9591   else {
9592     llvm_unreachable("I don't know size of pointer!");
9593   }
9594 
9595   return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
9596 }
9597 
9598 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
9599                                            Expr *SrcExpr, FixItHint &Hint) {
9600   if (!SemaRef.getLangOpts().ObjC1)
9601     return;
9602 
9603   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9604   if (!PT)
9605     return;
9606 
9607   // Check if the destination is of type 'id'.
9608   if (!PT->isObjCIdType()) {
9609     // Check if the destination is the 'NSString' interface.
9610     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9611     if (!ID || !ID->getIdentifier()->isStr("NSString"))
9612       return;
9613   }
9614 
9615   // Ignore any parens, implicit casts (should only be
9616   // array-to-pointer decays), and not-so-opaque values.  The last is
9617   // important for making this trigger for property assignments.
9618   SrcExpr = SrcExpr->IgnoreParenImpCasts();
9619   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9620     if (OV->getSourceExpr())
9621       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9622 
9623   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
9624   if (!SL || !SL->isAscii())
9625     return;
9626 
9627   Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
9628 }
9629 
9630 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9631                                     SourceLocation Loc,
9632                                     QualType DstType, QualType SrcType,
9633                                     Expr *SrcExpr, AssignmentAction Action,
9634                                     bool *Complained) {
9635   if (Complained)
9636     *Complained = false;
9637 
9638   // Decode the result (notice that AST's are still created for extensions).
9639   bool CheckInferredResultType = false;
9640   bool isInvalid = false;
9641   unsigned DiagKind = 0;
9642   FixItHint Hint;
9643   ConversionFixItGenerator ConvHints;
9644   bool MayHaveConvFixit = false;
9645   bool MayHaveFunctionDiff = false;
9646 
9647   switch (ConvTy) {
9648   case Compatible:
9649       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9650       return false;
9651 
9652   case PointerToInt:
9653     DiagKind = diag::ext_typecheck_convert_pointer_int;
9654     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9655     MayHaveConvFixit = true;
9656     break;
9657   case IntToPointer:
9658     DiagKind = diag::ext_typecheck_convert_int_pointer;
9659     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9660     MayHaveConvFixit = true;
9661     break;
9662   case IncompatiblePointer:
9663     MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
9664     DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9665     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9666       SrcType->isObjCObjectPointerType();
9667     if (Hint.isNull() && !CheckInferredResultType) {
9668       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9669     }
9670     MayHaveConvFixit = true;
9671     break;
9672   case IncompatiblePointerSign:
9673     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9674     break;
9675   case FunctionVoidPointer:
9676     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9677     break;
9678   case IncompatiblePointerDiscardsQualifiers: {
9679     // Perform array-to-pointer decay if necessary.
9680     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9681 
9682     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9683     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9684     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9685       DiagKind = diag::err_typecheck_incompatible_address_space;
9686       break;
9687 
9688 
9689     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
9690       DiagKind = diag::err_typecheck_incompatible_ownership;
9691       break;
9692     }
9693 
9694     llvm_unreachable("unknown error case for discarding qualifiers!");
9695     // fallthrough
9696   }
9697   case CompatiblePointerDiscardsQualifiers:
9698     // If the qualifiers lost were because we were applying the
9699     // (deprecated) C++ conversion from a string literal to a char*
9700     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
9701     // Ideally, this check would be performed in
9702     // checkPointerTypesForAssignment. However, that would require a
9703     // bit of refactoring (so that the second argument is an
9704     // expression, rather than a type), which should be done as part
9705     // of a larger effort to fix checkPointerTypesForAssignment for
9706     // C++ semantics.
9707     if (getLangOpts().CPlusPlus &&
9708         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9709       return false;
9710     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9711     break;
9712   case IncompatibleNestedPointerQualifiers:
9713     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
9714     break;
9715   case IntToBlockPointer:
9716     DiagKind = diag::err_int_to_block_pointer;
9717     break;
9718   case IncompatibleBlockPointer:
9719     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
9720     break;
9721   case IncompatibleObjCQualifiedId:
9722     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
9723     // it can give a more specific diagnostic.
9724     DiagKind = diag::warn_incompatible_qualified_id;
9725     break;
9726   case IncompatibleVectors:
9727     DiagKind = diag::warn_incompatible_vectors;
9728     break;
9729   case IncompatibleObjCWeakRef:
9730     DiagKind = diag::err_arc_weak_unavailable_assign;
9731     break;
9732   case Incompatible:
9733     DiagKind = diag::err_typecheck_convert_incompatible;
9734     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9735     MayHaveConvFixit = true;
9736     isInvalid = true;
9737     MayHaveFunctionDiff = true;
9738     break;
9739   }
9740 
9741   QualType FirstType, SecondType;
9742   switch (Action) {
9743   case AA_Assigning:
9744   case AA_Initializing:
9745     // The destination type comes first.
9746     FirstType = DstType;
9747     SecondType = SrcType;
9748     break;
9749 
9750   case AA_Returning:
9751   case AA_Passing:
9752   case AA_Converting:
9753   case AA_Sending:
9754   case AA_Casting:
9755     // The source type comes first.
9756     FirstType = SrcType;
9757     SecondType = DstType;
9758     break;
9759   }
9760 
9761   PartialDiagnostic FDiag = PDiag(DiagKind);
9762   FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9763 
9764   // If we can fix the conversion, suggest the FixIts.
9765   assert(ConvHints.isNull() || Hint.isNull());
9766   if (!ConvHints.isNull()) {
9767     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9768          HE = ConvHints.Hints.end(); HI != HE; ++HI)
9769       FDiag << *HI;
9770   } else {
9771     FDiag << Hint;
9772   }
9773   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9774 
9775   if (MayHaveFunctionDiff)
9776     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9777 
9778   Diag(Loc, FDiag);
9779 
9780   if (SecondType == Context.OverloadTy)
9781     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9782                               FirstType);
9783 
9784   if (CheckInferredResultType)
9785     EmitRelatedResultTypeNote(SrcExpr);
9786 
9787   if (Complained)
9788     *Complained = true;
9789   return isInvalid;
9790 }
9791 
9792 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9793                                                  llvm::APSInt *Result) {
9794   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9795   public:
9796     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9797       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9798     }
9799   } Diagnoser;
9800 
9801   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9802 }
9803 
9804 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9805                                                  llvm::APSInt *Result,
9806                                                  unsigned DiagID,
9807                                                  bool AllowFold) {
9808   class IDDiagnoser : public VerifyICEDiagnoser {
9809     unsigned DiagID;
9810 
9811   public:
9812     IDDiagnoser(unsigned DiagID)
9813       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9814 
9815     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9816       S.Diag(Loc, DiagID) << SR;
9817     }
9818   } Diagnoser(DiagID);
9819 
9820   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9821 }
9822 
9823 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9824                                             SourceRange SR) {
9825   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
9826 }
9827 
9828 ExprResult
9829 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9830                                       VerifyICEDiagnoser &Diagnoser,
9831                                       bool AllowFold) {
9832   SourceLocation DiagLoc = E->getLocStart();
9833 
9834   if (getLangOpts().CPlusPlus0x) {
9835     // C++11 [expr.const]p5:
9836     //   If an expression of literal class type is used in a context where an
9837     //   integral constant expression is required, then that class type shall
9838     //   have a single non-explicit conversion function to an integral or
9839     //   unscoped enumeration type
9840     ExprResult Converted;
9841     if (!Diagnoser.Suppress) {
9842       class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9843       public:
9844         CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9845 
9846         virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9847                                                  QualType T) {
9848           return S.Diag(Loc, diag::err_ice_not_integral) << T;
9849         }
9850 
9851         virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9852                                                      SourceLocation Loc,
9853                                                      QualType T) {
9854           return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9855         }
9856 
9857         virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9858                                                        SourceLocation Loc,
9859                                                        QualType T,
9860                                                        QualType ConvTy) {
9861           return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9862         }
9863 
9864         virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9865                                                    CXXConversionDecl *Conv,
9866                                                    QualType ConvTy) {
9867           return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9868                    << ConvTy->isEnumeralType() << ConvTy;
9869         }
9870 
9871         virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9872                                                     QualType T) {
9873           return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9874         }
9875 
9876         virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9877                                                 CXXConversionDecl *Conv,
9878                                                 QualType ConvTy) {
9879           return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9880                    << ConvTy->isEnumeralType() << ConvTy;
9881         }
9882 
9883         virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9884                                                      SourceLocation Loc,
9885                                                      QualType T,
9886                                                      QualType ConvTy) {
9887           return DiagnosticBuilder::getEmpty();
9888         }
9889       } ConvertDiagnoser;
9890 
9891       Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9892                                                      ConvertDiagnoser,
9893                                              /*AllowScopedEnumerations*/ false);
9894     } else {
9895       // The caller wants to silently enquire whether this is an ICE. Don't
9896       // produce any diagnostics if it isn't.
9897       class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
9898       public:
9899         SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
9900 
9901         virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9902                                                  QualType T) {
9903           return DiagnosticBuilder::getEmpty();
9904         }
9905 
9906         virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9907                                                      SourceLocation Loc,
9908                                                      QualType T) {
9909           return DiagnosticBuilder::getEmpty();
9910         }
9911 
9912         virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9913                                                        SourceLocation Loc,
9914                                                        QualType T,
9915                                                        QualType ConvTy) {
9916           return DiagnosticBuilder::getEmpty();
9917         }
9918 
9919         virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9920                                                    CXXConversionDecl *Conv,
9921                                                    QualType ConvTy) {
9922           return DiagnosticBuilder::getEmpty();
9923         }
9924 
9925         virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9926                                                     QualType T) {
9927           return DiagnosticBuilder::getEmpty();
9928         }
9929 
9930         virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9931                                                 CXXConversionDecl *Conv,
9932                                                 QualType ConvTy) {
9933           return DiagnosticBuilder::getEmpty();
9934         }
9935 
9936         virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9937                                                      SourceLocation Loc,
9938                                                      QualType T,
9939                                                      QualType ConvTy) {
9940           return DiagnosticBuilder::getEmpty();
9941         }
9942       } ConvertDiagnoser;
9943 
9944       Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9945                                                      ConvertDiagnoser, false);
9946     }
9947     if (Converted.isInvalid())
9948       return Converted;
9949     E = Converted.take();
9950     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9951       return ExprError();
9952   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
9953     // An ICE must be of integral or unscoped enumeration type.
9954     if (!Diagnoser.Suppress)
9955       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
9956     return ExprError();
9957   }
9958 
9959   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
9960   // in the non-ICE case.
9961   if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
9962     if (Result)
9963       *Result = E->EvaluateKnownConstInt(Context);
9964     return Owned(E);
9965   }
9966 
9967   Expr::EvalResult EvalResult;
9968   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
9969   EvalResult.Diag = &Notes;
9970 
9971   // Try to evaluate the expression, and produce diagnostics explaining why it's
9972   // not a constant expression as a side-effect.
9973   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
9974                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
9975 
9976   // In C++11, we can rely on diagnostics being produced for any expression
9977   // which is not a constant expression. If no diagnostics were produced, then
9978   // this is a constant expression.
9979   if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
9980     if (Result)
9981       *Result = EvalResult.Val.getInt();
9982     return Owned(E);
9983   }
9984 
9985   // If our only note is the usual "invalid subexpression" note, just point
9986   // the caret at its location rather than producing an essentially
9987   // redundant note.
9988   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9989         diag::note_invalid_subexpr_in_const_expr) {
9990     DiagLoc = Notes[0].first;
9991     Notes.clear();
9992   }
9993 
9994   if (!Folded || !AllowFold) {
9995     if (!Diagnoser.Suppress) {
9996       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
9997       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9998         Diag(Notes[I].first, Notes[I].second);
9999     }
10000 
10001     return ExprError();
10002   }
10003 
10004   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
10005   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10006     Diag(Notes[I].first, Notes[I].second);
10007 
10008   if (Result)
10009     *Result = EvalResult.Val.getInt();
10010   return Owned(E);
10011 }
10012 
10013 namespace {
10014   // Handle the case where we conclude a expression which we speculatively
10015   // considered to be unevaluated is actually evaluated.
10016   class TransformToPE : public TreeTransform<TransformToPE> {
10017     typedef TreeTransform<TransformToPE> BaseTransform;
10018 
10019   public:
10020     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10021 
10022     // Make sure we redo semantic analysis
10023     bool AlwaysRebuild() { return true; }
10024 
10025     // Make sure we handle LabelStmts correctly.
10026     // FIXME: This does the right thing, but maybe we need a more general
10027     // fix to TreeTransform?
10028     StmtResult TransformLabelStmt(LabelStmt *S) {
10029       S->getDecl()->setStmt(0);
10030       return BaseTransform::TransformLabelStmt(S);
10031     }
10032 
10033     // We need to special-case DeclRefExprs referring to FieldDecls which
10034     // are not part of a member pointer formation; normal TreeTransforming
10035     // doesn't catch this case because of the way we represent them in the AST.
10036     // FIXME: This is a bit ugly; is it really the best way to handle this
10037     // case?
10038     //
10039     // Error on DeclRefExprs referring to FieldDecls.
10040     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10041       if (isa<FieldDecl>(E->getDecl()) &&
10042           SemaRef.ExprEvalContexts.back().Context != Sema::Unevaluated)
10043         return SemaRef.Diag(E->getLocation(),
10044                             diag::err_invalid_non_static_member_use)
10045             << E->getDecl() << E->getSourceRange();
10046 
10047       return BaseTransform::TransformDeclRefExpr(E);
10048     }
10049 
10050     // Exception: filter out member pointer formation
10051     ExprResult TransformUnaryOperator(UnaryOperator *E) {
10052       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10053         return E;
10054 
10055       return BaseTransform::TransformUnaryOperator(E);
10056     }
10057 
10058     ExprResult TransformLambdaExpr(LambdaExpr *E) {
10059       // Lambdas never need to be transformed.
10060       return E;
10061     }
10062   };
10063 }
10064 
10065 ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
10066   assert(ExprEvalContexts.back().Context == Unevaluated &&
10067          "Should only transform unevaluated expressions");
10068   ExprEvalContexts.back().Context =
10069       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10070   if (ExprEvalContexts.back().Context == Unevaluated)
10071     return E;
10072   return TransformToPE(*this).TransformExpr(E);
10073 }
10074 
10075 void
10076 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10077                                       Decl *LambdaContextDecl,
10078                                       bool IsDecltype) {
10079   ExprEvalContexts.push_back(
10080              ExpressionEvaluationContextRecord(NewContext,
10081                                                ExprCleanupObjects.size(),
10082                                                ExprNeedsCleanups,
10083                                                LambdaContextDecl,
10084                                                IsDecltype));
10085   ExprNeedsCleanups = false;
10086   if (!MaybeODRUseExprs.empty())
10087     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
10088 }
10089 
10090 void Sema::PopExpressionEvaluationContext() {
10091   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
10092 
10093   if (!Rec.Lambdas.empty()) {
10094     if (Rec.Context == Unevaluated) {
10095       // C++11 [expr.prim.lambda]p2:
10096       //   A lambda-expression shall not appear in an unevaluated operand
10097       //   (Clause 5).
10098       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10099         Diag(Rec.Lambdas[I]->getLocStart(),
10100              diag::err_lambda_unevaluated_operand);
10101     } else {
10102       // Mark the capture expressions odr-used. This was deferred
10103       // during lambda expression creation.
10104       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10105         LambdaExpr *Lambda = Rec.Lambdas[I];
10106         for (LambdaExpr::capture_init_iterator
10107                   C = Lambda->capture_init_begin(),
10108                CEnd = Lambda->capture_init_end();
10109              C != CEnd; ++C) {
10110           MarkDeclarationsReferencedInExpr(*C);
10111         }
10112       }
10113     }
10114   }
10115 
10116   // When are coming out of an unevaluated context, clear out any
10117   // temporaries that we may have created as part of the evaluation of
10118   // the expression in that context: they aren't relevant because they
10119   // will never be constructed.
10120   if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
10121     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10122                              ExprCleanupObjects.end());
10123     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
10124     CleanupVarDeclMarking();
10125     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
10126   // Otherwise, merge the contexts together.
10127   } else {
10128     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
10129     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10130                             Rec.SavedMaybeODRUseExprs.end());
10131   }
10132 
10133   // Pop the current expression evaluation context off the stack.
10134   ExprEvalContexts.pop_back();
10135 }
10136 
10137 void Sema::DiscardCleanupsInEvaluationContext() {
10138   ExprCleanupObjects.erase(
10139          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10140          ExprCleanupObjects.end());
10141   ExprNeedsCleanups = false;
10142   MaybeODRUseExprs.clear();
10143 }
10144 
10145 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10146   if (!E->getType()->isVariablyModifiedType())
10147     return E;
10148   return TranformToPotentiallyEvaluated(E);
10149 }
10150 
10151 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
10152   // Do not mark anything as "used" within a dependent context; wait for
10153   // an instantiation.
10154   if (SemaRef.CurContext->isDependentContext())
10155     return false;
10156 
10157   switch (SemaRef.ExprEvalContexts.back().Context) {
10158     case Sema::Unevaluated:
10159       // We are in an expression that is not potentially evaluated; do nothing.
10160       // (Depending on how you read the standard, we actually do need to do
10161       // something here for null pointer constants, but the standard's
10162       // definition of a null pointer constant is completely crazy.)
10163       return false;
10164 
10165     case Sema::ConstantEvaluated:
10166     case Sema::PotentiallyEvaluated:
10167       // We are in a potentially evaluated expression (or a constant-expression
10168       // in C++03); we need to do implicit template instantiation, implicitly
10169       // define class members, and mark most declarations as used.
10170       return true;
10171 
10172     case Sema::PotentiallyEvaluatedIfUsed:
10173       // Referenced declarations will only be used if the construct in the
10174       // containing expression is used.
10175       return false;
10176   }
10177   llvm_unreachable("Invalid context");
10178 }
10179 
10180 /// \brief Mark a function referenced, and check whether it is odr-used
10181 /// (C++ [basic.def.odr]p2, C99 6.9p3)
10182 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10183   assert(Func && "No function?");
10184 
10185   Func->setReferenced();
10186 
10187   // Don't mark this function as used multiple times, unless it's a constexpr
10188   // function which we need to instantiate.
10189   if (Func->isUsed(false) &&
10190       !(Func->isConstexpr() && !Func->getBody() &&
10191         Func->isImplicitlyInstantiable()))
10192     return;
10193 
10194   if (!IsPotentiallyEvaluatedContext(*this))
10195     return;
10196 
10197   // Note that this declaration has been used.
10198   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
10199     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
10200       if (Constructor->isDefaultConstructor()) {
10201         if (Constructor->isTrivial())
10202           return;
10203         if (!Constructor->isUsed(false))
10204           DefineImplicitDefaultConstructor(Loc, Constructor);
10205       } else if (Constructor->isCopyConstructor()) {
10206         if (!Constructor->isUsed(false))
10207           DefineImplicitCopyConstructor(Loc, Constructor);
10208       } else if (Constructor->isMoveConstructor()) {
10209         if (!Constructor->isUsed(false))
10210           DefineImplicitMoveConstructor(Loc, Constructor);
10211       }
10212     }
10213 
10214     MarkVTableUsed(Loc, Constructor->getParent());
10215   } else if (CXXDestructorDecl *Destructor =
10216                  dyn_cast<CXXDestructorDecl>(Func)) {
10217     if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10218         !Destructor->isUsed(false))
10219       DefineImplicitDestructor(Loc, Destructor);
10220     if (Destructor->isVirtual())
10221       MarkVTableUsed(Loc, Destructor->getParent());
10222   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
10223     if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10224         MethodDecl->isOverloadedOperator() &&
10225         MethodDecl->getOverloadedOperator() == OO_Equal) {
10226       if (!MethodDecl->isUsed(false)) {
10227         if (MethodDecl->isCopyAssignmentOperator())
10228           DefineImplicitCopyAssignment(Loc, MethodDecl);
10229         else
10230           DefineImplicitMoveAssignment(Loc, MethodDecl);
10231       }
10232     } else if (isa<CXXConversionDecl>(MethodDecl) &&
10233                MethodDecl->getParent()->isLambda()) {
10234       CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10235       if (Conversion->isLambdaToBlockPointerConversion())
10236         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10237       else
10238         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
10239     } else if (MethodDecl->isVirtual())
10240       MarkVTableUsed(Loc, MethodDecl->getParent());
10241   }
10242 
10243   // Recursive functions should be marked when used from another function.
10244   // FIXME: Is this really right?
10245   if (CurContext == Func) return;
10246 
10247   // Resolve the exception specification for any function which is
10248   // used: CodeGen will need it.
10249   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
10250   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10251     ResolveExceptionSpec(Loc, FPT);
10252 
10253   // Implicit instantiation of function templates and member functions of
10254   // class templates.
10255   if (Func->isImplicitlyInstantiable()) {
10256     bool AlreadyInstantiated = false;
10257     SourceLocation PointOfInstantiation = Loc;
10258     if (FunctionTemplateSpecializationInfo *SpecInfo
10259                               = Func->getTemplateSpecializationInfo()) {
10260       if (SpecInfo->getPointOfInstantiation().isInvalid())
10261         SpecInfo->setPointOfInstantiation(Loc);
10262       else if (SpecInfo->getTemplateSpecializationKind()
10263                  == TSK_ImplicitInstantiation) {
10264         AlreadyInstantiated = true;
10265         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10266       }
10267     } else if (MemberSpecializationInfo *MSInfo
10268                                 = Func->getMemberSpecializationInfo()) {
10269       if (MSInfo->getPointOfInstantiation().isInvalid())
10270         MSInfo->setPointOfInstantiation(Loc);
10271       else if (MSInfo->getTemplateSpecializationKind()
10272                  == TSK_ImplicitInstantiation) {
10273         AlreadyInstantiated = true;
10274         PointOfInstantiation = MSInfo->getPointOfInstantiation();
10275       }
10276     }
10277 
10278     if (!AlreadyInstantiated || Func->isConstexpr()) {
10279       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10280           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
10281         PendingLocalImplicitInstantiations.push_back(
10282             std::make_pair(Func, PointOfInstantiation));
10283       else if (Func->isConstexpr())
10284         // Do not defer instantiations of constexpr functions, to avoid the
10285         // expression evaluator needing to call back into Sema if it sees a
10286         // call to such a function.
10287         InstantiateFunctionDefinition(PointOfInstantiation, Func);
10288       else {
10289         PendingInstantiations.push_back(std::make_pair(Func,
10290                                                        PointOfInstantiation));
10291         // Notify the consumer that a function was implicitly instantiated.
10292         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10293       }
10294     }
10295   } else {
10296     // Walk redefinitions, as some of them may be instantiable.
10297     for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10298          e(Func->redecls_end()); i != e; ++i) {
10299       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10300         MarkFunctionReferenced(Loc, *i);
10301     }
10302   }
10303 
10304   // Keep track of used but undefined functions.
10305   if (!Func->isPure() && !Func->hasBody() &&
10306       Func->getLinkage() != ExternalLinkage) {
10307     SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10308     if (old.isInvalid()) old = Loc;
10309   }
10310 
10311   Func->setUsed(true);
10312 }
10313 
10314 static void
10315 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10316                                    VarDecl *var, DeclContext *DC) {
10317   DeclContext *VarDC = var->getDeclContext();
10318 
10319   //  If the parameter still belongs to the translation unit, then
10320   //  we're actually just using one parameter in the declaration of
10321   //  the next.
10322   if (isa<ParmVarDecl>(var) &&
10323       isa<TranslationUnitDecl>(VarDC))
10324     return;
10325 
10326   // For C code, don't diagnose about capture if we're not actually in code
10327   // right now; it's impossible to write a non-constant expression outside of
10328   // function context, so we'll get other (more useful) diagnostics later.
10329   //
10330   // For C++, things get a bit more nasty... it would be nice to suppress this
10331   // diagnostic for certain cases like using a local variable in an array bound
10332   // for a member of a local class, but the correct predicate is not obvious.
10333   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
10334     return;
10335 
10336   if (isa<CXXMethodDecl>(VarDC) &&
10337       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10338     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10339       << var->getIdentifier();
10340   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10341     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10342       << var->getIdentifier() << fn->getDeclName();
10343   } else if (isa<BlockDecl>(VarDC)) {
10344     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10345       << var->getIdentifier();
10346   } else {
10347     // FIXME: Is there any other context where a local variable can be
10348     // declared?
10349     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10350       << var->getIdentifier();
10351   }
10352 
10353   S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10354     << var->getIdentifier();
10355 
10356   // FIXME: Add additional diagnostic info about class etc. which prevents
10357   // capture.
10358 }
10359 
10360 /// \brief Capture the given variable in the given lambda expression.
10361 static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
10362                                   VarDecl *Var, QualType FieldType,
10363                                   QualType DeclRefType,
10364                                   SourceLocation Loc,
10365                                   bool RefersToEnclosingLocal) {
10366   CXXRecordDecl *Lambda = LSI->Lambda;
10367 
10368   // Build the non-static data member.
10369   FieldDecl *Field
10370     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10371                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
10372                         0, false, ICIS_NoInit);
10373   Field->setImplicit(true);
10374   Field->setAccess(AS_private);
10375   Lambda->addDecl(Field);
10376 
10377   // C++11 [expr.prim.lambda]p21:
10378   //   When the lambda-expression is evaluated, the entities that
10379   //   are captured by copy are used to direct-initialize each
10380   //   corresponding non-static data member of the resulting closure
10381   //   object. (For array members, the array elements are
10382   //   direct-initialized in increasing subscript order.) These
10383   //   initializations are performed in the (unspecified) order in
10384   //   which the non-static data members are declared.
10385 
10386   // Introduce a new evaluation context for the initialization, so
10387   // that temporaries introduced as part of the capture are retained
10388   // to be re-"exported" from the lambda expression itself.
10389   S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10390 
10391   // C++ [expr.prim.labda]p12:
10392   //   An entity captured by a lambda-expression is odr-used (3.2) in
10393   //   the scope containing the lambda-expression.
10394   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10395                                           DeclRefType, VK_LValue, Loc);
10396   Var->setReferenced(true);
10397   Var->setUsed(true);
10398 
10399   // When the field has array type, create index variables for each
10400   // dimension of the array. We use these index variables to subscript
10401   // the source array, and other clients (e.g., CodeGen) will perform
10402   // the necessary iteration with these index variables.
10403   SmallVector<VarDecl *, 4> IndexVariables;
10404   QualType BaseType = FieldType;
10405   QualType SizeType = S.Context.getSizeType();
10406   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
10407   while (const ConstantArrayType *Array
10408                         = S.Context.getAsConstantArrayType(BaseType)) {
10409     // Create the iteration variable for this array index.
10410     IdentifierInfo *IterationVarName = 0;
10411     {
10412       SmallString<8> Str;
10413       llvm::raw_svector_ostream OS(Str);
10414       OS << "__i" << IndexVariables.size();
10415       IterationVarName = &S.Context.Idents.get(OS.str());
10416     }
10417     VarDecl *IterationVar
10418       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10419                         IterationVarName, SizeType,
10420                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10421                         SC_None, SC_None);
10422     IndexVariables.push_back(IterationVar);
10423     LSI->ArrayIndexVars.push_back(IterationVar);
10424 
10425     // Create a reference to the iteration variable.
10426     ExprResult IterationVarRef
10427       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10428     assert(!IterationVarRef.isInvalid() &&
10429            "Reference to invented variable cannot fail!");
10430     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10431     assert(!IterationVarRef.isInvalid() &&
10432            "Conversion of invented variable cannot fail!");
10433 
10434     // Subscript the array with this iteration variable.
10435     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10436                              Ref, Loc, IterationVarRef.take(), Loc);
10437     if (Subscript.isInvalid()) {
10438       S.CleanupVarDeclMarking();
10439       S.DiscardCleanupsInEvaluationContext();
10440       S.PopExpressionEvaluationContext();
10441       return ExprError();
10442     }
10443 
10444     Ref = Subscript.take();
10445     BaseType = Array->getElementType();
10446   }
10447 
10448   // Construct the entity that we will be initializing. For an array, this
10449   // will be first element in the array, which may require several levels
10450   // of array-subscript entities.
10451   SmallVector<InitializedEntity, 4> Entities;
10452   Entities.reserve(1 + IndexVariables.size());
10453   Entities.push_back(
10454     InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
10455   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10456     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10457                                                             0,
10458                                                             Entities.back()));
10459 
10460   InitializationKind InitKind
10461     = InitializationKind::CreateDirect(Loc, Loc, Loc);
10462   InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
10463   ExprResult Result(true);
10464   if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
10465     Result = Init.Perform(S, Entities.back(), InitKind,
10466                           MultiExprArg(S, &Ref, 1));
10467 
10468   // If this initialization requires any cleanups (e.g., due to a
10469   // default argument to a copy constructor), note that for the
10470   // lambda.
10471   if (S.ExprNeedsCleanups)
10472     LSI->ExprNeedsCleanups = true;
10473 
10474   // Exit the expression evaluation context used for the capture.
10475   S.CleanupVarDeclMarking();
10476   S.DiscardCleanupsInEvaluationContext();
10477   S.PopExpressionEvaluationContext();
10478   return Result;
10479 }
10480 
10481 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10482                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
10483                               bool BuildAndDiagnose,
10484                               QualType &CaptureType,
10485                               QualType &DeclRefType) {
10486   bool Nested = false;
10487 
10488   DeclContext *DC = CurContext;
10489   if (Var->getDeclContext() == DC) return true;
10490   if (!Var->hasLocalStorage()) return true;
10491 
10492   bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
10493 
10494   // Walk up the stack to determine whether we can capture the variable,
10495   // performing the "simple" checks that don't depend on type. We stop when
10496   // we've either hit the declared scope of the variable or find an existing
10497   // capture of that variable.
10498   CaptureType = Var->getType();
10499   DeclRefType = CaptureType.getNonReferenceType();
10500   bool Explicit = (Kind != TryCapture_Implicit);
10501   unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
10502   do {
10503     // Only block literals and lambda expressions can capture; other
10504     // scopes don't work.
10505     DeclContext *ParentDC;
10506     if (isa<BlockDecl>(DC))
10507       ParentDC = DC->getParent();
10508     else if (isa<CXXMethodDecl>(DC) &&
10509              cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
10510              cast<CXXRecordDecl>(DC->getParent())->isLambda())
10511       ParentDC = DC->getParent()->getParent();
10512     else {
10513       if (BuildAndDiagnose)
10514         diagnoseUncapturableValueReference(*this, Loc, Var, DC);
10515       return true;
10516     }
10517 
10518     CapturingScopeInfo *CSI =
10519       cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
10520 
10521     // Check whether we've already captured it.
10522     if (CSI->CaptureMap.count(Var)) {
10523       // If we found a capture, any subcaptures are nested.
10524       Nested = true;
10525 
10526       // Retrieve the capture type for this variable.
10527       CaptureType = CSI->getCapture(Var).getCaptureType();
10528 
10529       // Compute the type of an expression that refers to this variable.
10530       DeclRefType = CaptureType.getNonReferenceType();
10531 
10532       const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10533       if (Cap.isCopyCapture() &&
10534           !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10535         DeclRefType.addConst();
10536       break;
10537     }
10538 
10539     bool IsBlock = isa<BlockScopeInfo>(CSI);
10540     bool IsLambda = !IsBlock;
10541 
10542     // Lambdas are not allowed to capture unnamed variables
10543     // (e.g. anonymous unions).
10544     // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10545     // assuming that's the intent.
10546     if (IsLambda && !Var->getDeclName()) {
10547       if (BuildAndDiagnose) {
10548         Diag(Loc, diag::err_lambda_capture_anonymous_var);
10549         Diag(Var->getLocation(), diag::note_declared_at);
10550       }
10551       return true;
10552     }
10553 
10554     // Prohibit variably-modified types; they're difficult to deal with.
10555     if (Var->getType()->isVariablyModifiedType()) {
10556       if (BuildAndDiagnose) {
10557         if (IsBlock)
10558           Diag(Loc, diag::err_ref_vm_type);
10559         else
10560           Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10561         Diag(Var->getLocation(), diag::note_previous_decl)
10562           << Var->getDeclName();
10563       }
10564       return true;
10565     }
10566 
10567     // Lambdas are not allowed to capture __block variables; they don't
10568     // support the expected semantics.
10569     if (IsLambda && HasBlocksAttr) {
10570       if (BuildAndDiagnose) {
10571         Diag(Loc, diag::err_lambda_capture_block)
10572           << Var->getDeclName();
10573         Diag(Var->getLocation(), diag::note_previous_decl)
10574           << Var->getDeclName();
10575       }
10576       return true;
10577     }
10578 
10579     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10580       // No capture-default
10581       if (BuildAndDiagnose) {
10582         Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10583         Diag(Var->getLocation(), diag::note_previous_decl)
10584           << Var->getDeclName();
10585         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10586              diag::note_lambda_decl);
10587       }
10588       return true;
10589     }
10590 
10591     FunctionScopesIndex--;
10592     DC = ParentDC;
10593     Explicit = false;
10594   } while (!Var->getDeclContext()->Equals(DC));
10595 
10596   // Walk back down the scope stack, computing the type of the capture at
10597   // each step, checking type-specific requirements, and adding captures if
10598   // requested.
10599   for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10600        ++I) {
10601     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
10602 
10603     // Compute the type of the capture and of a reference to the capture within
10604     // this scope.
10605     if (isa<BlockScopeInfo>(CSI)) {
10606       Expr *CopyExpr = 0;
10607       bool ByRef = false;
10608 
10609       // Blocks are not allowed to capture arrays.
10610       if (CaptureType->isArrayType()) {
10611         if (BuildAndDiagnose) {
10612           Diag(Loc, diag::err_ref_array_type);
10613           Diag(Var->getLocation(), diag::note_previous_decl)
10614           << Var->getDeclName();
10615         }
10616         return true;
10617       }
10618 
10619       // Forbid the block-capture of autoreleasing variables.
10620       if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10621         if (BuildAndDiagnose) {
10622           Diag(Loc, diag::err_arc_autoreleasing_capture)
10623             << /*block*/ 0;
10624           Diag(Var->getLocation(), diag::note_previous_decl)
10625             << Var->getDeclName();
10626         }
10627         return true;
10628       }
10629 
10630       if (HasBlocksAttr || CaptureType->isReferenceType()) {
10631         // Block capture by reference does not change the capture or
10632         // declaration reference types.
10633         ByRef = true;
10634       } else {
10635         // Block capture by copy introduces 'const'.
10636         CaptureType = CaptureType.getNonReferenceType().withConst();
10637         DeclRefType = CaptureType;
10638 
10639         if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
10640           if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10641             // The capture logic needs the destructor, so make sure we mark it.
10642             // Usually this is unnecessary because most local variables have
10643             // their destructors marked at declaration time, but parameters are
10644             // an exception because it's technically only the call site that
10645             // actually requires the destructor.
10646             if (isa<ParmVarDecl>(Var))
10647               FinalizeVarWithDestructor(Var, Record);
10648 
10649             // According to the blocks spec, the capture of a variable from
10650             // the stack requires a const copy constructor.  This is not true
10651             // of the copy/move done to move a __block variable to the heap.
10652             Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
10653                                                       DeclRefType.withConst(),
10654                                                       VK_LValue, Loc);
10655             ExprResult Result
10656               = PerformCopyInitialization(
10657                   InitializedEntity::InitializeBlock(Var->getLocation(),
10658                                                      CaptureType, false),
10659                   Loc, Owned(DeclRef));
10660 
10661             // Build a full-expression copy expression if initialization
10662             // succeeded and used a non-trivial constructor.  Recover from
10663             // errors by pretending that the copy isn't necessary.
10664             if (!Result.isInvalid() &&
10665                 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10666                    ->isTrivial()) {
10667               Result = MaybeCreateExprWithCleanups(Result);
10668               CopyExpr = Result.take();
10669             }
10670           }
10671         }
10672       }
10673 
10674       // Actually capture the variable.
10675       if (BuildAndDiagnose)
10676         CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10677                         SourceLocation(), CaptureType, CopyExpr);
10678       Nested = true;
10679       continue;
10680     }
10681 
10682     LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10683 
10684     // Determine whether we are capturing by reference or by value.
10685     bool ByRef = false;
10686     if (I == N - 1 && Kind != TryCapture_Implicit) {
10687       ByRef = (Kind == TryCapture_ExplicitByRef);
10688     } else {
10689       ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
10690     }
10691 
10692     // Compute the type of the field that will capture this variable.
10693     if (ByRef) {
10694       // C++11 [expr.prim.lambda]p15:
10695       //   An entity is captured by reference if it is implicitly or
10696       //   explicitly captured but not captured by copy. It is
10697       //   unspecified whether additional unnamed non-static data
10698       //   members are declared in the closure type for entities
10699       //   captured by reference.
10700       //
10701       // FIXME: It is not clear whether we want to build an lvalue reference
10702       // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10703       // to do the former, while EDG does the latter. Core issue 1249 will
10704       // clarify, but for now we follow GCC because it's a more permissive and
10705       // easily defensible position.
10706       CaptureType = Context.getLValueReferenceType(DeclRefType);
10707     } else {
10708       // C++11 [expr.prim.lambda]p14:
10709       //   For each entity captured by copy, an unnamed non-static
10710       //   data member is declared in the closure type. The
10711       //   declaration order of these members is unspecified. The type
10712       //   of such a data member is the type of the corresponding
10713       //   captured entity if the entity is not a reference to an
10714       //   object, or the referenced type otherwise. [Note: If the
10715       //   captured entity is a reference to a function, the
10716       //   corresponding data member is also a reference to a
10717       //   function. - end note ]
10718       if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10719         if (!RefType->getPointeeType()->isFunctionType())
10720           CaptureType = RefType->getPointeeType();
10721       }
10722 
10723       // Forbid the lambda copy-capture of autoreleasing variables.
10724       if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10725         if (BuildAndDiagnose) {
10726           Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10727           Diag(Var->getLocation(), diag::note_previous_decl)
10728             << Var->getDeclName();
10729         }
10730         return true;
10731       }
10732     }
10733 
10734     // Capture this variable in the lambda.
10735     Expr *CopyExpr = 0;
10736     if (BuildAndDiagnose) {
10737       ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
10738                                           DeclRefType, Loc,
10739                                           I == N-1);
10740       if (!Result.isInvalid())
10741         CopyExpr = Result.take();
10742     }
10743 
10744     // Compute the type of a reference to this captured variable.
10745     if (ByRef)
10746       DeclRefType = CaptureType.getNonReferenceType();
10747     else {
10748       // C++ [expr.prim.lambda]p5:
10749       //   The closure type for a lambda-expression has a public inline
10750       //   function call operator [...]. This function call operator is
10751       //   declared const (9.3.1) if and only if the lambda-expression’s
10752       //   parameter-declaration-clause is not followed by mutable.
10753       DeclRefType = CaptureType.getNonReferenceType();
10754       if (!LSI->Mutable && !CaptureType->isReferenceType())
10755         DeclRefType.addConst();
10756     }
10757 
10758     // Add the capture.
10759     if (BuildAndDiagnose)
10760       CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10761                       EllipsisLoc, CaptureType, CopyExpr);
10762     Nested = true;
10763   }
10764 
10765   return false;
10766 }
10767 
10768 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10769                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10770   QualType CaptureType;
10771   QualType DeclRefType;
10772   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10773                             /*BuildAndDiagnose=*/true, CaptureType,
10774                             DeclRefType);
10775 }
10776 
10777 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10778   QualType CaptureType;
10779   QualType DeclRefType;
10780 
10781   // Determine whether we can capture this variable.
10782   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10783                          /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10784     return QualType();
10785 
10786   return DeclRefType;
10787 }
10788 
10789 static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10790                                SourceLocation Loc) {
10791   // Keep track of used but undefined variables.
10792   // FIXME: We shouldn't suppress this warning for static data members.
10793   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
10794       Var->getLinkage() != ExternalLinkage &&
10795       !(Var->isStaticDataMember() && Var->hasInit())) {
10796     SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10797     if (old.isInvalid()) old = Loc;
10798   }
10799 
10800   SemaRef.tryCaptureVariable(Var, Loc);
10801 
10802   Var->setUsed(true);
10803 }
10804 
10805 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10806   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10807   // an object that satisfies the requirements for appearing in a
10808   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10809   // is immediately applied."  This function handles the lvalue-to-rvalue
10810   // conversion part.
10811   MaybeODRUseExprs.erase(E->IgnoreParens());
10812 }
10813 
10814 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10815   if (!Res.isUsable())
10816     return Res;
10817 
10818   // If a constant-expression is a reference to a variable where we delay
10819   // deciding whether it is an odr-use, just assume we will apply the
10820   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
10821   // (a non-type template argument), we have special handling anyway.
10822   UpdateMarkingForLValueToRValue(Res.get());
10823   return Res;
10824 }
10825 
10826 void Sema::CleanupVarDeclMarking() {
10827   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10828                                         e = MaybeODRUseExprs.end();
10829        i != e; ++i) {
10830     VarDecl *Var;
10831     SourceLocation Loc;
10832     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
10833       Var = cast<VarDecl>(DRE->getDecl());
10834       Loc = DRE->getLocation();
10835     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10836       Var = cast<VarDecl>(ME->getMemberDecl());
10837       Loc = ME->getMemberLoc();
10838     } else {
10839       llvm_unreachable("Unexpcted expression");
10840     }
10841 
10842     MarkVarDeclODRUsed(*this, Var, Loc);
10843   }
10844 
10845   MaybeODRUseExprs.clear();
10846 }
10847 
10848 // Mark a VarDecl referenced, and perform the necessary handling to compute
10849 // odr-uses.
10850 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10851                                     VarDecl *Var, Expr *E) {
10852   Var->setReferenced();
10853 
10854   if (!IsPotentiallyEvaluatedContext(SemaRef))
10855     return;
10856 
10857   // Implicit instantiation of static data members of class templates.
10858   if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
10859     MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10860     assert(MSInfo && "Missing member specialization information?");
10861     bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10862     if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
10863         (!AlreadyInstantiated ||
10864          Var->isUsableInConstantExpressions(SemaRef.Context))) {
10865       if (!AlreadyInstantiated) {
10866         // This is a modification of an existing AST node. Notify listeners.
10867         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10868           L->StaticDataMemberInstantiated(Var);
10869         MSInfo->setPointOfInstantiation(Loc);
10870       }
10871       SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
10872       if (Var->isUsableInConstantExpressions(SemaRef.Context))
10873         // Do not defer instantiations of variables which could be used in a
10874         // constant expression.
10875         SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
10876       else
10877         SemaRef.PendingInstantiations.push_back(
10878             std::make_pair(Var, PointOfInstantiation));
10879     }
10880   }
10881 
10882   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10883   // an object that satisfies the requirements for appearing in a
10884   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10885   // is immediately applied."  We check the first part here, and
10886   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10887   // Note that we use the C++11 definition everywhere because nothing in
10888   // C++03 depends on whether we get the C++03 version correct. This does not
10889   // apply to references, since they are not objects.
10890   const VarDecl *DefVD;
10891   if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
10892       Var->isUsableInConstantExpressions(SemaRef.Context) &&
10893       Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10894     SemaRef.MaybeODRUseExprs.insert(E);
10895   else
10896     MarkVarDeclODRUsed(SemaRef, Var, Loc);
10897 }
10898 
10899 /// \brief Mark a variable referenced, and check whether it is odr-used
10900 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
10901 /// used directly for normal expressions referring to VarDecl.
10902 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10903   DoMarkVarDeclReferenced(*this, Loc, Var, 0);
10904 }
10905 
10906 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10907                                Decl *D, Expr *E) {
10908   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10909     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10910     return;
10911   }
10912 
10913   SemaRef.MarkAnyDeclReferenced(Loc, D);
10914 
10915   // If this is a call to a method via a cast, also mark the method in the
10916   // derived class used in case codegen can devirtualize the call.
10917   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10918   if (!ME)
10919     return;
10920   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
10921   if (!MD)
10922     return;
10923   const Expr *Base = ME->getBase();
10924   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
10925   if (!MostDerivedClassDecl)
10926     return;
10927   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
10928   if (!DM)
10929     return;
10930   SemaRef.MarkAnyDeclReferenced(Loc, DM);
10931 }
10932 
10933 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10934 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10935   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10936 }
10937 
10938 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10939 void Sema::MarkMemberReferenced(MemberExpr *E) {
10940   MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10941 }
10942 
10943 /// \brief Perform marking for a reference to an arbitrary declaration.  It
10944 /// marks the declaration referenced, and performs odr-use checking for functions
10945 /// and variables. This method should not be used when building an normal
10946 /// expression which refers to a variable.
10947 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10948   if (VarDecl *VD = dyn_cast<VarDecl>(D))
10949     MarkVariableReferenced(Loc, VD);
10950   else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10951     MarkFunctionReferenced(Loc, FD);
10952   else
10953     D->setReferenced();
10954 }
10955 
10956 namespace {
10957   // Mark all of the declarations referenced
10958   // FIXME: Not fully implemented yet! We need to have a better understanding
10959   // of when we're entering
10960   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10961     Sema &S;
10962     SourceLocation Loc;
10963 
10964   public:
10965     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
10966 
10967     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
10968 
10969     bool TraverseTemplateArgument(const TemplateArgument &Arg);
10970     bool TraverseRecordType(RecordType *T);
10971   };
10972 }
10973 
10974 bool MarkReferencedDecls::TraverseTemplateArgument(
10975   const TemplateArgument &Arg) {
10976   if (Arg.getKind() == TemplateArgument::Declaration) {
10977     if (Decl *D = Arg.getAsDecl())
10978       S.MarkAnyDeclReferenced(Loc, D);
10979   }
10980 
10981   return Inherited::TraverseTemplateArgument(Arg);
10982 }
10983 
10984 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
10985   if (ClassTemplateSpecializationDecl *Spec
10986                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10987     const TemplateArgumentList &Args = Spec->getTemplateArgs();
10988     return TraverseTemplateArguments(Args.data(), Args.size());
10989   }
10990 
10991   return true;
10992 }
10993 
10994 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10995   MarkReferencedDecls Marker(*this, Loc);
10996   Marker.TraverseType(Context.getCanonicalType(T));
10997 }
10998 
10999 namespace {
11000   /// \brief Helper class that marks all of the declarations referenced by
11001   /// potentially-evaluated subexpressions as "referenced".
11002   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11003     Sema &S;
11004     bool SkipLocalVariables;
11005 
11006   public:
11007     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11008 
11009     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11010       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
11011 
11012     void VisitDeclRefExpr(DeclRefExpr *E) {
11013       // If we were asked not to visit local variables, don't.
11014       if (SkipLocalVariables) {
11015         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11016           if (VD->hasLocalStorage())
11017             return;
11018       }
11019 
11020       S.MarkDeclRefReferenced(E);
11021     }
11022 
11023     void VisitMemberExpr(MemberExpr *E) {
11024       S.MarkMemberReferenced(E);
11025       Inherited::VisitMemberExpr(E);
11026     }
11027 
11028     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
11029       S.MarkFunctionReferenced(E->getLocStart(),
11030             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11031       Visit(E->getSubExpr());
11032     }
11033 
11034     void VisitCXXNewExpr(CXXNewExpr *E) {
11035       if (E->getOperatorNew())
11036         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
11037       if (E->getOperatorDelete())
11038         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11039       Inherited::VisitCXXNewExpr(E);
11040     }
11041 
11042     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11043       if (E->getOperatorDelete())
11044         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11045       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11046       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11047         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
11048         S.MarkFunctionReferenced(E->getLocStart(),
11049                                     S.LookupDestructor(Record));
11050       }
11051 
11052       Inherited::VisitCXXDeleteExpr(E);
11053     }
11054 
11055     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11056       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
11057       Inherited::VisitCXXConstructExpr(E);
11058     }
11059 
11060     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11061       Visit(E->getExpr());
11062     }
11063 
11064     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11065       Inherited::VisitImplicitCastExpr(E);
11066 
11067       if (E->getCastKind() == CK_LValueToRValue)
11068         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11069     }
11070   };
11071 }
11072 
11073 /// \brief Mark any declarations that appear within this expression or any
11074 /// potentially-evaluated subexpressions as "referenced".
11075 ///
11076 /// \param SkipLocalVariables If true, don't mark local variables as
11077 /// 'referenced'.
11078 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11079                                             bool SkipLocalVariables) {
11080   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
11081 }
11082 
11083 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
11084 /// of the program being compiled.
11085 ///
11086 /// This routine emits the given diagnostic when the code currently being
11087 /// type-checked is "potentially evaluated", meaning that there is a
11088 /// possibility that the code will actually be executable. Code in sizeof()
11089 /// expressions, code used only during overload resolution, etc., are not
11090 /// potentially evaluated. This routine will suppress such diagnostics or,
11091 /// in the absolutely nutty case of potentially potentially evaluated
11092 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
11093 /// later.
11094 ///
11095 /// This routine should be used for all diagnostics that describe the run-time
11096 /// behavior of a program, such as passing a non-POD value through an ellipsis.
11097 /// Failure to do so will likely result in spurious diagnostics or failures
11098 /// during overload resolution or within sizeof/alignof/typeof/typeid.
11099 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
11100                                const PartialDiagnostic &PD) {
11101   switch (ExprEvalContexts.back().Context) {
11102   case Unevaluated:
11103     // The argument will never be evaluated, so don't complain.
11104     break;
11105 
11106   case ConstantEvaluated:
11107     // Relevant diagnostics should be produced by constant evaluation.
11108     break;
11109 
11110   case PotentiallyEvaluated:
11111   case PotentiallyEvaluatedIfUsed:
11112     if (Statement && getCurFunctionOrMethodDecl()) {
11113       FunctionScopes.back()->PossiblyUnreachableDiags.
11114         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
11115     }
11116     else
11117       Diag(Loc, PD);
11118 
11119     return true;
11120   }
11121 
11122   return false;
11123 }
11124 
11125 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11126                                CallExpr *CE, FunctionDecl *FD) {
11127   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11128     return false;
11129 
11130   // If we're inside a decltype's expression, don't check for a valid return
11131   // type or construct temporaries until we know whether this is the last call.
11132   if (ExprEvalContexts.back().IsDecltype) {
11133     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11134     return false;
11135   }
11136 
11137   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
11138     FunctionDecl *FD;
11139     CallExpr *CE;
11140 
11141   public:
11142     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11143       : FD(FD), CE(CE) { }
11144 
11145     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11146       if (!FD) {
11147         S.Diag(Loc, diag::err_call_incomplete_return)
11148           << T << CE->getSourceRange();
11149         return;
11150       }
11151 
11152       S.Diag(Loc, diag::err_call_function_incomplete_return)
11153         << CE->getSourceRange() << FD->getDeclName() << T;
11154       S.Diag(FD->getLocation(),
11155              diag::note_function_with_incomplete_return_type_declared_here)
11156         << FD->getDeclName();
11157     }
11158   } Diagnoser(FD, CE);
11159 
11160   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
11161     return true;
11162 
11163   return false;
11164 }
11165 
11166 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
11167 // will prevent this condition from triggering, which is what we want.
11168 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11169   SourceLocation Loc;
11170 
11171   unsigned diagnostic = diag::warn_condition_is_assignment;
11172   bool IsOrAssign = false;
11173 
11174   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
11175     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
11176       return;
11177 
11178     IsOrAssign = Op->getOpcode() == BO_OrAssign;
11179 
11180     // Greylist some idioms by putting them into a warning subcategory.
11181     if (ObjCMessageExpr *ME
11182           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11183       Selector Sel = ME->getSelector();
11184 
11185       // self = [<foo> init...]
11186       if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
11187         diagnostic = diag::warn_condition_is_idiomatic_assignment;
11188 
11189       // <foo> = [<bar> nextObject]
11190       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
11191         diagnostic = diag::warn_condition_is_idiomatic_assignment;
11192     }
11193 
11194     Loc = Op->getOperatorLoc();
11195   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
11196     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
11197       return;
11198 
11199     IsOrAssign = Op->getOperator() == OO_PipeEqual;
11200     Loc = Op->getOperatorLoc();
11201   } else {
11202     // Not an assignment.
11203     return;
11204   }
11205 
11206   Diag(Loc, diagnostic) << E->getSourceRange();
11207 
11208   SourceLocation Open = E->getLocStart();
11209   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11210   Diag(Loc, diag::note_condition_assign_silence)
11211         << FixItHint::CreateInsertion(Open, "(")
11212         << FixItHint::CreateInsertion(Close, ")");
11213 
11214   if (IsOrAssign)
11215     Diag(Loc, diag::note_condition_or_assign_to_comparison)
11216       << FixItHint::CreateReplacement(Loc, "!=");
11217   else
11218     Diag(Loc, diag::note_condition_assign_to_comparison)
11219       << FixItHint::CreateReplacement(Loc, "==");
11220 }
11221 
11222 /// \brief Redundant parentheses over an equality comparison can indicate
11223 /// that the user intended an assignment used as condition.
11224 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
11225   // Don't warn if the parens came from a macro.
11226   SourceLocation parenLoc = ParenE->getLocStart();
11227   if (parenLoc.isInvalid() || parenLoc.isMacroID())
11228     return;
11229   // Don't warn for dependent expressions.
11230   if (ParenE->isTypeDependent())
11231     return;
11232 
11233   Expr *E = ParenE->IgnoreParens();
11234 
11235   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
11236     if (opE->getOpcode() == BO_EQ &&
11237         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11238                                                            == Expr::MLV_Valid) {
11239       SourceLocation Loc = opE->getOperatorLoc();
11240 
11241       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
11242       SourceRange ParenERange = ParenE->getSourceRange();
11243       Diag(Loc, diag::note_equality_comparison_silence)
11244         << FixItHint::CreateRemoval(ParenERange.getBegin())
11245         << FixItHint::CreateRemoval(ParenERange.getEnd());
11246       Diag(Loc, diag::note_equality_comparison_to_assign)
11247         << FixItHint::CreateReplacement(Loc, "=");
11248     }
11249 }
11250 
11251 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
11252   DiagnoseAssignmentAsCondition(E);
11253   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11254     DiagnoseEqualityWithExtraParens(parenE);
11255 
11256   ExprResult result = CheckPlaceholderExpr(E);
11257   if (result.isInvalid()) return ExprError();
11258   E = result.take();
11259 
11260   if (!E->isTypeDependent()) {
11261     if (getLangOpts().CPlusPlus)
11262       return CheckCXXBooleanCondition(E); // C++ 6.4p4
11263 
11264     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11265     if (ERes.isInvalid())
11266       return ExprError();
11267     E = ERes.take();
11268 
11269     QualType T = E->getType();
11270     if (!T->isScalarType()) { // C99 6.8.4.1p1
11271       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11272         << T << E->getSourceRange();
11273       return ExprError();
11274     }
11275   }
11276 
11277   return Owned(E);
11278 }
11279 
11280 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
11281                                        Expr *SubExpr) {
11282   if (!SubExpr)
11283     return ExprError();
11284 
11285   return CheckBooleanCondition(SubExpr, Loc);
11286 }
11287 
11288 namespace {
11289   /// A visitor for rebuilding a call to an __unknown_any expression
11290   /// to have an appropriate type.
11291   struct RebuildUnknownAnyFunction
11292     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11293 
11294     Sema &S;
11295 
11296     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11297 
11298     ExprResult VisitStmt(Stmt *S) {
11299       llvm_unreachable("unexpected statement!");
11300     }
11301 
11302     ExprResult VisitExpr(Expr *E) {
11303       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11304         << E->getSourceRange();
11305       return ExprError();
11306     }
11307 
11308     /// Rebuild an expression which simply semantically wraps another
11309     /// expression which it shares the type and value kind of.
11310     template <class T> ExprResult rebuildSugarExpr(T *E) {
11311       ExprResult SubResult = Visit(E->getSubExpr());
11312       if (SubResult.isInvalid()) return ExprError();
11313 
11314       Expr *SubExpr = SubResult.take();
11315       E->setSubExpr(SubExpr);
11316       E->setType(SubExpr->getType());
11317       E->setValueKind(SubExpr->getValueKind());
11318       assert(E->getObjectKind() == OK_Ordinary);
11319       return E;
11320     }
11321 
11322     ExprResult VisitParenExpr(ParenExpr *E) {
11323       return rebuildSugarExpr(E);
11324     }
11325 
11326     ExprResult VisitUnaryExtension(UnaryOperator *E) {
11327       return rebuildSugarExpr(E);
11328     }
11329 
11330     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11331       ExprResult SubResult = Visit(E->getSubExpr());
11332       if (SubResult.isInvalid()) return ExprError();
11333 
11334       Expr *SubExpr = SubResult.take();
11335       E->setSubExpr(SubExpr);
11336       E->setType(S.Context.getPointerType(SubExpr->getType()));
11337       assert(E->getValueKind() == VK_RValue);
11338       assert(E->getObjectKind() == OK_Ordinary);
11339       return E;
11340     }
11341 
11342     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11343       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
11344 
11345       E->setType(VD->getType());
11346 
11347       assert(E->getValueKind() == VK_RValue);
11348       if (S.getLangOpts().CPlusPlus &&
11349           !(isa<CXXMethodDecl>(VD) &&
11350             cast<CXXMethodDecl>(VD)->isInstance()))
11351         E->setValueKind(VK_LValue);
11352 
11353       return E;
11354     }
11355 
11356     ExprResult VisitMemberExpr(MemberExpr *E) {
11357       return resolveDecl(E, E->getMemberDecl());
11358     }
11359 
11360     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11361       return resolveDecl(E, E->getDecl());
11362     }
11363   };
11364 }
11365 
11366 /// Given a function expression of unknown-any type, try to rebuild it
11367 /// to have a function type.
11368 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11369   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11370   if (Result.isInvalid()) return ExprError();
11371   return S.DefaultFunctionArrayConversion(Result.take());
11372 }
11373 
11374 namespace {
11375   /// A visitor for rebuilding an expression of type __unknown_anytype
11376   /// into one which resolves the type directly on the referring
11377   /// expression.  Strict preservation of the original source
11378   /// structure is not a goal.
11379   struct RebuildUnknownAnyExpr
11380     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
11381 
11382     Sema &S;
11383 
11384     /// The current destination type.
11385     QualType DestType;
11386 
11387     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11388       : S(S), DestType(CastType) {}
11389 
11390     ExprResult VisitStmt(Stmt *S) {
11391       llvm_unreachable("unexpected statement!");
11392     }
11393 
11394     ExprResult VisitExpr(Expr *E) {
11395       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11396         << E->getSourceRange();
11397       return ExprError();
11398     }
11399 
11400     ExprResult VisitCallExpr(CallExpr *E);
11401     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
11402 
11403     /// Rebuild an expression which simply semantically wraps another
11404     /// expression which it shares the type and value kind of.
11405     template <class T> ExprResult rebuildSugarExpr(T *E) {
11406       ExprResult SubResult = Visit(E->getSubExpr());
11407       if (SubResult.isInvalid()) return ExprError();
11408       Expr *SubExpr = SubResult.take();
11409       E->setSubExpr(SubExpr);
11410       E->setType(SubExpr->getType());
11411       E->setValueKind(SubExpr->getValueKind());
11412       assert(E->getObjectKind() == OK_Ordinary);
11413       return E;
11414     }
11415 
11416     ExprResult VisitParenExpr(ParenExpr *E) {
11417       return rebuildSugarExpr(E);
11418     }
11419 
11420     ExprResult VisitUnaryExtension(UnaryOperator *E) {
11421       return rebuildSugarExpr(E);
11422     }
11423 
11424     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11425       const PointerType *Ptr = DestType->getAs<PointerType>();
11426       if (!Ptr) {
11427         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11428           << E->getSourceRange();
11429         return ExprError();
11430       }
11431       assert(E->getValueKind() == VK_RValue);
11432       assert(E->getObjectKind() == OK_Ordinary);
11433       E->setType(DestType);
11434 
11435       // Build the sub-expression as if it were an object of the pointee type.
11436       DestType = Ptr->getPointeeType();
11437       ExprResult SubResult = Visit(E->getSubExpr());
11438       if (SubResult.isInvalid()) return ExprError();
11439       E->setSubExpr(SubResult.take());
11440       return E;
11441     }
11442 
11443     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
11444 
11445     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
11446 
11447     ExprResult VisitMemberExpr(MemberExpr *E) {
11448       return resolveDecl(E, E->getMemberDecl());
11449     }
11450 
11451     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11452       return resolveDecl(E, E->getDecl());
11453     }
11454   };
11455 }
11456 
11457 /// Rebuilds a call expression which yielded __unknown_anytype.
11458 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11459   Expr *CalleeExpr = E->getCallee();
11460 
11461   enum FnKind {
11462     FK_MemberFunction,
11463     FK_FunctionPointer,
11464     FK_BlockPointer
11465   };
11466 
11467   FnKind Kind;
11468   QualType CalleeType = CalleeExpr->getType();
11469   if (CalleeType == S.Context.BoundMemberTy) {
11470     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11471     Kind = FK_MemberFunction;
11472     CalleeType = Expr::findBoundMemberType(CalleeExpr);
11473   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11474     CalleeType = Ptr->getPointeeType();
11475     Kind = FK_FunctionPointer;
11476   } else {
11477     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11478     Kind = FK_BlockPointer;
11479   }
11480   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
11481 
11482   // Verify that this is a legal result type of a function.
11483   if (DestType->isArrayType() || DestType->isFunctionType()) {
11484     unsigned diagID = diag::err_func_returning_array_function;
11485     if (Kind == FK_BlockPointer)
11486       diagID = diag::err_block_returning_array_function;
11487 
11488     S.Diag(E->getExprLoc(), diagID)
11489       << DestType->isFunctionType() << DestType;
11490     return ExprError();
11491   }
11492 
11493   // Otherwise, go ahead and set DestType as the call's result.
11494   E->setType(DestType.getNonLValueExprType(S.Context));
11495   E->setValueKind(Expr::getValueKindForType(DestType));
11496   assert(E->getObjectKind() == OK_Ordinary);
11497 
11498   // Rebuild the function type, replacing the result type with DestType.
11499   if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
11500     DestType = S.Context.getFunctionType(DestType,
11501                                          Proto->arg_type_begin(),
11502                                          Proto->getNumArgs(),
11503                                          Proto->getExtProtoInfo());
11504   else
11505     DestType = S.Context.getFunctionNoProtoType(DestType,
11506                                                 FnType->getExtInfo());
11507 
11508   // Rebuild the appropriate pointer-to-function type.
11509   switch (Kind) {
11510   case FK_MemberFunction:
11511     // Nothing to do.
11512     break;
11513 
11514   case FK_FunctionPointer:
11515     DestType = S.Context.getPointerType(DestType);
11516     break;
11517 
11518   case FK_BlockPointer:
11519     DestType = S.Context.getBlockPointerType(DestType);
11520     break;
11521   }
11522 
11523   // Finally, we can recurse.
11524   ExprResult CalleeResult = Visit(CalleeExpr);
11525   if (!CalleeResult.isUsable()) return ExprError();
11526   E->setCallee(CalleeResult.take());
11527 
11528   // Bind a temporary if necessary.
11529   return S.MaybeBindToTemporary(E);
11530 }
11531 
11532 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
11533   // Verify that this is a legal result type of a call.
11534   if (DestType->isArrayType() || DestType->isFunctionType()) {
11535     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
11536       << DestType->isFunctionType() << DestType;
11537     return ExprError();
11538   }
11539 
11540   // Rewrite the method result type if available.
11541   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11542     assert(Method->getResultType() == S.Context.UnknownAnyTy);
11543     Method->setResultType(DestType);
11544   }
11545 
11546   // Change the type of the message.
11547   E->setType(DestType.getNonReferenceType());
11548   E->setValueKind(Expr::getValueKindForType(DestType));
11549 
11550   return S.MaybeBindToTemporary(E);
11551 }
11552 
11553 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
11554   // The only case we should ever see here is a function-to-pointer decay.
11555   if (E->getCastKind() == CK_FunctionToPointerDecay) {
11556     assert(E->getValueKind() == VK_RValue);
11557     assert(E->getObjectKind() == OK_Ordinary);
11558 
11559     E->setType(DestType);
11560 
11561     // Rebuild the sub-expression as the pointee (function) type.
11562     DestType = DestType->castAs<PointerType>()->getPointeeType();
11563 
11564     ExprResult Result = Visit(E->getSubExpr());
11565     if (!Result.isUsable()) return ExprError();
11566 
11567     E->setSubExpr(Result.take());
11568     return S.Owned(E);
11569   } else if (E->getCastKind() == CK_LValueToRValue) {
11570     assert(E->getValueKind() == VK_RValue);
11571     assert(E->getObjectKind() == OK_Ordinary);
11572 
11573     assert(isa<BlockPointerType>(E->getType()));
11574 
11575     E->setType(DestType);
11576 
11577     // The sub-expression has to be a lvalue reference, so rebuild it as such.
11578     DestType = S.Context.getLValueReferenceType(DestType);
11579 
11580     ExprResult Result = Visit(E->getSubExpr());
11581     if (!Result.isUsable()) return ExprError();
11582 
11583     E->setSubExpr(Result.take());
11584     return S.Owned(E);
11585   } else {
11586     llvm_unreachable("Unhandled cast type!");
11587   }
11588 }
11589 
11590 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11591   ExprValueKind ValueKind = VK_LValue;
11592   QualType Type = DestType;
11593 
11594   // We know how to make this work for certain kinds of decls:
11595 
11596   //  - functions
11597   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11598     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11599       DestType = Ptr->getPointeeType();
11600       ExprResult Result = resolveDecl(E, VD);
11601       if (Result.isInvalid()) return ExprError();
11602       return S.ImpCastExprToType(Result.take(), Type,
11603                                  CK_FunctionToPointerDecay, VK_RValue);
11604     }
11605 
11606     if (!Type->isFunctionType()) {
11607       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11608         << VD << E->getSourceRange();
11609       return ExprError();
11610     }
11611 
11612     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11613       if (MD->isInstance()) {
11614         ValueKind = VK_RValue;
11615         Type = S.Context.BoundMemberTy;
11616       }
11617 
11618     // Function references aren't l-values in C.
11619     if (!S.getLangOpts().CPlusPlus)
11620       ValueKind = VK_RValue;
11621 
11622   //  - variables
11623   } else if (isa<VarDecl>(VD)) {
11624     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11625       Type = RefTy->getPointeeType();
11626     } else if (Type->isFunctionType()) {
11627       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11628         << VD << E->getSourceRange();
11629       return ExprError();
11630     }
11631 
11632   //  - nothing else
11633   } else {
11634     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11635       << VD << E->getSourceRange();
11636     return ExprError();
11637   }
11638 
11639   VD->setType(DestType);
11640   E->setType(Type);
11641   E->setValueKind(ValueKind);
11642   return S.Owned(E);
11643 }
11644 
11645 /// Check a cast of an unknown-any type.  We intentionally only
11646 /// trigger this for C-style casts.
11647 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11648                                      Expr *CastExpr, CastKind &CastKind,
11649                                      ExprValueKind &VK, CXXCastPath &Path) {
11650   // Rewrite the casted expression from scratch.
11651   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
11652   if (!result.isUsable()) return ExprError();
11653 
11654   CastExpr = result.take();
11655   VK = CastExpr->getValueKind();
11656   CastKind = CK_NoOp;
11657 
11658   return CastExpr;
11659 }
11660 
11661 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11662   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11663 }
11664 
11665 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11666   Expr *orig = E;
11667   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
11668   while (true) {
11669     E = E->IgnoreParenImpCasts();
11670     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11671       E = call->getCallee();
11672       diagID = diag::err_uncasted_call_of_unknown_any;
11673     } else {
11674       break;
11675     }
11676   }
11677 
11678   SourceLocation loc;
11679   NamedDecl *d;
11680   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
11681     loc = ref->getLocation();
11682     d = ref->getDecl();
11683   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
11684     loc = mem->getMemberLoc();
11685     d = mem->getMemberDecl();
11686   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
11687     diagID = diag::err_uncasted_call_of_unknown_any;
11688     loc = msg->getSelectorStartLoc();
11689     d = msg->getMethodDecl();
11690     if (!d) {
11691       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11692         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11693         << orig->getSourceRange();
11694       return ExprError();
11695     }
11696   } else {
11697     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11698       << E->getSourceRange();
11699     return ExprError();
11700   }
11701 
11702   S.Diag(loc, diagID) << d << orig->getSourceRange();
11703 
11704   // Never recoverable.
11705   return ExprError();
11706 }
11707 
11708 /// Check for operands with placeholder types and complain if found.
11709 /// Returns true if there was an error and no recovery was possible.
11710 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
11711   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11712   if (!placeholderType) return Owned(E);
11713 
11714   switch (placeholderType->getKind()) {
11715 
11716   // Overloaded expressions.
11717   case BuiltinType::Overload: {
11718     // Try to resolve a single function template specialization.
11719     // This is obligatory.
11720     ExprResult result = Owned(E);
11721     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11722       return result;
11723 
11724     // If that failed, try to recover with a call.
11725     } else {
11726       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11727                            /*complain*/ true);
11728       return result;
11729     }
11730   }
11731 
11732   // Bound member functions.
11733   case BuiltinType::BoundMember: {
11734     ExprResult result = Owned(E);
11735     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11736                          /*complain*/ true);
11737     return result;
11738   }
11739 
11740   // ARC unbridged casts.
11741   case BuiltinType::ARCUnbridgedCast: {
11742     Expr *realCast = stripARCUnbridgedCast(E);
11743     diagnoseARCUnbridgedCast(realCast);
11744     return Owned(realCast);
11745   }
11746 
11747   // Expressions of unknown type.
11748   case BuiltinType::UnknownAny:
11749     return diagnoseUnknownAnyExpr(*this, E);
11750 
11751   // Pseudo-objects.
11752   case BuiltinType::PseudoObject:
11753     return checkPseudoObjectRValue(E);
11754 
11755   // Everything else should be impossible.
11756 #define BUILTIN_TYPE(Id, SingletonId) \
11757   case BuiltinType::Id:
11758 #define PLACEHOLDER_TYPE(Id, SingletonId)
11759 #include "clang/AST/BuiltinTypes.def"
11760     break;
11761   }
11762 
11763   llvm_unreachable("invalid placeholder type!");
11764 }
11765 
11766 bool Sema::CheckCaseExpression(Expr *E) {
11767   if (E->isTypeDependent())
11768     return true;
11769   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11770     return E->getType()->isIntegralOrEnumerationType();
11771   return false;
11772 }
11773 
11774 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11775 ExprResult
11776 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11777   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11778          "Unknown Objective-C Boolean value!");
11779   return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
11780                                         Context.ObjCBuiltinBoolTy, OpLoc));
11781 }
11782