1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "TreeTransform.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/ASTMutationListener.h"
20 #include "clang/AST/CXXInheritance.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/Template.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     // If the function has a deduced return type, and we can't deduce it,
61     // then we can't use it either.
62     if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() &&
63         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/false))
64       return false;
65   }
66 
67   // See if this function is unavailable.
68   if (D->getAvailability() == AR_Unavailable &&
69       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
70     return false;
71 
72   return true;
73 }
74 
75 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
76   // Warn if this is used but marked unused.
77   if (D->hasAttr<UnusedAttr>()) {
78     const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
79     if (!DC->hasAttr<UnusedAttr>())
80       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
81   }
82 }
83 
84 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
85                               NamedDecl *D, SourceLocation Loc,
86                               const ObjCInterfaceDecl *UnknownObjCClass) {
87   // See if this declaration is unavailable or deprecated.
88   std::string Message;
89   AvailabilityResult Result = D->getAvailability(&Message);
90   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
91     if (Result == AR_Available) {
92       const DeclContext *DC = ECD->getDeclContext();
93       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
94         Result = TheEnumDecl->getAvailability(&Message);
95     }
96 
97   const ObjCPropertyDecl *ObjCPDecl = 0;
98   if (Result == AR_Deprecated || Result == AR_Unavailable) {
99     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
100       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
101         AvailabilityResult PDeclResult = PD->getAvailability(0);
102         if (PDeclResult == Result)
103           ObjCPDecl = PD;
104       }
105     }
106   }
107 
108   switch (Result) {
109     case AR_Available:
110     case AR_NotYetIntroduced:
111       break;
112 
113     case AR_Deprecated:
114       if (S.getCurContextAvailability() != AR_Deprecated)
115         S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
116       break;
117 
118     case AR_Unavailable:
119       if (S.getCurContextAvailability() != AR_Unavailable) {
120         if (Message.empty()) {
121           if (!UnknownObjCClass) {
122             S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
123             if (ObjCPDecl)
124               S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
125                 << ObjCPDecl->getDeclName() << 1;
126           }
127           else
128             S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
129               << D->getDeclName();
130         }
131         else
132           S.Diag(Loc, diag::err_unavailable_message)
133             << D->getDeclName() << Message;
134         S.Diag(D->getLocation(), diag::note_unavailable_here)
135                   << isa<FunctionDecl>(D) << false;
136         if (ObjCPDecl)
137           S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
138           << ObjCPDecl->getDeclName() << 1;
139       }
140       break;
141     }
142     return Result;
143 }
144 
145 /// \brief Emit a note explaining that this function is deleted.
146 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
147   assert(Decl->isDeleted());
148 
149   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
150 
151   if (Method && Method->isDeleted() && Method->isDefaulted()) {
152     // If the method was explicitly defaulted, point at that declaration.
153     if (!Method->isImplicit())
154       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
155 
156     // Try to diagnose why this special member function was implicitly
157     // deleted. This might fail, if that reason no longer applies.
158     CXXSpecialMember CSM = getSpecialMember(Method);
159     if (CSM != CXXInvalid)
160       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
161 
162     return;
163   }
164 
165   if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
166     if (CXXConstructorDecl *BaseCD =
167             const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
168       Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
169       if (BaseCD->isDeleted()) {
170         NoteDeletedFunction(BaseCD);
171       } else {
172         // FIXME: An explanation of why exactly it can't be inherited
173         // would be nice.
174         Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
175       }
176       return;
177     }
178   }
179 
180   Diag(Decl->getLocation(), diag::note_unavailable_here)
181     << 1 << true;
182 }
183 
184 /// \brief Determine whether a FunctionDecl was ever declared with an
185 /// explicit storage class.
186 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
187   for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
188                                      E = D->redecls_end();
189        I != E; ++I) {
190     if (I->getStorageClass() != SC_None)
191       return true;
192   }
193   return false;
194 }
195 
196 /// \brief Check whether we're in an extern inline function and referring to a
197 /// variable or function with internal linkage (C11 6.7.4p3).
198 ///
199 /// This is only a warning because we used to silently accept this code, but
200 /// in many cases it will not behave correctly. This is not enabled in C++ mode
201 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
202 /// and so while there may still be user mistakes, most of the time we can't
203 /// prove that there are errors.
204 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
205                                                       const NamedDecl *D,
206                                                       SourceLocation Loc) {
207   // This is disabled under C++; there are too many ways for this to fire in
208   // contexts where the warning is a false positive, or where it is technically
209   // correct but benign.
210   if (S.getLangOpts().CPlusPlus)
211     return;
212 
213   // Check if this is an inlined function or method.
214   FunctionDecl *Current = S.getCurFunctionDecl();
215   if (!Current)
216     return;
217   if (!Current->isInlined())
218     return;
219   if (!Current->isExternallyVisible())
220     return;
221 
222   // Check if the decl has internal linkage.
223   if (D->getFormalLinkage() != InternalLinkage)
224     return;
225 
226   // Downgrade from ExtWarn to Extension if
227   //  (1) the supposedly external inline function is in the main file,
228   //      and probably won't be included anywhere else.
229   //  (2) the thing we're referencing is a pure function.
230   //  (3) the thing we're referencing is another inline function.
231   // This last can give us false negatives, but it's better than warning on
232   // wrappers for simple C library functions.
233   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
234   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
235   if (!DowngradeWarning && UsedFn)
236     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
237 
238   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
239                                : diag::warn_internal_in_extern_inline)
240     << /*IsVar=*/!UsedFn << D;
241 
242   S.MaybeSuggestAddingStaticToDecl(Current);
243 
244   S.Diag(D->getCanonicalDecl()->getLocation(),
245          diag::note_internal_decl_declared_here)
246     << D;
247 }
248 
249 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
250   const FunctionDecl *First = Cur->getFirstDecl();
251 
252   // Suggest "static" on the function, if possible.
253   if (!hasAnyExplicitStorageClass(First)) {
254     SourceLocation DeclBegin = First->getSourceRange().getBegin();
255     Diag(DeclBegin, diag::note_convert_inline_to_static)
256       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
257   }
258 }
259 
260 /// \brief Determine whether the use of this declaration is valid, and
261 /// emit any corresponding diagnostics.
262 ///
263 /// This routine diagnoses various problems with referencing
264 /// declarations that can occur when using a declaration. For example,
265 /// it might warn if a deprecated or unavailable declaration is being
266 /// used, or produce an error (and return true) if a C++0x deleted
267 /// function is being used.
268 ///
269 /// \returns true if there was an error (this declaration cannot be
270 /// referenced), false otherwise.
271 ///
272 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
273                              const ObjCInterfaceDecl *UnknownObjCClass) {
274   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
275     // If there were any diagnostics suppressed by template argument deduction,
276     // emit them now.
277     SuppressedDiagnosticsMap::iterator
278       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
279     if (Pos != SuppressedDiagnostics.end()) {
280       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
281       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
282         Diag(Suppressed[I].first, Suppressed[I].second);
283 
284       // Clear out the list of suppressed diagnostics, so that we don't emit
285       // them again for this specialization. However, we don't obsolete this
286       // entry from the table, because we want to avoid ever emitting these
287       // diagnostics again.
288       Suppressed.clear();
289     }
290   }
291 
292   // See if this is an auto-typed variable whose initializer we are parsing.
293   if (ParsingInitForAutoVars.count(D)) {
294     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
295       << D->getDeclName();
296     return true;
297   }
298 
299   // See if this is a deleted function.
300   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
301     if (FD->isDeleted()) {
302       Diag(Loc, diag::err_deleted_function_use);
303       NoteDeletedFunction(FD);
304       return true;
305     }
306 
307     // If the function has a deduced return type, and we can't deduce it,
308     // then we can't use it either.
309     if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() &&
310         DeduceReturnType(FD, Loc))
311       return true;
312   }
313   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
314 
315   DiagnoseUnusedOfDecl(*this, D, Loc);
316 
317   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
318 
319   return false;
320 }
321 
322 /// \brief Retrieve the message suffix that should be added to a
323 /// diagnostic complaining about the given function being deleted or
324 /// unavailable.
325 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
326   std::string Message;
327   if (FD->getAvailability(&Message))
328     return ": " + Message;
329 
330   return std::string();
331 }
332 
333 /// DiagnoseSentinelCalls - This routine checks whether a call or
334 /// message-send is to a declaration with the sentinel attribute, and
335 /// if so, it checks that the requirements of the sentinel are
336 /// satisfied.
337 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
338                                  ArrayRef<Expr *> Args) {
339   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
340   if (!attr)
341     return;
342 
343   // The number of formal parameters of the declaration.
344   unsigned numFormalParams;
345 
346   // The kind of declaration.  This is also an index into a %select in
347   // the diagnostic.
348   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
349 
350   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
351     numFormalParams = MD->param_size();
352     calleeType = CT_Method;
353   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
354     numFormalParams = FD->param_size();
355     calleeType = CT_Function;
356   } else if (isa<VarDecl>(D)) {
357     QualType type = cast<ValueDecl>(D)->getType();
358     const FunctionType *fn = 0;
359     if (const PointerType *ptr = type->getAs<PointerType>()) {
360       fn = ptr->getPointeeType()->getAs<FunctionType>();
361       if (!fn) return;
362       calleeType = CT_Function;
363     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
364       fn = ptr->getPointeeType()->castAs<FunctionType>();
365       calleeType = CT_Block;
366     } else {
367       return;
368     }
369 
370     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
371       numFormalParams = proto->getNumArgs();
372     } else {
373       numFormalParams = 0;
374     }
375   } else {
376     return;
377   }
378 
379   // "nullPos" is the number of formal parameters at the end which
380   // effectively count as part of the variadic arguments.  This is
381   // useful if you would prefer to not have *any* formal parameters,
382   // but the language forces you to have at least one.
383   unsigned nullPos = attr->getNullPos();
384   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
385   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
386 
387   // The number of arguments which should follow the sentinel.
388   unsigned numArgsAfterSentinel = attr->getSentinel();
389 
390   // If there aren't enough arguments for all the formal parameters,
391   // the sentinel, and the args after the sentinel, complain.
392   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
393     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
394     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
395     return;
396   }
397 
398   // Otherwise, find the sentinel expression.
399   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
400   if (!sentinelExpr) return;
401   if (sentinelExpr->isValueDependent()) return;
402   if (Context.isSentinelNullExpr(sentinelExpr)) return;
403 
404   // Pick a reasonable string to insert.  Optimistically use 'nil' or
405   // 'NULL' if those are actually defined in the context.  Only use
406   // 'nil' for ObjC methods, where it's much more likely that the
407   // variadic arguments form a list of object pointers.
408   SourceLocation MissingNilLoc
409     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
410   std::string NullValue;
411   if (calleeType == CT_Method &&
412       PP.getIdentifierInfo("nil")->hasMacroDefinition())
413     NullValue = "nil";
414   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
415     NullValue = "NULL";
416   else
417     NullValue = "(void*) 0";
418 
419   if (MissingNilLoc.isInvalid())
420     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
421   else
422     Diag(MissingNilLoc, diag::warn_missing_sentinel)
423       << int(calleeType)
424       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
425   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
426 }
427 
428 SourceRange Sema::getExprRange(Expr *E) const {
429   return E ? E->getSourceRange() : SourceRange();
430 }
431 
432 //===----------------------------------------------------------------------===//
433 //  Standard Promotions and Conversions
434 //===----------------------------------------------------------------------===//
435 
436 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
437 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
438   // Handle any placeholder expressions which made it here.
439   if (E->getType()->isPlaceholderType()) {
440     ExprResult result = CheckPlaceholderExpr(E);
441     if (result.isInvalid()) return ExprError();
442     E = result.take();
443   }
444 
445   QualType Ty = E->getType();
446   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
447 
448   if (Ty->isFunctionType())
449     E = ImpCastExprToType(E, Context.getPointerType(Ty),
450                           CK_FunctionToPointerDecay).take();
451   else if (Ty->isArrayType()) {
452     // In C90 mode, arrays only promote to pointers if the array expression is
453     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
454     // type 'array of type' is converted to an expression that has type 'pointer
455     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
456     // that has type 'array of type' ...".  The relevant change is "an lvalue"
457     // (C90) to "an expression" (C99).
458     //
459     // C++ 4.2p1:
460     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
461     // T" can be converted to an rvalue of type "pointer to T".
462     //
463     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
464       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
465                             CK_ArrayToPointerDecay).take();
466   }
467   return Owned(E);
468 }
469 
470 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
471   // Check to see if we are dereferencing a null pointer.  If so,
472   // and if not volatile-qualified, this is undefined behavior that the
473   // optimizer will delete, so warn about it.  People sometimes try to use this
474   // to get a deterministic trap and are surprised by clang's behavior.  This
475   // only handles the pattern "*null", which is a very syntactic check.
476   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
477     if (UO->getOpcode() == UO_Deref &&
478         UO->getSubExpr()->IgnoreParenCasts()->
479           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
480         !UO->getType().isVolatileQualified()) {
481     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
482                           S.PDiag(diag::warn_indirection_through_null)
483                             << UO->getSubExpr()->getSourceRange());
484     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
485                         S.PDiag(diag::note_indirection_through_null));
486   }
487 }
488 
489 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
490                                     SourceLocation AssignLoc,
491                                     const Expr* RHS) {
492   const ObjCIvarDecl *IV = OIRE->getDecl();
493   if (!IV)
494     return;
495 
496   DeclarationName MemberName = IV->getDeclName();
497   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
498   if (!Member || !Member->isStr("isa"))
499     return;
500 
501   const Expr *Base = OIRE->getBase();
502   QualType BaseType = Base->getType();
503   if (OIRE->isArrow())
504     BaseType = BaseType->getPointeeType();
505   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
506     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
507       ObjCInterfaceDecl *ClassDeclared = 0;
508       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
509       if (!ClassDeclared->getSuperClass()
510           && (*ClassDeclared->ivar_begin()) == IV) {
511         if (RHS) {
512           NamedDecl *ObjectSetClass =
513             S.LookupSingleName(S.TUScope,
514                                &S.Context.Idents.get("object_setClass"),
515                                SourceLocation(), S.LookupOrdinaryName);
516           if (ObjectSetClass) {
517             SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
518             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
519             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
520             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
521                                                      AssignLoc), ",") <<
522             FixItHint::CreateInsertion(RHSLocEnd, ")");
523           }
524           else
525             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
526         } else {
527           NamedDecl *ObjectGetClass =
528             S.LookupSingleName(S.TUScope,
529                                &S.Context.Idents.get("object_getClass"),
530                                SourceLocation(), S.LookupOrdinaryName);
531           if (ObjectGetClass)
532             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
533             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
534             FixItHint::CreateReplacement(
535                                          SourceRange(OIRE->getOpLoc(),
536                                                      OIRE->getLocEnd()), ")");
537           else
538             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
539         }
540         S.Diag(IV->getLocation(), diag::note_ivar_decl);
541       }
542     }
543 }
544 
545 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
546   // Handle any placeholder expressions which made it here.
547   if (E->getType()->isPlaceholderType()) {
548     ExprResult result = CheckPlaceholderExpr(E);
549     if (result.isInvalid()) return ExprError();
550     E = result.take();
551   }
552 
553   // C++ [conv.lval]p1:
554   //   A glvalue of a non-function, non-array type T can be
555   //   converted to a prvalue.
556   if (!E->isGLValue()) return Owned(E);
557 
558   QualType T = E->getType();
559   assert(!T.isNull() && "r-value conversion on typeless expression?");
560 
561   // We don't want to throw lvalue-to-rvalue casts on top of
562   // expressions of certain types in C++.
563   if (getLangOpts().CPlusPlus &&
564       (E->getType() == Context.OverloadTy ||
565        T->isDependentType() ||
566        T->isRecordType()))
567     return Owned(E);
568 
569   // The C standard is actually really unclear on this point, and
570   // DR106 tells us what the result should be but not why.  It's
571   // generally best to say that void types just doesn't undergo
572   // lvalue-to-rvalue at all.  Note that expressions of unqualified
573   // 'void' type are never l-values, but qualified void can be.
574   if (T->isVoidType())
575     return Owned(E);
576 
577   // OpenCL usually rejects direct accesses to values of 'half' type.
578   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
579       T->isHalfType()) {
580     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
581       << 0 << T;
582     return ExprError();
583   }
584 
585   CheckForNullPointerDereference(*this, E);
586   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
587     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
588                                      &Context.Idents.get("object_getClass"),
589                                      SourceLocation(), LookupOrdinaryName);
590     if (ObjectGetClass)
591       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
592         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
593         FixItHint::CreateReplacement(
594                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
595     else
596       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
597   }
598   else if (const ObjCIvarRefExpr *OIRE =
599             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
600     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0);
601 
602   // C++ [conv.lval]p1:
603   //   [...] If T is a non-class type, the type of the prvalue is the
604   //   cv-unqualified version of T. Otherwise, the type of the
605   //   rvalue is T.
606   //
607   // C99 6.3.2.1p2:
608   //   If the lvalue has qualified type, the value has the unqualified
609   //   version of the type of the lvalue; otherwise, the value has the
610   //   type of the lvalue.
611   if (T.hasQualifiers())
612     T = T.getUnqualifiedType();
613 
614   UpdateMarkingForLValueToRValue(E);
615 
616   // Loading a __weak object implicitly retains the value, so we need a cleanup to
617   // balance that.
618   if (getLangOpts().ObjCAutoRefCount &&
619       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
620     ExprNeedsCleanups = true;
621 
622   ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
623                                                   E, 0, VK_RValue));
624 
625   // C11 6.3.2.1p2:
626   //   ... if the lvalue has atomic type, the value has the non-atomic version
627   //   of the type of the lvalue ...
628   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
629     T = Atomic->getValueType().getUnqualifiedType();
630     Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
631                                          Res.get(), 0, VK_RValue));
632   }
633 
634   return Res;
635 }
636 
637 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
638   ExprResult Res = DefaultFunctionArrayConversion(E);
639   if (Res.isInvalid())
640     return ExprError();
641   Res = DefaultLvalueConversion(Res.take());
642   if (Res.isInvalid())
643     return ExprError();
644   return Res;
645 }
646 
647 
648 /// UsualUnaryConversions - Performs various conversions that are common to most
649 /// operators (C99 6.3). The conversions of array and function types are
650 /// sometimes suppressed. For example, the array->pointer conversion doesn't
651 /// apply if the array is an argument to the sizeof or address (&) operators.
652 /// In these instances, this routine should *not* be called.
653 ExprResult Sema::UsualUnaryConversions(Expr *E) {
654   // First, convert to an r-value.
655   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
656   if (Res.isInvalid())
657     return ExprError();
658   E = Res.take();
659 
660   QualType Ty = E->getType();
661   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
662 
663   // Half FP have to be promoted to float unless it is natively supported
664   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
665     return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
666 
667   // Try to perform integral promotions if the object has a theoretically
668   // promotable type.
669   if (Ty->isIntegralOrUnscopedEnumerationType()) {
670     // C99 6.3.1.1p2:
671     //
672     //   The following may be used in an expression wherever an int or
673     //   unsigned int may be used:
674     //     - an object or expression with an integer type whose integer
675     //       conversion rank is less than or equal to the rank of int
676     //       and unsigned int.
677     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
678     //
679     //   If an int can represent all values of the original type, the
680     //   value is converted to an int; otherwise, it is converted to an
681     //   unsigned int. These are called the integer promotions. All
682     //   other types are unchanged by the integer promotions.
683 
684     QualType PTy = Context.isPromotableBitField(E);
685     if (!PTy.isNull()) {
686       E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
687       return Owned(E);
688     }
689     if (Ty->isPromotableIntegerType()) {
690       QualType PT = Context.getPromotedIntegerType(Ty);
691       E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
692       return Owned(E);
693     }
694   }
695   return Owned(E);
696 }
697 
698 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
699 /// do not have a prototype. Arguments that have type float or __fp16
700 /// are promoted to double. All other argument types are converted by
701 /// UsualUnaryConversions().
702 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
703   QualType Ty = E->getType();
704   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
705 
706   ExprResult Res = UsualUnaryConversions(E);
707   if (Res.isInvalid())
708     return ExprError();
709   E = Res.take();
710 
711   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
712   // double.
713   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
714   if (BTy && (BTy->getKind() == BuiltinType::Half ||
715               BTy->getKind() == BuiltinType::Float))
716     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
717 
718   // C++ performs lvalue-to-rvalue conversion as a default argument
719   // promotion, even on class types, but note:
720   //   C++11 [conv.lval]p2:
721   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
722   //     operand or a subexpression thereof the value contained in the
723   //     referenced object is not accessed. Otherwise, if the glvalue
724   //     has a class type, the conversion copy-initializes a temporary
725   //     of type T from the glvalue and the result of the conversion
726   //     is a prvalue for the temporary.
727   // FIXME: add some way to gate this entire thing for correctness in
728   // potentially potentially evaluated contexts.
729   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
730     ExprResult Temp = PerformCopyInitialization(
731                        InitializedEntity::InitializeTemporary(E->getType()),
732                                                 E->getExprLoc(),
733                                                 Owned(E));
734     if (Temp.isInvalid())
735       return ExprError();
736     E = Temp.get();
737   }
738 
739   return Owned(E);
740 }
741 
742 /// Determine the degree of POD-ness for an expression.
743 /// Incomplete types are considered POD, since this check can be performed
744 /// when we're in an unevaluated context.
745 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
746   if (Ty->isIncompleteType()) {
747     // C++11 [expr.call]p7:
748     //   After these conversions, if the argument does not have arithmetic,
749     //   enumeration, pointer, pointer to member, or class type, the program
750     //   is ill-formed.
751     //
752     // Since we've already performed array-to-pointer and function-to-pointer
753     // decay, the only such type in C++ is cv void. This also handles
754     // initializer lists as variadic arguments.
755     if (Ty->isVoidType())
756       return VAK_Invalid;
757 
758     if (Ty->isObjCObjectType())
759       return VAK_Invalid;
760     return VAK_Valid;
761   }
762 
763   if (Ty.isCXX98PODType(Context))
764     return VAK_Valid;
765 
766   // C++11 [expr.call]p7:
767   //   Passing a potentially-evaluated argument of class type (Clause 9)
768   //   having a non-trivial copy constructor, a non-trivial move constructor,
769   //   or a non-trivial destructor, with no corresponding parameter,
770   //   is conditionally-supported with implementation-defined semantics.
771   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
772     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
773       if (!Record->hasNonTrivialCopyConstructor() &&
774           !Record->hasNonTrivialMoveConstructor() &&
775           !Record->hasNonTrivialDestructor())
776         return VAK_ValidInCXX11;
777 
778   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
779     return VAK_Valid;
780 
781   if (Ty->isObjCObjectType())
782     return VAK_Invalid;
783 
784   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
785   // permitted to reject them. We should consider doing so.
786   return VAK_Undefined;
787 }
788 
789 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
790   // Don't allow one to pass an Objective-C interface to a vararg.
791   const QualType &Ty = E->getType();
792   VarArgKind VAK = isValidVarArgType(Ty);
793 
794   // Complain about passing non-POD types through varargs.
795   switch (VAK) {
796   case VAK_Valid:
797     break;
798 
799   case VAK_ValidInCXX11:
800     DiagRuntimeBehavior(
801         E->getLocStart(), 0,
802         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
803           << E->getType() << CT);
804     break;
805 
806   case VAK_Undefined:
807     DiagRuntimeBehavior(
808         E->getLocStart(), 0,
809         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
810           << getLangOpts().CPlusPlus11 << Ty << CT);
811     break;
812 
813   case VAK_Invalid:
814     if (Ty->isObjCObjectType())
815       DiagRuntimeBehavior(
816           E->getLocStart(), 0,
817           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
818             << Ty << CT);
819     else
820       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
821         << isa<InitListExpr>(E) << Ty << CT;
822     break;
823   }
824 }
825 
826 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
827 /// will create a trap if the resulting type is not a POD type.
828 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
829                                                   FunctionDecl *FDecl) {
830   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
831     // Strip the unbridged-cast placeholder expression off, if applicable.
832     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
833         (CT == VariadicMethod ||
834          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
835       E = stripARCUnbridgedCast(E);
836 
837     // Otherwise, do normal placeholder checking.
838     } else {
839       ExprResult ExprRes = CheckPlaceholderExpr(E);
840       if (ExprRes.isInvalid())
841         return ExprError();
842       E = ExprRes.take();
843     }
844   }
845 
846   ExprResult ExprRes = DefaultArgumentPromotion(E);
847   if (ExprRes.isInvalid())
848     return ExprError();
849   E = ExprRes.take();
850 
851   // Diagnostics regarding non-POD argument types are
852   // emitted along with format string checking in Sema::CheckFunctionCall().
853   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
854     // Turn this into a trap.
855     CXXScopeSpec SS;
856     SourceLocation TemplateKWLoc;
857     UnqualifiedId Name;
858     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
859                        E->getLocStart());
860     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
861                                           Name, true, false);
862     if (TrapFn.isInvalid())
863       return ExprError();
864 
865     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
866                                     E->getLocStart(), None,
867                                     E->getLocEnd());
868     if (Call.isInvalid())
869       return ExprError();
870 
871     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
872                                   Call.get(), E);
873     if (Comma.isInvalid())
874       return ExprError();
875     return Comma.get();
876   }
877 
878   if (!getLangOpts().CPlusPlus &&
879       RequireCompleteType(E->getExprLoc(), E->getType(),
880                           diag::err_call_incomplete_argument))
881     return ExprError();
882 
883   return Owned(E);
884 }
885 
886 /// \brief Converts an integer to complex float type.  Helper function of
887 /// UsualArithmeticConversions()
888 ///
889 /// \return false if the integer expression is an integer type and is
890 /// successfully converted to the complex type.
891 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
892                                                   ExprResult &ComplexExpr,
893                                                   QualType IntTy,
894                                                   QualType ComplexTy,
895                                                   bool SkipCast) {
896   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
897   if (SkipCast) return false;
898   if (IntTy->isIntegerType()) {
899     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
900     IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
901     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
902                                   CK_FloatingRealToComplex);
903   } else {
904     assert(IntTy->isComplexIntegerType());
905     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
906                                   CK_IntegralComplexToFloatingComplex);
907   }
908   return false;
909 }
910 
911 /// \brief Takes two complex float types and converts them to the same type.
912 /// Helper function of UsualArithmeticConversions()
913 static QualType
914 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
915                                             ExprResult &RHS, QualType LHSType,
916                                             QualType RHSType,
917                                             bool IsCompAssign) {
918   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
919 
920   if (order < 0) {
921     // _Complex float -> _Complex double
922     if (!IsCompAssign)
923       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
924     return RHSType;
925   }
926   if (order > 0)
927     // _Complex float -> _Complex double
928     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
929   return LHSType;
930 }
931 
932 /// \brief Converts otherExpr to complex float and promotes complexExpr if
933 /// necessary.  Helper function of UsualArithmeticConversions()
934 static QualType handleOtherComplexFloatConversion(Sema &S,
935                                                   ExprResult &ComplexExpr,
936                                                   ExprResult &OtherExpr,
937                                                   QualType ComplexTy,
938                                                   QualType OtherTy,
939                                                   bool ConvertComplexExpr,
940                                                   bool ConvertOtherExpr) {
941   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
942 
943   // If just the complexExpr is complex, the otherExpr needs to be converted,
944   // and the complexExpr might need to be promoted.
945   if (order > 0) { // complexExpr is wider
946     // float -> _Complex double
947     if (ConvertOtherExpr) {
948       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
949       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
950       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
951                                       CK_FloatingRealToComplex);
952     }
953     return ComplexTy;
954   }
955 
956   // otherTy is at least as wide.  Find its corresponding complex type.
957   QualType result = (order == 0 ? ComplexTy :
958                                   S.Context.getComplexType(OtherTy));
959 
960   // double -> _Complex double
961   if (ConvertOtherExpr)
962     OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
963                                     CK_FloatingRealToComplex);
964 
965   // _Complex float -> _Complex double
966   if (ConvertComplexExpr && order < 0)
967     ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
968                                       CK_FloatingComplexCast);
969 
970   return result;
971 }
972 
973 /// \brief Handle arithmetic conversion with complex types.  Helper function of
974 /// UsualArithmeticConversions()
975 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
976                                              ExprResult &RHS, QualType LHSType,
977                                              QualType RHSType,
978                                              bool IsCompAssign) {
979   // if we have an integer operand, the result is the complex type.
980   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
981                                              /*skipCast*/false))
982     return LHSType;
983   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
984                                              /*skipCast*/IsCompAssign))
985     return RHSType;
986 
987   // This handles complex/complex, complex/float, or float/complex.
988   // When both operands are complex, the shorter operand is converted to the
989   // type of the longer, and that is the type of the result. This corresponds
990   // to what is done when combining two real floating-point operands.
991   // The fun begins when size promotion occur across type domains.
992   // From H&S 6.3.4: When one operand is complex and the other is a real
993   // floating-point type, the less precise type is converted, within it's
994   // real or complex domain, to the precision of the other type. For example,
995   // when combining a "long double" with a "double _Complex", the
996   // "double _Complex" is promoted to "long double _Complex".
997 
998   bool LHSComplexFloat = LHSType->isComplexType();
999   bool RHSComplexFloat = RHSType->isComplexType();
1000 
1001   // If both are complex, just cast to the more precise type.
1002   if (LHSComplexFloat && RHSComplexFloat)
1003     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
1004                                                        LHSType, RHSType,
1005                                                        IsCompAssign);
1006 
1007   // If only one operand is complex, promote it if necessary and convert the
1008   // other operand to complex.
1009   if (LHSComplexFloat)
1010     return handleOtherComplexFloatConversion(
1011         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
1012         /*convertOtherExpr*/ true);
1013 
1014   assert(RHSComplexFloat);
1015   return handleOtherComplexFloatConversion(
1016       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
1017       /*convertOtherExpr*/ !IsCompAssign);
1018 }
1019 
1020 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1021 /// of UsualArithmeticConversions()
1022 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1023                                            ExprResult &IntExpr,
1024                                            QualType FloatTy, QualType IntTy,
1025                                            bool ConvertFloat, bool ConvertInt) {
1026   if (IntTy->isIntegerType()) {
1027     if (ConvertInt)
1028       // Convert intExpr to the lhs floating point type.
1029       IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
1030                                     CK_IntegralToFloating);
1031     return FloatTy;
1032   }
1033 
1034   // Convert both sides to the appropriate complex float.
1035   assert(IntTy->isComplexIntegerType());
1036   QualType result = S.Context.getComplexType(FloatTy);
1037 
1038   // _Complex int -> _Complex float
1039   if (ConvertInt)
1040     IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
1041                                   CK_IntegralComplexToFloatingComplex);
1042 
1043   // float -> _Complex float
1044   if (ConvertFloat)
1045     FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
1046                                     CK_FloatingRealToComplex);
1047 
1048   return result;
1049 }
1050 
1051 /// \brief Handle arithmethic conversion with floating point types.  Helper
1052 /// function of UsualArithmeticConversions()
1053 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1054                                       ExprResult &RHS, QualType LHSType,
1055                                       QualType RHSType, bool IsCompAssign) {
1056   bool LHSFloat = LHSType->isRealFloatingType();
1057   bool RHSFloat = RHSType->isRealFloatingType();
1058 
1059   // If we have two real floating types, convert the smaller operand
1060   // to the bigger result.
1061   if (LHSFloat && RHSFloat) {
1062     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1063     if (order > 0) {
1064       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
1065       return LHSType;
1066     }
1067 
1068     assert(order < 0 && "illegal float comparison");
1069     if (!IsCompAssign)
1070       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
1071     return RHSType;
1072   }
1073 
1074   if (LHSFloat)
1075     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1076                                       /*convertFloat=*/!IsCompAssign,
1077                                       /*convertInt=*/ true);
1078   assert(RHSFloat);
1079   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1080                                     /*convertInt=*/ true,
1081                                     /*convertFloat=*/!IsCompAssign);
1082 }
1083 
1084 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1085 
1086 namespace {
1087 /// These helper callbacks are placed in an anonymous namespace to
1088 /// permit their use as function template parameters.
1089 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1090   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1091 }
1092 
1093 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1094   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1095                              CK_IntegralComplexCast);
1096 }
1097 }
1098 
1099 /// \brief Handle integer arithmetic conversions.  Helper function of
1100 /// UsualArithmeticConversions()
1101 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1102 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1103                                         ExprResult &RHS, QualType LHSType,
1104                                         QualType RHSType, bool IsCompAssign) {
1105   // The rules for this case are in C99 6.3.1.8
1106   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1107   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1108   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1109   if (LHSSigned == RHSSigned) {
1110     // Same signedness; use the higher-ranked type
1111     if (order >= 0) {
1112       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1113       return LHSType;
1114     } else if (!IsCompAssign)
1115       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1116     return RHSType;
1117   } else if (order != (LHSSigned ? 1 : -1)) {
1118     // The unsigned type has greater than or equal rank to the
1119     // signed type, so use the unsigned type
1120     if (RHSSigned) {
1121       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1122       return LHSType;
1123     } else if (!IsCompAssign)
1124       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1125     return RHSType;
1126   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1127     // The two types are different widths; if we are here, that
1128     // means the signed type is larger than the unsigned type, so
1129     // use the signed type.
1130     if (LHSSigned) {
1131       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1132       return LHSType;
1133     } else if (!IsCompAssign)
1134       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1135     return RHSType;
1136   } else {
1137     // The signed type is higher-ranked than the unsigned type,
1138     // but isn't actually any bigger (like unsigned int and long
1139     // on most 32-bit systems).  Use the unsigned type corresponding
1140     // to the signed type.
1141     QualType result =
1142       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1143     RHS = (*doRHSCast)(S, RHS.take(), result);
1144     if (!IsCompAssign)
1145       LHS = (*doLHSCast)(S, LHS.take(), result);
1146     return result;
1147   }
1148 }
1149 
1150 /// \brief Handle conversions with GCC complex int extension.  Helper function
1151 /// of UsualArithmeticConversions()
1152 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1153                                            ExprResult &RHS, QualType LHSType,
1154                                            QualType RHSType,
1155                                            bool IsCompAssign) {
1156   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1157   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1158 
1159   if (LHSComplexInt && RHSComplexInt) {
1160     QualType LHSEltType = LHSComplexInt->getElementType();
1161     QualType RHSEltType = RHSComplexInt->getElementType();
1162     QualType ScalarType =
1163       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1164         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1165 
1166     return S.Context.getComplexType(ScalarType);
1167   }
1168 
1169   if (LHSComplexInt) {
1170     QualType LHSEltType = LHSComplexInt->getElementType();
1171     QualType ScalarType =
1172       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1173         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1174     QualType ComplexType = S.Context.getComplexType(ScalarType);
1175     RHS = S.ImpCastExprToType(RHS.take(), ComplexType,
1176                               CK_IntegralRealToComplex);
1177 
1178     return ComplexType;
1179   }
1180 
1181   assert(RHSComplexInt);
1182 
1183   QualType RHSEltType = RHSComplexInt->getElementType();
1184   QualType ScalarType =
1185     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1186       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1187   QualType ComplexType = S.Context.getComplexType(ScalarType);
1188 
1189   if (!IsCompAssign)
1190     LHS = S.ImpCastExprToType(LHS.take(), ComplexType,
1191                               CK_IntegralRealToComplex);
1192   return ComplexType;
1193 }
1194 
1195 /// UsualArithmeticConversions - Performs various conversions that are common to
1196 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1197 /// routine returns the first non-arithmetic type found. The client is
1198 /// responsible for emitting appropriate error diagnostics.
1199 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1200                                           bool IsCompAssign) {
1201   if (!IsCompAssign) {
1202     LHS = UsualUnaryConversions(LHS.take());
1203     if (LHS.isInvalid())
1204       return QualType();
1205   }
1206 
1207   RHS = UsualUnaryConversions(RHS.take());
1208   if (RHS.isInvalid())
1209     return QualType();
1210 
1211   // For conversion purposes, we ignore any qualifiers.
1212   // For example, "const float" and "float" are equivalent.
1213   QualType LHSType =
1214     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1215   QualType RHSType =
1216     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1217 
1218   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1219   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1220     LHSType = AtomicLHS->getValueType();
1221 
1222   // If both types are identical, no conversion is needed.
1223   if (LHSType == RHSType)
1224     return LHSType;
1225 
1226   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1227   // The caller can deal with this (e.g. pointer + int).
1228   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1229     return QualType();
1230 
1231   // Apply unary and bitfield promotions to the LHS's type.
1232   QualType LHSUnpromotedType = LHSType;
1233   if (LHSType->isPromotableIntegerType())
1234     LHSType = Context.getPromotedIntegerType(LHSType);
1235   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1236   if (!LHSBitfieldPromoteTy.isNull())
1237     LHSType = LHSBitfieldPromoteTy;
1238   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1239     LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
1240 
1241   // If both types are identical, no conversion is needed.
1242   if (LHSType == RHSType)
1243     return LHSType;
1244 
1245   // At this point, we have two different arithmetic types.
1246 
1247   // Handle complex types first (C99 6.3.1.8p1).
1248   if (LHSType->isComplexType() || RHSType->isComplexType())
1249     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1250                                         IsCompAssign);
1251 
1252   // Now handle "real" floating types (i.e. float, double, long double).
1253   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1254     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1255                                  IsCompAssign);
1256 
1257   // Handle GCC complex int extension.
1258   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1259     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1260                                       IsCompAssign);
1261 
1262   // Finally, we have two differing integer types.
1263   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1264            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1265 }
1266 
1267 
1268 //===----------------------------------------------------------------------===//
1269 //  Semantic Analysis for various Expression Types
1270 //===----------------------------------------------------------------------===//
1271 
1272 
1273 ExprResult
1274 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1275                                 SourceLocation DefaultLoc,
1276                                 SourceLocation RParenLoc,
1277                                 Expr *ControllingExpr,
1278                                 ArrayRef<ParsedType> ArgTypes,
1279                                 ArrayRef<Expr *> ArgExprs) {
1280   unsigned NumAssocs = ArgTypes.size();
1281   assert(NumAssocs == ArgExprs.size());
1282 
1283   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1284   for (unsigned i = 0; i < NumAssocs; ++i) {
1285     if (ArgTypes[i])
1286       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1287     else
1288       Types[i] = 0;
1289   }
1290 
1291   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1292                                              ControllingExpr,
1293                                              llvm::makeArrayRef(Types, NumAssocs),
1294                                              ArgExprs);
1295   delete [] Types;
1296   return ER;
1297 }
1298 
1299 ExprResult
1300 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1301                                  SourceLocation DefaultLoc,
1302                                  SourceLocation RParenLoc,
1303                                  Expr *ControllingExpr,
1304                                  ArrayRef<TypeSourceInfo *> Types,
1305                                  ArrayRef<Expr *> Exprs) {
1306   unsigned NumAssocs = Types.size();
1307   assert(NumAssocs == Exprs.size());
1308   if (ControllingExpr->getType()->isPlaceholderType()) {
1309     ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1310     if (result.isInvalid()) return ExprError();
1311     ControllingExpr = result.take();
1312   }
1313 
1314   bool TypeErrorFound = false,
1315        IsResultDependent = ControllingExpr->isTypeDependent(),
1316        ContainsUnexpandedParameterPack
1317          = ControllingExpr->containsUnexpandedParameterPack();
1318 
1319   for (unsigned i = 0; i < NumAssocs; ++i) {
1320     if (Exprs[i]->containsUnexpandedParameterPack())
1321       ContainsUnexpandedParameterPack = true;
1322 
1323     if (Types[i]) {
1324       if (Types[i]->getType()->containsUnexpandedParameterPack())
1325         ContainsUnexpandedParameterPack = true;
1326 
1327       if (Types[i]->getType()->isDependentType()) {
1328         IsResultDependent = true;
1329       } else {
1330         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1331         // complete object type other than a variably modified type."
1332         unsigned D = 0;
1333         if (Types[i]->getType()->isIncompleteType())
1334           D = diag::err_assoc_type_incomplete;
1335         else if (!Types[i]->getType()->isObjectType())
1336           D = diag::err_assoc_type_nonobject;
1337         else if (Types[i]->getType()->isVariablyModifiedType())
1338           D = diag::err_assoc_type_variably_modified;
1339 
1340         if (D != 0) {
1341           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1342             << Types[i]->getTypeLoc().getSourceRange()
1343             << Types[i]->getType();
1344           TypeErrorFound = true;
1345         }
1346 
1347         // C11 6.5.1.1p2 "No two generic associations in the same generic
1348         // selection shall specify compatible types."
1349         for (unsigned j = i+1; j < NumAssocs; ++j)
1350           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1351               Context.typesAreCompatible(Types[i]->getType(),
1352                                          Types[j]->getType())) {
1353             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1354                  diag::err_assoc_compatible_types)
1355               << Types[j]->getTypeLoc().getSourceRange()
1356               << Types[j]->getType()
1357               << Types[i]->getType();
1358             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1359                  diag::note_compat_assoc)
1360               << Types[i]->getTypeLoc().getSourceRange()
1361               << Types[i]->getType();
1362             TypeErrorFound = true;
1363           }
1364       }
1365     }
1366   }
1367   if (TypeErrorFound)
1368     return ExprError();
1369 
1370   // If we determined that the generic selection is result-dependent, don't
1371   // try to compute the result expression.
1372   if (IsResultDependent)
1373     return Owned(new (Context) GenericSelectionExpr(
1374                    Context, KeyLoc, ControllingExpr,
1375                    Types, Exprs,
1376                    DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
1377 
1378   SmallVector<unsigned, 1> CompatIndices;
1379   unsigned DefaultIndex = -1U;
1380   for (unsigned i = 0; i < NumAssocs; ++i) {
1381     if (!Types[i])
1382       DefaultIndex = i;
1383     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1384                                         Types[i]->getType()))
1385       CompatIndices.push_back(i);
1386   }
1387 
1388   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1389   // type compatible with at most one of the types named in its generic
1390   // association list."
1391   if (CompatIndices.size() > 1) {
1392     // We strip parens here because the controlling expression is typically
1393     // parenthesized in macro definitions.
1394     ControllingExpr = ControllingExpr->IgnoreParens();
1395     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1396       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1397       << (unsigned) CompatIndices.size();
1398     for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
1399          E = CompatIndices.end(); I != E; ++I) {
1400       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1401            diag::note_compat_assoc)
1402         << Types[*I]->getTypeLoc().getSourceRange()
1403         << Types[*I]->getType();
1404     }
1405     return ExprError();
1406   }
1407 
1408   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1409   // its controlling expression shall have type compatible with exactly one of
1410   // the types named in its generic association list."
1411   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1412     // We strip parens here because the controlling expression is typically
1413     // parenthesized in macro definitions.
1414     ControllingExpr = ControllingExpr->IgnoreParens();
1415     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1416       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1417     return ExprError();
1418   }
1419 
1420   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1421   // type name that is compatible with the type of the controlling expression,
1422   // then the result expression of the generic selection is the expression
1423   // in that generic association. Otherwise, the result expression of the
1424   // generic selection is the expression in the default generic association."
1425   unsigned ResultIndex =
1426     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1427 
1428   return Owned(new (Context) GenericSelectionExpr(
1429                  Context, KeyLoc, ControllingExpr,
1430                  Types, Exprs,
1431                  DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
1432                  ResultIndex));
1433 }
1434 
1435 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1436 /// location of the token and the offset of the ud-suffix within it.
1437 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1438                                      unsigned Offset) {
1439   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1440                                         S.getLangOpts());
1441 }
1442 
1443 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1444 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1445 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1446                                                  IdentifierInfo *UDSuffix,
1447                                                  SourceLocation UDSuffixLoc,
1448                                                  ArrayRef<Expr*> Args,
1449                                                  SourceLocation LitEndLoc) {
1450   assert(Args.size() <= 2 && "too many arguments for literal operator");
1451 
1452   QualType ArgTy[2];
1453   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1454     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1455     if (ArgTy[ArgIdx]->isArrayType())
1456       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1457   }
1458 
1459   DeclarationName OpName =
1460     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1461   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1462   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1463 
1464   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1465   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1466                               /*AllowRaw*/false, /*AllowTemplate*/false,
1467                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1468     return ExprError();
1469 
1470   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1471 }
1472 
1473 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1474 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1475 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1476 /// multiple tokens.  However, the common case is that StringToks points to one
1477 /// string.
1478 ///
1479 ExprResult
1480 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1481                          Scope *UDLScope) {
1482   assert(NumStringToks && "Must have at least one string!");
1483 
1484   StringLiteralParser Literal(StringToks, NumStringToks, PP);
1485   if (Literal.hadError)
1486     return ExprError();
1487 
1488   SmallVector<SourceLocation, 4> StringTokLocs;
1489   for (unsigned i = 0; i != NumStringToks; ++i)
1490     StringTokLocs.push_back(StringToks[i].getLocation());
1491 
1492   QualType CharTy = Context.CharTy;
1493   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1494   if (Literal.isWide()) {
1495     CharTy = Context.getWideCharType();
1496     Kind = StringLiteral::Wide;
1497   } else if (Literal.isUTF8()) {
1498     Kind = StringLiteral::UTF8;
1499   } else if (Literal.isUTF16()) {
1500     CharTy = Context.Char16Ty;
1501     Kind = StringLiteral::UTF16;
1502   } else if (Literal.isUTF32()) {
1503     CharTy = Context.Char32Ty;
1504     Kind = StringLiteral::UTF32;
1505   } else if (Literal.isPascal()) {
1506     CharTy = Context.UnsignedCharTy;
1507   }
1508 
1509   QualType CharTyConst = CharTy;
1510   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1511   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1512     CharTyConst.addConst();
1513 
1514   // Get an array type for the string, according to C99 6.4.5.  This includes
1515   // the nul terminator character as well as the string length for pascal
1516   // strings.
1517   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1518                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1519                                  ArrayType::Normal, 0);
1520 
1521   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1522   if (getLangOpts().OpenCL) {
1523     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1524   }
1525 
1526   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1527   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1528                                              Kind, Literal.Pascal, StrTy,
1529                                              &StringTokLocs[0],
1530                                              StringTokLocs.size());
1531   if (Literal.getUDSuffix().empty())
1532     return Owned(Lit);
1533 
1534   // We're building a user-defined literal.
1535   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1536   SourceLocation UDSuffixLoc =
1537     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1538                    Literal.getUDSuffixOffset());
1539 
1540   // Make sure we're allowed user-defined literals here.
1541   if (!UDLScope)
1542     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1543 
1544   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1545   //   operator "" X (str, len)
1546   QualType SizeType = Context.getSizeType();
1547 
1548   DeclarationName OpName =
1549     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1550   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1551   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1552 
1553   QualType ArgTy[] = {
1554     Context.getArrayDecayedType(StrTy), SizeType
1555   };
1556 
1557   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1558   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1559                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1560                                 /*AllowStringTemplate*/true)) {
1561 
1562   case LOLR_Cooked: {
1563     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1564     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1565                                                     StringTokLocs[0]);
1566     Expr *Args[] = { Lit, LenArg };
1567 
1568     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1569   }
1570 
1571   case LOLR_StringTemplate: {
1572     TemplateArgumentListInfo ExplicitArgs;
1573 
1574     unsigned CharBits = Context.getIntWidth(CharTy);
1575     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1576     llvm::APSInt Value(CharBits, CharIsUnsigned);
1577 
1578     TemplateArgument TypeArg(CharTy);
1579     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1580     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1581 
1582     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1583       Value = Lit->getCodeUnit(I);
1584       TemplateArgument Arg(Context, Value, CharTy);
1585       TemplateArgumentLocInfo ArgInfo;
1586       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1587     }
1588     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1589                                     &ExplicitArgs);
1590   }
1591   case LOLR_Raw:
1592   case LOLR_Template:
1593     llvm_unreachable("unexpected literal operator lookup result");
1594   case LOLR_Error:
1595     return ExprError();
1596   }
1597   llvm_unreachable("unexpected literal operator lookup result");
1598 }
1599 
1600 ExprResult
1601 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1602                        SourceLocation Loc,
1603                        const CXXScopeSpec *SS) {
1604   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1605   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1606 }
1607 
1608 /// BuildDeclRefExpr - Build an expression that references a
1609 /// declaration that does not require a closure capture.
1610 ExprResult
1611 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1612                        const DeclarationNameInfo &NameInfo,
1613                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1614                        const TemplateArgumentListInfo *TemplateArgs) {
1615   if (getLangOpts().CUDA)
1616     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1617       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1618         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1619                            CalleeTarget = IdentifyCUDATarget(Callee);
1620         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1621           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1622             << CalleeTarget << D->getIdentifier() << CallerTarget;
1623           Diag(D->getLocation(), diag::note_previous_decl)
1624             << D->getIdentifier();
1625           return ExprError();
1626         }
1627       }
1628 
1629   bool refersToEnclosingScope =
1630     (CurContext != D->getDeclContext() &&
1631      D->getDeclContext()->isFunctionOrMethod()) ||
1632     (isa<VarDecl>(D) &&
1633      cast<VarDecl>(D)->isInitCapture());
1634 
1635   DeclRefExpr *E;
1636   if (isa<VarTemplateSpecializationDecl>(D)) {
1637     VarTemplateSpecializationDecl *VarSpec =
1638         cast<VarTemplateSpecializationDecl>(D);
1639 
1640     E = DeclRefExpr::Create(
1641         Context,
1642         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1643         VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope,
1644         NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs);
1645   } else {
1646     assert(!TemplateArgs && "No template arguments for non-variable"
1647                             " template specialization references");
1648     E = DeclRefExpr::Create(
1649         Context,
1650         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1651         SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD);
1652   }
1653 
1654   MarkDeclRefReferenced(E);
1655 
1656   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1657       Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1658     DiagnosticsEngine::Level Level =
1659       Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1660                                E->getLocStart());
1661     if (Level != DiagnosticsEngine::Ignored)
1662       recordUseOfEvaluatedWeak(E);
1663   }
1664 
1665   // Just in case we're building an illegal pointer-to-member.
1666   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1667   if (FD && FD->isBitField())
1668     E->setObjectKind(OK_BitField);
1669 
1670   return Owned(E);
1671 }
1672 
1673 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1674 /// possibly a list of template arguments.
1675 ///
1676 /// If this produces template arguments, it is permitted to call
1677 /// DecomposeTemplateName.
1678 ///
1679 /// This actually loses a lot of source location information for
1680 /// non-standard name kinds; we should consider preserving that in
1681 /// some way.
1682 void
1683 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1684                              TemplateArgumentListInfo &Buffer,
1685                              DeclarationNameInfo &NameInfo,
1686                              const TemplateArgumentListInfo *&TemplateArgs) {
1687   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1688     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1689     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1690 
1691     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1692                                        Id.TemplateId->NumArgs);
1693     translateTemplateArguments(TemplateArgsPtr, Buffer);
1694 
1695     TemplateName TName = Id.TemplateId->Template.get();
1696     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1697     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1698     TemplateArgs = &Buffer;
1699   } else {
1700     NameInfo = GetNameFromUnqualifiedId(Id);
1701     TemplateArgs = 0;
1702   }
1703 }
1704 
1705 /// Diagnose an empty lookup.
1706 ///
1707 /// \return false if new lookup candidates were found
1708 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1709                                CorrectionCandidateCallback &CCC,
1710                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1711                                ArrayRef<Expr *> Args) {
1712   DeclarationName Name = R.getLookupName();
1713 
1714   unsigned diagnostic = diag::err_undeclared_var_use;
1715   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1716   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1717       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1718       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1719     diagnostic = diag::err_undeclared_use;
1720     diagnostic_suggest = diag::err_undeclared_use_suggest;
1721   }
1722 
1723   // If the original lookup was an unqualified lookup, fake an
1724   // unqualified lookup.  This is useful when (for example) the
1725   // original lookup would not have found something because it was a
1726   // dependent name.
1727   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1728     ? CurContext : 0;
1729   while (DC) {
1730     if (isa<CXXRecordDecl>(DC)) {
1731       LookupQualifiedName(R, DC);
1732 
1733       if (!R.empty()) {
1734         // Don't give errors about ambiguities in this lookup.
1735         R.suppressDiagnostics();
1736 
1737         // During a default argument instantiation the CurContext points
1738         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1739         // function parameter list, hence add an explicit check.
1740         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1741                               ActiveTemplateInstantiations.back().Kind ==
1742             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1743         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1744         bool isInstance = CurMethod &&
1745                           CurMethod->isInstance() &&
1746                           DC == CurMethod->getParent() && !isDefaultArgument;
1747 
1748 
1749         // Give a code modification hint to insert 'this->'.
1750         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1751         // Actually quite difficult!
1752         if (getLangOpts().MicrosoftMode)
1753           diagnostic = diag::warn_found_via_dependent_bases_lookup;
1754         if (isInstance) {
1755           Diag(R.getNameLoc(), diagnostic) << Name
1756             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1757           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1758               CallsUndergoingInstantiation.back()->getCallee());
1759 
1760           CXXMethodDecl *DepMethod;
1761           if (CurMethod->isDependentContext())
1762             DepMethod = CurMethod;
1763           else if (CurMethod->getTemplatedKind() ==
1764               FunctionDecl::TK_FunctionTemplateSpecialization)
1765             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1766                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1767           else
1768             DepMethod = cast<CXXMethodDecl>(
1769                 CurMethod->getInstantiatedFromMemberFunction());
1770           assert(DepMethod && "No template pattern found");
1771 
1772           QualType DepThisType = DepMethod->getThisType(Context);
1773           CheckCXXThisCapture(R.getNameLoc());
1774           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1775                                      R.getNameLoc(), DepThisType, false);
1776           TemplateArgumentListInfo TList;
1777           if (ULE->hasExplicitTemplateArgs())
1778             ULE->copyTemplateArgumentsInto(TList);
1779 
1780           CXXScopeSpec SS;
1781           SS.Adopt(ULE->getQualifierLoc());
1782           CXXDependentScopeMemberExpr *DepExpr =
1783               CXXDependentScopeMemberExpr::Create(
1784                   Context, DepThis, DepThisType, true, SourceLocation(),
1785                   SS.getWithLocInContext(Context),
1786                   ULE->getTemplateKeywordLoc(), 0,
1787                   R.getLookupNameInfo(),
1788                   ULE->hasExplicitTemplateArgs() ? &TList : 0);
1789           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1790         } else {
1791           Diag(R.getNameLoc(), diagnostic) << Name;
1792         }
1793 
1794         // Do we really want to note all of these?
1795         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1796           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1797 
1798         // Return true if we are inside a default argument instantiation
1799         // and the found name refers to an instance member function, otherwise
1800         // the function calling DiagnoseEmptyLookup will try to create an
1801         // implicit member call and this is wrong for default argument.
1802         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1803           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1804           return true;
1805         }
1806 
1807         // Tell the callee to try to recover.
1808         return false;
1809       }
1810 
1811       R.clear();
1812     }
1813 
1814     // In Microsoft mode, if we are performing lookup from within a friend
1815     // function definition declared at class scope then we must set
1816     // DC to the lexical parent to be able to search into the parent
1817     // class.
1818     if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
1819         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1820         DC->getLexicalParent()->isRecord())
1821       DC = DC->getLexicalParent();
1822     else
1823       DC = DC->getParent();
1824   }
1825 
1826   // We didn't find anything, so try to correct for a typo.
1827   TypoCorrection Corrected;
1828   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1829                                     S, &SS, CCC))) {
1830     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1831     bool DroppedSpecifier =
1832         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1833     R.setLookupName(Corrected.getCorrection());
1834 
1835     bool AcceptableWithRecovery = false;
1836     bool AcceptableWithoutRecovery = false;
1837     NamedDecl *ND = Corrected.getCorrectionDecl();
1838     if (ND) {
1839       if (Corrected.isOverloaded()) {
1840         OverloadCandidateSet OCS(R.getNameLoc());
1841         OverloadCandidateSet::iterator Best;
1842         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1843                                         CDEnd = Corrected.end();
1844              CD != CDEnd; ++CD) {
1845           if (FunctionTemplateDecl *FTD =
1846                    dyn_cast<FunctionTemplateDecl>(*CD))
1847             AddTemplateOverloadCandidate(
1848                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1849                 Args, OCS);
1850           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1851             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1852               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1853                                    Args, OCS);
1854         }
1855         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1856         case OR_Success:
1857           ND = Best->Function;
1858           Corrected.setCorrectionDecl(ND);
1859           break;
1860         default:
1861           // FIXME: Arbitrarily pick the first declaration for the note.
1862           Corrected.setCorrectionDecl(ND);
1863           break;
1864         }
1865       }
1866       R.addDecl(ND);
1867 
1868       AcceptableWithRecovery =
1869           isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1870       // FIXME: If we ended up with a typo for a type name or
1871       // Objective-C class name, we're in trouble because the parser
1872       // is in the wrong place to recover. Suggest the typo
1873       // correction, but don't make it a fix-it since we're not going
1874       // to recover well anyway.
1875       AcceptableWithoutRecovery =
1876           isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1877     } else {
1878       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1879       // because we aren't able to recover.
1880       AcceptableWithoutRecovery = true;
1881     }
1882 
1883     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1884       unsigned NoteID = (Corrected.getCorrectionDecl() &&
1885                          isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1886                             ? diag::note_implicit_param_decl
1887                             : diag::note_previous_decl;
1888       if (SS.isEmpty())
1889         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1890                      PDiag(NoteID), AcceptableWithRecovery);
1891       else
1892         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1893                                   << Name << computeDeclContext(SS, false)
1894                                   << DroppedSpecifier << SS.getRange(),
1895                      PDiag(NoteID), AcceptableWithRecovery);
1896 
1897       // Tell the callee whether to try to recover.
1898       return !AcceptableWithRecovery;
1899     }
1900   }
1901   R.clear();
1902 
1903   // Emit a special diagnostic for failed member lookups.
1904   // FIXME: computing the declaration context might fail here (?)
1905   if (!SS.isEmpty()) {
1906     Diag(R.getNameLoc(), diag::err_no_member)
1907       << Name << computeDeclContext(SS, false)
1908       << SS.getRange();
1909     return true;
1910   }
1911 
1912   // Give up, we can't recover.
1913   Diag(R.getNameLoc(), diagnostic) << Name;
1914   return true;
1915 }
1916 
1917 ExprResult Sema::ActOnIdExpression(Scope *S,
1918                                    CXXScopeSpec &SS,
1919                                    SourceLocation TemplateKWLoc,
1920                                    UnqualifiedId &Id,
1921                                    bool HasTrailingLParen,
1922                                    bool IsAddressOfOperand,
1923                                    CorrectionCandidateCallback *CCC,
1924                                    bool IsInlineAsmIdentifier) {
1925   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1926          "cannot be direct & operand and have a trailing lparen");
1927   if (SS.isInvalid())
1928     return ExprError();
1929 
1930   TemplateArgumentListInfo TemplateArgsBuffer;
1931 
1932   // Decompose the UnqualifiedId into the following data.
1933   DeclarationNameInfo NameInfo;
1934   const TemplateArgumentListInfo *TemplateArgs;
1935   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1936 
1937   DeclarationName Name = NameInfo.getName();
1938   IdentifierInfo *II = Name.getAsIdentifierInfo();
1939   SourceLocation NameLoc = NameInfo.getLoc();
1940 
1941   // C++ [temp.dep.expr]p3:
1942   //   An id-expression is type-dependent if it contains:
1943   //     -- an identifier that was declared with a dependent type,
1944   //        (note: handled after lookup)
1945   //     -- a template-id that is dependent,
1946   //        (note: handled in BuildTemplateIdExpr)
1947   //     -- a conversion-function-id that specifies a dependent type,
1948   //     -- a nested-name-specifier that contains a class-name that
1949   //        names a dependent type.
1950   // Determine whether this is a member of an unknown specialization;
1951   // we need to handle these differently.
1952   bool DependentID = false;
1953   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1954       Name.getCXXNameType()->isDependentType()) {
1955     DependentID = true;
1956   } else if (SS.isSet()) {
1957     if (DeclContext *DC = computeDeclContext(SS, false)) {
1958       if (RequireCompleteDeclContext(SS, DC))
1959         return ExprError();
1960     } else {
1961       DependentID = true;
1962     }
1963   }
1964 
1965   if (DependentID)
1966     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1967                                       IsAddressOfOperand, TemplateArgs);
1968 
1969   // Perform the required lookup.
1970   LookupResult R(*this, NameInfo,
1971                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1972                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1973   if (TemplateArgs) {
1974     // Lookup the template name again to correctly establish the context in
1975     // which it was found. This is really unfortunate as we already did the
1976     // lookup to determine that it was a template name in the first place. If
1977     // this becomes a performance hit, we can work harder to preserve those
1978     // results until we get here but it's likely not worth it.
1979     bool MemberOfUnknownSpecialization;
1980     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1981                        MemberOfUnknownSpecialization);
1982 
1983     if (MemberOfUnknownSpecialization ||
1984         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1985       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1986                                         IsAddressOfOperand, TemplateArgs);
1987   } else {
1988     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
1989     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1990 
1991     // If the result might be in a dependent base class, this is a dependent
1992     // id-expression.
1993     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1994       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1995                                         IsAddressOfOperand, TemplateArgs);
1996 
1997     // If this reference is in an Objective-C method, then we need to do
1998     // some special Objective-C lookup, too.
1999     if (IvarLookupFollowUp) {
2000       ExprResult E(LookupInObjCMethod(R, S, II, true));
2001       if (E.isInvalid())
2002         return ExprError();
2003 
2004       if (Expr *Ex = E.takeAs<Expr>())
2005         return Owned(Ex);
2006     }
2007   }
2008 
2009   if (R.isAmbiguous())
2010     return ExprError();
2011 
2012   // Determine whether this name might be a candidate for
2013   // argument-dependent lookup.
2014   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2015 
2016   if (R.empty() && !ADL) {
2017 
2018     // Otherwise, this could be an implicitly declared function reference (legal
2019     // in C90, extension in C99, forbidden in C++).
2020     if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2021       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2022       if (D) R.addDecl(D);
2023     }
2024 
2025     // If this name wasn't predeclared and if this is not a function
2026     // call, diagnose the problem.
2027     if (R.empty()) {
2028       // In Microsoft mode, if we are inside a template class member function
2029       // whose parent class has dependent base classes, and we can't resolve
2030       // an identifier, then assume the identifier is a member of a dependent
2031       // base class.  The goal is to postpone name lookup to instantiation time
2032       // to be able to search into the type dependent base classes.
2033       // FIXME: If we want 100% compatibility with MSVC, we will have delay all
2034       // unqualified name lookup.  Any name lookup during template parsing means
2035       // clang might find something that MSVC doesn't.  For now, we only handle
2036       // the common case of members of a dependent base class.
2037       if (getLangOpts().MicrosoftMode) {
2038         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2039         if (MD && MD->isInstance() && MD->getParent()->hasAnyDependentBases()) {
2040           assert(SS.isEmpty() && "qualifiers should be already handled");
2041           QualType ThisType = MD->getThisType(Context);
2042           // Since the 'this' expression is synthesized, we don't need to
2043           // perform the double-lookup check.
2044           NamedDecl *FirstQualifierInScope = 0;
2045           return Owned(CXXDependentScopeMemberExpr::Create(
2046               Context, /*This=*/0, ThisType, /*IsArrow=*/true,
2047               /*Op=*/SourceLocation(), SS.getWithLocInContext(Context),
2048               TemplateKWLoc, FirstQualifierInScope, NameInfo, TemplateArgs));
2049         }
2050       }
2051 
2052       // Don't diagnose an empty lookup for inline assmebly.
2053       if (IsInlineAsmIdentifier)
2054         return ExprError();
2055 
2056       CorrectionCandidateCallback DefaultValidator;
2057       if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
2058         return ExprError();
2059 
2060       assert(!R.empty() &&
2061              "DiagnoseEmptyLookup returned false but added no results");
2062 
2063       // If we found an Objective-C instance variable, let
2064       // LookupInObjCMethod build the appropriate expression to
2065       // reference the ivar.
2066       if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2067         R.clear();
2068         ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2069         // In a hopelessly buggy code, Objective-C instance variable
2070         // lookup fails and no expression will be built to reference it.
2071         if (!E.isInvalid() && !E.get())
2072           return ExprError();
2073         return E;
2074       }
2075     }
2076   }
2077 
2078   // This is guaranteed from this point on.
2079   assert(!R.empty() || ADL);
2080 
2081   // Check whether this might be a C++ implicit instance member access.
2082   // C++ [class.mfct.non-static]p3:
2083   //   When an id-expression that is not part of a class member access
2084   //   syntax and not used to form a pointer to member is used in the
2085   //   body of a non-static member function of class X, if name lookup
2086   //   resolves the name in the id-expression to a non-static non-type
2087   //   member of some class C, the id-expression is transformed into a
2088   //   class member access expression using (*this) as the
2089   //   postfix-expression to the left of the . operator.
2090   //
2091   // But we don't actually need to do this for '&' operands if R
2092   // resolved to a function or overloaded function set, because the
2093   // expression is ill-formed if it actually works out to be a
2094   // non-static member function:
2095   //
2096   // C++ [expr.ref]p4:
2097   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2098   //   [t]he expression can be used only as the left-hand operand of a
2099   //   member function call.
2100   //
2101   // There are other safeguards against such uses, but it's important
2102   // to get this right here so that we don't end up making a
2103   // spuriously dependent expression if we're inside a dependent
2104   // instance method.
2105   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2106     bool MightBeImplicitMember;
2107     if (!IsAddressOfOperand)
2108       MightBeImplicitMember = true;
2109     else if (!SS.isEmpty())
2110       MightBeImplicitMember = false;
2111     else if (R.isOverloadedResult())
2112       MightBeImplicitMember = false;
2113     else if (R.isUnresolvableResult())
2114       MightBeImplicitMember = true;
2115     else
2116       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2117                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2118                               isa<MSPropertyDecl>(R.getFoundDecl());
2119 
2120     if (MightBeImplicitMember)
2121       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2122                                              R, TemplateArgs);
2123   }
2124 
2125   if (TemplateArgs || TemplateKWLoc.isValid()) {
2126 
2127     // In C++1y, if this is a variable template id, then check it
2128     // in BuildTemplateIdExpr().
2129     // The single lookup result must be a variable template declaration.
2130     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2131         Id.TemplateId->Kind == TNK_Var_template) {
2132       assert(R.getAsSingle<VarTemplateDecl>() &&
2133              "There should only be one declaration found.");
2134     }
2135 
2136     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2137   }
2138 
2139   return BuildDeclarationNameExpr(SS, R, ADL);
2140 }
2141 
2142 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2143 /// declaration name, generally during template instantiation.
2144 /// There's a large number of things which don't need to be done along
2145 /// this path.
2146 ExprResult
2147 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2148                                         const DeclarationNameInfo &NameInfo,
2149                                         bool IsAddressOfOperand) {
2150   DeclContext *DC = computeDeclContext(SS, false);
2151   if (!DC)
2152     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2153                                      NameInfo, /*TemplateArgs=*/0);
2154 
2155   if (RequireCompleteDeclContext(SS, DC))
2156     return ExprError();
2157 
2158   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2159   LookupQualifiedName(R, DC);
2160 
2161   if (R.isAmbiguous())
2162     return ExprError();
2163 
2164   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2165     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2166                                      NameInfo, /*TemplateArgs=*/0);
2167 
2168   if (R.empty()) {
2169     Diag(NameInfo.getLoc(), diag::err_no_member)
2170       << NameInfo.getName() << DC << SS.getRange();
2171     return ExprError();
2172   }
2173 
2174   // Defend against this resolving to an implicit member access. We usually
2175   // won't get here if this might be a legitimate a class member (we end up in
2176   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2177   // a pointer-to-member or in an unevaluated context in C++11.
2178   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2179     return BuildPossibleImplicitMemberExpr(SS,
2180                                            /*TemplateKWLoc=*/SourceLocation(),
2181                                            R, /*TemplateArgs=*/0);
2182 
2183   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2184 }
2185 
2186 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2187 /// detected that we're currently inside an ObjC method.  Perform some
2188 /// additional lookup.
2189 ///
2190 /// Ideally, most of this would be done by lookup, but there's
2191 /// actually quite a lot of extra work involved.
2192 ///
2193 /// Returns a null sentinel to indicate trivial success.
2194 ExprResult
2195 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2196                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2197   SourceLocation Loc = Lookup.getNameLoc();
2198   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2199 
2200   // Check for error condition which is already reported.
2201   if (!CurMethod)
2202     return ExprError();
2203 
2204   // There are two cases to handle here.  1) scoped lookup could have failed,
2205   // in which case we should look for an ivar.  2) scoped lookup could have
2206   // found a decl, but that decl is outside the current instance method (i.e.
2207   // a global variable).  In these two cases, we do a lookup for an ivar with
2208   // this name, if the lookup sucedes, we replace it our current decl.
2209 
2210   // If we're in a class method, we don't normally want to look for
2211   // ivars.  But if we don't find anything else, and there's an
2212   // ivar, that's an error.
2213   bool IsClassMethod = CurMethod->isClassMethod();
2214 
2215   bool LookForIvars;
2216   if (Lookup.empty())
2217     LookForIvars = true;
2218   else if (IsClassMethod)
2219     LookForIvars = false;
2220   else
2221     LookForIvars = (Lookup.isSingleResult() &&
2222                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2223   ObjCInterfaceDecl *IFace = 0;
2224   if (LookForIvars) {
2225     IFace = CurMethod->getClassInterface();
2226     ObjCInterfaceDecl *ClassDeclared;
2227     ObjCIvarDecl *IV = 0;
2228     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2229       // Diagnose using an ivar in a class method.
2230       if (IsClassMethod)
2231         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2232                          << IV->getDeclName());
2233 
2234       // If we're referencing an invalid decl, just return this as a silent
2235       // error node.  The error diagnostic was already emitted on the decl.
2236       if (IV->isInvalidDecl())
2237         return ExprError();
2238 
2239       // Check if referencing a field with __attribute__((deprecated)).
2240       if (DiagnoseUseOfDecl(IV, Loc))
2241         return ExprError();
2242 
2243       // Diagnose the use of an ivar outside of the declaring class.
2244       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2245           !declaresSameEntity(ClassDeclared, IFace) &&
2246           !getLangOpts().DebuggerSupport)
2247         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2248 
2249       // FIXME: This should use a new expr for a direct reference, don't
2250       // turn this into Self->ivar, just return a BareIVarExpr or something.
2251       IdentifierInfo &II = Context.Idents.get("self");
2252       UnqualifiedId SelfName;
2253       SelfName.setIdentifier(&II, SourceLocation());
2254       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2255       CXXScopeSpec SelfScopeSpec;
2256       SourceLocation TemplateKWLoc;
2257       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2258                                               SelfName, false, false);
2259       if (SelfExpr.isInvalid())
2260         return ExprError();
2261 
2262       SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2263       if (SelfExpr.isInvalid())
2264         return ExprError();
2265 
2266       MarkAnyDeclReferenced(Loc, IV, true);
2267       if (!IV->getBackingIvarReferencedInAccessor()) {
2268         // Mark this ivar 'referenced' in this method, if it is a backing ivar
2269         // of a property and current method is one of its property accessor.
2270         const ObjCPropertyDecl *PDecl;
2271         const ObjCIvarDecl *BIV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
2272         if (BIV && BIV == IV)
2273           IV->setBackingIvarReferencedInAccessor(true);
2274       }
2275 
2276       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2277       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2278           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2279         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2280 
2281       ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2282                                                               Loc, IV->getLocation(),
2283                                                               SelfExpr.take(),
2284                                                               true, true);
2285 
2286       if (getLangOpts().ObjCAutoRefCount) {
2287         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2288           DiagnosticsEngine::Level Level =
2289             Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2290           if (Level != DiagnosticsEngine::Ignored)
2291             recordUseOfEvaluatedWeak(Result);
2292         }
2293         if (CurContext->isClosure())
2294           Diag(Loc, diag::warn_implicitly_retains_self)
2295             << FixItHint::CreateInsertion(Loc, "self->");
2296       }
2297 
2298       return Owned(Result);
2299     }
2300   } else if (CurMethod->isInstanceMethod()) {
2301     // We should warn if a local variable hides an ivar.
2302     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2303       ObjCInterfaceDecl *ClassDeclared;
2304       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2305         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2306             declaresSameEntity(IFace, ClassDeclared))
2307           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2308       }
2309     }
2310   } else if (Lookup.isSingleResult() &&
2311              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2312     // If accessing a stand-alone ivar in a class method, this is an error.
2313     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2314       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2315                        << IV->getDeclName());
2316   }
2317 
2318   if (Lookup.empty() && II && AllowBuiltinCreation) {
2319     // FIXME. Consolidate this with similar code in LookupName.
2320     if (unsigned BuiltinID = II->getBuiltinID()) {
2321       if (!(getLangOpts().CPlusPlus &&
2322             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2323         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2324                                            S, Lookup.isForRedeclaration(),
2325                                            Lookup.getNameLoc());
2326         if (D) Lookup.addDecl(D);
2327       }
2328     }
2329   }
2330   // Sentinel value saying that we didn't do anything special.
2331   return Owned((Expr*) 0);
2332 }
2333 
2334 /// \brief Cast a base object to a member's actual type.
2335 ///
2336 /// Logically this happens in three phases:
2337 ///
2338 /// * First we cast from the base type to the naming class.
2339 ///   The naming class is the class into which we were looking
2340 ///   when we found the member;  it's the qualifier type if a
2341 ///   qualifier was provided, and otherwise it's the base type.
2342 ///
2343 /// * Next we cast from the naming class to the declaring class.
2344 ///   If the member we found was brought into a class's scope by
2345 ///   a using declaration, this is that class;  otherwise it's
2346 ///   the class declaring the member.
2347 ///
2348 /// * Finally we cast from the declaring class to the "true"
2349 ///   declaring class of the member.  This conversion does not
2350 ///   obey access control.
2351 ExprResult
2352 Sema::PerformObjectMemberConversion(Expr *From,
2353                                     NestedNameSpecifier *Qualifier,
2354                                     NamedDecl *FoundDecl,
2355                                     NamedDecl *Member) {
2356   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2357   if (!RD)
2358     return Owned(From);
2359 
2360   QualType DestRecordType;
2361   QualType DestType;
2362   QualType FromRecordType;
2363   QualType FromType = From->getType();
2364   bool PointerConversions = false;
2365   if (isa<FieldDecl>(Member)) {
2366     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2367 
2368     if (FromType->getAs<PointerType>()) {
2369       DestType = Context.getPointerType(DestRecordType);
2370       FromRecordType = FromType->getPointeeType();
2371       PointerConversions = true;
2372     } else {
2373       DestType = DestRecordType;
2374       FromRecordType = FromType;
2375     }
2376   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2377     if (Method->isStatic())
2378       return Owned(From);
2379 
2380     DestType = Method->getThisType(Context);
2381     DestRecordType = DestType->getPointeeType();
2382 
2383     if (FromType->getAs<PointerType>()) {
2384       FromRecordType = FromType->getPointeeType();
2385       PointerConversions = true;
2386     } else {
2387       FromRecordType = FromType;
2388       DestType = DestRecordType;
2389     }
2390   } else {
2391     // No conversion necessary.
2392     return Owned(From);
2393   }
2394 
2395   if (DestType->isDependentType() || FromType->isDependentType())
2396     return Owned(From);
2397 
2398   // If the unqualified types are the same, no conversion is necessary.
2399   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2400     return Owned(From);
2401 
2402   SourceRange FromRange = From->getSourceRange();
2403   SourceLocation FromLoc = FromRange.getBegin();
2404 
2405   ExprValueKind VK = From->getValueKind();
2406 
2407   // C++ [class.member.lookup]p8:
2408   //   [...] Ambiguities can often be resolved by qualifying a name with its
2409   //   class name.
2410   //
2411   // If the member was a qualified name and the qualified referred to a
2412   // specific base subobject type, we'll cast to that intermediate type
2413   // first and then to the object in which the member is declared. That allows
2414   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2415   //
2416   //   class Base { public: int x; };
2417   //   class Derived1 : public Base { };
2418   //   class Derived2 : public Base { };
2419   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2420   //
2421   //   void VeryDerived::f() {
2422   //     x = 17; // error: ambiguous base subobjects
2423   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2424   //   }
2425   if (Qualifier && Qualifier->getAsType()) {
2426     QualType QType = QualType(Qualifier->getAsType(), 0);
2427     assert(QType->isRecordType() && "lookup done with non-record type");
2428 
2429     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2430 
2431     // In C++98, the qualifier type doesn't actually have to be a base
2432     // type of the object type, in which case we just ignore it.
2433     // Otherwise build the appropriate casts.
2434     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2435       CXXCastPath BasePath;
2436       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2437                                        FromLoc, FromRange, &BasePath))
2438         return ExprError();
2439 
2440       if (PointerConversions)
2441         QType = Context.getPointerType(QType);
2442       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2443                                VK, &BasePath).take();
2444 
2445       FromType = QType;
2446       FromRecordType = QRecordType;
2447 
2448       // If the qualifier type was the same as the destination type,
2449       // we're done.
2450       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2451         return Owned(From);
2452     }
2453   }
2454 
2455   bool IgnoreAccess = false;
2456 
2457   // If we actually found the member through a using declaration, cast
2458   // down to the using declaration's type.
2459   //
2460   // Pointer equality is fine here because only one declaration of a
2461   // class ever has member declarations.
2462   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2463     assert(isa<UsingShadowDecl>(FoundDecl));
2464     QualType URecordType = Context.getTypeDeclType(
2465                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2466 
2467     // We only need to do this if the naming-class to declaring-class
2468     // conversion is non-trivial.
2469     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2470       assert(IsDerivedFrom(FromRecordType, URecordType));
2471       CXXCastPath BasePath;
2472       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2473                                        FromLoc, FromRange, &BasePath))
2474         return ExprError();
2475 
2476       QualType UType = URecordType;
2477       if (PointerConversions)
2478         UType = Context.getPointerType(UType);
2479       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2480                                VK, &BasePath).take();
2481       FromType = UType;
2482       FromRecordType = URecordType;
2483     }
2484 
2485     // We don't do access control for the conversion from the
2486     // declaring class to the true declaring class.
2487     IgnoreAccess = true;
2488   }
2489 
2490   CXXCastPath BasePath;
2491   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2492                                    FromLoc, FromRange, &BasePath,
2493                                    IgnoreAccess))
2494     return ExprError();
2495 
2496   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2497                            VK, &BasePath);
2498 }
2499 
2500 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2501                                       const LookupResult &R,
2502                                       bool HasTrailingLParen) {
2503   // Only when used directly as the postfix-expression of a call.
2504   if (!HasTrailingLParen)
2505     return false;
2506 
2507   // Never if a scope specifier was provided.
2508   if (SS.isSet())
2509     return false;
2510 
2511   // Only in C++ or ObjC++.
2512   if (!getLangOpts().CPlusPlus)
2513     return false;
2514 
2515   // Turn off ADL when we find certain kinds of declarations during
2516   // normal lookup:
2517   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2518     NamedDecl *D = *I;
2519 
2520     // C++0x [basic.lookup.argdep]p3:
2521     //     -- a declaration of a class member
2522     // Since using decls preserve this property, we check this on the
2523     // original decl.
2524     if (D->isCXXClassMember())
2525       return false;
2526 
2527     // C++0x [basic.lookup.argdep]p3:
2528     //     -- a block-scope function declaration that is not a
2529     //        using-declaration
2530     // NOTE: we also trigger this for function templates (in fact, we
2531     // don't check the decl type at all, since all other decl types
2532     // turn off ADL anyway).
2533     if (isa<UsingShadowDecl>(D))
2534       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2535     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2536       return false;
2537 
2538     // C++0x [basic.lookup.argdep]p3:
2539     //     -- a declaration that is neither a function or a function
2540     //        template
2541     // And also for builtin functions.
2542     if (isa<FunctionDecl>(D)) {
2543       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2544 
2545       // But also builtin functions.
2546       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2547         return false;
2548     } else if (!isa<FunctionTemplateDecl>(D))
2549       return false;
2550   }
2551 
2552   return true;
2553 }
2554 
2555 
2556 /// Diagnoses obvious problems with the use of the given declaration
2557 /// as an expression.  This is only actually called for lookups that
2558 /// were not overloaded, and it doesn't promise that the declaration
2559 /// will in fact be used.
2560 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2561   if (isa<TypedefNameDecl>(D)) {
2562     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2563     return true;
2564   }
2565 
2566   if (isa<ObjCInterfaceDecl>(D)) {
2567     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2568     return true;
2569   }
2570 
2571   if (isa<NamespaceDecl>(D)) {
2572     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2573     return true;
2574   }
2575 
2576   return false;
2577 }
2578 
2579 ExprResult
2580 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2581                                LookupResult &R,
2582                                bool NeedsADL) {
2583   // If this is a single, fully-resolved result and we don't need ADL,
2584   // just build an ordinary singleton decl ref.
2585   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2586     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2587                                     R.getRepresentativeDecl());
2588 
2589   // We only need to check the declaration if there's exactly one
2590   // result, because in the overloaded case the results can only be
2591   // functions and function templates.
2592   if (R.isSingleResult() &&
2593       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2594     return ExprError();
2595 
2596   // Otherwise, just build an unresolved lookup expression.  Suppress
2597   // any lookup-related diagnostics; we'll hash these out later, when
2598   // we've picked a target.
2599   R.suppressDiagnostics();
2600 
2601   UnresolvedLookupExpr *ULE
2602     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2603                                    SS.getWithLocInContext(Context),
2604                                    R.getLookupNameInfo(),
2605                                    NeedsADL, R.isOverloadedResult(),
2606                                    R.begin(), R.end());
2607 
2608   return Owned(ULE);
2609 }
2610 
2611 /// \brief Complete semantic analysis for a reference to the given declaration.
2612 ExprResult Sema::BuildDeclarationNameExpr(
2613     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2614     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) {
2615   assert(D && "Cannot refer to a NULL declaration");
2616   assert(!isa<FunctionTemplateDecl>(D) &&
2617          "Cannot refer unambiguously to a function template");
2618 
2619   SourceLocation Loc = NameInfo.getLoc();
2620   if (CheckDeclInExpr(*this, Loc, D))
2621     return ExprError();
2622 
2623   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2624     // Specifically diagnose references to class templates that are missing
2625     // a template argument list.
2626     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2627                                            << Template << SS.getRange();
2628     Diag(Template->getLocation(), diag::note_template_decl_here);
2629     return ExprError();
2630   }
2631 
2632   // Make sure that we're referring to a value.
2633   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2634   if (!VD) {
2635     Diag(Loc, diag::err_ref_non_value)
2636       << D << SS.getRange();
2637     Diag(D->getLocation(), diag::note_declared_at);
2638     return ExprError();
2639   }
2640 
2641   // Check whether this declaration can be used. Note that we suppress
2642   // this check when we're going to perform argument-dependent lookup
2643   // on this function name, because this might not be the function
2644   // that overload resolution actually selects.
2645   if (DiagnoseUseOfDecl(VD, Loc))
2646     return ExprError();
2647 
2648   // Only create DeclRefExpr's for valid Decl's.
2649   if (VD->isInvalidDecl())
2650     return ExprError();
2651 
2652   // Handle members of anonymous structs and unions.  If we got here,
2653   // and the reference is to a class member indirect field, then this
2654   // must be the subject of a pointer-to-member expression.
2655   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2656     if (!indirectField->isCXXClassMember())
2657       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2658                                                       indirectField);
2659 
2660   {
2661     QualType type = VD->getType();
2662     ExprValueKind valueKind = VK_RValue;
2663 
2664     switch (D->getKind()) {
2665     // Ignore all the non-ValueDecl kinds.
2666 #define ABSTRACT_DECL(kind)
2667 #define VALUE(type, base)
2668 #define DECL(type, base) \
2669     case Decl::type:
2670 #include "clang/AST/DeclNodes.inc"
2671       llvm_unreachable("invalid value decl kind");
2672 
2673     // These shouldn't make it here.
2674     case Decl::ObjCAtDefsField:
2675     case Decl::ObjCIvar:
2676       llvm_unreachable("forming non-member reference to ivar?");
2677 
2678     // Enum constants are always r-values and never references.
2679     // Unresolved using declarations are dependent.
2680     case Decl::EnumConstant:
2681     case Decl::UnresolvedUsingValue:
2682       valueKind = VK_RValue;
2683       break;
2684 
2685     // Fields and indirect fields that got here must be for
2686     // pointer-to-member expressions; we just call them l-values for
2687     // internal consistency, because this subexpression doesn't really
2688     // exist in the high-level semantics.
2689     case Decl::Field:
2690     case Decl::IndirectField:
2691       assert(getLangOpts().CPlusPlus &&
2692              "building reference to field in C?");
2693 
2694       // These can't have reference type in well-formed programs, but
2695       // for internal consistency we do this anyway.
2696       type = type.getNonReferenceType();
2697       valueKind = VK_LValue;
2698       break;
2699 
2700     // Non-type template parameters are either l-values or r-values
2701     // depending on the type.
2702     case Decl::NonTypeTemplateParm: {
2703       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2704         type = reftype->getPointeeType();
2705         valueKind = VK_LValue; // even if the parameter is an r-value reference
2706         break;
2707       }
2708 
2709       // For non-references, we need to strip qualifiers just in case
2710       // the template parameter was declared as 'const int' or whatever.
2711       valueKind = VK_RValue;
2712       type = type.getUnqualifiedType();
2713       break;
2714     }
2715 
2716     case Decl::Var:
2717     case Decl::VarTemplateSpecialization:
2718     case Decl::VarTemplatePartialSpecialization:
2719       // In C, "extern void blah;" is valid and is an r-value.
2720       if (!getLangOpts().CPlusPlus &&
2721           !type.hasQualifiers() &&
2722           type->isVoidType()) {
2723         valueKind = VK_RValue;
2724         break;
2725       }
2726       // fallthrough
2727 
2728     case Decl::ImplicitParam:
2729     case Decl::ParmVar: {
2730       // These are always l-values.
2731       valueKind = VK_LValue;
2732       type = type.getNonReferenceType();
2733 
2734       // FIXME: Does the addition of const really only apply in
2735       // potentially-evaluated contexts? Since the variable isn't actually
2736       // captured in an unevaluated context, it seems that the answer is no.
2737       if (!isUnevaluatedContext()) {
2738         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2739         if (!CapturedType.isNull())
2740           type = CapturedType;
2741       }
2742 
2743       break;
2744     }
2745 
2746     case Decl::Function: {
2747       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2748         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2749           type = Context.BuiltinFnTy;
2750           valueKind = VK_RValue;
2751           break;
2752         }
2753       }
2754 
2755       const FunctionType *fty = type->castAs<FunctionType>();
2756 
2757       // If we're referring to a function with an __unknown_anytype
2758       // result type, make the entire expression __unknown_anytype.
2759       if (fty->getResultType() == Context.UnknownAnyTy) {
2760         type = Context.UnknownAnyTy;
2761         valueKind = VK_RValue;
2762         break;
2763       }
2764 
2765       // Functions are l-values in C++.
2766       if (getLangOpts().CPlusPlus) {
2767         valueKind = VK_LValue;
2768         break;
2769       }
2770 
2771       // C99 DR 316 says that, if a function type comes from a
2772       // function definition (without a prototype), that type is only
2773       // used for checking compatibility. Therefore, when referencing
2774       // the function, we pretend that we don't have the full function
2775       // type.
2776       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2777           isa<FunctionProtoType>(fty))
2778         type = Context.getFunctionNoProtoType(fty->getResultType(),
2779                                               fty->getExtInfo());
2780 
2781       // Functions are r-values in C.
2782       valueKind = VK_RValue;
2783       break;
2784     }
2785 
2786     case Decl::MSProperty:
2787       valueKind = VK_LValue;
2788       break;
2789 
2790     case Decl::CXXMethod:
2791       // If we're referring to a method with an __unknown_anytype
2792       // result type, make the entire expression __unknown_anytype.
2793       // This should only be possible with a type written directly.
2794       if (const FunctionProtoType *proto
2795             = dyn_cast<FunctionProtoType>(VD->getType()))
2796         if (proto->getResultType() == Context.UnknownAnyTy) {
2797           type = Context.UnknownAnyTy;
2798           valueKind = VK_RValue;
2799           break;
2800         }
2801 
2802       // C++ methods are l-values if static, r-values if non-static.
2803       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2804         valueKind = VK_LValue;
2805         break;
2806       }
2807       // fallthrough
2808 
2809     case Decl::CXXConversion:
2810     case Decl::CXXDestructor:
2811     case Decl::CXXConstructor:
2812       valueKind = VK_RValue;
2813       break;
2814     }
2815 
2816     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2817                             TemplateArgs);
2818   }
2819 }
2820 
2821 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2822                                      PredefinedExpr::IdentType IT) {
2823   // Pick the current block, lambda, captured statement or function.
2824   Decl *currentDecl = 0;
2825   if (const BlockScopeInfo *BSI = getCurBlock())
2826     currentDecl = BSI->TheDecl;
2827   else if (const LambdaScopeInfo *LSI = getCurLambda())
2828     currentDecl = LSI->CallOperator;
2829   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
2830     currentDecl = CSI->TheCapturedDecl;
2831   else
2832     currentDecl = getCurFunctionOrMethodDecl();
2833 
2834   if (!currentDecl) {
2835     Diag(Loc, diag::ext_predef_outside_function);
2836     currentDecl = Context.getTranslationUnitDecl();
2837   }
2838 
2839   QualType ResTy;
2840   if (cast<DeclContext>(currentDecl)->isDependentContext())
2841     ResTy = Context.DependentTy;
2842   else {
2843     // Pre-defined identifiers are of type char[x], where x is the length of
2844     // the string.
2845     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2846 
2847     llvm::APInt LengthI(32, Length + 1);
2848     if (IT == PredefinedExpr::LFunction)
2849       ResTy = Context.WideCharTy.withConst();
2850     else
2851       ResTy = Context.CharTy.withConst();
2852     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2853   }
2854 
2855   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2856 }
2857 
2858 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2859   PredefinedExpr::IdentType IT;
2860 
2861   switch (Kind) {
2862   default: llvm_unreachable("Unknown simple primary expr!");
2863   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2864   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2865   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
2866   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2867   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2868   }
2869 
2870   return BuildPredefinedExpr(Loc, IT);
2871 }
2872 
2873 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2874   SmallString<16> CharBuffer;
2875   bool Invalid = false;
2876   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2877   if (Invalid)
2878     return ExprError();
2879 
2880   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2881                             PP, Tok.getKind());
2882   if (Literal.hadError())
2883     return ExprError();
2884 
2885   QualType Ty;
2886   if (Literal.isWide())
2887     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
2888   else if (Literal.isUTF16())
2889     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2890   else if (Literal.isUTF32())
2891     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2892   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2893     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2894   else
2895     Ty = Context.CharTy;  // 'x' -> char in C++
2896 
2897   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2898   if (Literal.isWide())
2899     Kind = CharacterLiteral::Wide;
2900   else if (Literal.isUTF16())
2901     Kind = CharacterLiteral::UTF16;
2902   else if (Literal.isUTF32())
2903     Kind = CharacterLiteral::UTF32;
2904 
2905   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2906                                              Tok.getLocation());
2907 
2908   if (Literal.getUDSuffix().empty())
2909     return Owned(Lit);
2910 
2911   // We're building a user-defined literal.
2912   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2913   SourceLocation UDSuffixLoc =
2914     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2915 
2916   // Make sure we're allowed user-defined literals here.
2917   if (!UDLScope)
2918     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2919 
2920   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2921   //   operator "" X (ch)
2922   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2923                                         Lit, Tok.getLocation());
2924 }
2925 
2926 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2927   unsigned IntSize = Context.getTargetInfo().getIntWidth();
2928   return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2929                                       Context.IntTy, Loc));
2930 }
2931 
2932 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2933                                   QualType Ty, SourceLocation Loc) {
2934   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2935 
2936   using llvm::APFloat;
2937   APFloat Val(Format);
2938 
2939   APFloat::opStatus result = Literal.GetFloatValue(Val);
2940 
2941   // Overflow is always an error, but underflow is only an error if
2942   // we underflowed to zero (APFloat reports denormals as underflow).
2943   if ((result & APFloat::opOverflow) ||
2944       ((result & APFloat::opUnderflow) && Val.isZero())) {
2945     unsigned diagnostic;
2946     SmallString<20> buffer;
2947     if (result & APFloat::opOverflow) {
2948       diagnostic = diag::warn_float_overflow;
2949       APFloat::getLargest(Format).toString(buffer);
2950     } else {
2951       diagnostic = diag::warn_float_underflow;
2952       APFloat::getSmallest(Format).toString(buffer);
2953     }
2954 
2955     S.Diag(Loc, diagnostic)
2956       << Ty
2957       << StringRef(buffer.data(), buffer.size());
2958   }
2959 
2960   bool isExact = (result == APFloat::opOK);
2961   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2962 }
2963 
2964 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
2965   // Fast path for a single digit (which is quite common).  A single digit
2966   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
2967   if (Tok.getLength() == 1) {
2968     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2969     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
2970   }
2971 
2972   SmallString<128> SpellingBuffer;
2973   // NumericLiteralParser wants to overread by one character.  Add padding to
2974   // the buffer in case the token is copied to the buffer.  If getSpelling()
2975   // returns a StringRef to the memory buffer, it should have a null char at
2976   // the EOF, so it is also safe.
2977   SpellingBuffer.resize(Tok.getLength() + 1);
2978 
2979   // Get the spelling of the token, which eliminates trigraphs, etc.
2980   bool Invalid = false;
2981   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
2982   if (Invalid)
2983     return ExprError();
2984 
2985   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
2986   if (Literal.hadError)
2987     return ExprError();
2988 
2989   if (Literal.hasUDSuffix()) {
2990     // We're building a user-defined literal.
2991     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2992     SourceLocation UDSuffixLoc =
2993       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2994 
2995     // Make sure we're allowed user-defined literals here.
2996     if (!UDLScope)
2997       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
2998 
2999     QualType CookedTy;
3000     if (Literal.isFloatingLiteral()) {
3001       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3002       // long double, the literal is treated as a call of the form
3003       //   operator "" X (f L)
3004       CookedTy = Context.LongDoubleTy;
3005     } else {
3006       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3007       // unsigned long long, the literal is treated as a call of the form
3008       //   operator "" X (n ULL)
3009       CookedTy = Context.UnsignedLongLongTy;
3010     }
3011 
3012     DeclarationName OpName =
3013       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3014     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3015     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3016 
3017     SourceLocation TokLoc = Tok.getLocation();
3018 
3019     // Perform literal operator lookup to determine if we're building a raw
3020     // literal or a cooked one.
3021     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3022     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3023                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3024                                   /*AllowStringTemplate*/false)) {
3025     case LOLR_Error:
3026       return ExprError();
3027 
3028     case LOLR_Cooked: {
3029       Expr *Lit;
3030       if (Literal.isFloatingLiteral()) {
3031         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3032       } else {
3033         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3034         if (Literal.GetIntegerValue(ResultVal))
3035           Diag(Tok.getLocation(), diag::err_integer_too_large);
3036         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3037                                      Tok.getLocation());
3038       }
3039       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3040     }
3041 
3042     case LOLR_Raw: {
3043       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3044       // literal is treated as a call of the form
3045       //   operator "" X ("n")
3046       unsigned Length = Literal.getUDSuffixOffset();
3047       QualType StrTy = Context.getConstantArrayType(
3048           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3049           ArrayType::Normal, 0);
3050       Expr *Lit = StringLiteral::Create(
3051           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3052           /*Pascal*/false, StrTy, &TokLoc, 1);
3053       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3054     }
3055 
3056     case LOLR_Template: {
3057       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3058       // template), L is treated as a call fo the form
3059       //   operator "" X <'c1', 'c2', ... 'ck'>()
3060       // where n is the source character sequence c1 c2 ... ck.
3061       TemplateArgumentListInfo ExplicitArgs;
3062       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3063       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3064       llvm::APSInt Value(CharBits, CharIsUnsigned);
3065       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3066         Value = TokSpelling[I];
3067         TemplateArgument Arg(Context, Value, Context.CharTy);
3068         TemplateArgumentLocInfo ArgInfo;
3069         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3070       }
3071       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3072                                       &ExplicitArgs);
3073     }
3074     case LOLR_StringTemplate:
3075       llvm_unreachable("unexpected literal operator lookup result");
3076     }
3077   }
3078 
3079   Expr *Res;
3080 
3081   if (Literal.isFloatingLiteral()) {
3082     QualType Ty;
3083     if (Literal.isFloat)
3084       Ty = Context.FloatTy;
3085     else if (!Literal.isLong)
3086       Ty = Context.DoubleTy;
3087     else
3088       Ty = Context.LongDoubleTy;
3089 
3090     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3091 
3092     if (Ty == Context.DoubleTy) {
3093       if (getLangOpts().SinglePrecisionConstants) {
3094         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
3095       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
3096         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3097         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
3098       }
3099     }
3100   } else if (!Literal.isIntegerLiteral()) {
3101     return ExprError();
3102   } else {
3103     QualType Ty;
3104 
3105     // 'long long' is a C99 or C++11 feature.
3106     if (!getLangOpts().C99 && Literal.isLongLong) {
3107       if (getLangOpts().CPlusPlus)
3108         Diag(Tok.getLocation(),
3109              getLangOpts().CPlusPlus11 ?
3110              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3111       else
3112         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3113     }
3114 
3115     // Get the value in the widest-possible width.
3116     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3117     // The microsoft literal suffix extensions support 128-bit literals, which
3118     // may be wider than [u]intmax_t.
3119     // FIXME: Actually, they don't. We seem to have accidentally invented the
3120     //        i128 suffix.
3121     if (Literal.isMicrosoftInteger && MaxWidth < 128 &&
3122         PP.getTargetInfo().hasInt128Type())
3123       MaxWidth = 128;
3124     llvm::APInt ResultVal(MaxWidth, 0);
3125 
3126     if (Literal.GetIntegerValue(ResultVal)) {
3127       // If this value didn't fit into uintmax_t, error and force to ull.
3128       Diag(Tok.getLocation(), diag::err_integer_too_large);
3129       Ty = Context.UnsignedLongLongTy;
3130       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3131              "long long is not intmax_t?");
3132     } else {
3133       // If this value fits into a ULL, try to figure out what else it fits into
3134       // according to the rules of C99 6.4.4.1p5.
3135 
3136       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3137       // be an unsigned int.
3138       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3139 
3140       // Check from smallest to largest, picking the smallest type we can.
3141       unsigned Width = 0;
3142       if (!Literal.isLong && !Literal.isLongLong) {
3143         // Are int/unsigned possibilities?
3144         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3145 
3146         // Does it fit in a unsigned int?
3147         if (ResultVal.isIntN(IntSize)) {
3148           // Does it fit in a signed int?
3149           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3150             Ty = Context.IntTy;
3151           else if (AllowUnsigned)
3152             Ty = Context.UnsignedIntTy;
3153           Width = IntSize;
3154         }
3155       }
3156 
3157       // Are long/unsigned long possibilities?
3158       if (Ty.isNull() && !Literal.isLongLong) {
3159         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3160 
3161         // Does it fit in a unsigned long?
3162         if (ResultVal.isIntN(LongSize)) {
3163           // Does it fit in a signed long?
3164           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3165             Ty = Context.LongTy;
3166           else if (AllowUnsigned)
3167             Ty = Context.UnsignedLongTy;
3168           Width = LongSize;
3169         }
3170       }
3171 
3172       // Check long long if needed.
3173       if (Ty.isNull()) {
3174         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3175 
3176         // Does it fit in a unsigned long long?
3177         if (ResultVal.isIntN(LongLongSize)) {
3178           // Does it fit in a signed long long?
3179           // To be compatible with MSVC, hex integer literals ending with the
3180           // LL or i64 suffix are always signed in Microsoft mode.
3181           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3182               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3183             Ty = Context.LongLongTy;
3184           else if (AllowUnsigned)
3185             Ty = Context.UnsignedLongLongTy;
3186           Width = LongLongSize;
3187         }
3188       }
3189 
3190       // If it doesn't fit in unsigned long long, and we're using Microsoft
3191       // extensions, then its a 128-bit integer literal.
3192       if (Ty.isNull() && Literal.isMicrosoftInteger &&
3193           PP.getTargetInfo().hasInt128Type()) {
3194         if (Literal.isUnsigned)
3195           Ty = Context.UnsignedInt128Ty;
3196         else
3197           Ty = Context.Int128Ty;
3198         Width = 128;
3199       }
3200 
3201       // If we still couldn't decide a type, we probably have something that
3202       // does not fit in a signed long long, but has no U suffix.
3203       if (Ty.isNull()) {
3204         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
3205         Ty = Context.UnsignedLongLongTy;
3206         Width = Context.getTargetInfo().getLongLongWidth();
3207       }
3208 
3209       if (ResultVal.getBitWidth() != Width)
3210         ResultVal = ResultVal.trunc(Width);
3211     }
3212     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3213   }
3214 
3215   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3216   if (Literal.isImaginary)
3217     Res = new (Context) ImaginaryLiteral(Res,
3218                                         Context.getComplexType(Res->getType()));
3219 
3220   return Owned(Res);
3221 }
3222 
3223 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3224   assert((E != 0) && "ActOnParenExpr() missing expr");
3225   return Owned(new (Context) ParenExpr(L, R, E));
3226 }
3227 
3228 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3229                                          SourceLocation Loc,
3230                                          SourceRange ArgRange) {
3231   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3232   // scalar or vector data type argument..."
3233   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3234   // type (C99 6.2.5p18) or void.
3235   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3236     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3237       << T << ArgRange;
3238     return true;
3239   }
3240 
3241   assert((T->isVoidType() || !T->isIncompleteType()) &&
3242          "Scalar types should always be complete");
3243   return false;
3244 }
3245 
3246 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3247                                            SourceLocation Loc,
3248                                            SourceRange ArgRange,
3249                                            UnaryExprOrTypeTrait TraitKind) {
3250   // Invalid types must be hard errors for SFINAE in C++.
3251   if (S.LangOpts.CPlusPlus)
3252     return true;
3253 
3254   // C99 6.5.3.4p1:
3255   if (T->isFunctionType() &&
3256       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3257     // sizeof(function)/alignof(function) is allowed as an extension.
3258     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3259       << TraitKind << ArgRange;
3260     return false;
3261   }
3262 
3263   // Allow sizeof(void)/alignof(void) as an extension.
3264   if (T->isVoidType()) {
3265     S.Diag(Loc, diag::ext_sizeof_alignof_void_type) << TraitKind << ArgRange;
3266     return false;
3267   }
3268 
3269   return true;
3270 }
3271 
3272 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3273                                              SourceLocation Loc,
3274                                              SourceRange ArgRange,
3275                                              UnaryExprOrTypeTrait TraitKind) {
3276   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3277   // runtime doesn't allow it.
3278   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3279     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3280       << T << (TraitKind == UETT_SizeOf)
3281       << ArgRange;
3282     return true;
3283   }
3284 
3285   return false;
3286 }
3287 
3288 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3289 /// pointer type is equal to T) and emit a warning if it is.
3290 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3291                                      Expr *E) {
3292   // Don't warn if the operation changed the type.
3293   if (T != E->getType())
3294     return;
3295 
3296   // Now look for array decays.
3297   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3298   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3299     return;
3300 
3301   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3302                                              << ICE->getType()
3303                                              << ICE->getSubExpr()->getType();
3304 }
3305 
3306 /// \brief Check the constrains on expression operands to unary type expression
3307 /// and type traits.
3308 ///
3309 /// Completes any types necessary and validates the constraints on the operand
3310 /// expression. The logic mostly mirrors the type-based overload, but may modify
3311 /// the expression as it completes the type for that expression through template
3312 /// instantiation, etc.
3313 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3314                                             UnaryExprOrTypeTrait ExprKind) {
3315   QualType ExprTy = E->getType();
3316   assert(!ExprTy->isReferenceType());
3317 
3318   if (ExprKind == UETT_VecStep)
3319     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3320                                         E->getSourceRange());
3321 
3322   // Whitelist some types as extensions
3323   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3324                                       E->getSourceRange(), ExprKind))
3325     return false;
3326 
3327   if (RequireCompleteExprType(E,
3328                               diag::err_sizeof_alignof_incomplete_type,
3329                               ExprKind, E->getSourceRange()))
3330     return true;
3331 
3332   // Completing the expression's type may have changed it.
3333   ExprTy = E->getType();
3334   assert(!ExprTy->isReferenceType());
3335 
3336   if (ExprTy->isFunctionType()) {
3337     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3338       << ExprKind << E->getSourceRange();
3339     return true;
3340   }
3341 
3342   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3343                                        E->getSourceRange(), ExprKind))
3344     return true;
3345 
3346   if (ExprKind == UETT_SizeOf) {
3347     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3348       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3349         QualType OType = PVD->getOriginalType();
3350         QualType Type = PVD->getType();
3351         if (Type->isPointerType() && OType->isArrayType()) {
3352           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3353             << Type << OType;
3354           Diag(PVD->getLocation(), diag::note_declared_at);
3355         }
3356       }
3357     }
3358 
3359     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3360     // decays into a pointer and returns an unintended result. This is most
3361     // likely a typo for "sizeof(array) op x".
3362     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3363       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3364                                BO->getLHS());
3365       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3366                                BO->getRHS());
3367     }
3368   }
3369 
3370   return false;
3371 }
3372 
3373 /// \brief Check the constraints on operands to unary expression and type
3374 /// traits.
3375 ///
3376 /// This will complete any types necessary, and validate the various constraints
3377 /// on those operands.
3378 ///
3379 /// The UsualUnaryConversions() function is *not* called by this routine.
3380 /// C99 6.3.2.1p[2-4] all state:
3381 ///   Except when it is the operand of the sizeof operator ...
3382 ///
3383 /// C++ [expr.sizeof]p4
3384 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3385 ///   standard conversions are not applied to the operand of sizeof.
3386 ///
3387 /// This policy is followed for all of the unary trait expressions.
3388 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3389                                             SourceLocation OpLoc,
3390                                             SourceRange ExprRange,
3391                                             UnaryExprOrTypeTrait ExprKind) {
3392   if (ExprType->isDependentType())
3393     return false;
3394 
3395   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3396   //   the result is the size of the referenced type."
3397   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3398   //   result shall be the alignment of the referenced type."
3399   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3400     ExprType = Ref->getPointeeType();
3401 
3402   if (ExprKind == UETT_VecStep)
3403     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3404 
3405   // Whitelist some types as extensions
3406   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3407                                       ExprKind))
3408     return false;
3409 
3410   if (RequireCompleteType(OpLoc, ExprType,
3411                           diag::err_sizeof_alignof_incomplete_type,
3412                           ExprKind, ExprRange))
3413     return true;
3414 
3415   if (ExprType->isFunctionType()) {
3416     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3417       << ExprKind << ExprRange;
3418     return true;
3419   }
3420 
3421   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3422                                        ExprKind))
3423     return true;
3424 
3425   return false;
3426 }
3427 
3428 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3429   E = E->IgnoreParens();
3430 
3431   // Cannot know anything else if the expression is dependent.
3432   if (E->isTypeDependent())
3433     return false;
3434 
3435   if (E->getObjectKind() == OK_BitField) {
3436     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3437        << 1 << E->getSourceRange();
3438     return true;
3439   }
3440 
3441   ValueDecl *D = 0;
3442   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3443     D = DRE->getDecl();
3444   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3445     D = ME->getMemberDecl();
3446   }
3447 
3448   // If it's a field, require the containing struct to have a
3449   // complete definition so that we can compute the layout.
3450   //
3451   // This requires a very particular set of circumstances.  For a
3452   // field to be contained within an incomplete type, we must in the
3453   // process of parsing that type.  To have an expression refer to a
3454   // field, it must be an id-expression or a member-expression, but
3455   // the latter are always ill-formed when the base type is
3456   // incomplete, including only being partially complete.  An
3457   // id-expression can never refer to a field in C because fields
3458   // are not in the ordinary namespace.  In C++, an id-expression
3459   // can implicitly be a member access, but only if there's an
3460   // implicit 'this' value, and all such contexts are subject to
3461   // delayed parsing --- except for trailing return types in C++11.
3462   // And if an id-expression referring to a field occurs in a
3463   // context that lacks a 'this' value, it's ill-formed --- except,
3464   // again, in C++11, where such references are allowed in an
3465   // unevaluated context.  So C++11 introduces some new complexity.
3466   //
3467   // For the record, since __alignof__ on expressions is a GCC
3468   // extension, GCC seems to permit this but always gives the
3469   // nonsensical answer 0.
3470   //
3471   // We don't really need the layout here --- we could instead just
3472   // directly check for all the appropriate alignment-lowing
3473   // attributes --- but that would require duplicating a lot of
3474   // logic that just isn't worth duplicating for such a marginal
3475   // use-case.
3476   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3477     // Fast path this check, since we at least know the record has a
3478     // definition if we can find a member of it.
3479     if (!FD->getParent()->isCompleteDefinition()) {
3480       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3481         << E->getSourceRange();
3482       return true;
3483     }
3484 
3485     // Otherwise, if it's a field, and the field doesn't have
3486     // reference type, then it must have a complete type (or be a
3487     // flexible array member, which we explicitly want to
3488     // white-list anyway), which makes the following checks trivial.
3489     if (!FD->getType()->isReferenceType())
3490       return false;
3491   }
3492 
3493   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3494 }
3495 
3496 bool Sema::CheckVecStepExpr(Expr *E) {
3497   E = E->IgnoreParens();
3498 
3499   // Cannot know anything else if the expression is dependent.
3500   if (E->isTypeDependent())
3501     return false;
3502 
3503   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3504 }
3505 
3506 /// \brief Build a sizeof or alignof expression given a type operand.
3507 ExprResult
3508 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3509                                      SourceLocation OpLoc,
3510                                      UnaryExprOrTypeTrait ExprKind,
3511                                      SourceRange R) {
3512   if (!TInfo)
3513     return ExprError();
3514 
3515   QualType T = TInfo->getType();
3516 
3517   if (!T->isDependentType() &&
3518       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3519     return ExprError();
3520 
3521   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3522   return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3523                                                       Context.getSizeType(),
3524                                                       OpLoc, R.getEnd()));
3525 }
3526 
3527 /// \brief Build a sizeof or alignof expression given an expression
3528 /// operand.
3529 ExprResult
3530 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3531                                      UnaryExprOrTypeTrait ExprKind) {
3532   ExprResult PE = CheckPlaceholderExpr(E);
3533   if (PE.isInvalid())
3534     return ExprError();
3535 
3536   E = PE.get();
3537 
3538   // Verify that the operand is valid.
3539   bool isInvalid = false;
3540   if (E->isTypeDependent()) {
3541     // Delay type-checking for type-dependent expressions.
3542   } else if (ExprKind == UETT_AlignOf) {
3543     isInvalid = CheckAlignOfExpr(*this, E);
3544   } else if (ExprKind == UETT_VecStep) {
3545     isInvalid = CheckVecStepExpr(E);
3546   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3547     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3548     isInvalid = true;
3549   } else {
3550     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3551   }
3552 
3553   if (isInvalid)
3554     return ExprError();
3555 
3556   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3557     PE = TransformToPotentiallyEvaluated(E);
3558     if (PE.isInvalid()) return ExprError();
3559     E = PE.take();
3560   }
3561 
3562   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3563   return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3564       ExprKind, E, Context.getSizeType(), OpLoc,
3565       E->getSourceRange().getEnd()));
3566 }
3567 
3568 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3569 /// expr and the same for @c alignof and @c __alignof
3570 /// Note that the ArgRange is invalid if isType is false.
3571 ExprResult
3572 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3573                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3574                                     void *TyOrEx, const SourceRange &ArgRange) {
3575   // If error parsing type, ignore.
3576   if (TyOrEx == 0) return ExprError();
3577 
3578   if (IsType) {
3579     TypeSourceInfo *TInfo;
3580     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3581     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3582   }
3583 
3584   Expr *ArgEx = (Expr *)TyOrEx;
3585   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3586   return Result;
3587 }
3588 
3589 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3590                                      bool IsReal) {
3591   if (V.get()->isTypeDependent())
3592     return S.Context.DependentTy;
3593 
3594   // _Real and _Imag are only l-values for normal l-values.
3595   if (V.get()->getObjectKind() != OK_Ordinary) {
3596     V = S.DefaultLvalueConversion(V.take());
3597     if (V.isInvalid())
3598       return QualType();
3599   }
3600 
3601   // These operators return the element type of a complex type.
3602   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3603     return CT->getElementType();
3604 
3605   // Otherwise they pass through real integer and floating point types here.
3606   if (V.get()->getType()->isArithmeticType())
3607     return V.get()->getType();
3608 
3609   // Test for placeholders.
3610   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3611   if (PR.isInvalid()) return QualType();
3612   if (PR.get() != V.get()) {
3613     V = PR;
3614     return CheckRealImagOperand(S, V, Loc, IsReal);
3615   }
3616 
3617   // Reject anything else.
3618   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3619     << (IsReal ? "__real" : "__imag");
3620   return QualType();
3621 }
3622 
3623 
3624 
3625 ExprResult
3626 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3627                           tok::TokenKind Kind, Expr *Input) {
3628   UnaryOperatorKind Opc;
3629   switch (Kind) {
3630   default: llvm_unreachable("Unknown unary op!");
3631   case tok::plusplus:   Opc = UO_PostInc; break;
3632   case tok::minusminus: Opc = UO_PostDec; break;
3633   }
3634 
3635   // Since this might is a postfix expression, get rid of ParenListExprs.
3636   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3637   if (Result.isInvalid()) return ExprError();
3638   Input = Result.take();
3639 
3640   return BuildUnaryOp(S, OpLoc, Opc, Input);
3641 }
3642 
3643 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3644 ///
3645 /// \return true on error
3646 static bool checkArithmeticOnObjCPointer(Sema &S,
3647                                          SourceLocation opLoc,
3648                                          Expr *op) {
3649   assert(op->getType()->isObjCObjectPointerType());
3650   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
3651       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
3652     return false;
3653 
3654   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3655     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3656     << op->getSourceRange();
3657   return true;
3658 }
3659 
3660 ExprResult
3661 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3662                               Expr *idx, SourceLocation rbLoc) {
3663   // Since this might be a postfix expression, get rid of ParenListExprs.
3664   if (isa<ParenListExpr>(base)) {
3665     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3666     if (result.isInvalid()) return ExprError();
3667     base = result.take();
3668   }
3669 
3670   // Handle any non-overload placeholder types in the base and index
3671   // expressions.  We can't handle overloads here because the other
3672   // operand might be an overloadable type, in which case the overload
3673   // resolution for the operator overload should get the first crack
3674   // at the overload.
3675   if (base->getType()->isNonOverloadPlaceholderType()) {
3676     ExprResult result = CheckPlaceholderExpr(base);
3677     if (result.isInvalid()) return ExprError();
3678     base = result.take();
3679   }
3680   if (idx->getType()->isNonOverloadPlaceholderType()) {
3681     ExprResult result = CheckPlaceholderExpr(idx);
3682     if (result.isInvalid()) return ExprError();
3683     idx = result.take();
3684   }
3685 
3686   // Build an unanalyzed expression if either operand is type-dependent.
3687   if (getLangOpts().CPlusPlus &&
3688       (base->isTypeDependent() || idx->isTypeDependent())) {
3689     return Owned(new (Context) ArraySubscriptExpr(base, idx,
3690                                                   Context.DependentTy,
3691                                                   VK_LValue, OK_Ordinary,
3692                                                   rbLoc));
3693   }
3694 
3695   // Use C++ overloaded-operator rules if either operand has record
3696   // type.  The spec says to do this if either type is *overloadable*,
3697   // but enum types can't declare subscript operators or conversion
3698   // operators, so there's nothing interesting for overload resolution
3699   // to do if there aren't any record types involved.
3700   //
3701   // ObjC pointers have their own subscripting logic that is not tied
3702   // to overload resolution and so should not take this path.
3703   if (getLangOpts().CPlusPlus &&
3704       (base->getType()->isRecordType() ||
3705        (!base->getType()->isObjCObjectPointerType() &&
3706         idx->getType()->isRecordType()))) {
3707     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3708   }
3709 
3710   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3711 }
3712 
3713 ExprResult
3714 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3715                                       Expr *Idx, SourceLocation RLoc) {
3716   Expr *LHSExp = Base;
3717   Expr *RHSExp = Idx;
3718 
3719   // Perform default conversions.
3720   if (!LHSExp->getType()->getAs<VectorType>()) {
3721     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3722     if (Result.isInvalid())
3723       return ExprError();
3724     LHSExp = Result.take();
3725   }
3726   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3727   if (Result.isInvalid())
3728     return ExprError();
3729   RHSExp = Result.take();
3730 
3731   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3732   ExprValueKind VK = VK_LValue;
3733   ExprObjectKind OK = OK_Ordinary;
3734 
3735   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3736   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3737   // in the subscript position. As a result, we need to derive the array base
3738   // and index from the expression types.
3739   Expr *BaseExpr, *IndexExpr;
3740   QualType ResultType;
3741   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3742     BaseExpr = LHSExp;
3743     IndexExpr = RHSExp;
3744     ResultType = Context.DependentTy;
3745   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3746     BaseExpr = LHSExp;
3747     IndexExpr = RHSExp;
3748     ResultType = PTy->getPointeeType();
3749   } else if (const ObjCObjectPointerType *PTy =
3750                LHSTy->getAs<ObjCObjectPointerType>()) {
3751     BaseExpr = LHSExp;
3752     IndexExpr = RHSExp;
3753 
3754     // Use custom logic if this should be the pseudo-object subscript
3755     // expression.
3756     if (!LangOpts.isSubscriptPointerArithmetic())
3757       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3758 
3759     ResultType = PTy->getPointeeType();
3760   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3761      // Handle the uncommon case of "123[Ptr]".
3762     BaseExpr = RHSExp;
3763     IndexExpr = LHSExp;
3764     ResultType = PTy->getPointeeType();
3765   } else if (const ObjCObjectPointerType *PTy =
3766                RHSTy->getAs<ObjCObjectPointerType>()) {
3767      // Handle the uncommon case of "123[Ptr]".
3768     BaseExpr = RHSExp;
3769     IndexExpr = LHSExp;
3770     ResultType = PTy->getPointeeType();
3771     if (!LangOpts.isSubscriptPointerArithmetic()) {
3772       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3773         << ResultType << BaseExpr->getSourceRange();
3774       return ExprError();
3775     }
3776   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3777     BaseExpr = LHSExp;    // vectors: V[123]
3778     IndexExpr = RHSExp;
3779     VK = LHSExp->getValueKind();
3780     if (VK != VK_RValue)
3781       OK = OK_VectorComponent;
3782 
3783     // FIXME: need to deal with const...
3784     ResultType = VTy->getElementType();
3785   } else if (LHSTy->isArrayType()) {
3786     // If we see an array that wasn't promoted by
3787     // DefaultFunctionArrayLvalueConversion, it must be an array that
3788     // wasn't promoted because of the C90 rule that doesn't
3789     // allow promoting non-lvalue arrays.  Warn, then
3790     // force the promotion here.
3791     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3792         LHSExp->getSourceRange();
3793     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3794                                CK_ArrayToPointerDecay).take();
3795     LHSTy = LHSExp->getType();
3796 
3797     BaseExpr = LHSExp;
3798     IndexExpr = RHSExp;
3799     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3800   } else if (RHSTy->isArrayType()) {
3801     // Same as previous, except for 123[f().a] case
3802     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3803         RHSExp->getSourceRange();
3804     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3805                                CK_ArrayToPointerDecay).take();
3806     RHSTy = RHSExp->getType();
3807 
3808     BaseExpr = RHSExp;
3809     IndexExpr = LHSExp;
3810     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3811   } else {
3812     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3813        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3814   }
3815   // C99 6.5.2.1p1
3816   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3817     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3818                      << IndexExpr->getSourceRange());
3819 
3820   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3821        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3822          && !IndexExpr->isTypeDependent())
3823     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3824 
3825   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3826   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3827   // type. Note that Functions are not objects, and that (in C99 parlance)
3828   // incomplete types are not object types.
3829   if (ResultType->isFunctionType()) {
3830     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3831       << ResultType << BaseExpr->getSourceRange();
3832     return ExprError();
3833   }
3834 
3835   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3836     // GNU extension: subscripting on pointer to void
3837     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3838       << BaseExpr->getSourceRange();
3839 
3840     // C forbids expressions of unqualified void type from being l-values.
3841     // See IsCForbiddenLValueType.
3842     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3843   } else if (!ResultType->isDependentType() &&
3844       RequireCompleteType(LLoc, ResultType,
3845                           diag::err_subscript_incomplete_type, BaseExpr))
3846     return ExprError();
3847 
3848   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3849          !ResultType.isCForbiddenLValueType());
3850 
3851   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3852                                                 ResultType, VK, OK, RLoc));
3853 }
3854 
3855 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3856                                         FunctionDecl *FD,
3857                                         ParmVarDecl *Param) {
3858   if (Param->hasUnparsedDefaultArg()) {
3859     Diag(CallLoc,
3860          diag::err_use_of_default_argument_to_function_declared_later) <<
3861       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3862     Diag(UnparsedDefaultArgLocs[Param],
3863          diag::note_default_argument_declared_here);
3864     return ExprError();
3865   }
3866 
3867   if (Param->hasUninstantiatedDefaultArg()) {
3868     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3869 
3870     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3871                                                  Param);
3872 
3873     // Instantiate the expression.
3874     MultiLevelTemplateArgumentList MutiLevelArgList
3875       = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3876 
3877     InstantiatingTemplate Inst(*this, CallLoc, Param,
3878                                MutiLevelArgList.getInnermost());
3879     if (Inst.isInvalid())
3880       return ExprError();
3881 
3882     ExprResult Result;
3883     {
3884       // C++ [dcl.fct.default]p5:
3885       //   The names in the [default argument] expression are bound, and
3886       //   the semantic constraints are checked, at the point where the
3887       //   default argument expression appears.
3888       ContextRAII SavedContext(*this, FD);
3889       LocalInstantiationScope Local(*this);
3890       Result = SubstExpr(UninstExpr, MutiLevelArgList);
3891     }
3892     if (Result.isInvalid())
3893       return ExprError();
3894 
3895     // Check the expression as an initializer for the parameter.
3896     InitializedEntity Entity
3897       = InitializedEntity::InitializeParameter(Context, Param);
3898     InitializationKind Kind
3899       = InitializationKind::CreateCopy(Param->getLocation(),
3900              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3901     Expr *ResultE = Result.takeAs<Expr>();
3902 
3903     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3904     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3905     if (Result.isInvalid())
3906       return ExprError();
3907 
3908     Expr *Arg = Result.takeAs<Expr>();
3909     CheckCompletedExpr(Arg, Param->getOuterLocStart());
3910     // Build the default argument expression.
3911     return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
3912   }
3913 
3914   // If the default expression creates temporaries, we need to
3915   // push them to the current stack of expression temporaries so they'll
3916   // be properly destroyed.
3917   // FIXME: We should really be rebuilding the default argument with new
3918   // bound temporaries; see the comment in PR5810.
3919   // We don't need to do that with block decls, though, because
3920   // blocks in default argument expression can never capture anything.
3921   if (isa<ExprWithCleanups>(Param->getInit())) {
3922     // Set the "needs cleanups" bit regardless of whether there are
3923     // any explicit objects.
3924     ExprNeedsCleanups = true;
3925 
3926     // Append all the objects to the cleanup list.  Right now, this
3927     // should always be a no-op, because blocks in default argument
3928     // expressions should never be able to capture anything.
3929     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3930            "default argument expression has capturing blocks?");
3931   }
3932 
3933   // We already type-checked the argument, so we know it works.
3934   // Just mark all of the declarations in this potentially-evaluated expression
3935   // as being "referenced".
3936   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3937                                    /*SkipLocalVariables=*/true);
3938   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3939 }
3940 
3941 
3942 Sema::VariadicCallType
3943 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3944                           Expr *Fn) {
3945   if (Proto && Proto->isVariadic()) {
3946     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3947       return VariadicConstructor;
3948     else if (Fn && Fn->getType()->isBlockPointerType())
3949       return VariadicBlock;
3950     else if (FDecl) {
3951       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3952         if (Method->isInstance())
3953           return VariadicMethod;
3954     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
3955       return VariadicMethod;
3956     return VariadicFunction;
3957   }
3958   return VariadicDoesNotApply;
3959 }
3960 
3961 namespace {
3962 class FunctionCallCCC : public FunctionCallFilterCCC {
3963 public:
3964   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
3965                   unsigned NumArgs, bool HasExplicitTemplateArgs)
3966       : FunctionCallFilterCCC(SemaRef, NumArgs, HasExplicitTemplateArgs),
3967         FunctionName(FuncName) {}
3968 
3969   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
3970     if (!candidate.getCorrectionSpecifier() ||
3971         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
3972       return false;
3973     }
3974 
3975     return FunctionCallFilterCCC::ValidateCandidate(candidate);
3976   }
3977 
3978 private:
3979   const IdentifierInfo *const FunctionName;
3980 };
3981 }
3982 
3983 static TypoCorrection TryTypoCorrectionForCall(Sema &S,
3984                                                DeclarationNameInfo FuncName,
3985                                                ArrayRef<Expr *> Args) {
3986   FunctionCallCCC CCC(S, FuncName.getName().getAsIdentifierInfo(),
3987                       Args.size(), false);
3988   if (TypoCorrection Corrected =
3989           S.CorrectTypo(FuncName, Sema::LookupOrdinaryName,
3990                         S.getScopeForContext(S.CurContext), NULL, CCC)) {
3991     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
3992       if (Corrected.isOverloaded()) {
3993         OverloadCandidateSet OCS(FuncName.getLoc());
3994         OverloadCandidateSet::iterator Best;
3995         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
3996                                            CDEnd = Corrected.end();
3997              CD != CDEnd; ++CD) {
3998           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
3999             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4000                                    OCS);
4001         }
4002         switch (OCS.BestViableFunction(S, FuncName.getLoc(), Best)) {
4003         case OR_Success:
4004           ND = Best->Function;
4005           Corrected.setCorrectionDecl(ND);
4006           break;
4007         default:
4008           break;
4009         }
4010       }
4011       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
4012         return Corrected;
4013       }
4014     }
4015   }
4016   return TypoCorrection();
4017 }
4018 
4019 /// ConvertArgumentsForCall - Converts the arguments specified in
4020 /// Args/NumArgs to the parameter types of the function FDecl with
4021 /// function prototype Proto. Call is the call expression itself, and
4022 /// Fn is the function expression. For a C++ member function, this
4023 /// routine does not attempt to convert the object argument. Returns
4024 /// true if the call is ill-formed.
4025 bool
4026 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4027                               FunctionDecl *FDecl,
4028                               const FunctionProtoType *Proto,
4029                               ArrayRef<Expr *> Args,
4030                               SourceLocation RParenLoc,
4031                               bool IsExecConfig) {
4032   // Bail out early if calling a builtin with custom typechecking.
4033   // We don't need to do this in the
4034   if (FDecl)
4035     if (unsigned ID = FDecl->getBuiltinID())
4036       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4037         return false;
4038 
4039   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4040   // assignment, to the types of the corresponding parameter, ...
4041   unsigned NumArgsInProto = Proto->getNumArgs();
4042   bool Invalid = false;
4043   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
4044   unsigned FnKind = Fn->getType()->isBlockPointerType()
4045                        ? 1 /* block */
4046                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4047                                        : 0 /* function */);
4048 
4049   // If too few arguments are available (and we don't have default
4050   // arguments for the remaining parameters), don't make the call.
4051   if (Args.size() < NumArgsInProto) {
4052     if (Args.size() < MinArgs) {
4053       MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4054       TypoCorrection TC;
4055       if (FDecl && (TC = TryTypoCorrectionForCall(
4056                         *this, DeclarationNameInfo(FDecl->getDeclName(),
4057                                                    (ME ? ME->getMemberLoc()
4058                                                        : Fn->getLocStart())),
4059                         Args))) {
4060         unsigned diag_id =
4061             MinArgs == NumArgsInProto && !Proto->isVariadic()
4062                 ? diag::err_typecheck_call_too_few_args_suggest
4063                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4064         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4065                                         << static_cast<unsigned>(Args.size())
4066                                         << Fn->getSourceRange());
4067       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4068         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
4069                           ? diag::err_typecheck_call_too_few_args_one
4070                           : diag::err_typecheck_call_too_few_args_at_least_one)
4071           << FnKind
4072           << FDecl->getParamDecl(0) << Fn->getSourceRange();
4073       else
4074         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
4075                           ? diag::err_typecheck_call_too_few_args
4076                           : diag::err_typecheck_call_too_few_args_at_least)
4077           << FnKind
4078           << MinArgs << static_cast<unsigned>(Args.size())
4079           << Fn->getSourceRange();
4080 
4081       // Emit the location of the prototype.
4082       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4083         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4084           << FDecl;
4085 
4086       return true;
4087     }
4088     Call->setNumArgs(Context, NumArgsInProto);
4089   }
4090 
4091   // If too many are passed and not variadic, error on the extras and drop
4092   // them.
4093   if (Args.size() > NumArgsInProto) {
4094     if (!Proto->isVariadic()) {
4095       TypoCorrection TC;
4096       if (FDecl && (TC = TryTypoCorrectionForCall(
4097                         *this, DeclarationNameInfo(FDecl->getDeclName(),
4098                                                    Fn->getLocStart()),
4099                         Args))) {
4100         unsigned diag_id =
4101             MinArgs == NumArgsInProto && !Proto->isVariadic()
4102                 ? diag::err_typecheck_call_too_many_args_suggest
4103                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4104         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumArgsInProto
4105                                         << static_cast<unsigned>(Args.size())
4106                                         << Fn->getSourceRange());
4107       } else if (NumArgsInProto == 1 && FDecl &&
4108                  FDecl->getParamDecl(0)->getDeclName())
4109         Diag(Args[NumArgsInProto]->getLocStart(),
4110              MinArgs == NumArgsInProto
4111                ? diag::err_typecheck_call_too_many_args_one
4112                : diag::err_typecheck_call_too_many_args_at_most_one)
4113           << FnKind
4114           << FDecl->getParamDecl(0) << static_cast<unsigned>(Args.size())
4115           << Fn->getSourceRange()
4116           << SourceRange(Args[NumArgsInProto]->getLocStart(),
4117                          Args.back()->getLocEnd());
4118       else
4119         Diag(Args[NumArgsInProto]->getLocStart(),
4120              MinArgs == NumArgsInProto
4121                ? diag::err_typecheck_call_too_many_args
4122                : diag::err_typecheck_call_too_many_args_at_most)
4123           << FnKind
4124           << NumArgsInProto << static_cast<unsigned>(Args.size())
4125           << Fn->getSourceRange()
4126           << SourceRange(Args[NumArgsInProto]->getLocStart(),
4127                          Args.back()->getLocEnd());
4128 
4129       // Emit the location of the prototype.
4130       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4131         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4132           << FDecl;
4133 
4134       // This deletes the extra arguments.
4135       Call->setNumArgs(Context, NumArgsInProto);
4136       return true;
4137     }
4138   }
4139   SmallVector<Expr *, 8> AllArgs;
4140   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4141 
4142   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4143                                    Proto, 0, Args, AllArgs, CallType);
4144   if (Invalid)
4145     return true;
4146   unsigned TotalNumArgs = AllArgs.size();
4147   for (unsigned i = 0; i < TotalNumArgs; ++i)
4148     Call->setArg(i, AllArgs[i]);
4149 
4150   return false;
4151 }
4152 
4153 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4154                                   FunctionDecl *FDecl,
4155                                   const FunctionProtoType *Proto,
4156                                   unsigned FirstProtoArg,
4157                                   ArrayRef<Expr *> Args,
4158                                   SmallVectorImpl<Expr *> &AllArgs,
4159                                   VariadicCallType CallType,
4160                                   bool AllowExplicit,
4161                                   bool IsListInitialization) {
4162   unsigned NumArgsInProto = Proto->getNumArgs();
4163   unsigned NumArgsToCheck = Args.size();
4164   bool Invalid = false;
4165   if (Args.size() != NumArgsInProto)
4166     // Use default arguments for missing arguments
4167     NumArgsToCheck = NumArgsInProto;
4168   unsigned ArgIx = 0;
4169   // Continue to check argument types (even if we have too few/many args).
4170   for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
4171     QualType ProtoArgType = Proto->getArgType(i);
4172 
4173     Expr *Arg;
4174     ParmVarDecl *Param;
4175     if (ArgIx < Args.size()) {
4176       Arg = Args[ArgIx++];
4177 
4178       if (RequireCompleteType(Arg->getLocStart(),
4179                               ProtoArgType,
4180                               diag::err_call_incomplete_argument, Arg))
4181         return true;
4182 
4183       // Pass the argument
4184       Param = 0;
4185       if (FDecl && i < FDecl->getNumParams())
4186         Param = FDecl->getParamDecl(i);
4187 
4188       // Strip the unbridged-cast placeholder expression off, if applicable.
4189       bool CFAudited = false;
4190       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4191           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4192           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4193         Arg = stripARCUnbridgedCast(Arg);
4194       else if (getLangOpts().ObjCAutoRefCount &&
4195                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4196                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4197         CFAudited = true;
4198 
4199       InitializedEntity Entity = Param ?
4200           InitializedEntity::InitializeParameter(Context, Param, ProtoArgType)
4201         : InitializedEntity::InitializeParameter(Context, ProtoArgType,
4202                                                  Proto->isArgConsumed(i));
4203 
4204       // Remember that parameter belongs to a CF audited API.
4205       if (CFAudited)
4206         Entity.setParameterCFAudited();
4207 
4208       ExprResult ArgE = PerformCopyInitialization(Entity,
4209                                                   SourceLocation(),
4210                                                   Owned(Arg),
4211                                                   IsListInitialization,
4212                                                   AllowExplicit);
4213       if (ArgE.isInvalid())
4214         return true;
4215 
4216       Arg = ArgE.takeAs<Expr>();
4217     } else {
4218       assert(FDecl && "can't use default arguments without a known callee");
4219       Param = FDecl->getParamDecl(i);
4220 
4221       ExprResult ArgExpr =
4222         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4223       if (ArgExpr.isInvalid())
4224         return true;
4225 
4226       Arg = ArgExpr.takeAs<Expr>();
4227     }
4228 
4229     // Check for array bounds violations for each argument to the call. This
4230     // check only triggers warnings when the argument isn't a more complex Expr
4231     // with its own checking, such as a BinaryOperator.
4232     CheckArrayAccess(Arg);
4233 
4234     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4235     CheckStaticArrayArgument(CallLoc, Param, Arg);
4236 
4237     AllArgs.push_back(Arg);
4238   }
4239 
4240   // If this is a variadic call, handle args passed through "...".
4241   if (CallType != VariadicDoesNotApply) {
4242     // Assume that extern "C" functions with variadic arguments that
4243     // return __unknown_anytype aren't *really* variadic.
4244     if (Proto->getResultType() == Context.UnknownAnyTy &&
4245         FDecl && FDecl->isExternC()) {
4246       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4247         QualType paramType; // ignored
4248         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
4249         Invalid |= arg.isInvalid();
4250         AllArgs.push_back(arg.take());
4251       }
4252 
4253     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4254     } else {
4255       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4256         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4257                                                           FDecl);
4258         Invalid |= Arg.isInvalid();
4259         AllArgs.push_back(Arg.take());
4260       }
4261     }
4262 
4263     // Check for array bounds violations.
4264     for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4265       CheckArrayAccess(Args[i]);
4266   }
4267   return Invalid;
4268 }
4269 
4270 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4271   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4272   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4273     TL = DTL.getOriginalLoc();
4274   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4275     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4276       << ATL.getLocalSourceRange();
4277 }
4278 
4279 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4280 /// array parameter, check that it is non-null, and that if it is formed by
4281 /// array-to-pointer decay, the underlying array is sufficiently large.
4282 ///
4283 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4284 /// array type derivation, then for each call to the function, the value of the
4285 /// corresponding actual argument shall provide access to the first element of
4286 /// an array with at least as many elements as specified by the size expression.
4287 void
4288 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4289                                ParmVarDecl *Param,
4290                                const Expr *ArgExpr) {
4291   // Static array parameters are not supported in C++.
4292   if (!Param || getLangOpts().CPlusPlus)
4293     return;
4294 
4295   QualType OrigTy = Param->getOriginalType();
4296 
4297   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4298   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4299     return;
4300 
4301   if (ArgExpr->isNullPointerConstant(Context,
4302                                      Expr::NPC_NeverValueDependent)) {
4303     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4304     DiagnoseCalleeStaticArrayParam(*this, Param);
4305     return;
4306   }
4307 
4308   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4309   if (!CAT)
4310     return;
4311 
4312   const ConstantArrayType *ArgCAT =
4313     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4314   if (!ArgCAT)
4315     return;
4316 
4317   if (ArgCAT->getSize().ult(CAT->getSize())) {
4318     Diag(CallLoc, diag::warn_static_array_too_small)
4319       << ArgExpr->getSourceRange()
4320       << (unsigned) ArgCAT->getSize().getZExtValue()
4321       << (unsigned) CAT->getSize().getZExtValue();
4322     DiagnoseCalleeStaticArrayParam(*this, Param);
4323   }
4324 }
4325 
4326 /// Given a function expression of unknown-any type, try to rebuild it
4327 /// to have a function type.
4328 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4329 
4330 /// Is the given type a placeholder that we need to lower out
4331 /// immediately during argument processing?
4332 static bool isPlaceholderToRemoveAsArg(QualType type) {
4333   // Placeholders are never sugared.
4334   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4335   if (!placeholder) return false;
4336 
4337   switch (placeholder->getKind()) {
4338   // Ignore all the non-placeholder types.
4339 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4340 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4341 #include "clang/AST/BuiltinTypes.def"
4342     return false;
4343 
4344   // We cannot lower out overload sets; they might validly be resolved
4345   // by the call machinery.
4346   case BuiltinType::Overload:
4347     return false;
4348 
4349   // Unbridged casts in ARC can be handled in some call positions and
4350   // should be left in place.
4351   case BuiltinType::ARCUnbridgedCast:
4352     return false;
4353 
4354   // Pseudo-objects should be converted as soon as possible.
4355   case BuiltinType::PseudoObject:
4356     return true;
4357 
4358   // The debugger mode could theoretically but currently does not try
4359   // to resolve unknown-typed arguments based on known parameter types.
4360   case BuiltinType::UnknownAny:
4361     return true;
4362 
4363   // These are always invalid as call arguments and should be reported.
4364   case BuiltinType::BoundMember:
4365   case BuiltinType::BuiltinFn:
4366     return true;
4367   }
4368   llvm_unreachable("bad builtin type kind");
4369 }
4370 
4371 /// Check an argument list for placeholders that we won't try to
4372 /// handle later.
4373 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4374   // Apply this processing to all the arguments at once instead of
4375   // dying at the first failure.
4376   bool hasInvalid = false;
4377   for (size_t i = 0, e = args.size(); i != e; i++) {
4378     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4379       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4380       if (result.isInvalid()) hasInvalid = true;
4381       else args[i] = result.take();
4382     }
4383   }
4384   return hasInvalid;
4385 }
4386 
4387 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4388 /// This provides the location of the left/right parens and a list of comma
4389 /// locations.
4390 ExprResult
4391 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4392                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
4393                     Expr *ExecConfig, bool IsExecConfig) {
4394   // Since this might be a postfix expression, get rid of ParenListExprs.
4395   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4396   if (Result.isInvalid()) return ExprError();
4397   Fn = Result.take();
4398 
4399   if (checkArgsForPlaceholders(*this, ArgExprs))
4400     return ExprError();
4401 
4402   if (getLangOpts().CPlusPlus) {
4403     // If this is a pseudo-destructor expression, build the call immediately.
4404     if (isa<CXXPseudoDestructorExpr>(Fn)) {
4405       if (!ArgExprs.empty()) {
4406         // Pseudo-destructor calls should not have any arguments.
4407         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4408           << FixItHint::CreateRemoval(
4409                                     SourceRange(ArgExprs[0]->getLocStart(),
4410                                                 ArgExprs.back()->getLocEnd()));
4411       }
4412 
4413       return Owned(new (Context) CallExpr(Context, Fn, None,
4414                                           Context.VoidTy, VK_RValue,
4415                                           RParenLoc));
4416     }
4417     if (Fn->getType() == Context.PseudoObjectTy) {
4418       ExprResult result = CheckPlaceholderExpr(Fn);
4419       if (result.isInvalid()) return ExprError();
4420       Fn = result.take();
4421     }
4422 
4423     // Determine whether this is a dependent call inside a C++ template,
4424     // in which case we won't do any semantic analysis now.
4425     // FIXME: Will need to cache the results of name lookup (including ADL) in
4426     // Fn.
4427     bool Dependent = false;
4428     if (Fn->isTypeDependent())
4429       Dependent = true;
4430     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4431       Dependent = true;
4432 
4433     if (Dependent) {
4434       if (ExecConfig) {
4435         return Owned(new (Context) CUDAKernelCallExpr(
4436             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4437             Context.DependentTy, VK_RValue, RParenLoc));
4438       } else {
4439         return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
4440                                             Context.DependentTy, VK_RValue,
4441                                             RParenLoc));
4442       }
4443     }
4444 
4445     // Determine whether this is a call to an object (C++ [over.call.object]).
4446     if (Fn->getType()->isRecordType())
4447       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
4448                                                 ArgExprs, RParenLoc));
4449 
4450     if (Fn->getType() == Context.UnknownAnyTy) {
4451       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4452       if (result.isInvalid()) return ExprError();
4453       Fn = result.take();
4454     }
4455 
4456     if (Fn->getType() == Context.BoundMemberTy) {
4457       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4458     }
4459   }
4460 
4461   // Check for overloaded calls.  This can happen even in C due to extensions.
4462   if (Fn->getType() == Context.OverloadTy) {
4463     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4464 
4465     // We aren't supposed to apply this logic for if there's an '&' involved.
4466     if (!find.HasFormOfMemberPointer) {
4467       OverloadExpr *ovl = find.Expression;
4468       if (isa<UnresolvedLookupExpr>(ovl)) {
4469         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4470         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4471                                        RParenLoc, ExecConfig);
4472       } else {
4473         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4474                                          RParenLoc);
4475       }
4476     }
4477   }
4478 
4479   // If we're directly calling a function, get the appropriate declaration.
4480   if (Fn->getType() == Context.UnknownAnyTy) {
4481     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4482     if (result.isInvalid()) return ExprError();
4483     Fn = result.take();
4484   }
4485 
4486   Expr *NakedFn = Fn->IgnoreParens();
4487 
4488   NamedDecl *NDecl = 0;
4489   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4490     if (UnOp->getOpcode() == UO_AddrOf)
4491       NakedFn = UnOp->getSubExpr()->IgnoreParens();
4492 
4493   if (isa<DeclRefExpr>(NakedFn))
4494     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4495   else if (isa<MemberExpr>(NakedFn))
4496     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4497 
4498   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4499                                ExecConfig, IsExecConfig);
4500 }
4501 
4502 ExprResult
4503 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4504                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
4505   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4506   if (!ConfigDecl)
4507     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4508                           << "cudaConfigureCall");
4509   QualType ConfigQTy = ConfigDecl->getType();
4510 
4511   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4512       ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
4513   MarkFunctionReferenced(LLLLoc, ConfigDecl);
4514 
4515   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
4516                        /*IsExecConfig=*/true);
4517 }
4518 
4519 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4520 ///
4521 /// __builtin_astype( value, dst type )
4522 ///
4523 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4524                                  SourceLocation BuiltinLoc,
4525                                  SourceLocation RParenLoc) {
4526   ExprValueKind VK = VK_RValue;
4527   ExprObjectKind OK = OK_Ordinary;
4528   QualType DstTy = GetTypeFromParser(ParsedDestTy);
4529   QualType SrcTy = E->getType();
4530   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4531     return ExprError(Diag(BuiltinLoc,
4532                           diag::err_invalid_astype_of_different_size)
4533                      << DstTy
4534                      << SrcTy
4535                      << E->getSourceRange());
4536   return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
4537                RParenLoc));
4538 }
4539 
4540 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
4541 /// provided arguments.
4542 ///
4543 /// __builtin_convertvector( value, dst type )
4544 ///
4545 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4546                                         SourceLocation BuiltinLoc,
4547                                         SourceLocation RParenLoc) {
4548   TypeSourceInfo *TInfo;
4549   GetTypeFromParser(ParsedDestTy, &TInfo);
4550   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
4551 }
4552 
4553 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4554 /// i.e. an expression not of \p OverloadTy.  The expression should
4555 /// unary-convert to an expression of function-pointer or
4556 /// block-pointer type.
4557 ///
4558 /// \param NDecl the declaration being called, if available
4559 ExprResult
4560 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4561                             SourceLocation LParenLoc,
4562                             ArrayRef<Expr *> Args,
4563                             SourceLocation RParenLoc,
4564                             Expr *Config, bool IsExecConfig) {
4565   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4566   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4567 
4568   // Promote the function operand.
4569   // We special-case function promotion here because we only allow promoting
4570   // builtin functions to function pointers in the callee of a call.
4571   ExprResult Result;
4572   if (BuiltinID &&
4573       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4574     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4575                                CK_BuiltinFnToFnPtr).take();
4576   } else {
4577     Result = UsualUnaryConversions(Fn);
4578   }
4579   if (Result.isInvalid())
4580     return ExprError();
4581   Fn = Result.take();
4582 
4583   // Make the call expr early, before semantic checks.  This guarantees cleanup
4584   // of arguments and function on error.
4585   CallExpr *TheCall;
4586   if (Config)
4587     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4588                                                cast<CallExpr>(Config), Args,
4589                                                Context.BoolTy, VK_RValue,
4590                                                RParenLoc);
4591   else
4592     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4593                                      VK_RValue, RParenLoc);
4594 
4595   // Bail out early if calling a builtin with custom typechecking.
4596   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4597     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4598 
4599  retry:
4600   const FunctionType *FuncT;
4601   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4602     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4603     // have type pointer to function".
4604     FuncT = PT->getPointeeType()->getAs<FunctionType>();
4605     if (FuncT == 0)
4606       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4607                          << Fn->getType() << Fn->getSourceRange());
4608   } else if (const BlockPointerType *BPT =
4609                Fn->getType()->getAs<BlockPointerType>()) {
4610     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4611   } else {
4612     // Handle calls to expressions of unknown-any type.
4613     if (Fn->getType() == Context.UnknownAnyTy) {
4614       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4615       if (rewrite.isInvalid()) return ExprError();
4616       Fn = rewrite.take();
4617       TheCall->setCallee(Fn);
4618       goto retry;
4619     }
4620 
4621     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4622       << Fn->getType() << Fn->getSourceRange());
4623   }
4624 
4625   if (getLangOpts().CUDA) {
4626     if (Config) {
4627       // CUDA: Kernel calls must be to global functions
4628       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4629         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4630             << FDecl->getName() << Fn->getSourceRange());
4631 
4632       // CUDA: Kernel function must have 'void' return type
4633       if (!FuncT->getResultType()->isVoidType())
4634         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4635             << Fn->getType() << Fn->getSourceRange());
4636     } else {
4637       // CUDA: Calls to global functions must be configured
4638       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4639         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4640             << FDecl->getName() << Fn->getSourceRange());
4641     }
4642   }
4643 
4644   // Check for a valid return type
4645   if (CheckCallReturnType(FuncT->getResultType(),
4646                           Fn->getLocStart(), TheCall,
4647                           FDecl))
4648     return ExprError();
4649 
4650   // We know the result type of the call, set it.
4651   TheCall->setType(FuncT->getCallResultType(Context));
4652   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
4653 
4654   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4655   if (Proto) {
4656     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4657                                 IsExecConfig))
4658       return ExprError();
4659   } else {
4660     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4661 
4662     if (FDecl) {
4663       // Check if we have too few/too many template arguments, based
4664       // on our knowledge of the function definition.
4665       const FunctionDecl *Def = 0;
4666       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
4667         Proto = Def->getType()->getAs<FunctionProtoType>();
4668        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
4669           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4670           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
4671       }
4672 
4673       // If the function we're calling isn't a function prototype, but we have
4674       // a function prototype from a prior declaratiom, use that prototype.
4675       if (!FDecl->hasPrototype())
4676         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4677     }
4678 
4679     // Promote the arguments (C99 6.5.2.2p6).
4680     for (unsigned i = 0, e = Args.size(); i != e; i++) {
4681       Expr *Arg = Args[i];
4682 
4683       if (Proto && i < Proto->getNumArgs()) {
4684         InitializedEntity Entity
4685           = InitializedEntity::InitializeParameter(Context,
4686                                                    Proto->getArgType(i),
4687                                                    Proto->isArgConsumed(i));
4688         ExprResult ArgE = PerformCopyInitialization(Entity,
4689                                                     SourceLocation(),
4690                                                     Owned(Arg));
4691         if (ArgE.isInvalid())
4692           return true;
4693 
4694         Arg = ArgE.takeAs<Expr>();
4695 
4696       } else {
4697         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4698 
4699         if (ArgE.isInvalid())
4700           return true;
4701 
4702         Arg = ArgE.takeAs<Expr>();
4703       }
4704 
4705       if (RequireCompleteType(Arg->getLocStart(),
4706                               Arg->getType(),
4707                               diag::err_call_incomplete_argument, Arg))
4708         return ExprError();
4709 
4710       TheCall->setArg(i, Arg);
4711     }
4712   }
4713 
4714   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4715     if (!Method->isStatic())
4716       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4717         << Fn->getSourceRange());
4718 
4719   // Check for sentinels
4720   if (NDecl)
4721     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
4722 
4723   // Do special checking on direct calls to functions.
4724   if (FDecl) {
4725     if (CheckFunctionCall(FDecl, TheCall, Proto))
4726       return ExprError();
4727 
4728     if (BuiltinID)
4729       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4730   } else if (NDecl) {
4731     if (CheckPointerCall(NDecl, TheCall, Proto))
4732       return ExprError();
4733   } else {
4734     if (CheckOtherCall(TheCall, Proto))
4735       return ExprError();
4736   }
4737 
4738   return MaybeBindToTemporary(TheCall);
4739 }
4740 
4741 ExprResult
4742 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4743                            SourceLocation RParenLoc, Expr *InitExpr) {
4744   assert(Ty && "ActOnCompoundLiteral(): missing type");
4745   // FIXME: put back this assert when initializers are worked out.
4746   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4747 
4748   TypeSourceInfo *TInfo;
4749   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4750   if (!TInfo)
4751     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4752 
4753   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4754 }
4755 
4756 ExprResult
4757 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4758                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4759   QualType literalType = TInfo->getType();
4760 
4761   if (literalType->isArrayType()) {
4762     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4763           diag::err_illegal_decl_array_incomplete_type,
4764           SourceRange(LParenLoc,
4765                       LiteralExpr->getSourceRange().getEnd())))
4766       return ExprError();
4767     if (literalType->isVariableArrayType())
4768       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4769         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4770   } else if (!literalType->isDependentType() &&
4771              RequireCompleteType(LParenLoc, literalType,
4772                diag::err_typecheck_decl_incomplete_type,
4773                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4774     return ExprError();
4775 
4776   InitializedEntity Entity
4777     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
4778   InitializationKind Kind
4779     = InitializationKind::CreateCStyleCast(LParenLoc,
4780                                            SourceRange(LParenLoc, RParenLoc),
4781                                            /*InitList=*/true);
4782   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
4783   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4784                                       &literalType);
4785   if (Result.isInvalid())
4786     return ExprError();
4787   LiteralExpr = Result.get();
4788 
4789   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4790   if (isFileScope &&
4791       !LiteralExpr->isTypeDependent() &&
4792       !LiteralExpr->isValueDependent() &&
4793       !literalType->isDependentType()) { // 6.5.2.5p3
4794     if (CheckForConstantInitializer(LiteralExpr, literalType))
4795       return ExprError();
4796   }
4797 
4798   // In C, compound literals are l-values for some reason.
4799   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4800 
4801   return MaybeBindToTemporary(
4802            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4803                                              VK, LiteralExpr, isFileScope));
4804 }
4805 
4806 ExprResult
4807 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4808                     SourceLocation RBraceLoc) {
4809   // Immediately handle non-overload placeholders.  Overloads can be
4810   // resolved contextually, but everything else here can't.
4811   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4812     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4813       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4814 
4815       // Ignore failures; dropping the entire initializer list because
4816       // of one failure would be terrible for indexing/etc.
4817       if (result.isInvalid()) continue;
4818 
4819       InitArgList[I] = result.take();
4820     }
4821   }
4822 
4823   // Semantic analysis for initializers is done by ActOnDeclarator() and
4824   // CheckInitializer() - it requires knowledge of the object being intialized.
4825 
4826   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4827                                                RBraceLoc);
4828   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4829   return Owned(E);
4830 }
4831 
4832 /// Do an explicit extend of the given block pointer if we're in ARC.
4833 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4834   assert(E.get()->getType()->isBlockPointerType());
4835   assert(E.get()->isRValue());
4836 
4837   // Only do this in an r-value context.
4838   if (!S.getLangOpts().ObjCAutoRefCount) return;
4839 
4840   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4841                                CK_ARCExtendBlockObject, E.get(),
4842                                /*base path*/ 0, VK_RValue);
4843   S.ExprNeedsCleanups = true;
4844 }
4845 
4846 /// Prepare a conversion of the given expression to an ObjC object
4847 /// pointer type.
4848 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4849   QualType type = E.get()->getType();
4850   if (type->isObjCObjectPointerType()) {
4851     return CK_BitCast;
4852   } else if (type->isBlockPointerType()) {
4853     maybeExtendBlockObject(*this, E);
4854     return CK_BlockPointerToObjCPointerCast;
4855   } else {
4856     assert(type->isPointerType());
4857     return CK_CPointerToObjCPointerCast;
4858   }
4859 }
4860 
4861 /// Prepares for a scalar cast, performing all the necessary stages
4862 /// except the final cast and returning the kind required.
4863 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4864   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4865   // Also, callers should have filtered out the invalid cases with
4866   // pointers.  Everything else should be possible.
4867 
4868   QualType SrcTy = Src.get()->getType();
4869   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4870     return CK_NoOp;
4871 
4872   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4873   case Type::STK_MemberPointer:
4874     llvm_unreachable("member pointer type in C");
4875 
4876   case Type::STK_CPointer:
4877   case Type::STK_BlockPointer:
4878   case Type::STK_ObjCObjectPointer:
4879     switch (DestTy->getScalarTypeKind()) {
4880     case Type::STK_CPointer:
4881       return CK_BitCast;
4882     case Type::STK_BlockPointer:
4883       return (SrcKind == Type::STK_BlockPointer
4884                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4885     case Type::STK_ObjCObjectPointer:
4886       if (SrcKind == Type::STK_ObjCObjectPointer)
4887         return CK_BitCast;
4888       if (SrcKind == Type::STK_CPointer)
4889         return CK_CPointerToObjCPointerCast;
4890       maybeExtendBlockObject(*this, Src);
4891       return CK_BlockPointerToObjCPointerCast;
4892     case Type::STK_Bool:
4893       return CK_PointerToBoolean;
4894     case Type::STK_Integral:
4895       return CK_PointerToIntegral;
4896     case Type::STK_Floating:
4897     case Type::STK_FloatingComplex:
4898     case Type::STK_IntegralComplex:
4899     case Type::STK_MemberPointer:
4900       llvm_unreachable("illegal cast from pointer");
4901     }
4902     llvm_unreachable("Should have returned before this");
4903 
4904   case Type::STK_Bool: // casting from bool is like casting from an integer
4905   case Type::STK_Integral:
4906     switch (DestTy->getScalarTypeKind()) {
4907     case Type::STK_CPointer:
4908     case Type::STK_ObjCObjectPointer:
4909     case Type::STK_BlockPointer:
4910       if (Src.get()->isNullPointerConstant(Context,
4911                                            Expr::NPC_ValueDependentIsNull))
4912         return CK_NullToPointer;
4913       return CK_IntegralToPointer;
4914     case Type::STK_Bool:
4915       return CK_IntegralToBoolean;
4916     case Type::STK_Integral:
4917       return CK_IntegralCast;
4918     case Type::STK_Floating:
4919       return CK_IntegralToFloating;
4920     case Type::STK_IntegralComplex:
4921       Src = ImpCastExprToType(Src.take(),
4922                               DestTy->castAs<ComplexType>()->getElementType(),
4923                               CK_IntegralCast);
4924       return CK_IntegralRealToComplex;
4925     case Type::STK_FloatingComplex:
4926       Src = ImpCastExprToType(Src.take(),
4927                               DestTy->castAs<ComplexType>()->getElementType(),
4928                               CK_IntegralToFloating);
4929       return CK_FloatingRealToComplex;
4930     case Type::STK_MemberPointer:
4931       llvm_unreachable("member pointer type in C");
4932     }
4933     llvm_unreachable("Should have returned before this");
4934 
4935   case Type::STK_Floating:
4936     switch (DestTy->getScalarTypeKind()) {
4937     case Type::STK_Floating:
4938       return CK_FloatingCast;
4939     case Type::STK_Bool:
4940       return CK_FloatingToBoolean;
4941     case Type::STK_Integral:
4942       return CK_FloatingToIntegral;
4943     case Type::STK_FloatingComplex:
4944       Src = ImpCastExprToType(Src.take(),
4945                               DestTy->castAs<ComplexType>()->getElementType(),
4946                               CK_FloatingCast);
4947       return CK_FloatingRealToComplex;
4948     case Type::STK_IntegralComplex:
4949       Src = ImpCastExprToType(Src.take(),
4950                               DestTy->castAs<ComplexType>()->getElementType(),
4951                               CK_FloatingToIntegral);
4952       return CK_IntegralRealToComplex;
4953     case Type::STK_CPointer:
4954     case Type::STK_ObjCObjectPointer:
4955     case Type::STK_BlockPointer:
4956       llvm_unreachable("valid float->pointer cast?");
4957     case Type::STK_MemberPointer:
4958       llvm_unreachable("member pointer type in C");
4959     }
4960     llvm_unreachable("Should have returned before this");
4961 
4962   case Type::STK_FloatingComplex:
4963     switch (DestTy->getScalarTypeKind()) {
4964     case Type::STK_FloatingComplex:
4965       return CK_FloatingComplexCast;
4966     case Type::STK_IntegralComplex:
4967       return CK_FloatingComplexToIntegralComplex;
4968     case Type::STK_Floating: {
4969       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4970       if (Context.hasSameType(ET, DestTy))
4971         return CK_FloatingComplexToReal;
4972       Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4973       return CK_FloatingCast;
4974     }
4975     case Type::STK_Bool:
4976       return CK_FloatingComplexToBoolean;
4977     case Type::STK_Integral:
4978       Src = ImpCastExprToType(Src.take(),
4979                               SrcTy->castAs<ComplexType>()->getElementType(),
4980                               CK_FloatingComplexToReal);
4981       return CK_FloatingToIntegral;
4982     case Type::STK_CPointer:
4983     case Type::STK_ObjCObjectPointer:
4984     case Type::STK_BlockPointer:
4985       llvm_unreachable("valid complex float->pointer cast?");
4986     case Type::STK_MemberPointer:
4987       llvm_unreachable("member pointer type in C");
4988     }
4989     llvm_unreachable("Should have returned before this");
4990 
4991   case Type::STK_IntegralComplex:
4992     switch (DestTy->getScalarTypeKind()) {
4993     case Type::STK_FloatingComplex:
4994       return CK_IntegralComplexToFloatingComplex;
4995     case Type::STK_IntegralComplex:
4996       return CK_IntegralComplexCast;
4997     case Type::STK_Integral: {
4998       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4999       if (Context.hasSameType(ET, DestTy))
5000         return CK_IntegralComplexToReal;
5001       Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
5002       return CK_IntegralCast;
5003     }
5004     case Type::STK_Bool:
5005       return CK_IntegralComplexToBoolean;
5006     case Type::STK_Floating:
5007       Src = ImpCastExprToType(Src.take(),
5008                               SrcTy->castAs<ComplexType>()->getElementType(),
5009                               CK_IntegralComplexToReal);
5010       return CK_IntegralToFloating;
5011     case Type::STK_CPointer:
5012     case Type::STK_ObjCObjectPointer:
5013     case Type::STK_BlockPointer:
5014       llvm_unreachable("valid complex int->pointer cast?");
5015     case Type::STK_MemberPointer:
5016       llvm_unreachable("member pointer type in C");
5017     }
5018     llvm_unreachable("Should have returned before this");
5019   }
5020 
5021   llvm_unreachable("Unhandled scalar cast");
5022 }
5023 
5024 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5025                            CastKind &Kind) {
5026   assert(VectorTy->isVectorType() && "Not a vector type!");
5027 
5028   if (Ty->isVectorType() || Ty->isIntegerType()) {
5029     if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
5030       return Diag(R.getBegin(),
5031                   Ty->isVectorType() ?
5032                   diag::err_invalid_conversion_between_vectors :
5033                   diag::err_invalid_conversion_between_vector_and_integer)
5034         << VectorTy << Ty << R;
5035   } else
5036     return Diag(R.getBegin(),
5037                 diag::err_invalid_conversion_between_vector_and_scalar)
5038       << VectorTy << Ty << R;
5039 
5040   Kind = CK_BitCast;
5041   return false;
5042 }
5043 
5044 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5045                                     Expr *CastExpr, CastKind &Kind) {
5046   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5047 
5048   QualType SrcTy = CastExpr->getType();
5049 
5050   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5051   // an ExtVectorType.
5052   // In OpenCL, casts between vectors of different types are not allowed.
5053   // (See OpenCL 6.2).
5054   if (SrcTy->isVectorType()) {
5055     if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
5056         || (getLangOpts().OpenCL &&
5057             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5058       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5059         << DestTy << SrcTy << R;
5060       return ExprError();
5061     }
5062     Kind = CK_BitCast;
5063     return Owned(CastExpr);
5064   }
5065 
5066   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5067   // conversion will take place first from scalar to elt type, and then
5068   // splat from elt type to vector.
5069   if (SrcTy->isPointerType())
5070     return Diag(R.getBegin(),
5071                 diag::err_invalid_conversion_between_vector_and_scalar)
5072       << DestTy << SrcTy << R;
5073 
5074   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5075   ExprResult CastExprRes = Owned(CastExpr);
5076   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
5077   if (CastExprRes.isInvalid())
5078     return ExprError();
5079   CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
5080 
5081   Kind = CK_VectorSplat;
5082   return Owned(CastExpr);
5083 }
5084 
5085 ExprResult
5086 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5087                     Declarator &D, ParsedType &Ty,
5088                     SourceLocation RParenLoc, Expr *CastExpr) {
5089   assert(!D.isInvalidType() && (CastExpr != 0) &&
5090          "ActOnCastExpr(): missing type or expr");
5091 
5092   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5093   if (D.isInvalidType())
5094     return ExprError();
5095 
5096   if (getLangOpts().CPlusPlus) {
5097     // Check that there are no default arguments (C++ only).
5098     CheckExtraCXXDefaultArguments(D);
5099   }
5100 
5101   checkUnusedDeclAttributes(D);
5102 
5103   QualType castType = castTInfo->getType();
5104   Ty = CreateParsedType(castType, castTInfo);
5105 
5106   bool isVectorLiteral = false;
5107 
5108   // Check for an altivec or OpenCL literal,
5109   // i.e. all the elements are integer constants.
5110   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5111   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5112   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
5113        && castType->isVectorType() && (PE || PLE)) {
5114     if (PLE && PLE->getNumExprs() == 0) {
5115       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5116       return ExprError();
5117     }
5118     if (PE || PLE->getNumExprs() == 1) {
5119       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5120       if (!E->getType()->isVectorType())
5121         isVectorLiteral = true;
5122     }
5123     else
5124       isVectorLiteral = true;
5125   }
5126 
5127   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5128   // then handle it as such.
5129   if (isVectorLiteral)
5130     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5131 
5132   // If the Expr being casted is a ParenListExpr, handle it specially.
5133   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5134   // sequence of BinOp comma operators.
5135   if (isa<ParenListExpr>(CastExpr)) {
5136     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5137     if (Result.isInvalid()) return ExprError();
5138     CastExpr = Result.take();
5139   }
5140 
5141   if (getLangOpts().CPlusPlus && !castType->isVoidType())
5142     Diag(CastExpr->getLocStart(), diag::warn_old_style_cast)
5143         << SourceRange(LParenLoc, RParenLoc);
5144 
5145   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5146 }
5147 
5148 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5149                                     SourceLocation RParenLoc, Expr *E,
5150                                     TypeSourceInfo *TInfo) {
5151   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5152          "Expected paren or paren list expression");
5153 
5154   Expr **exprs;
5155   unsigned numExprs;
5156   Expr *subExpr;
5157   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5158   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5159     LiteralLParenLoc = PE->getLParenLoc();
5160     LiteralRParenLoc = PE->getRParenLoc();
5161     exprs = PE->getExprs();
5162     numExprs = PE->getNumExprs();
5163   } else { // isa<ParenExpr> by assertion at function entrance
5164     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5165     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5166     subExpr = cast<ParenExpr>(E)->getSubExpr();
5167     exprs = &subExpr;
5168     numExprs = 1;
5169   }
5170 
5171   QualType Ty = TInfo->getType();
5172   assert(Ty->isVectorType() && "Expected vector type");
5173 
5174   SmallVector<Expr *, 8> initExprs;
5175   const VectorType *VTy = Ty->getAs<VectorType>();
5176   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5177 
5178   // '(...)' form of vector initialization in AltiVec: the number of
5179   // initializers must be one or must match the size of the vector.
5180   // If a single value is specified in the initializer then it will be
5181   // replicated to all the components of the vector
5182   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5183     // The number of initializers must be one or must match the size of the
5184     // vector. If a single value is specified in the initializer then it will
5185     // be replicated to all the components of the vector
5186     if (numExprs == 1) {
5187       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5188       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5189       if (Literal.isInvalid())
5190         return ExprError();
5191       Literal = ImpCastExprToType(Literal.take(), ElemTy,
5192                                   PrepareScalarCast(Literal, ElemTy));
5193       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
5194     }
5195     else if (numExprs < numElems) {
5196       Diag(E->getExprLoc(),
5197            diag::err_incorrect_number_of_vector_initializers);
5198       return ExprError();
5199     }
5200     else
5201       initExprs.append(exprs, exprs + numExprs);
5202   }
5203   else {
5204     // For OpenCL, when the number of initializers is a single value,
5205     // it will be replicated to all components of the vector.
5206     if (getLangOpts().OpenCL &&
5207         VTy->getVectorKind() == VectorType::GenericVector &&
5208         numExprs == 1) {
5209         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5210         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5211         if (Literal.isInvalid())
5212           return ExprError();
5213         Literal = ImpCastExprToType(Literal.take(), ElemTy,
5214                                     PrepareScalarCast(Literal, ElemTy));
5215         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
5216     }
5217 
5218     initExprs.append(exprs, exprs + numExprs);
5219   }
5220   // FIXME: This means that pretty-printing the final AST will produce curly
5221   // braces instead of the original commas.
5222   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5223                                                    initExprs, LiteralRParenLoc);
5224   initE->setType(Ty);
5225   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5226 }
5227 
5228 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5229 /// the ParenListExpr into a sequence of comma binary operators.
5230 ExprResult
5231 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5232   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5233   if (!E)
5234     return Owned(OrigExpr);
5235 
5236   ExprResult Result(E->getExpr(0));
5237 
5238   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5239     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5240                         E->getExpr(i));
5241 
5242   if (Result.isInvalid()) return ExprError();
5243 
5244   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5245 }
5246 
5247 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5248                                     SourceLocation R,
5249                                     MultiExprArg Val) {
5250   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5251   return Owned(expr);
5252 }
5253 
5254 /// \brief Emit a specialized diagnostic when one expression is a null pointer
5255 /// constant and the other is not a pointer.  Returns true if a diagnostic is
5256 /// emitted.
5257 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5258                                       SourceLocation QuestionLoc) {
5259   Expr *NullExpr = LHSExpr;
5260   Expr *NonPointerExpr = RHSExpr;
5261   Expr::NullPointerConstantKind NullKind =
5262       NullExpr->isNullPointerConstant(Context,
5263                                       Expr::NPC_ValueDependentIsNotNull);
5264 
5265   if (NullKind == Expr::NPCK_NotNull) {
5266     NullExpr = RHSExpr;
5267     NonPointerExpr = LHSExpr;
5268     NullKind =
5269         NullExpr->isNullPointerConstant(Context,
5270                                         Expr::NPC_ValueDependentIsNotNull);
5271   }
5272 
5273   if (NullKind == Expr::NPCK_NotNull)
5274     return false;
5275 
5276   if (NullKind == Expr::NPCK_ZeroExpression)
5277     return false;
5278 
5279   if (NullKind == Expr::NPCK_ZeroLiteral) {
5280     // In this case, check to make sure that we got here from a "NULL"
5281     // string in the source code.
5282     NullExpr = NullExpr->IgnoreParenImpCasts();
5283     SourceLocation loc = NullExpr->getExprLoc();
5284     if (!findMacroSpelling(loc, "NULL"))
5285       return false;
5286   }
5287 
5288   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5289   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5290       << NonPointerExpr->getType() << DiagType
5291       << NonPointerExpr->getSourceRange();
5292   return true;
5293 }
5294 
5295 /// \brief Return false if the condition expression is valid, true otherwise.
5296 static bool checkCondition(Sema &S, Expr *Cond) {
5297   QualType CondTy = Cond->getType();
5298 
5299   // C99 6.5.15p2
5300   if (CondTy->isScalarType()) return false;
5301 
5302   // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
5303   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
5304     return false;
5305 
5306   // Emit the proper error message.
5307   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
5308                               diag::err_typecheck_cond_expect_scalar :
5309                               diag::err_typecheck_cond_expect_scalar_or_vector)
5310     << CondTy;
5311   return true;
5312 }
5313 
5314 /// \brief Return false if the two expressions can be converted to a vector,
5315 /// true otherwise
5316 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
5317                                                     ExprResult &RHS,
5318                                                     QualType CondTy) {
5319   // Both operands should be of scalar type.
5320   if (!LHS.get()->getType()->isScalarType()) {
5321     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5322       << CondTy;
5323     return true;
5324   }
5325   if (!RHS.get()->getType()->isScalarType()) {
5326     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5327       << CondTy;
5328     return true;
5329   }
5330 
5331   // Implicity convert these scalars to the type of the condition.
5332   LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5333   RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
5334   return false;
5335 }
5336 
5337 /// \brief Handle when one or both operands are void type.
5338 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5339                                          ExprResult &RHS) {
5340     Expr *LHSExpr = LHS.get();
5341     Expr *RHSExpr = RHS.get();
5342 
5343     if (!LHSExpr->getType()->isVoidType())
5344       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5345         << RHSExpr->getSourceRange();
5346     if (!RHSExpr->getType()->isVoidType())
5347       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5348         << LHSExpr->getSourceRange();
5349     LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
5350     RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
5351     return S.Context.VoidTy;
5352 }
5353 
5354 /// \brief Return false if the NullExpr can be promoted to PointerTy,
5355 /// true otherwise.
5356 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5357                                         QualType PointerTy) {
5358   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5359       !NullExpr.get()->isNullPointerConstant(S.Context,
5360                                             Expr::NPC_ValueDependentIsNull))
5361     return true;
5362 
5363   NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
5364   return false;
5365 }
5366 
5367 /// \brief Checks compatibility between two pointers and return the resulting
5368 /// type.
5369 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5370                                                      ExprResult &RHS,
5371                                                      SourceLocation Loc) {
5372   QualType LHSTy = LHS.get()->getType();
5373   QualType RHSTy = RHS.get()->getType();
5374 
5375   if (S.Context.hasSameType(LHSTy, RHSTy)) {
5376     // Two identical pointers types are always compatible.
5377     return LHSTy;
5378   }
5379 
5380   QualType lhptee, rhptee;
5381 
5382   // Get the pointee types.
5383   bool IsBlockPointer = false;
5384   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5385     lhptee = LHSBTy->getPointeeType();
5386     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5387     IsBlockPointer = true;
5388   } else {
5389     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5390     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5391   }
5392 
5393   // C99 6.5.15p6: If both operands are pointers to compatible types or to
5394   // differently qualified versions of compatible types, the result type is
5395   // a pointer to an appropriately qualified version of the composite
5396   // type.
5397 
5398   // Only CVR-qualifiers exist in the standard, and the differently-qualified
5399   // clause doesn't make sense for our extensions. E.g. address space 2 should
5400   // be incompatible with address space 3: they may live on different devices or
5401   // anything.
5402   Qualifiers lhQual = lhptee.getQualifiers();
5403   Qualifiers rhQual = rhptee.getQualifiers();
5404 
5405   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5406   lhQual.removeCVRQualifiers();
5407   rhQual.removeCVRQualifiers();
5408 
5409   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5410   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5411 
5412   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5413 
5414   if (CompositeTy.isNull()) {
5415     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
5416       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5417       << RHS.get()->getSourceRange();
5418     // In this situation, we assume void* type. No especially good
5419     // reason, but this is what gcc does, and we do have to pick
5420     // to get a consistent AST.
5421     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5422     LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5423     RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5424     return incompatTy;
5425   }
5426 
5427   // The pointer types are compatible.
5428   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5429   if (IsBlockPointer)
5430     ResultTy = S.Context.getBlockPointerType(ResultTy);
5431   else
5432     ResultTy = S.Context.getPointerType(ResultTy);
5433 
5434   LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
5435   RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
5436   return ResultTy;
5437 }
5438 
5439 /// \brief Return the resulting type when the operands are both block pointers.
5440 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5441                                                           ExprResult &LHS,
5442                                                           ExprResult &RHS,
5443                                                           SourceLocation Loc) {
5444   QualType LHSTy = LHS.get()->getType();
5445   QualType RHSTy = RHS.get()->getType();
5446 
5447   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5448     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5449       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5450       LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5451       RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5452       return destType;
5453     }
5454     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5455       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5456       << RHS.get()->getSourceRange();
5457     return QualType();
5458   }
5459 
5460   // We have 2 block pointer types.
5461   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5462 }
5463 
5464 /// \brief Return the resulting type when the operands are both pointers.
5465 static QualType
5466 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5467                                             ExprResult &RHS,
5468                                             SourceLocation Loc) {
5469   // get the pointer types
5470   QualType LHSTy = LHS.get()->getType();
5471   QualType RHSTy = RHS.get()->getType();
5472 
5473   // get the "pointed to" types
5474   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5475   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5476 
5477   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5478   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5479     // Figure out necessary qualifiers (C99 6.5.15p6)
5480     QualType destPointee
5481       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5482     QualType destType = S.Context.getPointerType(destPointee);
5483     // Add qualifiers if necessary.
5484     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5485     // Promote to void*.
5486     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5487     return destType;
5488   }
5489   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5490     QualType destPointee
5491       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5492     QualType destType = S.Context.getPointerType(destPointee);
5493     // Add qualifiers if necessary.
5494     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5495     // Promote to void*.
5496     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5497     return destType;
5498   }
5499 
5500   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5501 }
5502 
5503 /// \brief Return false if the first expression is not an integer and the second
5504 /// expression is not a pointer, true otherwise.
5505 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5506                                         Expr* PointerExpr, SourceLocation Loc,
5507                                         bool IsIntFirstExpr) {
5508   if (!PointerExpr->getType()->isPointerType() ||
5509       !Int.get()->getType()->isIntegerType())
5510     return false;
5511 
5512   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5513   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5514 
5515   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5516     << Expr1->getType() << Expr2->getType()
5517     << Expr1->getSourceRange() << Expr2->getSourceRange();
5518   Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
5519                             CK_IntegralToPointer);
5520   return true;
5521 }
5522 
5523 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5524 /// In that case, LHS = cond.
5525 /// C99 6.5.15
5526 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5527                                         ExprResult &RHS, ExprValueKind &VK,
5528                                         ExprObjectKind &OK,
5529                                         SourceLocation QuestionLoc) {
5530 
5531   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5532   if (!LHSResult.isUsable()) return QualType();
5533   LHS = LHSResult;
5534 
5535   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5536   if (!RHSResult.isUsable()) return QualType();
5537   RHS = RHSResult;
5538 
5539   // C++ is sufficiently different to merit its own checker.
5540   if (getLangOpts().CPlusPlus)
5541     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5542 
5543   VK = VK_RValue;
5544   OK = OK_Ordinary;
5545 
5546   // First, check the condition.
5547   Cond = UsualUnaryConversions(Cond.take());
5548   if (Cond.isInvalid())
5549     return QualType();
5550   if (checkCondition(*this, Cond.get()))
5551     return QualType();
5552 
5553   // Now check the two expressions.
5554   if (LHS.get()->getType()->isVectorType() ||
5555       RHS.get()->getType()->isVectorType())
5556     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5557 
5558   UsualArithmeticConversions(LHS, RHS);
5559   if (LHS.isInvalid() || RHS.isInvalid())
5560     return QualType();
5561 
5562   QualType CondTy = Cond.get()->getType();
5563   QualType LHSTy = LHS.get()->getType();
5564   QualType RHSTy = RHS.get()->getType();
5565 
5566   // If the condition is a vector, and both operands are scalar,
5567   // attempt to implicity convert them to the vector type to act like the
5568   // built in select. (OpenCL v1.1 s6.3.i)
5569   if (getLangOpts().OpenCL && CondTy->isVectorType())
5570     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5571       return QualType();
5572 
5573   // If both operands have arithmetic type, do the usual arithmetic conversions
5574   // to find a common type: C99 6.5.15p3,5.
5575   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType())
5576     return LHS.get()->getType();
5577 
5578   // If both operands are the same structure or union type, the result is that
5579   // type.
5580   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5581     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5582       if (LHSRT->getDecl() == RHSRT->getDecl())
5583         // "If both the operands have structure or union type, the result has
5584         // that type."  This implies that CV qualifiers are dropped.
5585         return LHSTy.getUnqualifiedType();
5586     // FIXME: Type of conditional expression must be complete in C mode.
5587   }
5588 
5589   // C99 6.5.15p5: "If both operands have void type, the result has void type."
5590   // The following || allows only one side to be void (a GCC-ism).
5591   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5592     return checkConditionalVoidType(*this, LHS, RHS);
5593   }
5594 
5595   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5596   // the type of the other operand."
5597   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5598   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5599 
5600   // All objective-c pointer type analysis is done here.
5601   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5602                                                         QuestionLoc);
5603   if (LHS.isInvalid() || RHS.isInvalid())
5604     return QualType();
5605   if (!compositeType.isNull())
5606     return compositeType;
5607 
5608 
5609   // Handle block pointer types.
5610   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5611     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5612                                                      QuestionLoc);
5613 
5614   // Check constraints for C object pointers types (C99 6.5.15p3,6).
5615   if (LHSTy->isPointerType() && RHSTy->isPointerType())
5616     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5617                                                        QuestionLoc);
5618 
5619   // GCC compatibility: soften pointer/integer mismatch.  Note that
5620   // null pointers have been filtered out by this point.
5621   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5622       /*isIntFirstExpr=*/true))
5623     return RHSTy;
5624   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5625       /*isIntFirstExpr=*/false))
5626     return LHSTy;
5627 
5628   // Emit a better diagnostic if one of the expressions is a null pointer
5629   // constant and the other is not a pointer type. In this case, the user most
5630   // likely forgot to take the address of the other expression.
5631   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5632     return QualType();
5633 
5634   // Otherwise, the operands are not compatible.
5635   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5636     << LHSTy << RHSTy << LHS.get()->getSourceRange()
5637     << RHS.get()->getSourceRange();
5638   return QualType();
5639 }
5640 
5641 /// FindCompositeObjCPointerType - Helper method to find composite type of
5642 /// two objective-c pointer types of the two input expressions.
5643 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5644                                             SourceLocation QuestionLoc) {
5645   QualType LHSTy = LHS.get()->getType();
5646   QualType RHSTy = RHS.get()->getType();
5647 
5648   // Handle things like Class and struct objc_class*.  Here we case the result
5649   // to the pseudo-builtin, because that will be implicitly cast back to the
5650   // redefinition type if an attempt is made to access its fields.
5651   if (LHSTy->isObjCClassType() &&
5652       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5653     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5654     return LHSTy;
5655   }
5656   if (RHSTy->isObjCClassType() &&
5657       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5658     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5659     return RHSTy;
5660   }
5661   // And the same for struct objc_object* / id
5662   if (LHSTy->isObjCIdType() &&
5663       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5664     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5665     return LHSTy;
5666   }
5667   if (RHSTy->isObjCIdType() &&
5668       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5669     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5670     return RHSTy;
5671   }
5672   // And the same for struct objc_selector* / SEL
5673   if (Context.isObjCSelType(LHSTy) &&
5674       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5675     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
5676     return LHSTy;
5677   }
5678   if (Context.isObjCSelType(RHSTy) &&
5679       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5680     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
5681     return RHSTy;
5682   }
5683   // Check constraints for Objective-C object pointers types.
5684   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5685 
5686     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5687       // Two identical object pointer types are always compatible.
5688       return LHSTy;
5689     }
5690     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5691     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5692     QualType compositeType = LHSTy;
5693 
5694     // If both operands are interfaces and either operand can be
5695     // assigned to the other, use that type as the composite
5696     // type. This allows
5697     //   xxx ? (A*) a : (B*) b
5698     // where B is a subclass of A.
5699     //
5700     // Additionally, as for assignment, if either type is 'id'
5701     // allow silent coercion. Finally, if the types are
5702     // incompatible then make sure to use 'id' as the composite
5703     // type so the result is acceptable for sending messages to.
5704 
5705     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5706     // It could return the composite type.
5707     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5708       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5709     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5710       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5711     } else if ((LHSTy->isObjCQualifiedIdType() ||
5712                 RHSTy->isObjCQualifiedIdType()) &&
5713                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5714       // Need to handle "id<xx>" explicitly.
5715       // GCC allows qualified id and any Objective-C type to devolve to
5716       // id. Currently localizing to here until clear this should be
5717       // part of ObjCQualifiedIdTypesAreCompatible.
5718       compositeType = Context.getObjCIdType();
5719     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5720       compositeType = Context.getObjCIdType();
5721     } else if (!(compositeType =
5722                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5723       ;
5724     else {
5725       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5726       << LHSTy << RHSTy
5727       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5728       QualType incompatTy = Context.getObjCIdType();
5729       LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5730       RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5731       return incompatTy;
5732     }
5733     // The object pointer types are compatible.
5734     LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5735     RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
5736     return compositeType;
5737   }
5738   // Check Objective-C object pointer types and 'void *'
5739   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5740     if (getLangOpts().ObjCAutoRefCount) {
5741       // ARC forbids the implicit conversion of object pointers to 'void *',
5742       // so these types are not compatible.
5743       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5744           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5745       LHS = RHS = true;
5746       return QualType();
5747     }
5748     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5749     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5750     QualType destPointee
5751     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5752     QualType destType = Context.getPointerType(destPointee);
5753     // Add qualifiers if necessary.
5754     LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5755     // Promote to void*.
5756     RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5757     return destType;
5758   }
5759   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5760     if (getLangOpts().ObjCAutoRefCount) {
5761       // ARC forbids the implicit conversion of object pointers to 'void *',
5762       // so these types are not compatible.
5763       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5764           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5765       LHS = RHS = true;
5766       return QualType();
5767     }
5768     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5769     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5770     QualType destPointee
5771     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5772     QualType destType = Context.getPointerType(destPointee);
5773     // Add qualifiers if necessary.
5774     RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5775     // Promote to void*.
5776     LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5777     return destType;
5778   }
5779   return QualType();
5780 }
5781 
5782 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5783 /// ParenRange in parentheses.
5784 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5785                                const PartialDiagnostic &Note,
5786                                SourceRange ParenRange) {
5787   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5788   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5789       EndLoc.isValid()) {
5790     Self.Diag(Loc, Note)
5791       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5792       << FixItHint::CreateInsertion(EndLoc, ")");
5793   } else {
5794     // We can't display the parentheses, so just show the bare note.
5795     Self.Diag(Loc, Note) << ParenRange;
5796   }
5797 }
5798 
5799 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5800   return Opc >= BO_Mul && Opc <= BO_Shr;
5801 }
5802 
5803 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5804 /// expression, either using a built-in or overloaded operator,
5805 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5806 /// expression.
5807 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5808                                    Expr **RHSExprs) {
5809   // Don't strip parenthesis: we should not warn if E is in parenthesis.
5810   E = E->IgnoreImpCasts();
5811   E = E->IgnoreConversionOperator();
5812   E = E->IgnoreImpCasts();
5813 
5814   // Built-in binary operator.
5815   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5816     if (IsArithmeticOp(OP->getOpcode())) {
5817       *Opcode = OP->getOpcode();
5818       *RHSExprs = OP->getRHS();
5819       return true;
5820     }
5821   }
5822 
5823   // Overloaded operator.
5824   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5825     if (Call->getNumArgs() != 2)
5826       return false;
5827 
5828     // Make sure this is really a binary operator that is safe to pass into
5829     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5830     OverloadedOperatorKind OO = Call->getOperator();
5831     if (OO < OO_Plus || OO > OO_Arrow ||
5832         OO == OO_PlusPlus || OO == OO_MinusMinus)
5833       return false;
5834 
5835     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5836     if (IsArithmeticOp(OpKind)) {
5837       *Opcode = OpKind;
5838       *RHSExprs = Call->getArg(1);
5839       return true;
5840     }
5841   }
5842 
5843   return false;
5844 }
5845 
5846 static bool IsLogicOp(BinaryOperatorKind Opc) {
5847   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5848 }
5849 
5850 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5851 /// or is a logical expression such as (x==y) which has int type, but is
5852 /// commonly interpreted as boolean.
5853 static bool ExprLooksBoolean(Expr *E) {
5854   E = E->IgnoreParenImpCasts();
5855 
5856   if (E->getType()->isBooleanType())
5857     return true;
5858   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5859     return IsLogicOp(OP->getOpcode());
5860   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5861     return OP->getOpcode() == UO_LNot;
5862 
5863   return false;
5864 }
5865 
5866 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5867 /// and binary operator are mixed in a way that suggests the programmer assumed
5868 /// the conditional operator has higher precedence, for example:
5869 /// "int x = a + someBinaryCondition ? 1 : 2".
5870 static void DiagnoseConditionalPrecedence(Sema &Self,
5871                                           SourceLocation OpLoc,
5872                                           Expr *Condition,
5873                                           Expr *LHSExpr,
5874                                           Expr *RHSExpr) {
5875   BinaryOperatorKind CondOpcode;
5876   Expr *CondRHS;
5877 
5878   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5879     return;
5880   if (!ExprLooksBoolean(CondRHS))
5881     return;
5882 
5883   // The condition is an arithmetic binary expression, with a right-
5884   // hand side that looks boolean, so warn.
5885 
5886   Self.Diag(OpLoc, diag::warn_precedence_conditional)
5887       << Condition->getSourceRange()
5888       << BinaryOperator::getOpcodeStr(CondOpcode);
5889 
5890   SuggestParentheses(Self, OpLoc,
5891     Self.PDiag(diag::note_precedence_silence)
5892       << BinaryOperator::getOpcodeStr(CondOpcode),
5893     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5894 
5895   SuggestParentheses(Self, OpLoc,
5896     Self.PDiag(diag::note_precedence_conditional_first),
5897     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5898 }
5899 
5900 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5901 /// in the case of a the GNU conditional expr extension.
5902 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5903                                     SourceLocation ColonLoc,
5904                                     Expr *CondExpr, Expr *LHSExpr,
5905                                     Expr *RHSExpr) {
5906   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5907   // was the condition.
5908   OpaqueValueExpr *opaqueValue = 0;
5909   Expr *commonExpr = 0;
5910   if (LHSExpr == 0) {
5911     commonExpr = CondExpr;
5912     // Lower out placeholder types first.  This is important so that we don't
5913     // try to capture a placeholder. This happens in few cases in C++; such
5914     // as Objective-C++'s dictionary subscripting syntax.
5915     if (commonExpr->hasPlaceholderType()) {
5916       ExprResult result = CheckPlaceholderExpr(commonExpr);
5917       if (!result.isUsable()) return ExprError();
5918       commonExpr = result.take();
5919     }
5920     // We usually want to apply unary conversions *before* saving, except
5921     // in the special case of a C++ l-value conditional.
5922     if (!(getLangOpts().CPlusPlus
5923           && !commonExpr->isTypeDependent()
5924           && commonExpr->getValueKind() == RHSExpr->getValueKind()
5925           && commonExpr->isGLValue()
5926           && commonExpr->isOrdinaryOrBitFieldObject()
5927           && RHSExpr->isOrdinaryOrBitFieldObject()
5928           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5929       ExprResult commonRes = UsualUnaryConversions(commonExpr);
5930       if (commonRes.isInvalid())
5931         return ExprError();
5932       commonExpr = commonRes.take();
5933     }
5934 
5935     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5936                                                 commonExpr->getType(),
5937                                                 commonExpr->getValueKind(),
5938                                                 commonExpr->getObjectKind(),
5939                                                 commonExpr);
5940     LHSExpr = CondExpr = opaqueValue;
5941   }
5942 
5943   ExprValueKind VK = VK_RValue;
5944   ExprObjectKind OK = OK_Ordinary;
5945   ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5946   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
5947                                              VK, OK, QuestionLoc);
5948   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5949       RHS.isInvalid())
5950     return ExprError();
5951 
5952   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5953                                 RHS.get());
5954 
5955   if (!commonExpr)
5956     return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5957                                                    LHS.take(), ColonLoc,
5958                                                    RHS.take(), result, VK, OK));
5959 
5960   return Owned(new (Context)
5961     BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5962                               RHS.take(), QuestionLoc, ColonLoc, result, VK,
5963                               OK));
5964 }
5965 
5966 // checkPointerTypesForAssignment - This is a very tricky routine (despite
5967 // being closely modeled after the C99 spec:-). The odd characteristic of this
5968 // routine is it effectively iqnores the qualifiers on the top level pointee.
5969 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5970 // FIXME: add a couple examples in this comment.
5971 static Sema::AssignConvertType
5972 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5973   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5974   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5975 
5976   // get the "pointed to" type (ignoring qualifiers at the top level)
5977   const Type *lhptee, *rhptee;
5978   Qualifiers lhq, rhq;
5979   llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5980   llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
5981 
5982   Sema::AssignConvertType ConvTy = Sema::Compatible;
5983 
5984   // C99 6.5.16.1p1: This following citation is common to constraints
5985   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5986   // qualifiers of the type *pointed to* by the right;
5987 
5988   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5989   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5990       lhq.compatiblyIncludesObjCLifetime(rhq)) {
5991     // Ignore lifetime for further calculation.
5992     lhq.removeObjCLifetime();
5993     rhq.removeObjCLifetime();
5994   }
5995 
5996   if (!lhq.compatiblyIncludes(rhq)) {
5997     // Treat address-space mismatches as fatal.  TODO: address subspaces
5998     if (lhq.getAddressSpace() != rhq.getAddressSpace())
5999       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6000 
6001     // It's okay to add or remove GC or lifetime qualifiers when converting to
6002     // and from void*.
6003     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
6004                         .compatiblyIncludes(
6005                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
6006              && (lhptee->isVoidType() || rhptee->isVoidType()))
6007       ; // keep old
6008 
6009     // Treat lifetime mismatches as fatal.
6010     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6011       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6012 
6013     // For GCC compatibility, other qualifier mismatches are treated
6014     // as still compatible in C.
6015     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6016   }
6017 
6018   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6019   // incomplete type and the other is a pointer to a qualified or unqualified
6020   // version of void...
6021   if (lhptee->isVoidType()) {
6022     if (rhptee->isIncompleteOrObjectType())
6023       return ConvTy;
6024 
6025     // As an extension, we allow cast to/from void* to function pointer.
6026     assert(rhptee->isFunctionType());
6027     return Sema::FunctionVoidPointer;
6028   }
6029 
6030   if (rhptee->isVoidType()) {
6031     if (lhptee->isIncompleteOrObjectType())
6032       return ConvTy;
6033 
6034     // As an extension, we allow cast to/from void* to function pointer.
6035     assert(lhptee->isFunctionType());
6036     return Sema::FunctionVoidPointer;
6037   }
6038 
6039   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6040   // unqualified versions of compatible types, ...
6041   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6042   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6043     // Check if the pointee types are compatible ignoring the sign.
6044     // We explicitly check for char so that we catch "char" vs
6045     // "unsigned char" on systems where "char" is unsigned.
6046     if (lhptee->isCharType())
6047       ltrans = S.Context.UnsignedCharTy;
6048     else if (lhptee->hasSignedIntegerRepresentation())
6049       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6050 
6051     if (rhptee->isCharType())
6052       rtrans = S.Context.UnsignedCharTy;
6053     else if (rhptee->hasSignedIntegerRepresentation())
6054       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6055 
6056     if (ltrans == rtrans) {
6057       // Types are compatible ignoring the sign. Qualifier incompatibility
6058       // takes priority over sign incompatibility because the sign
6059       // warning can be disabled.
6060       if (ConvTy != Sema::Compatible)
6061         return ConvTy;
6062 
6063       return Sema::IncompatiblePointerSign;
6064     }
6065 
6066     // If we are a multi-level pointer, it's possible that our issue is simply
6067     // one of qualification - e.g. char ** -> const char ** is not allowed. If
6068     // the eventual target type is the same and the pointers have the same
6069     // level of indirection, this must be the issue.
6070     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6071       do {
6072         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6073         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6074       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6075 
6076       if (lhptee == rhptee)
6077         return Sema::IncompatibleNestedPointerQualifiers;
6078     }
6079 
6080     // General pointer incompatibility takes priority over qualifiers.
6081     return Sema::IncompatiblePointer;
6082   }
6083   if (!S.getLangOpts().CPlusPlus &&
6084       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6085     return Sema::IncompatiblePointer;
6086   return ConvTy;
6087 }
6088 
6089 /// checkBlockPointerTypesForAssignment - This routine determines whether two
6090 /// block pointer types are compatible or whether a block and normal pointer
6091 /// are compatible. It is more restrict than comparing two function pointer
6092 // types.
6093 static Sema::AssignConvertType
6094 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6095                                     QualType RHSType) {
6096   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6097   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6098 
6099   QualType lhptee, rhptee;
6100 
6101   // get the "pointed to" type (ignoring qualifiers at the top level)
6102   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6103   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6104 
6105   // In C++, the types have to match exactly.
6106   if (S.getLangOpts().CPlusPlus)
6107     return Sema::IncompatibleBlockPointer;
6108 
6109   Sema::AssignConvertType ConvTy = Sema::Compatible;
6110 
6111   // For blocks we enforce that qualifiers are identical.
6112   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6113     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6114 
6115   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6116     return Sema::IncompatibleBlockPointer;
6117 
6118   return ConvTy;
6119 }
6120 
6121 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6122 /// for assignment compatibility.
6123 static Sema::AssignConvertType
6124 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6125                                    QualType RHSType) {
6126   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6127   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6128 
6129   if (LHSType->isObjCBuiltinType()) {
6130     // Class is not compatible with ObjC object pointers.
6131     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6132         !RHSType->isObjCQualifiedClassType())
6133       return Sema::IncompatiblePointer;
6134     return Sema::Compatible;
6135   }
6136   if (RHSType->isObjCBuiltinType()) {
6137     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6138         !LHSType->isObjCQualifiedClassType())
6139       return Sema::IncompatiblePointer;
6140     return Sema::Compatible;
6141   }
6142   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6143   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6144 
6145   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6146       // make an exception for id<P>
6147       !LHSType->isObjCQualifiedIdType())
6148     return Sema::CompatiblePointerDiscardsQualifiers;
6149 
6150   if (S.Context.typesAreCompatible(LHSType, RHSType))
6151     return Sema::Compatible;
6152   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6153     return Sema::IncompatibleObjCQualifiedId;
6154   return Sema::IncompatiblePointer;
6155 }
6156 
6157 Sema::AssignConvertType
6158 Sema::CheckAssignmentConstraints(SourceLocation Loc,
6159                                  QualType LHSType, QualType RHSType) {
6160   // Fake up an opaque expression.  We don't actually care about what
6161   // cast operations are required, so if CheckAssignmentConstraints
6162   // adds casts to this they'll be wasted, but fortunately that doesn't
6163   // usually happen on valid code.
6164   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6165   ExprResult RHSPtr = &RHSExpr;
6166   CastKind K = CK_Invalid;
6167 
6168   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
6169 }
6170 
6171 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6172 /// has code to accommodate several GCC extensions when type checking
6173 /// pointers. Here are some objectionable examples that GCC considers warnings:
6174 ///
6175 ///  int a, *pint;
6176 ///  short *pshort;
6177 ///  struct foo *pfoo;
6178 ///
6179 ///  pint = pshort; // warning: assignment from incompatible pointer type
6180 ///  a = pint; // warning: assignment makes integer from pointer without a cast
6181 ///  pint = a; // warning: assignment makes pointer from integer without a cast
6182 ///  pint = pfoo; // warning: assignment from incompatible pointer type
6183 ///
6184 /// As a result, the code for dealing with pointers is more complex than the
6185 /// C99 spec dictates.
6186 ///
6187 /// Sets 'Kind' for any result kind except Incompatible.
6188 Sema::AssignConvertType
6189 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6190                                  CastKind &Kind) {
6191   QualType RHSType = RHS.get()->getType();
6192   QualType OrigLHSType = LHSType;
6193 
6194   // Get canonical types.  We're not formatting these types, just comparing
6195   // them.
6196   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6197   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6198 
6199   // Common case: no conversion required.
6200   if (LHSType == RHSType) {
6201     Kind = CK_NoOp;
6202     return Compatible;
6203   }
6204 
6205   // If we have an atomic type, try a non-atomic assignment, then just add an
6206   // atomic qualification step.
6207   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6208     Sema::AssignConvertType result =
6209       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6210     if (result != Compatible)
6211       return result;
6212     if (Kind != CK_NoOp)
6213       RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
6214     Kind = CK_NonAtomicToAtomic;
6215     return Compatible;
6216   }
6217 
6218   // If the left-hand side is a reference type, then we are in a
6219   // (rare!) case where we've allowed the use of references in C,
6220   // e.g., as a parameter type in a built-in function. In this case,
6221   // just make sure that the type referenced is compatible with the
6222   // right-hand side type. The caller is responsible for adjusting
6223   // LHSType so that the resulting expression does not have reference
6224   // type.
6225   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6226     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6227       Kind = CK_LValueBitCast;
6228       return Compatible;
6229     }
6230     return Incompatible;
6231   }
6232 
6233   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6234   // to the same ExtVector type.
6235   if (LHSType->isExtVectorType()) {
6236     if (RHSType->isExtVectorType())
6237       return Incompatible;
6238     if (RHSType->isArithmeticType()) {
6239       // CK_VectorSplat does T -> vector T, so first cast to the
6240       // element type.
6241       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6242       if (elType != RHSType) {
6243         Kind = PrepareScalarCast(RHS, elType);
6244         RHS = ImpCastExprToType(RHS.take(), elType, Kind);
6245       }
6246       Kind = CK_VectorSplat;
6247       return Compatible;
6248     }
6249   }
6250 
6251   // Conversions to or from vector type.
6252   if (LHSType->isVectorType() || RHSType->isVectorType()) {
6253     if (LHSType->isVectorType() && RHSType->isVectorType()) {
6254       // Allow assignments of an AltiVec vector type to an equivalent GCC
6255       // vector type and vice versa
6256       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6257         Kind = CK_BitCast;
6258         return Compatible;
6259       }
6260 
6261       // If we are allowing lax vector conversions, and LHS and RHS are both
6262       // vectors, the total size only needs to be the same. This is a bitcast;
6263       // no bits are changed but the result type is different.
6264       if (getLangOpts().LaxVectorConversions &&
6265           (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
6266         Kind = CK_BitCast;
6267         return IncompatibleVectors;
6268       }
6269     }
6270     return Incompatible;
6271   }
6272 
6273   // Arithmetic conversions.
6274   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
6275       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
6276     Kind = PrepareScalarCast(RHS, LHSType);
6277     return Compatible;
6278   }
6279 
6280   // Conversions to normal pointers.
6281   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
6282     // U* -> T*
6283     if (isa<PointerType>(RHSType)) {
6284       Kind = CK_BitCast;
6285       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
6286     }
6287 
6288     // int -> T*
6289     if (RHSType->isIntegerType()) {
6290       Kind = CK_IntegralToPointer; // FIXME: null?
6291       return IntToPointer;
6292     }
6293 
6294     // C pointers are not compatible with ObjC object pointers,
6295     // with two exceptions:
6296     if (isa<ObjCObjectPointerType>(RHSType)) {
6297       //  - conversions to void*
6298       if (LHSPointer->getPointeeType()->isVoidType()) {
6299         Kind = CK_BitCast;
6300         return Compatible;
6301       }
6302 
6303       //  - conversions from 'Class' to the redefinition type
6304       if (RHSType->isObjCClassType() &&
6305           Context.hasSameType(LHSType,
6306                               Context.getObjCClassRedefinitionType())) {
6307         Kind = CK_BitCast;
6308         return Compatible;
6309       }
6310 
6311       Kind = CK_BitCast;
6312       return IncompatiblePointer;
6313     }
6314 
6315     // U^ -> void*
6316     if (RHSType->getAs<BlockPointerType>()) {
6317       if (LHSPointer->getPointeeType()->isVoidType()) {
6318         Kind = CK_BitCast;
6319         return Compatible;
6320       }
6321     }
6322 
6323     return Incompatible;
6324   }
6325 
6326   // Conversions to block pointers.
6327   if (isa<BlockPointerType>(LHSType)) {
6328     // U^ -> T^
6329     if (RHSType->isBlockPointerType()) {
6330       Kind = CK_BitCast;
6331       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
6332     }
6333 
6334     // int or null -> T^
6335     if (RHSType->isIntegerType()) {
6336       Kind = CK_IntegralToPointer; // FIXME: null
6337       return IntToBlockPointer;
6338     }
6339 
6340     // id -> T^
6341     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
6342       Kind = CK_AnyPointerToBlockPointerCast;
6343       return Compatible;
6344     }
6345 
6346     // void* -> T^
6347     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
6348       if (RHSPT->getPointeeType()->isVoidType()) {
6349         Kind = CK_AnyPointerToBlockPointerCast;
6350         return Compatible;
6351       }
6352 
6353     return Incompatible;
6354   }
6355 
6356   // Conversions to Objective-C pointers.
6357   if (isa<ObjCObjectPointerType>(LHSType)) {
6358     // A* -> B*
6359     if (RHSType->isObjCObjectPointerType()) {
6360       Kind = CK_BitCast;
6361       Sema::AssignConvertType result =
6362         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
6363       if (getLangOpts().ObjCAutoRefCount &&
6364           result == Compatible &&
6365           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
6366         result = IncompatibleObjCWeakRef;
6367       return result;
6368     }
6369 
6370     // int or null -> A*
6371     if (RHSType->isIntegerType()) {
6372       Kind = CK_IntegralToPointer; // FIXME: null
6373       return IntToPointer;
6374     }
6375 
6376     // In general, C pointers are not compatible with ObjC object pointers,
6377     // with two exceptions:
6378     if (isa<PointerType>(RHSType)) {
6379       Kind = CK_CPointerToObjCPointerCast;
6380 
6381       //  - conversions from 'void*'
6382       if (RHSType->isVoidPointerType()) {
6383         return Compatible;
6384       }
6385 
6386       //  - conversions to 'Class' from its redefinition type
6387       if (LHSType->isObjCClassType() &&
6388           Context.hasSameType(RHSType,
6389                               Context.getObjCClassRedefinitionType())) {
6390         return Compatible;
6391       }
6392 
6393       return IncompatiblePointer;
6394     }
6395 
6396     // T^ -> A*
6397     if (RHSType->isBlockPointerType()) {
6398       maybeExtendBlockObject(*this, RHS);
6399       Kind = CK_BlockPointerToObjCPointerCast;
6400       return Compatible;
6401     }
6402 
6403     return Incompatible;
6404   }
6405 
6406   // Conversions from pointers that are not covered by the above.
6407   if (isa<PointerType>(RHSType)) {
6408     // T* -> _Bool
6409     if (LHSType == Context.BoolTy) {
6410       Kind = CK_PointerToBoolean;
6411       return Compatible;
6412     }
6413 
6414     // T* -> int
6415     if (LHSType->isIntegerType()) {
6416       Kind = CK_PointerToIntegral;
6417       return PointerToInt;
6418     }
6419 
6420     return Incompatible;
6421   }
6422 
6423   // Conversions from Objective-C pointers that are not covered by the above.
6424   if (isa<ObjCObjectPointerType>(RHSType)) {
6425     // T* -> _Bool
6426     if (LHSType == Context.BoolTy) {
6427       Kind = CK_PointerToBoolean;
6428       return Compatible;
6429     }
6430 
6431     // T* -> int
6432     if (LHSType->isIntegerType()) {
6433       Kind = CK_PointerToIntegral;
6434       return PointerToInt;
6435     }
6436 
6437     return Incompatible;
6438   }
6439 
6440   // struct A -> struct B
6441   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6442     if (Context.typesAreCompatible(LHSType, RHSType)) {
6443       Kind = CK_NoOp;
6444       return Compatible;
6445     }
6446   }
6447 
6448   return Incompatible;
6449 }
6450 
6451 /// \brief Constructs a transparent union from an expression that is
6452 /// used to initialize the transparent union.
6453 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6454                                       ExprResult &EResult, QualType UnionType,
6455                                       FieldDecl *Field) {
6456   // Build an initializer list that designates the appropriate member
6457   // of the transparent union.
6458   Expr *E = EResult.take();
6459   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6460                                                    E, SourceLocation());
6461   Initializer->setType(UnionType);
6462   Initializer->setInitializedFieldInUnion(Field);
6463 
6464   // Build a compound literal constructing a value of the transparent
6465   // union type from this initializer list.
6466   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6467   EResult = S.Owned(
6468     new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6469                                 VK_RValue, Initializer, false));
6470 }
6471 
6472 Sema::AssignConvertType
6473 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
6474                                                ExprResult &RHS) {
6475   QualType RHSType = RHS.get()->getType();
6476 
6477   // If the ArgType is a Union type, we want to handle a potential
6478   // transparent_union GCC extension.
6479   const RecordType *UT = ArgType->getAsUnionType();
6480   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6481     return Incompatible;
6482 
6483   // The field to initialize within the transparent union.
6484   RecordDecl *UD = UT->getDecl();
6485   FieldDecl *InitField = 0;
6486   // It's compatible if the expression matches any of the fields.
6487   for (RecordDecl::field_iterator it = UD->field_begin(),
6488          itend = UD->field_end();
6489        it != itend; ++it) {
6490     if (it->getType()->isPointerType()) {
6491       // If the transparent union contains a pointer type, we allow:
6492       // 1) void pointer
6493       // 2) null pointer constant
6494       if (RHSType->isPointerType())
6495         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6496           RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
6497           InitField = *it;
6498           break;
6499         }
6500 
6501       if (RHS.get()->isNullPointerConstant(Context,
6502                                            Expr::NPC_ValueDependentIsNull)) {
6503         RHS = ImpCastExprToType(RHS.take(), it->getType(),
6504                                 CK_NullToPointer);
6505         InitField = *it;
6506         break;
6507       }
6508     }
6509 
6510     CastKind Kind = CK_Invalid;
6511     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6512           == Compatible) {
6513       RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
6514       InitField = *it;
6515       break;
6516     }
6517   }
6518 
6519   if (!InitField)
6520     return Incompatible;
6521 
6522   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6523   return Compatible;
6524 }
6525 
6526 Sema::AssignConvertType
6527 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6528                                        bool Diagnose,
6529                                        bool DiagnoseCFAudited) {
6530   if (getLangOpts().CPlusPlus) {
6531     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6532       // C++ 5.17p3: If the left operand is not of class type, the
6533       // expression is implicitly converted (C++ 4) to the
6534       // cv-unqualified type of the left operand.
6535       ExprResult Res;
6536       if (Diagnose) {
6537         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6538                                         AA_Assigning);
6539       } else {
6540         ImplicitConversionSequence ICS =
6541             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6542                                   /*SuppressUserConversions=*/false,
6543                                   /*AllowExplicit=*/false,
6544                                   /*InOverloadResolution=*/false,
6545                                   /*CStyle=*/false,
6546                                   /*AllowObjCWritebackConversion=*/false);
6547         if (ICS.isFailure())
6548           return Incompatible;
6549         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6550                                         ICS, AA_Assigning);
6551       }
6552       if (Res.isInvalid())
6553         return Incompatible;
6554       Sema::AssignConvertType result = Compatible;
6555       if (getLangOpts().ObjCAutoRefCount &&
6556           !CheckObjCARCUnavailableWeakConversion(LHSType,
6557                                                  RHS.get()->getType()))
6558         result = IncompatibleObjCWeakRef;
6559       RHS = Res;
6560       return result;
6561     }
6562 
6563     // FIXME: Currently, we fall through and treat C++ classes like C
6564     // structures.
6565     // FIXME: We also fall through for atomics; not sure what should
6566     // happen there, though.
6567   }
6568 
6569   // C99 6.5.16.1p1: the left operand is a pointer and the right is
6570   // a null pointer constant.
6571   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
6572        LHSType->isBlockPointerType()) &&
6573       RHS.get()->isNullPointerConstant(Context,
6574                                        Expr::NPC_ValueDependentIsNull)) {
6575     CastKind Kind;
6576     CXXCastPath Path;
6577     CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
6578     RHS = ImpCastExprToType(RHS.take(), LHSType, Kind, VK_RValue, &Path);
6579     return Compatible;
6580   }
6581 
6582   // This check seems unnatural, however it is necessary to ensure the proper
6583   // conversion of functions/arrays. If the conversion were done for all
6584   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6585   // expressions that suppress this implicit conversion (&, sizeof).
6586   //
6587   // Suppress this for references: C++ 8.5.3p5.
6588   if (!LHSType->isReferenceType()) {
6589     RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6590     if (RHS.isInvalid())
6591       return Incompatible;
6592   }
6593 
6594   CastKind Kind = CK_Invalid;
6595   Sema::AssignConvertType result =
6596     CheckAssignmentConstraints(LHSType, RHS, Kind);
6597 
6598   // C99 6.5.16.1p2: The value of the right operand is converted to the
6599   // type of the assignment expression.
6600   // CheckAssignmentConstraints allows the left-hand side to be a reference,
6601   // so that we can use references in built-in functions even in C.
6602   // The getNonReferenceType() call makes sure that the resulting expression
6603   // does not have reference type.
6604   if (result != Incompatible && RHS.get()->getType() != LHSType) {
6605     QualType Ty = LHSType.getNonLValueExprType(Context);
6606     Expr *E = RHS.take();
6607     if (getLangOpts().ObjCAutoRefCount)
6608       CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
6609                              DiagnoseCFAudited);
6610     RHS = ImpCastExprToType(E, Ty, Kind);
6611   }
6612   return result;
6613 }
6614 
6615 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6616                                ExprResult &RHS) {
6617   Diag(Loc, diag::err_typecheck_invalid_operands)
6618     << LHS.get()->getType() << RHS.get()->getType()
6619     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6620   return QualType();
6621 }
6622 
6623 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6624                                    SourceLocation Loc, bool IsCompAssign) {
6625   if (!IsCompAssign) {
6626     LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6627     if (LHS.isInvalid())
6628       return QualType();
6629   }
6630   RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6631   if (RHS.isInvalid())
6632     return QualType();
6633 
6634   // For conversion purposes, we ignore any qualifiers.
6635   // For example, "const float" and "float" are equivalent.
6636   QualType LHSType =
6637     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6638   QualType RHSType =
6639     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6640 
6641   // If the vector types are identical, return.
6642   if (LHSType == RHSType)
6643     return LHSType;
6644 
6645   // Handle the case of equivalent AltiVec and GCC vector types
6646   if (LHSType->isVectorType() && RHSType->isVectorType() &&
6647       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6648     if (LHSType->isExtVectorType()) {
6649       RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6650       return LHSType;
6651     }
6652 
6653     if (!IsCompAssign)
6654       LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6655     return RHSType;
6656   }
6657 
6658   if (getLangOpts().LaxVectorConversions &&
6659       Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
6660     // If we are allowing lax vector conversions, and LHS and RHS are both
6661     // vectors, the total size only needs to be the same. This is a
6662     // bitcast; no bits are changed but the result type is different.
6663     // FIXME: Should we really be allowing this?
6664     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6665     return LHSType;
6666   }
6667 
6668   // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6669   // swap back (so that we don't reverse the inputs to a subtract, for instance.
6670   bool swapped = false;
6671   if (RHSType->isExtVectorType() && !IsCompAssign) {
6672     swapped = true;
6673     std::swap(RHS, LHS);
6674     std::swap(RHSType, LHSType);
6675   }
6676 
6677   // Handle the case of an ext vector and scalar.
6678   if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
6679     QualType EltTy = LV->getElementType();
6680     if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6681       int order = Context.getIntegerTypeOrder(EltTy, RHSType);
6682       if (order > 0)
6683         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
6684       if (order >= 0) {
6685         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6686         if (swapped) std::swap(RHS, LHS);
6687         return LHSType;
6688       }
6689     }
6690     if (EltTy->isRealFloatingType() && RHSType->isScalarType()) {
6691       if (RHSType->isRealFloatingType()) {
6692         int order = Context.getFloatingTypeOrder(EltTy, RHSType);
6693         if (order > 0)
6694           RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
6695         if (order >= 0) {
6696           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6697           if (swapped) std::swap(RHS, LHS);
6698           return LHSType;
6699         }
6700       }
6701       if (RHSType->isIntegralType(Context)) {
6702         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralToFloating);
6703         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6704         if (swapped) std::swap(RHS, LHS);
6705         return LHSType;
6706       }
6707     }
6708   }
6709 
6710   // Vectors of different size or scalar and non-ext-vector are errors.
6711   if (swapped) std::swap(RHS, LHS);
6712   Diag(Loc, diag::err_typecheck_vector_not_convertable)
6713     << LHS.get()->getType() << RHS.get()->getType()
6714     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6715   return QualType();
6716 }
6717 
6718 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6719 // expression.  These are mainly cases where the null pointer is used as an
6720 // integer instead of a pointer.
6721 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6722                                 SourceLocation Loc, bool IsCompare) {
6723   // The canonical way to check for a GNU null is with isNullPointerConstant,
6724   // but we use a bit of a hack here for speed; this is a relatively
6725   // hot path, and isNullPointerConstant is slow.
6726   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6727   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6728 
6729   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6730 
6731   // Avoid analyzing cases where the result will either be invalid (and
6732   // diagnosed as such) or entirely valid and not something to warn about.
6733   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6734       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6735     return;
6736 
6737   // Comparison operations would not make sense with a null pointer no matter
6738   // what the other expression is.
6739   if (!IsCompare) {
6740     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6741         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6742         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6743     return;
6744   }
6745 
6746   // The rest of the operations only make sense with a null pointer
6747   // if the other expression is a pointer.
6748   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6749       NonNullType->canDecayToPointerType())
6750     return;
6751 
6752   S.Diag(Loc, diag::warn_null_in_comparison_operation)
6753       << LHSNull /* LHS is NULL */ << NonNullType
6754       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6755 }
6756 
6757 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6758                                            SourceLocation Loc,
6759                                            bool IsCompAssign, bool IsDiv) {
6760   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6761 
6762   if (LHS.get()->getType()->isVectorType() ||
6763       RHS.get()->getType()->isVectorType())
6764     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6765 
6766   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6767   if (LHS.isInvalid() || RHS.isInvalid())
6768     return QualType();
6769 
6770 
6771   if (compType.isNull() || !compType->isArithmeticType())
6772     return InvalidOperands(Loc, LHS, RHS);
6773 
6774   // Check for division by zero.
6775   llvm::APSInt RHSValue;
6776   if (IsDiv && !RHS.get()->isValueDependent() &&
6777       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6778     DiagRuntimeBehavior(Loc, RHS.get(),
6779                         PDiag(diag::warn_division_by_zero)
6780                           << RHS.get()->getSourceRange());
6781 
6782   return compType;
6783 }
6784 
6785 QualType Sema::CheckRemainderOperands(
6786   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6787   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6788 
6789   if (LHS.get()->getType()->isVectorType() ||
6790       RHS.get()->getType()->isVectorType()) {
6791     if (LHS.get()->getType()->hasIntegerRepresentation() &&
6792         RHS.get()->getType()->hasIntegerRepresentation())
6793       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6794     return InvalidOperands(Loc, LHS, RHS);
6795   }
6796 
6797   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6798   if (LHS.isInvalid() || RHS.isInvalid())
6799     return QualType();
6800 
6801   if (compType.isNull() || !compType->isIntegerType())
6802     return InvalidOperands(Loc, LHS, RHS);
6803 
6804   // Check for remainder by zero.
6805   llvm::APSInt RHSValue;
6806   if (!RHS.get()->isValueDependent() &&
6807       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6808     DiagRuntimeBehavior(Loc, RHS.get(),
6809                         PDiag(diag::warn_remainder_by_zero)
6810                           << RHS.get()->getSourceRange());
6811 
6812   return compType;
6813 }
6814 
6815 /// \brief Diagnose invalid arithmetic on two void pointers.
6816 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
6817                                                 Expr *LHSExpr, Expr *RHSExpr) {
6818   S.Diag(Loc, S.getLangOpts().CPlusPlus
6819                 ? diag::err_typecheck_pointer_arith_void_type
6820                 : diag::ext_gnu_void_ptr)
6821     << 1 /* two pointers */ << LHSExpr->getSourceRange()
6822                             << RHSExpr->getSourceRange();
6823 }
6824 
6825 /// \brief Diagnose invalid arithmetic on a void pointer.
6826 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6827                                             Expr *Pointer) {
6828   S.Diag(Loc, S.getLangOpts().CPlusPlus
6829                 ? diag::err_typecheck_pointer_arith_void_type
6830                 : diag::ext_gnu_void_ptr)
6831     << 0 /* one pointer */ << Pointer->getSourceRange();
6832 }
6833 
6834 /// \brief Diagnose invalid arithmetic on two function pointers.
6835 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6836                                                     Expr *LHS, Expr *RHS) {
6837   assert(LHS->getType()->isAnyPointerType());
6838   assert(RHS->getType()->isAnyPointerType());
6839   S.Diag(Loc, S.getLangOpts().CPlusPlus
6840                 ? diag::err_typecheck_pointer_arith_function_type
6841                 : diag::ext_gnu_ptr_func_arith)
6842     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6843     // We only show the second type if it differs from the first.
6844     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6845                                                    RHS->getType())
6846     << RHS->getType()->getPointeeType()
6847     << LHS->getSourceRange() << RHS->getSourceRange();
6848 }
6849 
6850 /// \brief Diagnose invalid arithmetic on a function pointer.
6851 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6852                                                 Expr *Pointer) {
6853   assert(Pointer->getType()->isAnyPointerType());
6854   S.Diag(Loc, S.getLangOpts().CPlusPlus
6855                 ? diag::err_typecheck_pointer_arith_function_type
6856                 : diag::ext_gnu_ptr_func_arith)
6857     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6858     << 0 /* one pointer, so only one type */
6859     << Pointer->getSourceRange();
6860 }
6861 
6862 /// \brief Emit error if Operand is incomplete pointer type
6863 ///
6864 /// \returns True if pointer has incomplete type
6865 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6866                                                  Expr *Operand) {
6867   assert(Operand->getType()->isAnyPointerType() &&
6868          !Operand->getType()->isDependentType());
6869   QualType PointeeTy = Operand->getType()->getPointeeType();
6870   return S.RequireCompleteType(Loc, PointeeTy,
6871                                diag::err_typecheck_arithmetic_incomplete_type,
6872                                PointeeTy, Operand->getSourceRange());
6873 }
6874 
6875 /// \brief Check the validity of an arithmetic pointer operand.
6876 ///
6877 /// If the operand has pointer type, this code will check for pointer types
6878 /// which are invalid in arithmetic operations. These will be diagnosed
6879 /// appropriately, including whether or not the use is supported as an
6880 /// extension.
6881 ///
6882 /// \returns True when the operand is valid to use (even if as an extension).
6883 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6884                                             Expr *Operand) {
6885   if (!Operand->getType()->isAnyPointerType()) return true;
6886 
6887   QualType PointeeTy = Operand->getType()->getPointeeType();
6888   if (PointeeTy->isVoidType()) {
6889     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6890     return !S.getLangOpts().CPlusPlus;
6891   }
6892   if (PointeeTy->isFunctionType()) {
6893     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6894     return !S.getLangOpts().CPlusPlus;
6895   }
6896 
6897   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
6898 
6899   return true;
6900 }
6901 
6902 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6903 /// operands.
6904 ///
6905 /// This routine will diagnose any invalid arithmetic on pointer operands much
6906 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
6907 /// for emitting a single diagnostic even for operations where both LHS and RHS
6908 /// are (potentially problematic) pointers.
6909 ///
6910 /// \returns True when the operand is valid to use (even if as an extension).
6911 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
6912                                                 Expr *LHSExpr, Expr *RHSExpr) {
6913   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6914   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
6915   if (!isLHSPointer && !isRHSPointer) return true;
6916 
6917   QualType LHSPointeeTy, RHSPointeeTy;
6918   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6919   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
6920 
6921   // Check for arithmetic on pointers to incomplete types.
6922   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6923   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6924   if (isLHSVoidPtr || isRHSVoidPtr) {
6925     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6926     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6927     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
6928 
6929     return !S.getLangOpts().CPlusPlus;
6930   }
6931 
6932   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6933   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6934   if (isLHSFuncPtr || isRHSFuncPtr) {
6935     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6936     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6937                                                                 RHSExpr);
6938     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
6939 
6940     return !S.getLangOpts().CPlusPlus;
6941   }
6942 
6943   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6944     return false;
6945   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6946     return false;
6947 
6948   return true;
6949 }
6950 
6951 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6952 /// literal.
6953 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6954                                   Expr *LHSExpr, Expr *RHSExpr) {
6955   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6956   Expr* IndexExpr = RHSExpr;
6957   if (!StrExpr) {
6958     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6959     IndexExpr = LHSExpr;
6960   }
6961 
6962   bool IsStringPlusInt = StrExpr &&
6963       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6964   if (!IsStringPlusInt)
6965     return;
6966 
6967   llvm::APSInt index;
6968   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6969     unsigned StrLenWithNull = StrExpr->getLength() + 1;
6970     if (index.isNonNegative() &&
6971         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6972                               index.isUnsigned()))
6973       return;
6974   }
6975 
6976   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6977   Self.Diag(OpLoc, diag::warn_string_plus_int)
6978       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6979 
6980   // Only print a fixit for "str" + int, not for int + "str".
6981   if (IndexExpr == RHSExpr) {
6982     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6983     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
6984         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6985         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6986         << FixItHint::CreateInsertion(EndLoc, "]");
6987   } else
6988     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
6989 }
6990 
6991 /// \brief Emit a warning when adding a char literal to a string.
6992 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
6993                                    Expr *LHSExpr, Expr *RHSExpr) {
6994   const DeclRefExpr *StringRefExpr =
6995       dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts());
6996   const CharacterLiteral *CharExpr =
6997       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
6998   if (!StringRefExpr) {
6999     StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts());
7000     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
7001   }
7002 
7003   if (!CharExpr || !StringRefExpr)
7004     return;
7005 
7006   const QualType StringType = StringRefExpr->getType();
7007 
7008   // Return if not a PointerType.
7009   if (!StringType->isAnyPointerType())
7010     return;
7011 
7012   // Return if not a CharacterType.
7013   if (!StringType->getPointeeType()->isAnyCharacterType())
7014     return;
7015 
7016   ASTContext &Ctx = Self.getASTContext();
7017   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7018 
7019   const QualType CharType = CharExpr->getType();
7020   if (!CharType->isAnyCharacterType() &&
7021       CharType->isIntegerType() &&
7022       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
7023     Self.Diag(OpLoc, diag::warn_string_plus_char)
7024         << DiagRange << Ctx.CharTy;
7025   } else {
7026     Self.Diag(OpLoc, diag::warn_string_plus_char)
7027         << DiagRange << CharExpr->getType();
7028   }
7029 
7030   // Only print a fixit for str + char, not for char + str.
7031   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
7032     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7033     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7034         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7035         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7036         << FixItHint::CreateInsertion(EndLoc, "]");
7037   } else {
7038     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7039   }
7040 }
7041 
7042 /// \brief Emit error when two pointers are incompatible.
7043 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
7044                                            Expr *LHSExpr, Expr *RHSExpr) {
7045   assert(LHSExpr->getType()->isAnyPointerType());
7046   assert(RHSExpr->getType()->isAnyPointerType());
7047   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7048     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
7049     << RHSExpr->getSourceRange();
7050 }
7051 
7052 QualType Sema::CheckAdditionOperands( // C99 6.5.6
7053     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7054     QualType* CompLHSTy) {
7055   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7056 
7057   if (LHS.get()->getType()->isVectorType() ||
7058       RHS.get()->getType()->isVectorType()) {
7059     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7060     if (CompLHSTy) *CompLHSTy = compType;
7061     return compType;
7062   }
7063 
7064   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7065   if (LHS.isInvalid() || RHS.isInvalid())
7066     return QualType();
7067 
7068   // Diagnose "string literal" '+' int and string '+' "char literal".
7069   if (Opc == BO_Add) {
7070     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
7071     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
7072   }
7073 
7074   // handle the common case first (both operands are arithmetic).
7075   if (!compType.isNull() && compType->isArithmeticType()) {
7076     if (CompLHSTy) *CompLHSTy = compType;
7077     return compType;
7078   }
7079 
7080   // Type-checking.  Ultimately the pointer's going to be in PExp;
7081   // note that we bias towards the LHS being the pointer.
7082   Expr *PExp = LHS.get(), *IExp = RHS.get();
7083 
7084   bool isObjCPointer;
7085   if (PExp->getType()->isPointerType()) {
7086     isObjCPointer = false;
7087   } else if (PExp->getType()->isObjCObjectPointerType()) {
7088     isObjCPointer = true;
7089   } else {
7090     std::swap(PExp, IExp);
7091     if (PExp->getType()->isPointerType()) {
7092       isObjCPointer = false;
7093     } else if (PExp->getType()->isObjCObjectPointerType()) {
7094       isObjCPointer = true;
7095     } else {
7096       return InvalidOperands(Loc, LHS, RHS);
7097     }
7098   }
7099   assert(PExp->getType()->isAnyPointerType());
7100 
7101   if (!IExp->getType()->isIntegerType())
7102     return InvalidOperands(Loc, LHS, RHS);
7103 
7104   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
7105     return QualType();
7106 
7107   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
7108     return QualType();
7109 
7110   // Check array bounds for pointer arithemtic
7111   CheckArrayAccess(PExp, IExp);
7112 
7113   if (CompLHSTy) {
7114     QualType LHSTy = Context.isPromotableBitField(LHS.get());
7115     if (LHSTy.isNull()) {
7116       LHSTy = LHS.get()->getType();
7117       if (LHSTy->isPromotableIntegerType())
7118         LHSTy = Context.getPromotedIntegerType(LHSTy);
7119     }
7120     *CompLHSTy = LHSTy;
7121   }
7122 
7123   return PExp->getType();
7124 }
7125 
7126 // C99 6.5.6
7127 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
7128                                         SourceLocation Loc,
7129                                         QualType* CompLHSTy) {
7130   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7131 
7132   if (LHS.get()->getType()->isVectorType() ||
7133       RHS.get()->getType()->isVectorType()) {
7134     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7135     if (CompLHSTy) *CompLHSTy = compType;
7136     return compType;
7137   }
7138 
7139   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7140   if (LHS.isInvalid() || RHS.isInvalid())
7141     return QualType();
7142 
7143   // Enforce type constraints: C99 6.5.6p3.
7144 
7145   // Handle the common case first (both operands are arithmetic).
7146   if (!compType.isNull() && compType->isArithmeticType()) {
7147     if (CompLHSTy) *CompLHSTy = compType;
7148     return compType;
7149   }
7150 
7151   // Either ptr - int   or   ptr - ptr.
7152   if (LHS.get()->getType()->isAnyPointerType()) {
7153     QualType lpointee = LHS.get()->getType()->getPointeeType();
7154 
7155     // Diagnose bad cases where we step over interface counts.
7156     if (LHS.get()->getType()->isObjCObjectPointerType() &&
7157         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
7158       return QualType();
7159 
7160     // The result type of a pointer-int computation is the pointer type.
7161     if (RHS.get()->getType()->isIntegerType()) {
7162       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
7163         return QualType();
7164 
7165       // Check array bounds for pointer arithemtic
7166       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
7167                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
7168 
7169       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7170       return LHS.get()->getType();
7171     }
7172 
7173     // Handle pointer-pointer subtractions.
7174     if (const PointerType *RHSPTy
7175           = RHS.get()->getType()->getAs<PointerType>()) {
7176       QualType rpointee = RHSPTy->getPointeeType();
7177 
7178       if (getLangOpts().CPlusPlus) {
7179         // Pointee types must be the same: C++ [expr.add]
7180         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7181           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7182         }
7183       } else {
7184         // Pointee types must be compatible C99 6.5.6p3
7185         if (!Context.typesAreCompatible(
7186                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7187                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7188           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7189           return QualType();
7190         }
7191       }
7192 
7193       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
7194                                                LHS.get(), RHS.get()))
7195         return QualType();
7196 
7197       // The pointee type may have zero size.  As an extension, a structure or
7198       // union may have zero size or an array may have zero length.  In this
7199       // case subtraction does not make sense.
7200       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
7201         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
7202         if (ElementSize.isZero()) {
7203           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
7204             << rpointee.getUnqualifiedType()
7205             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7206         }
7207       }
7208 
7209       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7210       return Context.getPointerDiffType();
7211     }
7212   }
7213 
7214   return InvalidOperands(Loc, LHS, RHS);
7215 }
7216 
7217 static bool isScopedEnumerationType(QualType T) {
7218   if (const EnumType *ET = dyn_cast<EnumType>(T))
7219     return ET->getDecl()->isScoped();
7220   return false;
7221 }
7222 
7223 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
7224                                    SourceLocation Loc, unsigned Opc,
7225                                    QualType LHSType) {
7226   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
7227   // so skip remaining warnings as we don't want to modify values within Sema.
7228   if (S.getLangOpts().OpenCL)
7229     return;
7230 
7231   llvm::APSInt Right;
7232   // Check right/shifter operand
7233   if (RHS.get()->isValueDependent() ||
7234       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
7235     return;
7236 
7237   if (Right.isNegative()) {
7238     S.DiagRuntimeBehavior(Loc, RHS.get(),
7239                           S.PDiag(diag::warn_shift_negative)
7240                             << RHS.get()->getSourceRange());
7241     return;
7242   }
7243   llvm::APInt LeftBits(Right.getBitWidth(),
7244                        S.Context.getTypeSize(LHS.get()->getType()));
7245   if (Right.uge(LeftBits)) {
7246     S.DiagRuntimeBehavior(Loc, RHS.get(),
7247                           S.PDiag(diag::warn_shift_gt_typewidth)
7248                             << RHS.get()->getSourceRange());
7249     return;
7250   }
7251   if (Opc != BO_Shl)
7252     return;
7253 
7254   // When left shifting an ICE which is signed, we can check for overflow which
7255   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7256   // integers have defined behavior modulo one more than the maximum value
7257   // representable in the result type, so never warn for those.
7258   llvm::APSInt Left;
7259   if (LHS.get()->isValueDependent() ||
7260       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
7261       LHSType->hasUnsignedIntegerRepresentation())
7262     return;
7263   llvm::APInt ResultBits =
7264       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7265   if (LeftBits.uge(ResultBits))
7266     return;
7267   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7268   Result = Result.shl(Right);
7269 
7270   // Print the bit representation of the signed integer as an unsigned
7271   // hexadecimal number.
7272   SmallString<40> HexResult;
7273   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7274 
7275   // If we are only missing a sign bit, this is less likely to result in actual
7276   // bugs -- if the result is cast back to an unsigned type, it will have the
7277   // expected value. Thus we place this behind a different warning that can be
7278   // turned off separately if needed.
7279   if (LeftBits == ResultBits - 1) {
7280     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7281         << HexResult.str() << LHSType
7282         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7283     return;
7284   }
7285 
7286   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7287     << HexResult.str() << Result.getMinSignedBits() << LHSType
7288     << Left.getBitWidth() << LHS.get()->getSourceRange()
7289     << RHS.get()->getSourceRange();
7290 }
7291 
7292 // C99 6.5.7
7293 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
7294                                   SourceLocation Loc, unsigned Opc,
7295                                   bool IsCompAssign) {
7296   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7297 
7298   // Vector shifts promote their scalar inputs to vector type.
7299   if (LHS.get()->getType()->isVectorType() ||
7300       RHS.get()->getType()->isVectorType())
7301     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7302 
7303   // Shifts don't perform usual arithmetic conversions, they just do integer
7304   // promotions on each operand. C99 6.5.7p3
7305 
7306   // For the LHS, do usual unary conversions, but then reset them away
7307   // if this is a compound assignment.
7308   ExprResult OldLHS = LHS;
7309   LHS = UsualUnaryConversions(LHS.take());
7310   if (LHS.isInvalid())
7311     return QualType();
7312   QualType LHSType = LHS.get()->getType();
7313   if (IsCompAssign) LHS = OldLHS;
7314 
7315   // The RHS is simpler.
7316   RHS = UsualUnaryConversions(RHS.take());
7317   if (RHS.isInvalid())
7318     return QualType();
7319   QualType RHSType = RHS.get()->getType();
7320 
7321   // C99 6.5.7p2: Each of the operands shall have integer type.
7322   if (!LHSType->hasIntegerRepresentation() ||
7323       !RHSType->hasIntegerRepresentation())
7324     return InvalidOperands(Loc, LHS, RHS);
7325 
7326   // C++0x: Don't allow scoped enums. FIXME: Use something better than
7327   // hasIntegerRepresentation() above instead of this.
7328   if (isScopedEnumerationType(LHSType) ||
7329       isScopedEnumerationType(RHSType)) {
7330     return InvalidOperands(Loc, LHS, RHS);
7331   }
7332   // Sanity-check shift operands
7333   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
7334 
7335   // "The type of the result is that of the promoted left operand."
7336   return LHSType;
7337 }
7338 
7339 static bool IsWithinTemplateSpecialization(Decl *D) {
7340   if (DeclContext *DC = D->getDeclContext()) {
7341     if (isa<ClassTemplateSpecializationDecl>(DC))
7342       return true;
7343     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7344       return FD->isFunctionTemplateSpecialization();
7345   }
7346   return false;
7347 }
7348 
7349 /// If two different enums are compared, raise a warning.
7350 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
7351                                 Expr *RHS) {
7352   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
7353   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
7354 
7355   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
7356   if (!LHSEnumType)
7357     return;
7358   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
7359   if (!RHSEnumType)
7360     return;
7361 
7362   // Ignore anonymous enums.
7363   if (!LHSEnumType->getDecl()->getIdentifier())
7364     return;
7365   if (!RHSEnumType->getDecl()->getIdentifier())
7366     return;
7367 
7368   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
7369     return;
7370 
7371   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7372       << LHSStrippedType << RHSStrippedType
7373       << LHS->getSourceRange() << RHS->getSourceRange();
7374 }
7375 
7376 /// \brief Diagnose bad pointer comparisons.
7377 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
7378                                               ExprResult &LHS, ExprResult &RHS,
7379                                               bool IsError) {
7380   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
7381                       : diag::ext_typecheck_comparison_of_distinct_pointers)
7382     << LHS.get()->getType() << RHS.get()->getType()
7383     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7384 }
7385 
7386 /// \brief Returns false if the pointers are converted to a composite type,
7387 /// true otherwise.
7388 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
7389                                            ExprResult &LHS, ExprResult &RHS) {
7390   // C++ [expr.rel]p2:
7391   //   [...] Pointer conversions (4.10) and qualification
7392   //   conversions (4.4) are performed on pointer operands (or on
7393   //   a pointer operand and a null pointer constant) to bring
7394   //   them to their composite pointer type. [...]
7395   //
7396   // C++ [expr.eq]p1 uses the same notion for (in)equality
7397   // comparisons of pointers.
7398 
7399   // C++ [expr.eq]p2:
7400   //   In addition, pointers to members can be compared, or a pointer to
7401   //   member and a null pointer constant. Pointer to member conversions
7402   //   (4.11) and qualification conversions (4.4) are performed to bring
7403   //   them to a common type. If one operand is a null pointer constant,
7404   //   the common type is the type of the other operand. Otherwise, the
7405   //   common type is a pointer to member type similar (4.4) to the type
7406   //   of one of the operands, with a cv-qualification signature (4.4)
7407   //   that is the union of the cv-qualification signatures of the operand
7408   //   types.
7409 
7410   QualType LHSType = LHS.get()->getType();
7411   QualType RHSType = RHS.get()->getType();
7412   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
7413          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
7414 
7415   bool NonStandardCompositeType = false;
7416   bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
7417   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
7418   if (T.isNull()) {
7419     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
7420     return true;
7421   }
7422 
7423   if (NonStandardCompositeType)
7424     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
7425       << LHSType << RHSType << T << LHS.get()->getSourceRange()
7426       << RHS.get()->getSourceRange();
7427 
7428   LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
7429   RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
7430   return false;
7431 }
7432 
7433 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
7434                                                     ExprResult &LHS,
7435                                                     ExprResult &RHS,
7436                                                     bool IsError) {
7437   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
7438                       : diag::ext_typecheck_comparison_of_fptr_to_void)
7439     << LHS.get()->getType() << RHS.get()->getType()
7440     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7441 }
7442 
7443 static bool isObjCObjectLiteral(ExprResult &E) {
7444   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
7445   case Stmt::ObjCArrayLiteralClass:
7446   case Stmt::ObjCDictionaryLiteralClass:
7447   case Stmt::ObjCStringLiteralClass:
7448   case Stmt::ObjCBoxedExprClass:
7449     return true;
7450   default:
7451     // Note that ObjCBoolLiteral is NOT an object literal!
7452     return false;
7453   }
7454 }
7455 
7456 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
7457   const ObjCObjectPointerType *Type =
7458     LHS->getType()->getAs<ObjCObjectPointerType>();
7459 
7460   // If this is not actually an Objective-C object, bail out.
7461   if (!Type)
7462     return false;
7463 
7464   // Get the LHS object's interface type.
7465   QualType InterfaceType = Type->getPointeeType();
7466   if (const ObjCObjectType *iQFaceTy =
7467       InterfaceType->getAsObjCQualifiedInterfaceType())
7468     InterfaceType = iQFaceTy->getBaseType();
7469 
7470   // If the RHS isn't an Objective-C object, bail out.
7471   if (!RHS->getType()->isObjCObjectPointerType())
7472     return false;
7473 
7474   // Try to find the -isEqual: method.
7475   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
7476   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
7477                                                       InterfaceType,
7478                                                       /*instance=*/true);
7479   if (!Method) {
7480     if (Type->isObjCIdType()) {
7481       // For 'id', just check the global pool.
7482       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
7483                                                   /*receiverId=*/true,
7484                                                   /*warn=*/false);
7485     } else {
7486       // Check protocols.
7487       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
7488                                              /*instance=*/true);
7489     }
7490   }
7491 
7492   if (!Method)
7493     return false;
7494 
7495   QualType T = Method->param_begin()[0]->getType();
7496   if (!T->isObjCObjectPointerType())
7497     return false;
7498 
7499   QualType R = Method->getResultType();
7500   if (!R->isScalarType())
7501     return false;
7502 
7503   return true;
7504 }
7505 
7506 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
7507   FromE = FromE->IgnoreParenImpCasts();
7508   switch (FromE->getStmtClass()) {
7509     default:
7510       break;
7511     case Stmt::ObjCStringLiteralClass:
7512       // "string literal"
7513       return LK_String;
7514     case Stmt::ObjCArrayLiteralClass:
7515       // "array literal"
7516       return LK_Array;
7517     case Stmt::ObjCDictionaryLiteralClass:
7518       // "dictionary literal"
7519       return LK_Dictionary;
7520     case Stmt::BlockExprClass:
7521       return LK_Block;
7522     case Stmt::ObjCBoxedExprClass: {
7523       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
7524       switch (Inner->getStmtClass()) {
7525         case Stmt::IntegerLiteralClass:
7526         case Stmt::FloatingLiteralClass:
7527         case Stmt::CharacterLiteralClass:
7528         case Stmt::ObjCBoolLiteralExprClass:
7529         case Stmt::CXXBoolLiteralExprClass:
7530           // "numeric literal"
7531           return LK_Numeric;
7532         case Stmt::ImplicitCastExprClass: {
7533           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
7534           // Boolean literals can be represented by implicit casts.
7535           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
7536             return LK_Numeric;
7537           break;
7538         }
7539         default:
7540           break;
7541       }
7542       return LK_Boxed;
7543     }
7544   }
7545   return LK_None;
7546 }
7547 
7548 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
7549                                           ExprResult &LHS, ExprResult &RHS,
7550                                           BinaryOperator::Opcode Opc){
7551   Expr *Literal;
7552   Expr *Other;
7553   if (isObjCObjectLiteral(LHS)) {
7554     Literal = LHS.get();
7555     Other = RHS.get();
7556   } else {
7557     Literal = RHS.get();
7558     Other = LHS.get();
7559   }
7560 
7561   // Don't warn on comparisons against nil.
7562   Other = Other->IgnoreParenCasts();
7563   if (Other->isNullPointerConstant(S.getASTContext(),
7564                                    Expr::NPC_ValueDependentIsNotNull))
7565     return;
7566 
7567   // This should be kept in sync with warn_objc_literal_comparison.
7568   // LK_String should always be after the other literals, since it has its own
7569   // warning flag.
7570   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
7571   assert(LiteralKind != Sema::LK_Block);
7572   if (LiteralKind == Sema::LK_None) {
7573     llvm_unreachable("Unknown Objective-C object literal kind");
7574   }
7575 
7576   if (LiteralKind == Sema::LK_String)
7577     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7578       << Literal->getSourceRange();
7579   else
7580     S.Diag(Loc, diag::warn_objc_literal_comparison)
7581       << LiteralKind << Literal->getSourceRange();
7582 
7583   if (BinaryOperator::isEqualityOp(Opc) &&
7584       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7585     SourceLocation Start = LHS.get()->getLocStart();
7586     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
7587     CharSourceRange OpRange =
7588       CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
7589 
7590     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7591       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
7592       << FixItHint::CreateReplacement(OpRange, " isEqual:")
7593       << FixItHint::CreateInsertion(End, "]");
7594   }
7595 }
7596 
7597 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
7598                                                 ExprResult &RHS,
7599                                                 SourceLocation Loc,
7600                                                 unsigned OpaqueOpc) {
7601   // This checking requires bools.
7602   if (!S.getLangOpts().Bool) return;
7603 
7604   // Check that left hand side is !something.
7605   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
7606   if (!UO || UO->getOpcode() != UO_LNot) return;
7607 
7608   // Only check if the right hand side is non-bool arithmetic type.
7609   if (RHS.get()->getType()->isBooleanType()) return;
7610 
7611   // Make sure that the something in !something is not bool.
7612   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
7613   if (SubExpr->getType()->isBooleanType()) return;
7614 
7615   // Emit warning.
7616   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
7617       << Loc;
7618 
7619   // First note suggest !(x < y)
7620   SourceLocation FirstOpen = SubExpr->getLocStart();
7621   SourceLocation FirstClose = RHS.get()->getLocEnd();
7622   FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
7623   if (FirstClose.isInvalid())
7624     FirstOpen = SourceLocation();
7625   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
7626       << FixItHint::CreateInsertion(FirstOpen, "(")
7627       << FixItHint::CreateInsertion(FirstClose, ")");
7628 
7629   // Second note suggests (!x) < y
7630   SourceLocation SecondOpen = LHS.get()->getLocStart();
7631   SourceLocation SecondClose = LHS.get()->getLocEnd();
7632   SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
7633   if (SecondClose.isInvalid())
7634     SecondOpen = SourceLocation();
7635   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
7636       << FixItHint::CreateInsertion(SecondOpen, "(")
7637       << FixItHint::CreateInsertion(SecondClose, ")");
7638 }
7639 
7640 // Get the decl for a simple expression: a reference to a variable,
7641 // an implicit C++ field reference, or an implicit ObjC ivar reference.
7642 static ValueDecl *getCompareDecl(Expr *E) {
7643   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
7644     return DR->getDecl();
7645   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
7646     if (Ivar->isFreeIvar())
7647       return Ivar->getDecl();
7648   }
7649   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
7650     if (Mem->isImplicitAccess())
7651       return Mem->getMemberDecl();
7652   }
7653   return 0;
7654 }
7655 
7656 // C99 6.5.8, C++ [expr.rel]
7657 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
7658                                     SourceLocation Loc, unsigned OpaqueOpc,
7659                                     bool IsRelational) {
7660   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7661 
7662   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7663 
7664   // Handle vector comparisons separately.
7665   if (LHS.get()->getType()->isVectorType() ||
7666       RHS.get()->getType()->isVectorType())
7667     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
7668 
7669   QualType LHSType = LHS.get()->getType();
7670   QualType RHSType = RHS.get()->getType();
7671 
7672   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7673   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
7674 
7675   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
7676   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
7677 
7678   if (!LHSType->hasFloatingRepresentation() &&
7679       !(LHSType->isBlockPointerType() && IsRelational) &&
7680       !LHS.get()->getLocStart().isMacroID() &&
7681       !RHS.get()->getLocStart().isMacroID() &&
7682       ActiveTemplateInstantiations.empty()) {
7683     // For non-floating point types, check for self-comparisons of the form
7684     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7685     // often indicate logic errors in the program.
7686     //
7687     // NOTE: Don't warn about comparison expressions resulting from macro
7688     // expansion. Also don't warn about comparisons which are only self
7689     // comparisons within a template specialization. The warnings should catch
7690     // obvious cases in the definition of the template anyways. The idea is to
7691     // warn when the typed comparison operator will always evaluate to the same
7692     // result.
7693     ValueDecl *DL = getCompareDecl(LHSStripped);
7694     ValueDecl *DR = getCompareDecl(RHSStripped);
7695     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
7696       DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7697                           << 0 // self-
7698                           << (Opc == BO_EQ
7699                               || Opc == BO_LE
7700                               || Opc == BO_GE));
7701     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
7702                !DL->getType()->isReferenceType() &&
7703                !DR->getType()->isReferenceType()) {
7704         // what is it always going to eval to?
7705         char always_evals_to;
7706         switch(Opc) {
7707         case BO_EQ: // e.g. array1 == array2
7708           always_evals_to = 0; // false
7709           break;
7710         case BO_NE: // e.g. array1 != array2
7711           always_evals_to = 1; // true
7712           break;
7713         default:
7714           // best we can say is 'a constant'
7715           always_evals_to = 2; // e.g. array1 <= array2
7716           break;
7717         }
7718         DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7719                             << 1 // array
7720                             << always_evals_to);
7721     }
7722 
7723     if (isa<CastExpr>(LHSStripped))
7724       LHSStripped = LHSStripped->IgnoreParenCasts();
7725     if (isa<CastExpr>(RHSStripped))
7726       RHSStripped = RHSStripped->IgnoreParenCasts();
7727 
7728     // Warn about comparisons against a string constant (unless the other
7729     // operand is null), the user probably wants strcmp.
7730     Expr *literalString = 0;
7731     Expr *literalStringStripped = 0;
7732     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7733         !RHSStripped->isNullPointerConstant(Context,
7734                                             Expr::NPC_ValueDependentIsNull)) {
7735       literalString = LHS.get();
7736       literalStringStripped = LHSStripped;
7737     } else if ((isa<StringLiteral>(RHSStripped) ||
7738                 isa<ObjCEncodeExpr>(RHSStripped)) &&
7739                !LHSStripped->isNullPointerConstant(Context,
7740                                             Expr::NPC_ValueDependentIsNull)) {
7741       literalString = RHS.get();
7742       literalStringStripped = RHSStripped;
7743     }
7744 
7745     if (literalString) {
7746       DiagRuntimeBehavior(Loc, 0,
7747         PDiag(diag::warn_stringcompare)
7748           << isa<ObjCEncodeExpr>(literalStringStripped)
7749           << literalString->getSourceRange());
7750     }
7751   }
7752 
7753   // C99 6.5.8p3 / C99 6.5.9p4
7754   UsualArithmeticConversions(LHS, RHS);
7755   if (LHS.isInvalid() || RHS.isInvalid())
7756     return QualType();
7757 
7758   LHSType = LHS.get()->getType();
7759   RHSType = RHS.get()->getType();
7760 
7761   // The result of comparisons is 'bool' in C++, 'int' in C.
7762   QualType ResultTy = Context.getLogicalOperationType();
7763 
7764   if (IsRelational) {
7765     if (LHSType->isRealType() && RHSType->isRealType())
7766       return ResultTy;
7767   } else {
7768     // Check for comparisons of floating point operands using != and ==.
7769     if (LHSType->hasFloatingRepresentation())
7770       CheckFloatComparison(Loc, LHS.get(), RHS.get());
7771 
7772     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7773       return ResultTy;
7774   }
7775 
7776   bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
7777                                               Expr::NPC_ValueDependentIsNull);
7778   bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
7779                                               Expr::NPC_ValueDependentIsNull);
7780 
7781   // All of the following pointer-related warnings are GCC extensions, except
7782   // when handling null pointer constants.
7783   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7784     QualType LCanPointeeTy =
7785       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7786     QualType RCanPointeeTy =
7787       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7788 
7789     if (getLangOpts().CPlusPlus) {
7790       if (LCanPointeeTy == RCanPointeeTy)
7791         return ResultTy;
7792       if (!IsRelational &&
7793           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7794         // Valid unless comparison between non-null pointer and function pointer
7795         // This is a gcc extension compatibility comparison.
7796         // In a SFINAE context, we treat this as a hard error to maintain
7797         // conformance with the C++ standard.
7798         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7799             && !LHSIsNull && !RHSIsNull) {
7800           diagnoseFunctionPointerToVoidComparison(
7801               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
7802 
7803           if (isSFINAEContext())
7804             return QualType();
7805 
7806           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7807           return ResultTy;
7808         }
7809       }
7810 
7811       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7812         return QualType();
7813       else
7814         return ResultTy;
7815     }
7816     // C99 6.5.9p2 and C99 6.5.8p2
7817     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7818                                    RCanPointeeTy.getUnqualifiedType())) {
7819       // Valid unless a relational comparison of function pointers
7820       if (IsRelational && LCanPointeeTy->isFunctionType()) {
7821         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7822           << LHSType << RHSType << LHS.get()->getSourceRange()
7823           << RHS.get()->getSourceRange();
7824       }
7825     } else if (!IsRelational &&
7826                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7827       // Valid unless comparison between non-null pointer and function pointer
7828       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7829           && !LHSIsNull && !RHSIsNull)
7830         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
7831                                                 /*isError*/false);
7832     } else {
7833       // Invalid
7834       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
7835     }
7836     if (LCanPointeeTy != RCanPointeeTy) {
7837       if (LHSIsNull && !RHSIsNull)
7838         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7839       else
7840         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7841     }
7842     return ResultTy;
7843   }
7844 
7845   if (getLangOpts().CPlusPlus) {
7846     // Comparison of nullptr_t with itself.
7847     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
7848       return ResultTy;
7849 
7850     // Comparison of pointers with null pointer constants and equality
7851     // comparisons of member pointers to null pointer constants.
7852     if (RHSIsNull &&
7853         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
7854          (!IsRelational &&
7855           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7856       RHS = ImpCastExprToType(RHS.take(), LHSType,
7857                         LHSType->isMemberPointerType()
7858                           ? CK_NullToMemberPointer
7859                           : CK_NullToPointer);
7860       return ResultTy;
7861     }
7862     if (LHSIsNull &&
7863         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
7864          (!IsRelational &&
7865           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7866       LHS = ImpCastExprToType(LHS.take(), RHSType,
7867                         RHSType->isMemberPointerType()
7868                           ? CK_NullToMemberPointer
7869                           : CK_NullToPointer);
7870       return ResultTy;
7871     }
7872 
7873     // Comparison of member pointers.
7874     if (!IsRelational &&
7875         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7876       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7877         return QualType();
7878       else
7879         return ResultTy;
7880     }
7881 
7882     // Handle scoped enumeration types specifically, since they don't promote
7883     // to integers.
7884     if (LHS.get()->getType()->isEnumeralType() &&
7885         Context.hasSameUnqualifiedType(LHS.get()->getType(),
7886                                        RHS.get()->getType()))
7887       return ResultTy;
7888   }
7889 
7890   // Handle block pointer types.
7891   if (!IsRelational && LHSType->isBlockPointerType() &&
7892       RHSType->isBlockPointerType()) {
7893     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7894     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
7895 
7896     if (!LHSIsNull && !RHSIsNull &&
7897         !Context.typesAreCompatible(lpointee, rpointee)) {
7898       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7899         << LHSType << RHSType << LHS.get()->getSourceRange()
7900         << RHS.get()->getSourceRange();
7901     }
7902     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7903     return ResultTy;
7904   }
7905 
7906   // Allow block pointers to be compared with null pointer constants.
7907   if (!IsRelational
7908       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7909           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
7910     if (!LHSIsNull && !RHSIsNull) {
7911       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
7912              ->getPointeeType()->isVoidType())
7913             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
7914                 ->getPointeeType()->isVoidType())))
7915         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7916           << LHSType << RHSType << LHS.get()->getSourceRange()
7917           << RHS.get()->getSourceRange();
7918     }
7919     if (LHSIsNull && !RHSIsNull)
7920       LHS = ImpCastExprToType(LHS.take(), RHSType,
7921                               RHSType->isPointerType() ? CK_BitCast
7922                                 : CK_AnyPointerToBlockPointerCast);
7923     else
7924       RHS = ImpCastExprToType(RHS.take(), LHSType,
7925                               LHSType->isPointerType() ? CK_BitCast
7926                                 : CK_AnyPointerToBlockPointerCast);
7927     return ResultTy;
7928   }
7929 
7930   if (LHSType->isObjCObjectPointerType() ||
7931       RHSType->isObjCObjectPointerType()) {
7932     const PointerType *LPT = LHSType->getAs<PointerType>();
7933     const PointerType *RPT = RHSType->getAs<PointerType>();
7934     if (LPT || RPT) {
7935       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7936       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
7937 
7938       if (!LPtrToVoid && !RPtrToVoid &&
7939           !Context.typesAreCompatible(LHSType, RHSType)) {
7940         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7941                                           /*isError*/false);
7942       }
7943       if (LHSIsNull && !RHSIsNull) {
7944         Expr *E = LHS.take();
7945         if (getLangOpts().ObjCAutoRefCount)
7946           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
7947         LHS = ImpCastExprToType(E, RHSType,
7948                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7949       }
7950       else {
7951         Expr *E = RHS.take();
7952         if (getLangOpts().ObjCAutoRefCount)
7953           CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion);
7954         RHS = ImpCastExprToType(E, LHSType,
7955                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7956       }
7957       return ResultTy;
7958     }
7959     if (LHSType->isObjCObjectPointerType() &&
7960         RHSType->isObjCObjectPointerType()) {
7961       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7962         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7963                                           /*isError*/false);
7964       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7965         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
7966 
7967       if (LHSIsNull && !RHSIsNull)
7968         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7969       else
7970         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7971       return ResultTy;
7972     }
7973   }
7974   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7975       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
7976     unsigned DiagID = 0;
7977     bool isError = false;
7978     if (LangOpts.DebuggerSupport) {
7979       // Under a debugger, allow the comparison of pointers to integers,
7980       // since users tend to want to compare addresses.
7981     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
7982         (RHSIsNull && RHSType->isIntegerType())) {
7983       if (IsRelational && !getLangOpts().CPlusPlus)
7984         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
7985     } else if (IsRelational && !getLangOpts().CPlusPlus)
7986       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
7987     else if (getLangOpts().CPlusPlus) {
7988       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7989       isError = true;
7990     } else
7991       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
7992 
7993     if (DiagID) {
7994       Diag(Loc, DiagID)
7995         << LHSType << RHSType << LHS.get()->getSourceRange()
7996         << RHS.get()->getSourceRange();
7997       if (isError)
7998         return QualType();
7999     }
8000 
8001     if (LHSType->isIntegerType())
8002       LHS = ImpCastExprToType(LHS.take(), RHSType,
8003                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8004     else
8005       RHS = ImpCastExprToType(RHS.take(), LHSType,
8006                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8007     return ResultTy;
8008   }
8009 
8010   // Handle block pointers.
8011   if (!IsRelational && RHSIsNull
8012       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
8013     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
8014     return ResultTy;
8015   }
8016   if (!IsRelational && LHSIsNull
8017       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
8018     LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
8019     return ResultTy;
8020   }
8021 
8022   return InvalidOperands(Loc, LHS, RHS);
8023 }
8024 
8025 
8026 // Return a signed type that is of identical size and number of elements.
8027 // For floating point vectors, return an integer type of identical size
8028 // and number of elements.
8029 QualType Sema::GetSignedVectorType(QualType V) {
8030   const VectorType *VTy = V->getAs<VectorType>();
8031   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
8032   if (TypeSize == Context.getTypeSize(Context.CharTy))
8033     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
8034   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
8035     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
8036   else if (TypeSize == Context.getTypeSize(Context.IntTy))
8037     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
8038   else if (TypeSize == Context.getTypeSize(Context.LongTy))
8039     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
8040   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
8041          "Unhandled vector element size in vector compare");
8042   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8043 }
8044 
8045 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
8046 /// operates on extended vector types.  Instead of producing an IntTy result,
8047 /// like a scalar comparison, a vector comparison produces a vector of integer
8048 /// types.
8049 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8050                                           SourceLocation Loc,
8051                                           bool IsRelational) {
8052   // Check to make sure we're operating on vectors of the same type and width,
8053   // Allowing one side to be a scalar of element type.
8054   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
8055   if (vType.isNull())
8056     return vType;
8057 
8058   QualType LHSType = LHS.get()->getType();
8059 
8060   // If AltiVec, the comparison results in a numeric type, i.e.
8061   // bool for C++, int for C
8062   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
8063     return Context.getLogicalOperationType();
8064 
8065   // For non-floating point types, check for self-comparisons of the form
8066   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
8067   // often indicate logic errors in the program.
8068   if (!LHSType->hasFloatingRepresentation() &&
8069       ActiveTemplateInstantiations.empty()) {
8070     if (DeclRefExpr* DRL
8071           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
8072       if (DeclRefExpr* DRR
8073             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
8074         if (DRL->getDecl() == DRR->getDecl())
8075           DiagRuntimeBehavior(Loc, 0,
8076                               PDiag(diag::warn_comparison_always)
8077                                 << 0 // self-
8078                                 << 2 // "a constant"
8079                               );
8080   }
8081 
8082   // Check for comparisons of floating point operands using != and ==.
8083   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
8084     assert (RHS.get()->getType()->hasFloatingRepresentation());
8085     CheckFloatComparison(Loc, LHS.get(), RHS.get());
8086   }
8087 
8088   // Return a signed type for the vector.
8089   return GetSignedVectorType(LHSType);
8090 }
8091 
8092 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8093                                           SourceLocation Loc) {
8094   // Ensure that either both operands are of the same vector type, or
8095   // one operand is of a vector type and the other is of its element type.
8096   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
8097   if (vType.isNull())
8098     return InvalidOperands(Loc, LHS, RHS);
8099   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
8100       vType->hasFloatingRepresentation())
8101     return InvalidOperands(Loc, LHS, RHS);
8102 
8103   return GetSignedVectorType(LHS.get()->getType());
8104 }
8105 
8106 inline QualType Sema::CheckBitwiseOperands(
8107   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8108   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8109 
8110   if (LHS.get()->getType()->isVectorType() ||
8111       RHS.get()->getType()->isVectorType()) {
8112     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8113         RHS.get()->getType()->hasIntegerRepresentation())
8114       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
8115 
8116     return InvalidOperands(Loc, LHS, RHS);
8117   }
8118 
8119   ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
8120   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
8121                                                  IsCompAssign);
8122   if (LHSResult.isInvalid() || RHSResult.isInvalid())
8123     return QualType();
8124   LHS = LHSResult.take();
8125   RHS = RHSResult.take();
8126 
8127   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
8128     return compType;
8129   return InvalidOperands(Loc, LHS, RHS);
8130 }
8131 
8132 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
8133   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
8134 
8135   // Check vector operands differently.
8136   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
8137     return CheckVectorLogicalOperands(LHS, RHS, Loc);
8138 
8139   // Diagnose cases where the user write a logical and/or but probably meant a
8140   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
8141   // is a constant.
8142   if (LHS.get()->getType()->isIntegerType() &&
8143       !LHS.get()->getType()->isBooleanType() &&
8144       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
8145       // Don't warn in macros or template instantiations.
8146       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
8147     // If the RHS can be constant folded, and if it constant folds to something
8148     // that isn't 0 or 1 (which indicate a potential logical operation that
8149     // happened to fold to true/false) then warn.
8150     // Parens on the RHS are ignored.
8151     llvm::APSInt Result;
8152     if (RHS.get()->EvaluateAsInt(Result, Context))
8153       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
8154           (Result != 0 && Result != 1)) {
8155         Diag(Loc, diag::warn_logical_instead_of_bitwise)
8156           << RHS.get()->getSourceRange()
8157           << (Opc == BO_LAnd ? "&&" : "||");
8158         // Suggest replacing the logical operator with the bitwise version
8159         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
8160             << (Opc == BO_LAnd ? "&" : "|")
8161             << FixItHint::CreateReplacement(SourceRange(
8162                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
8163                                                 getLangOpts())),
8164                                             Opc == BO_LAnd ? "&" : "|");
8165         if (Opc == BO_LAnd)
8166           // Suggest replacing "Foo() && kNonZero" with "Foo()"
8167           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
8168               << FixItHint::CreateRemoval(
8169                   SourceRange(
8170                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
8171                                                  0, getSourceManager(),
8172                                                  getLangOpts()),
8173                       RHS.get()->getLocEnd()));
8174       }
8175   }
8176 
8177   if (!Context.getLangOpts().CPlusPlus) {
8178     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
8179     // not operate on the built-in scalar and vector float types.
8180     if (Context.getLangOpts().OpenCL &&
8181         Context.getLangOpts().OpenCLVersion < 120) {
8182       if (LHS.get()->getType()->isFloatingType() ||
8183           RHS.get()->getType()->isFloatingType())
8184         return InvalidOperands(Loc, LHS, RHS);
8185     }
8186 
8187     LHS = UsualUnaryConversions(LHS.take());
8188     if (LHS.isInvalid())
8189       return QualType();
8190 
8191     RHS = UsualUnaryConversions(RHS.take());
8192     if (RHS.isInvalid())
8193       return QualType();
8194 
8195     if (!LHS.get()->getType()->isScalarType() ||
8196         !RHS.get()->getType()->isScalarType())
8197       return InvalidOperands(Loc, LHS, RHS);
8198 
8199     return Context.IntTy;
8200   }
8201 
8202   // The following is safe because we only use this method for
8203   // non-overloadable operands.
8204 
8205   // C++ [expr.log.and]p1
8206   // C++ [expr.log.or]p1
8207   // The operands are both contextually converted to type bool.
8208   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
8209   if (LHSRes.isInvalid())
8210     return InvalidOperands(Loc, LHS, RHS);
8211   LHS = LHSRes;
8212 
8213   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
8214   if (RHSRes.isInvalid())
8215     return InvalidOperands(Loc, LHS, RHS);
8216   RHS = RHSRes;
8217 
8218   // C++ [expr.log.and]p2
8219   // C++ [expr.log.or]p2
8220   // The result is a bool.
8221   return Context.BoolTy;
8222 }
8223 
8224 static bool IsReadonlyMessage(Expr *E, Sema &S) {
8225   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
8226   if (!ME) return false;
8227   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
8228   ObjCMessageExpr *Base =
8229     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
8230   if (!Base) return false;
8231   return Base->getMethodDecl() != 0;
8232 }
8233 
8234 /// Is the given expression (which must be 'const') a reference to a
8235 /// variable which was originally non-const, but which has become
8236 /// 'const' due to being captured within a block?
8237 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
8238 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
8239   assert(E->isLValue() && E->getType().isConstQualified());
8240   E = E->IgnoreParens();
8241 
8242   // Must be a reference to a declaration from an enclosing scope.
8243   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
8244   if (!DRE) return NCCK_None;
8245   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
8246 
8247   // The declaration must be a variable which is not declared 'const'.
8248   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8249   if (!var) return NCCK_None;
8250   if (var->getType().isConstQualified()) return NCCK_None;
8251   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
8252 
8253   // Decide whether the first capture was for a block or a lambda.
8254   DeclContext *DC = S.CurContext, *Prev = 0;
8255   while (DC != var->getDeclContext()) {
8256     Prev = DC;
8257     DC = DC->getParent();
8258   }
8259   // Unless we have an init-capture, we've gone one step too far.
8260   if (!var->isInitCapture())
8261     DC = Prev;
8262   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
8263 }
8264 
8265 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
8266 /// emit an error and return true.  If so, return false.
8267 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
8268   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
8269   SourceLocation OrigLoc = Loc;
8270   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
8271                                                               &Loc);
8272   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8273     IsLV = Expr::MLV_InvalidMessageExpression;
8274   if (IsLV == Expr::MLV_Valid)
8275     return false;
8276 
8277   unsigned Diag = 0;
8278   bool NeedType = false;
8279   switch (IsLV) { // C99 6.5.16p2
8280   case Expr::MLV_ConstQualified:
8281     Diag = diag::err_typecheck_assign_const;
8282 
8283     // Use a specialized diagnostic when we're assigning to an object
8284     // from an enclosing function or block.
8285     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
8286       if (NCCK == NCCK_Block)
8287         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8288       else
8289         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
8290       break;
8291     }
8292 
8293     // In ARC, use some specialized diagnostics for occasions where we
8294     // infer 'const'.  These are always pseudo-strong variables.
8295     if (S.getLangOpts().ObjCAutoRefCount) {
8296       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8297       if (declRef && isa<VarDecl>(declRef->getDecl())) {
8298         VarDecl *var = cast<VarDecl>(declRef->getDecl());
8299 
8300         // Use the normal diagnostic if it's pseudo-__strong but the
8301         // user actually wrote 'const'.
8302         if (var->isARCPseudoStrong() &&
8303             (!var->getTypeSourceInfo() ||
8304              !var->getTypeSourceInfo()->getType().isConstQualified())) {
8305           // There are two pseudo-strong cases:
8306           //  - self
8307           ObjCMethodDecl *method = S.getCurMethodDecl();
8308           if (method && var == method->getSelfDecl())
8309             Diag = method->isClassMethod()
8310               ? diag::err_typecheck_arc_assign_self_class_method
8311               : diag::err_typecheck_arc_assign_self;
8312 
8313           //  - fast enumeration variables
8314           else
8315             Diag = diag::err_typecheck_arr_assign_enumeration;
8316 
8317           SourceRange Assign;
8318           if (Loc != OrigLoc)
8319             Assign = SourceRange(OrigLoc, OrigLoc);
8320           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8321           // We need to preserve the AST regardless, so migration tool
8322           // can do its job.
8323           return false;
8324         }
8325       }
8326     }
8327 
8328     break;
8329   case Expr::MLV_ArrayType:
8330   case Expr::MLV_ArrayTemporary:
8331     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8332     NeedType = true;
8333     break;
8334   case Expr::MLV_NotObjectType:
8335     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8336     NeedType = true;
8337     break;
8338   case Expr::MLV_LValueCast:
8339     Diag = diag::err_typecheck_lvalue_casts_not_supported;
8340     break;
8341   case Expr::MLV_Valid:
8342     llvm_unreachable("did not take early return for MLV_Valid");
8343   case Expr::MLV_InvalidExpression:
8344   case Expr::MLV_MemberFunction:
8345   case Expr::MLV_ClassTemporary:
8346     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8347     break;
8348   case Expr::MLV_IncompleteType:
8349   case Expr::MLV_IncompleteVoidType:
8350     return S.RequireCompleteType(Loc, E->getType(),
8351              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
8352   case Expr::MLV_DuplicateVectorComponents:
8353     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8354     break;
8355   case Expr::MLV_NoSetterProperty:
8356     llvm_unreachable("readonly properties should be processed differently");
8357   case Expr::MLV_InvalidMessageExpression:
8358     Diag = diag::error_readonly_message_assignment;
8359     break;
8360   case Expr::MLV_SubObjCPropertySetting:
8361     Diag = diag::error_no_subobject_property_setting;
8362     break;
8363   }
8364 
8365   SourceRange Assign;
8366   if (Loc != OrigLoc)
8367     Assign = SourceRange(OrigLoc, OrigLoc);
8368   if (NeedType)
8369     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
8370   else
8371     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8372   return true;
8373 }
8374 
8375 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
8376                                          SourceLocation Loc,
8377                                          Sema &Sema) {
8378   // C / C++ fields
8379   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
8380   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
8381   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
8382     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
8383       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
8384   }
8385 
8386   // Objective-C instance variables
8387   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
8388   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
8389   if (OL && OR && OL->getDecl() == OR->getDecl()) {
8390     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
8391     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
8392     if (RL && RR && RL->getDecl() == RR->getDecl())
8393       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
8394   }
8395 }
8396 
8397 // C99 6.5.16.1
8398 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
8399                                        SourceLocation Loc,
8400                                        QualType CompoundType) {
8401   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
8402 
8403   // Verify that LHS is a modifiable lvalue, and emit error if not.
8404   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
8405     return QualType();
8406 
8407   QualType LHSType = LHSExpr->getType();
8408   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
8409                                              CompoundType;
8410   AssignConvertType ConvTy;
8411   if (CompoundType.isNull()) {
8412     Expr *RHSCheck = RHS.get();
8413 
8414     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
8415 
8416     QualType LHSTy(LHSType);
8417     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
8418     if (RHS.isInvalid())
8419       return QualType();
8420     // Special case of NSObject attributes on c-style pointer types.
8421     if (ConvTy == IncompatiblePointer &&
8422         ((Context.isObjCNSObjectType(LHSType) &&
8423           RHSType->isObjCObjectPointerType()) ||
8424          (Context.isObjCNSObjectType(RHSType) &&
8425           LHSType->isObjCObjectPointerType())))
8426       ConvTy = Compatible;
8427 
8428     if (ConvTy == Compatible &&
8429         LHSType->isObjCObjectType())
8430         Diag(Loc, diag::err_objc_object_assignment)
8431           << LHSType;
8432 
8433     // If the RHS is a unary plus or minus, check to see if they = and + are
8434     // right next to each other.  If so, the user may have typo'd "x =+ 4"
8435     // instead of "x += 4".
8436     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8437       RHSCheck = ICE->getSubExpr();
8438     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
8439       if ((UO->getOpcode() == UO_Plus ||
8440            UO->getOpcode() == UO_Minus) &&
8441           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
8442           // Only if the two operators are exactly adjacent.
8443           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
8444           // And there is a space or other character before the subexpr of the
8445           // unary +/-.  We don't want to warn on "x=-1".
8446           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8447           UO->getSubExpr()->getLocStart().isFileID()) {
8448         Diag(Loc, diag::warn_not_compound_assign)
8449           << (UO->getOpcode() == UO_Plus ? "+" : "-")
8450           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
8451       }
8452     }
8453 
8454     if (ConvTy == Compatible) {
8455       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
8456         // Warn about retain cycles where a block captures the LHS, but
8457         // not if the LHS is a simple variable into which the block is
8458         // being stored...unless that variable can be captured by reference!
8459         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
8460         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
8461         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
8462           checkRetainCycles(LHSExpr, RHS.get());
8463 
8464         // It is safe to assign a weak reference into a strong variable.
8465         // Although this code can still have problems:
8466         //   id x = self.weakProp;
8467         //   id y = self.weakProp;
8468         // we do not warn to warn spuriously when 'x' and 'y' are on separate
8469         // paths through the function. This should be revisited if
8470         // -Wrepeated-use-of-weak is made flow-sensitive.
8471         DiagnosticsEngine::Level Level =
8472           Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8473                                    RHS.get()->getLocStart());
8474         if (Level != DiagnosticsEngine::Ignored)
8475           getCurFunction()->markSafeWeakUse(RHS.get());
8476 
8477       } else if (getLangOpts().ObjCAutoRefCount) {
8478         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
8479       }
8480     }
8481   } else {
8482     // Compound assignment "x += y"
8483     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
8484   }
8485 
8486   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
8487                                RHS.get(), AA_Assigning))
8488     return QualType();
8489 
8490   CheckForNullPointerDereference(*this, LHSExpr);
8491 
8492   // C99 6.5.16p3: The type of an assignment expression is the type of the
8493   // left operand unless the left operand has qualified type, in which case
8494   // it is the unqualified version of the type of the left operand.
8495   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8496   // is converted to the type of the assignment expression (above).
8497   // C++ 5.17p1: the type of the assignment expression is that of its left
8498   // operand.
8499   return (getLangOpts().CPlusPlus
8500           ? LHSType : LHSType.getUnqualifiedType());
8501 }
8502 
8503 // C99 6.5.17
8504 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
8505                                    SourceLocation Loc) {
8506   LHS = S.CheckPlaceholderExpr(LHS.take());
8507   RHS = S.CheckPlaceholderExpr(RHS.take());
8508   if (LHS.isInvalid() || RHS.isInvalid())
8509     return QualType();
8510 
8511   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8512   // operands, but not unary promotions.
8513   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
8514 
8515   // So we treat the LHS as a ignored value, and in C++ we allow the
8516   // containing site to determine what should be done with the RHS.
8517   LHS = S.IgnoredValueConversions(LHS.take());
8518   if (LHS.isInvalid())
8519     return QualType();
8520 
8521   S.DiagnoseUnusedExprResult(LHS.get());
8522 
8523   if (!S.getLangOpts().CPlusPlus) {
8524     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8525     if (RHS.isInvalid())
8526       return QualType();
8527     if (!RHS.get()->getType()->isVoidType())
8528       S.RequireCompleteType(Loc, RHS.get()->getType(),
8529                             diag::err_incomplete_type);
8530   }
8531 
8532   return RHS.get()->getType();
8533 }
8534 
8535 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8536 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
8537 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8538                                                ExprValueKind &VK,
8539                                                SourceLocation OpLoc,
8540                                                bool IsInc, bool IsPrefix) {
8541   if (Op->isTypeDependent())
8542     return S.Context.DependentTy;
8543 
8544   QualType ResType = Op->getType();
8545   // Atomic types can be used for increment / decrement where the non-atomic
8546   // versions can, so ignore the _Atomic() specifier for the purpose of
8547   // checking.
8548   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8549     ResType = ResAtomicType->getValueType();
8550 
8551   assert(!ResType.isNull() && "no type for increment/decrement expression");
8552 
8553   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
8554     // Decrement of bool is not allowed.
8555     if (!IsInc) {
8556       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8557       return QualType();
8558     }
8559     // Increment of bool sets it to true, but is deprecated.
8560     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8561   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
8562     // Error on enum increments and decrements in C++ mode
8563     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
8564     return QualType();
8565   } else if (ResType->isRealType()) {
8566     // OK!
8567   } else if (ResType->isPointerType()) {
8568     // C99 6.5.2.4p2, 6.5.6p2
8569     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
8570       return QualType();
8571   } else if (ResType->isObjCObjectPointerType()) {
8572     // On modern runtimes, ObjC pointer arithmetic is forbidden.
8573     // Otherwise, we just need a complete type.
8574     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8575         checkArithmeticOnObjCPointer(S, OpLoc, Op))
8576       return QualType();
8577   } else if (ResType->isAnyComplexType()) {
8578     // C99 does not support ++/-- on complex types, we allow as an extension.
8579     S.Diag(OpLoc, diag::ext_integer_increment_complex)
8580       << ResType << Op->getSourceRange();
8581   } else if (ResType->isPlaceholderType()) {
8582     ExprResult PR = S.CheckPlaceholderExpr(Op);
8583     if (PR.isInvalid()) return QualType();
8584     return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8585                                           IsInc, IsPrefix);
8586   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
8587     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8588   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
8589             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
8590     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
8591   } else {
8592     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8593       << ResType << int(IsInc) << Op->getSourceRange();
8594     return QualType();
8595   }
8596   // At this point, we know we have a real, complex or pointer type.
8597   // Now make sure the operand is a modifiable lvalue.
8598   if (CheckForModifiableLvalue(Op, OpLoc, S))
8599     return QualType();
8600   // In C++, a prefix increment is the same type as the operand. Otherwise
8601   // (in C or with postfix), the increment is the unqualified type of the
8602   // operand.
8603   if (IsPrefix && S.getLangOpts().CPlusPlus) {
8604     VK = VK_LValue;
8605     return ResType;
8606   } else {
8607     VK = VK_RValue;
8608     return ResType.getUnqualifiedType();
8609   }
8610 }
8611 
8612 
8613 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8614 /// This routine allows us to typecheck complex/recursive expressions
8615 /// where the declaration is needed for type checking. We only need to
8616 /// handle cases when the expression references a function designator
8617 /// or is an lvalue. Here are some examples:
8618 ///  - &(x) => x
8619 ///  - &*****f => f for f a function designator.
8620 ///  - &s.xx => s
8621 ///  - &s.zz[1].yy -> s, if zz is an array
8622 ///  - *(x + 1) -> x, if x is an array
8623 ///  - &"123"[2] -> 0
8624 ///  - & __real__ x -> x
8625 static ValueDecl *getPrimaryDecl(Expr *E) {
8626   switch (E->getStmtClass()) {
8627   case Stmt::DeclRefExprClass:
8628     return cast<DeclRefExpr>(E)->getDecl();
8629   case Stmt::MemberExprClass:
8630     // If this is an arrow operator, the address is an offset from
8631     // the base's value, so the object the base refers to is
8632     // irrelevant.
8633     if (cast<MemberExpr>(E)->isArrow())
8634       return 0;
8635     // Otherwise, the expression refers to a part of the base
8636     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8637   case Stmt::ArraySubscriptExprClass: {
8638     // FIXME: This code shouldn't be necessary!  We should catch the implicit
8639     // promotion of register arrays earlier.
8640     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8641     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8642       if (ICE->getSubExpr()->getType()->isArrayType())
8643         return getPrimaryDecl(ICE->getSubExpr());
8644     }
8645     return 0;
8646   }
8647   case Stmt::UnaryOperatorClass: {
8648     UnaryOperator *UO = cast<UnaryOperator>(E);
8649 
8650     switch(UO->getOpcode()) {
8651     case UO_Real:
8652     case UO_Imag:
8653     case UO_Extension:
8654       return getPrimaryDecl(UO->getSubExpr());
8655     default:
8656       return 0;
8657     }
8658   }
8659   case Stmt::ParenExprClass:
8660     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8661   case Stmt::ImplicitCastExprClass:
8662     // If the result of an implicit cast is an l-value, we care about
8663     // the sub-expression; otherwise, the result here doesn't matter.
8664     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8665   default:
8666     return 0;
8667   }
8668 }
8669 
8670 namespace {
8671   enum {
8672     AO_Bit_Field = 0,
8673     AO_Vector_Element = 1,
8674     AO_Property_Expansion = 2,
8675     AO_Register_Variable = 3,
8676     AO_No_Error = 4
8677   };
8678 }
8679 /// \brief Diagnose invalid operand for address of operations.
8680 ///
8681 /// \param Type The type of operand which cannot have its address taken.
8682 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8683                                          Expr *E, unsigned Type) {
8684   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8685 }
8686 
8687 /// CheckAddressOfOperand - The operand of & must be either a function
8688 /// designator or an lvalue designating an object. If it is an lvalue, the
8689 /// object cannot be declared with storage class register or be a bit field.
8690 /// Note: The usual conversions are *not* applied to the operand of the &
8691 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8692 /// In C++, the operand might be an overloaded function name, in which case
8693 /// we allow the '&' but retain the overloaded-function type.
8694 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
8695   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8696     if (PTy->getKind() == BuiltinType::Overload) {
8697       Expr *E = OrigOp.get()->IgnoreParens();
8698       if (!isa<OverloadExpr>(E)) {
8699         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
8700         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
8701           << OrigOp.get()->getSourceRange();
8702         return QualType();
8703       }
8704 
8705       OverloadExpr *Ovl = cast<OverloadExpr>(E);
8706       if (isa<UnresolvedMemberExpr>(Ovl))
8707         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
8708           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8709             << OrigOp.get()->getSourceRange();
8710           return QualType();
8711         }
8712 
8713       return Context.OverloadTy;
8714     }
8715 
8716     if (PTy->getKind() == BuiltinType::UnknownAny)
8717       return Context.UnknownAnyTy;
8718 
8719     if (PTy->getKind() == BuiltinType::BoundMember) {
8720       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8721         << OrigOp.get()->getSourceRange();
8722       return QualType();
8723     }
8724 
8725     OrigOp = CheckPlaceholderExpr(OrigOp.take());
8726     if (OrigOp.isInvalid()) return QualType();
8727   }
8728 
8729   if (OrigOp.get()->isTypeDependent())
8730     return Context.DependentTy;
8731 
8732   assert(!OrigOp.get()->getType()->isPlaceholderType());
8733 
8734   // Make sure to ignore parentheses in subsequent checks
8735   Expr *op = OrigOp.get()->IgnoreParens();
8736 
8737   if (getLangOpts().C99) {
8738     // Implement C99-only parts of addressof rules.
8739     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8740       if (uOp->getOpcode() == UO_Deref)
8741         // Per C99 6.5.3.2, the address of a deref always returns a valid result
8742         // (assuming the deref expression is valid).
8743         return uOp->getSubExpr()->getType();
8744     }
8745     // Technically, there should be a check for array subscript
8746     // expressions here, but the result of one is always an lvalue anyway.
8747   }
8748   ValueDecl *dcl = getPrimaryDecl(op);
8749   Expr::LValueClassification lval = op->ClassifyLValue(Context);
8750   unsigned AddressOfError = AO_No_Error;
8751 
8752   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
8753     bool sfinae = (bool)isSFINAEContext();
8754     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
8755                                   : diag::ext_typecheck_addrof_temporary)
8756       << op->getType() << op->getSourceRange();
8757     if (sfinae)
8758       return QualType();
8759     // Materialize the temporary as an lvalue so that we can take its address.
8760     OrigOp = op = new (Context)
8761         MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true, 0);
8762   } else if (isa<ObjCSelectorExpr>(op)) {
8763     return Context.getPointerType(op->getType());
8764   } else if (lval == Expr::LV_MemberFunction) {
8765     // If it's an instance method, make a member pointer.
8766     // The expression must have exactly the form &A::foo.
8767 
8768     // If the underlying expression isn't a decl ref, give up.
8769     if (!isa<DeclRefExpr>(op)) {
8770       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8771         << OrigOp.get()->getSourceRange();
8772       return QualType();
8773     }
8774     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8775     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8776 
8777     // The id-expression was parenthesized.
8778     if (OrigOp.get() != DRE) {
8779       Diag(OpLoc, diag::err_parens_pointer_member_function)
8780         << OrigOp.get()->getSourceRange();
8781 
8782     // The method was named without a qualifier.
8783     } else if (!DRE->getQualifier()) {
8784       if (MD->getParent()->getName().empty())
8785         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8786           << op->getSourceRange();
8787       else {
8788         SmallString<32> Str;
8789         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8790         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8791           << op->getSourceRange()
8792           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8793       }
8794     }
8795 
8796     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
8797     if (isa<CXXDestructorDecl>(MD))
8798       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
8799 
8800     return Context.getMemberPointerType(op->getType(),
8801               Context.getTypeDeclType(MD->getParent()).getTypePtr());
8802   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
8803     // C99 6.5.3.2p1
8804     // The operand must be either an l-value or a function designator
8805     if (!op->getType()->isFunctionType()) {
8806       // Use a special diagnostic for loads from property references.
8807       if (isa<PseudoObjectExpr>(op)) {
8808         AddressOfError = AO_Property_Expansion;
8809       } else {
8810         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8811           << op->getType() << op->getSourceRange();
8812         return QualType();
8813       }
8814     }
8815   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
8816     // The operand cannot be a bit-field
8817     AddressOfError = AO_Bit_Field;
8818   } else if (op->getObjectKind() == OK_VectorComponent) {
8819     // The operand cannot be an element of a vector
8820     AddressOfError = AO_Vector_Element;
8821   } else if (dcl) { // C99 6.5.3.2p1
8822     // We have an lvalue with a decl. Make sure the decl is not declared
8823     // with the register storage-class specifier.
8824     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
8825       // in C++ it is not error to take address of a register
8826       // variable (c++03 7.1.1P3)
8827       if (vd->getStorageClass() == SC_Register &&
8828           !getLangOpts().CPlusPlus) {
8829         AddressOfError = AO_Register_Variable;
8830       }
8831     } else if (isa<FunctionTemplateDecl>(dcl)) {
8832       return Context.OverloadTy;
8833     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8834       // Okay: we can take the address of a field.
8835       // Could be a pointer to member, though, if there is an explicit
8836       // scope qualifier for the class.
8837       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8838         DeclContext *Ctx = dcl->getDeclContext();
8839         if (Ctx && Ctx->isRecord()) {
8840           if (dcl->getType()->isReferenceType()) {
8841             Diag(OpLoc,
8842                  diag::err_cannot_form_pointer_to_member_of_reference_type)
8843               << dcl->getDeclName() << dcl->getType();
8844             return QualType();
8845           }
8846 
8847           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8848             Ctx = Ctx->getParent();
8849           return Context.getMemberPointerType(op->getType(),
8850                 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8851         }
8852       }
8853     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
8854       llvm_unreachable("Unknown/unexpected decl type");
8855   }
8856 
8857   if (AddressOfError != AO_No_Error) {
8858     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
8859     return QualType();
8860   }
8861 
8862   if (lval == Expr::LV_IncompleteVoidType) {
8863     // Taking the address of a void variable is technically illegal, but we
8864     // allow it in cases which are otherwise valid.
8865     // Example: "extern void x; void* y = &x;".
8866     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
8867   }
8868 
8869   // If the operand has type "type", the result has type "pointer to type".
8870   if (op->getType()->isObjCObjectType())
8871     return Context.getObjCObjectPointerType(op->getType());
8872   return Context.getPointerType(op->getType());
8873 }
8874 
8875 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
8876 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8877                                         SourceLocation OpLoc) {
8878   if (Op->isTypeDependent())
8879     return S.Context.DependentTy;
8880 
8881   ExprResult ConvResult = S.UsualUnaryConversions(Op);
8882   if (ConvResult.isInvalid())
8883     return QualType();
8884   Op = ConvResult.take();
8885   QualType OpTy = Op->getType();
8886   QualType Result;
8887 
8888   if (isa<CXXReinterpretCastExpr>(Op)) {
8889     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8890     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8891                                      Op->getSourceRange());
8892   }
8893 
8894   // Note that per both C89 and C99, indirection is always legal, even if OpTy
8895   // is an incomplete type or void.  It would be possible to warn about
8896   // dereferencing a void pointer, but it's completely well-defined, and such a
8897   // warning is unlikely to catch any mistakes.
8898   if (const PointerType *PT = OpTy->getAs<PointerType>())
8899     Result = PT->getPointeeType();
8900   else if (const ObjCObjectPointerType *OPT =
8901              OpTy->getAs<ObjCObjectPointerType>())
8902     Result = OPT->getPointeeType();
8903   else {
8904     ExprResult PR = S.CheckPlaceholderExpr(Op);
8905     if (PR.isInvalid()) return QualType();
8906     if (PR.take() != Op)
8907       return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
8908   }
8909 
8910   if (Result.isNull()) {
8911     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
8912       << OpTy << Op->getSourceRange();
8913     return QualType();
8914   }
8915 
8916   // Dereferences are usually l-values...
8917   VK = VK_LValue;
8918 
8919   // ...except that certain expressions are never l-values in C.
8920   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
8921     VK = VK_RValue;
8922 
8923   return Result;
8924 }
8925 
8926 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
8927   tok::TokenKind Kind) {
8928   BinaryOperatorKind Opc;
8929   switch (Kind) {
8930   default: llvm_unreachable("Unknown binop!");
8931   case tok::periodstar:           Opc = BO_PtrMemD; break;
8932   case tok::arrowstar:            Opc = BO_PtrMemI; break;
8933   case tok::star:                 Opc = BO_Mul; break;
8934   case tok::slash:                Opc = BO_Div; break;
8935   case tok::percent:              Opc = BO_Rem; break;
8936   case tok::plus:                 Opc = BO_Add; break;
8937   case tok::minus:                Opc = BO_Sub; break;
8938   case tok::lessless:             Opc = BO_Shl; break;
8939   case tok::greatergreater:       Opc = BO_Shr; break;
8940   case tok::lessequal:            Opc = BO_LE; break;
8941   case tok::less:                 Opc = BO_LT; break;
8942   case tok::greaterequal:         Opc = BO_GE; break;
8943   case tok::greater:              Opc = BO_GT; break;
8944   case tok::exclaimequal:         Opc = BO_NE; break;
8945   case tok::equalequal:           Opc = BO_EQ; break;
8946   case tok::amp:                  Opc = BO_And; break;
8947   case tok::caret:                Opc = BO_Xor; break;
8948   case tok::pipe:                 Opc = BO_Or; break;
8949   case tok::ampamp:               Opc = BO_LAnd; break;
8950   case tok::pipepipe:             Opc = BO_LOr; break;
8951   case tok::equal:                Opc = BO_Assign; break;
8952   case tok::starequal:            Opc = BO_MulAssign; break;
8953   case tok::slashequal:           Opc = BO_DivAssign; break;
8954   case tok::percentequal:         Opc = BO_RemAssign; break;
8955   case tok::plusequal:            Opc = BO_AddAssign; break;
8956   case tok::minusequal:           Opc = BO_SubAssign; break;
8957   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
8958   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
8959   case tok::ampequal:             Opc = BO_AndAssign; break;
8960   case tok::caretequal:           Opc = BO_XorAssign; break;
8961   case tok::pipeequal:            Opc = BO_OrAssign; break;
8962   case tok::comma:                Opc = BO_Comma; break;
8963   }
8964   return Opc;
8965 }
8966 
8967 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
8968   tok::TokenKind Kind) {
8969   UnaryOperatorKind Opc;
8970   switch (Kind) {
8971   default: llvm_unreachable("Unknown unary op!");
8972   case tok::plusplus:     Opc = UO_PreInc; break;
8973   case tok::minusminus:   Opc = UO_PreDec; break;
8974   case tok::amp:          Opc = UO_AddrOf; break;
8975   case tok::star:         Opc = UO_Deref; break;
8976   case tok::plus:         Opc = UO_Plus; break;
8977   case tok::minus:        Opc = UO_Minus; break;
8978   case tok::tilde:        Opc = UO_Not; break;
8979   case tok::exclaim:      Opc = UO_LNot; break;
8980   case tok::kw___real:    Opc = UO_Real; break;
8981   case tok::kw___imag:    Opc = UO_Imag; break;
8982   case tok::kw___extension__: Opc = UO_Extension; break;
8983   }
8984   return Opc;
8985 }
8986 
8987 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8988 /// This warning is only emitted for builtin assignment operations. It is also
8989 /// suppressed in the event of macro expansions.
8990 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
8991                                    SourceLocation OpLoc) {
8992   if (!S.ActiveTemplateInstantiations.empty())
8993     return;
8994   if (OpLoc.isInvalid() || OpLoc.isMacroID())
8995     return;
8996   LHSExpr = LHSExpr->IgnoreParenImpCasts();
8997   RHSExpr = RHSExpr->IgnoreParenImpCasts();
8998   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8999   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9000   if (!LHSDeclRef || !RHSDeclRef ||
9001       LHSDeclRef->getLocation().isMacroID() ||
9002       RHSDeclRef->getLocation().isMacroID())
9003     return;
9004   const ValueDecl *LHSDecl =
9005     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
9006   const ValueDecl *RHSDecl =
9007     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
9008   if (LHSDecl != RHSDecl)
9009     return;
9010   if (LHSDecl->getType().isVolatileQualified())
9011     return;
9012   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
9013     if (RefTy->getPointeeType().isVolatileQualified())
9014       return;
9015 
9016   S.Diag(OpLoc, diag::warn_self_assignment)
9017       << LHSDeclRef->getType()
9018       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9019 }
9020 
9021 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
9022 /// is usually indicative of introspection within the Objective-C pointer.
9023 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
9024                                           SourceLocation OpLoc) {
9025   if (!S.getLangOpts().ObjC1)
9026     return;
9027 
9028   const Expr *ObjCPointerExpr = 0, *OtherExpr = 0;
9029   const Expr *LHS = L.get();
9030   const Expr *RHS = R.get();
9031 
9032   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9033     ObjCPointerExpr = LHS;
9034     OtherExpr = RHS;
9035   }
9036   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9037     ObjCPointerExpr = RHS;
9038     OtherExpr = LHS;
9039   }
9040 
9041   // This warning is deliberately made very specific to reduce false
9042   // positives with logic that uses '&' for hashing.  This logic mainly
9043   // looks for code trying to introspect into tagged pointers, which
9044   // code should generally never do.
9045   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
9046     unsigned Diag = diag::warn_objc_pointer_masking;
9047     // Determine if we are introspecting the result of performSelectorXXX.
9048     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
9049     // Special case messages to -performSelector and friends, which
9050     // can return non-pointer values boxed in a pointer value.
9051     // Some clients may wish to silence warnings in this subcase.
9052     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
9053       Selector S = ME->getSelector();
9054       StringRef SelArg0 = S.getNameForSlot(0);
9055       if (SelArg0.startswith("performSelector"))
9056         Diag = diag::warn_objc_pointer_masking_performSelector;
9057     }
9058 
9059     S.Diag(OpLoc, Diag)
9060       << ObjCPointerExpr->getSourceRange();
9061   }
9062 }
9063 
9064 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
9065 /// operator @p Opc at location @c TokLoc. This routine only supports
9066 /// built-in operations; ActOnBinOp handles overloaded operators.
9067 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
9068                                     BinaryOperatorKind Opc,
9069                                     Expr *LHSExpr, Expr *RHSExpr) {
9070   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
9071     // The syntax only allows initializer lists on the RHS of assignment,
9072     // so we don't need to worry about accepting invalid code for
9073     // non-assignment operators.
9074     // C++11 5.17p9:
9075     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
9076     //   of x = {} is x = T().
9077     InitializationKind Kind =
9078         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
9079     InitializedEntity Entity =
9080         InitializedEntity::InitializeTemporary(LHSExpr->getType());
9081     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
9082     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
9083     if (Init.isInvalid())
9084       return Init;
9085     RHSExpr = Init.take();
9086   }
9087 
9088   ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
9089   QualType ResultTy;     // Result type of the binary operator.
9090   // The following two variables are used for compound assignment operators
9091   QualType CompLHSTy;    // Type of LHS after promotions for computation
9092   QualType CompResultTy; // Type of computation result
9093   ExprValueKind VK = VK_RValue;
9094   ExprObjectKind OK = OK_Ordinary;
9095 
9096   switch (Opc) {
9097   case BO_Assign:
9098     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
9099     if (getLangOpts().CPlusPlus &&
9100         LHS.get()->getObjectKind() != OK_ObjCProperty) {
9101       VK = LHS.get()->getValueKind();
9102       OK = LHS.get()->getObjectKind();
9103     }
9104     if (!ResultTy.isNull())
9105       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9106     break;
9107   case BO_PtrMemD:
9108   case BO_PtrMemI:
9109     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
9110                                             Opc == BO_PtrMemI);
9111     break;
9112   case BO_Mul:
9113   case BO_Div:
9114     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
9115                                            Opc == BO_Div);
9116     break;
9117   case BO_Rem:
9118     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
9119     break;
9120   case BO_Add:
9121     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
9122     break;
9123   case BO_Sub:
9124     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
9125     break;
9126   case BO_Shl:
9127   case BO_Shr:
9128     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
9129     break;
9130   case BO_LE:
9131   case BO_LT:
9132   case BO_GE:
9133   case BO_GT:
9134     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
9135     break;
9136   case BO_EQ:
9137   case BO_NE:
9138     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
9139     break;
9140   case BO_And:
9141     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
9142   case BO_Xor:
9143   case BO_Or:
9144     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
9145     break;
9146   case BO_LAnd:
9147   case BO_LOr:
9148     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
9149     break;
9150   case BO_MulAssign:
9151   case BO_DivAssign:
9152     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
9153                                                Opc == BO_DivAssign);
9154     CompLHSTy = CompResultTy;
9155     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9156       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9157     break;
9158   case BO_RemAssign:
9159     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
9160     CompLHSTy = CompResultTy;
9161     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9162       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9163     break;
9164   case BO_AddAssign:
9165     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
9166     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9167       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9168     break;
9169   case BO_SubAssign:
9170     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
9171     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9172       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9173     break;
9174   case BO_ShlAssign:
9175   case BO_ShrAssign:
9176     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
9177     CompLHSTy = CompResultTy;
9178     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9179       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9180     break;
9181   case BO_AndAssign:
9182   case BO_XorAssign:
9183   case BO_OrAssign:
9184     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
9185     CompLHSTy = CompResultTy;
9186     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9187       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9188     break;
9189   case BO_Comma:
9190     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
9191     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
9192       VK = RHS.get()->getValueKind();
9193       OK = RHS.get()->getObjectKind();
9194     }
9195     break;
9196   }
9197   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
9198     return ExprError();
9199 
9200   // Check for array bounds violations for both sides of the BinaryOperator
9201   CheckArrayAccess(LHS.get());
9202   CheckArrayAccess(RHS.get());
9203 
9204   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
9205     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
9206                                                  &Context.Idents.get("object_setClass"),
9207                                                  SourceLocation(), LookupOrdinaryName);
9208     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
9209       SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
9210       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
9211       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
9212       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
9213       FixItHint::CreateInsertion(RHSLocEnd, ")");
9214     }
9215     else
9216       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
9217   }
9218   else if (const ObjCIvarRefExpr *OIRE =
9219            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
9220     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
9221 
9222   if (CompResultTy.isNull())
9223     return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
9224                                               ResultTy, VK, OK, OpLoc,
9225                                               FPFeatures.fp_contract));
9226   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
9227       OK_ObjCProperty) {
9228     VK = VK_LValue;
9229     OK = LHS.get()->getObjectKind();
9230   }
9231   return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
9232                                                     ResultTy, VK, OK, CompLHSTy,
9233                                                     CompResultTy, OpLoc,
9234                                                     FPFeatures.fp_contract));
9235 }
9236 
9237 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9238 /// operators are mixed in a way that suggests that the programmer forgot that
9239 /// comparison operators have higher precedence. The most typical example of
9240 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
9241 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
9242                                       SourceLocation OpLoc, Expr *LHSExpr,
9243                                       Expr *RHSExpr) {
9244   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
9245   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
9246 
9247   // Check that one of the sides is a comparison operator.
9248   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
9249   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
9250   if (!isLeftComp && !isRightComp)
9251     return;
9252 
9253   // Bitwise operations are sometimes used as eager logical ops.
9254   // Don't diagnose this.
9255   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
9256   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
9257   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
9258     return;
9259 
9260   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
9261                                                    OpLoc)
9262                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
9263   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
9264   SourceRange ParensRange = isLeftComp ?
9265       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
9266     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
9267 
9268   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9269     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
9270   SuggestParentheses(Self, OpLoc,
9271     Self.PDiag(diag::note_precedence_silence) << OpStr,
9272     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
9273   SuggestParentheses(Self, OpLoc,
9274     Self.PDiag(diag::note_precedence_bitwise_first)
9275       << BinaryOperator::getOpcodeStr(Opc),
9276     ParensRange);
9277 }
9278 
9279 /// \brief It accepts a '&' expr that is inside a '|' one.
9280 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
9281 /// in parentheses.
9282 static void
9283 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
9284                                        BinaryOperator *Bop) {
9285   assert(Bop->getOpcode() == BO_And);
9286   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
9287       << Bop->getSourceRange() << OpLoc;
9288   SuggestParentheses(Self, Bop->getOperatorLoc(),
9289     Self.PDiag(diag::note_precedence_silence)
9290       << Bop->getOpcodeStr(),
9291     Bop->getSourceRange());
9292 }
9293 
9294 /// \brief It accepts a '&&' expr that is inside a '||' one.
9295 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9296 /// in parentheses.
9297 static void
9298 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
9299                                        BinaryOperator *Bop) {
9300   assert(Bop->getOpcode() == BO_LAnd);
9301   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9302       << Bop->getSourceRange() << OpLoc;
9303   SuggestParentheses(Self, Bop->getOperatorLoc(),
9304     Self.PDiag(diag::note_precedence_silence)
9305       << Bop->getOpcodeStr(),
9306     Bop->getSourceRange());
9307 }
9308 
9309 /// \brief Returns true if the given expression can be evaluated as a constant
9310 /// 'true'.
9311 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9312   bool Res;
9313   return !E->isValueDependent() &&
9314          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9315 }
9316 
9317 /// \brief Returns true if the given expression can be evaluated as a constant
9318 /// 'false'.
9319 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9320   bool Res;
9321   return !E->isValueDependent() &&
9322          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9323 }
9324 
9325 /// \brief Look for '&&' in the left hand of a '||' expr.
9326 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
9327                                              Expr *LHSExpr, Expr *RHSExpr) {
9328   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
9329     if (Bop->getOpcode() == BO_LAnd) {
9330       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9331       if (EvaluatesAsFalse(S, RHSExpr))
9332         return;
9333       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9334       if (!EvaluatesAsTrue(S, Bop->getLHS()))
9335         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9336     } else if (Bop->getOpcode() == BO_LOr) {
9337       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9338         // If it's "a || b && 1 || c" we didn't warn earlier for
9339         // "a || b && 1", but warn now.
9340         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9341           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9342       }
9343     }
9344   }
9345 }
9346 
9347 /// \brief Look for '&&' in the right hand of a '||' expr.
9348 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
9349                                              Expr *LHSExpr, Expr *RHSExpr) {
9350   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
9351     if (Bop->getOpcode() == BO_LAnd) {
9352       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9353       if (EvaluatesAsFalse(S, LHSExpr))
9354         return;
9355       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9356       if (!EvaluatesAsTrue(S, Bop->getRHS()))
9357         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9358     }
9359   }
9360 }
9361 
9362 /// \brief Look for '&' in the left or right hand of a '|' expr.
9363 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
9364                                              Expr *OrArg) {
9365   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
9366     if (Bop->getOpcode() == BO_And)
9367       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
9368   }
9369 }
9370 
9371 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
9372                                     Expr *SubExpr, StringRef Shift) {
9373   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
9374     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
9375       StringRef Op = Bop->getOpcodeStr();
9376       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
9377           << Bop->getSourceRange() << OpLoc << Shift << Op;
9378       SuggestParentheses(S, Bop->getOperatorLoc(),
9379           S.PDiag(diag::note_precedence_silence) << Op,
9380           Bop->getSourceRange());
9381     }
9382   }
9383 }
9384 
9385 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
9386                                  Expr *LHSExpr, Expr *RHSExpr) {
9387   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
9388   if (!OCE)
9389     return;
9390 
9391   FunctionDecl *FD = OCE->getDirectCallee();
9392   if (!FD || !FD->isOverloadedOperator())
9393     return;
9394 
9395   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
9396   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
9397     return;
9398 
9399   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
9400       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
9401       << (Kind == OO_LessLess);
9402   SuggestParentheses(S, OCE->getOperatorLoc(),
9403                      S.PDiag(diag::note_precedence_silence)
9404                          << (Kind == OO_LessLess ? "<<" : ">>"),
9405                      OCE->getSourceRange());
9406   SuggestParentheses(S, OpLoc,
9407                      S.PDiag(diag::note_evaluate_comparison_first),
9408                      SourceRange(OCE->getArg(1)->getLocStart(),
9409                                  RHSExpr->getLocEnd()));
9410 }
9411 
9412 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
9413 /// precedence.
9414 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
9415                                     SourceLocation OpLoc, Expr *LHSExpr,
9416                                     Expr *RHSExpr){
9417   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
9418   if (BinaryOperator::isBitwiseOp(Opc))
9419     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
9420 
9421   // Diagnose "arg1 & arg2 | arg3"
9422   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9423     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
9424     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
9425   }
9426 
9427   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9428   // We don't warn for 'assert(a || b && "bad")' since this is safe.
9429   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9430     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
9431     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
9432   }
9433 
9434   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
9435       || Opc == BO_Shr) {
9436     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
9437     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
9438     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
9439   }
9440 
9441   // Warn on overloaded shift operators and comparisons, such as:
9442   // cout << 5 == 4;
9443   if (BinaryOperator::isComparisonOp(Opc))
9444     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
9445 }
9446 
9447 // Binary Operators.  'Tok' is the token for the operator.
9448 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
9449                             tok::TokenKind Kind,
9450                             Expr *LHSExpr, Expr *RHSExpr) {
9451   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
9452   assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
9453   assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
9454 
9455   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9456   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
9457 
9458   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
9459 }
9460 
9461 /// Build an overloaded binary operator expression in the given scope.
9462 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
9463                                        BinaryOperatorKind Opc,
9464                                        Expr *LHS, Expr *RHS) {
9465   // Find all of the overloaded operators visible from this
9466   // point. We perform both an operator-name lookup from the local
9467   // scope and an argument-dependent lookup based on the types of
9468   // the arguments.
9469   UnresolvedSet<16> Functions;
9470   OverloadedOperatorKind OverOp
9471     = BinaryOperator::getOverloadedOperator(Opc);
9472   if (Sc && OverOp != OO_None)
9473     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
9474                                    RHS->getType(), Functions);
9475 
9476   // Build the (potentially-overloaded, potentially-dependent)
9477   // binary operation.
9478   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
9479 }
9480 
9481 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
9482                             BinaryOperatorKind Opc,
9483                             Expr *LHSExpr, Expr *RHSExpr) {
9484   // We want to end up calling one of checkPseudoObjectAssignment
9485   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
9486   // both expressions are overloadable or either is type-dependent),
9487   // or CreateBuiltinBinOp (in any other case).  We also want to get
9488   // any placeholder types out of the way.
9489 
9490   // Handle pseudo-objects in the LHS.
9491   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
9492     // Assignments with a pseudo-object l-value need special analysis.
9493     if (pty->getKind() == BuiltinType::PseudoObject &&
9494         BinaryOperator::isAssignmentOp(Opc))
9495       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
9496 
9497     // Don't resolve overloads if the other type is overloadable.
9498     if (pty->getKind() == BuiltinType::Overload) {
9499       // We can't actually test that if we still have a placeholder,
9500       // though.  Fortunately, none of the exceptions we see in that
9501       // code below are valid when the LHS is an overload set.  Note
9502       // that an overload set can be dependently-typed, but it never
9503       // instantiates to having an overloadable type.
9504       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9505       if (resolvedRHS.isInvalid()) return ExprError();
9506       RHSExpr = resolvedRHS.take();
9507 
9508       if (RHSExpr->isTypeDependent() ||
9509           RHSExpr->getType()->isOverloadableType())
9510         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9511     }
9512 
9513     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
9514     if (LHS.isInvalid()) return ExprError();
9515     LHSExpr = LHS.take();
9516   }
9517 
9518   // Handle pseudo-objects in the RHS.
9519   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
9520     // An overload in the RHS can potentially be resolved by the type
9521     // being assigned to.
9522     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
9523       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9524         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9525 
9526       if (LHSExpr->getType()->isOverloadableType())
9527         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9528 
9529       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9530     }
9531 
9532     // Don't resolve overloads if the other type is overloadable.
9533     if (pty->getKind() == BuiltinType::Overload &&
9534         LHSExpr->getType()->isOverloadableType())
9535       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9536 
9537     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9538     if (!resolvedRHS.isUsable()) return ExprError();
9539     RHSExpr = resolvedRHS.take();
9540   }
9541 
9542   if (getLangOpts().CPlusPlus) {
9543     // If either expression is type-dependent, always build an
9544     // overloaded op.
9545     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9546       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9547 
9548     // Otherwise, build an overloaded op if either expression has an
9549     // overloadable type.
9550     if (LHSExpr->getType()->isOverloadableType() ||
9551         RHSExpr->getType()->isOverloadableType())
9552       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9553   }
9554 
9555   // Build a built-in binary operation.
9556   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9557 }
9558 
9559 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
9560                                       UnaryOperatorKind Opc,
9561                                       Expr *InputExpr) {
9562   ExprResult Input = Owned(InputExpr);
9563   ExprValueKind VK = VK_RValue;
9564   ExprObjectKind OK = OK_Ordinary;
9565   QualType resultType;
9566   switch (Opc) {
9567   case UO_PreInc:
9568   case UO_PreDec:
9569   case UO_PostInc:
9570   case UO_PostDec:
9571     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
9572                                                 Opc == UO_PreInc ||
9573                                                 Opc == UO_PostInc,
9574                                                 Opc == UO_PreInc ||
9575                                                 Opc == UO_PreDec);
9576     break;
9577   case UO_AddrOf:
9578     resultType = CheckAddressOfOperand(Input, OpLoc);
9579     break;
9580   case UO_Deref: {
9581     Input = DefaultFunctionArrayLvalueConversion(Input.take());
9582     if (Input.isInvalid()) return ExprError();
9583     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
9584     break;
9585   }
9586   case UO_Plus:
9587   case UO_Minus:
9588     Input = UsualUnaryConversions(Input.take());
9589     if (Input.isInvalid()) return ExprError();
9590     resultType = Input.get()->getType();
9591     if (resultType->isDependentType())
9592       break;
9593     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9594         resultType->isVectorType())
9595       break;
9596     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
9597              Opc == UO_Plus &&
9598              resultType->isPointerType())
9599       break;
9600 
9601     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9602       << resultType << Input.get()->getSourceRange());
9603 
9604   case UO_Not: // bitwise complement
9605     Input = UsualUnaryConversions(Input.take());
9606     if (Input.isInvalid())
9607       return ExprError();
9608     resultType = Input.get()->getType();
9609     if (resultType->isDependentType())
9610       break;
9611     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9612     if (resultType->isComplexType() || resultType->isComplexIntegerType())
9613       // C99 does not support '~' for complex conjugation.
9614       Diag(OpLoc, diag::ext_integer_complement_complex)
9615           << resultType << Input.get()->getSourceRange();
9616     else if (resultType->hasIntegerRepresentation())
9617       break;
9618     else if (resultType->isExtVectorType()) {
9619       if (Context.getLangOpts().OpenCL) {
9620         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
9621         // on vector float types.
9622         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9623         if (!T->isIntegerType())
9624           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9625                            << resultType << Input.get()->getSourceRange());
9626       }
9627       break;
9628     } else {
9629       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9630                        << resultType << Input.get()->getSourceRange());
9631     }
9632     break;
9633 
9634   case UO_LNot: // logical negation
9635     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
9636     Input = DefaultFunctionArrayLvalueConversion(Input.take());
9637     if (Input.isInvalid()) return ExprError();
9638     resultType = Input.get()->getType();
9639 
9640     // Though we still have to promote half FP to float...
9641     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
9642       Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
9643       resultType = Context.FloatTy;
9644     }
9645 
9646     if (resultType->isDependentType())
9647       break;
9648     if (resultType->isScalarType()) {
9649       // C99 6.5.3.3p1: ok, fallthrough;
9650       if (Context.getLangOpts().CPlusPlus) {
9651         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9652         // operand contextually converted to bool.
9653         Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9654                                   ScalarTypeToBooleanCastKind(resultType));
9655       } else if (Context.getLangOpts().OpenCL &&
9656                  Context.getLangOpts().OpenCLVersion < 120) {
9657         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9658         // operate on scalar float types.
9659         if (!resultType->isIntegerType())
9660           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9661                            << resultType << Input.get()->getSourceRange());
9662       }
9663     } else if (resultType->isExtVectorType()) {
9664       if (Context.getLangOpts().OpenCL &&
9665           Context.getLangOpts().OpenCLVersion < 120) {
9666         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9667         // operate on vector float types.
9668         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9669         if (!T->isIntegerType())
9670           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9671                            << resultType << Input.get()->getSourceRange());
9672       }
9673       // Vector logical not returns the signed variant of the operand type.
9674       resultType = GetSignedVectorType(resultType);
9675       break;
9676     } else {
9677       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9678         << resultType << Input.get()->getSourceRange());
9679     }
9680 
9681     // LNot always has type int. C99 6.5.3.3p5.
9682     // In C++, it's bool. C++ 5.3.1p8
9683     resultType = Context.getLogicalOperationType();
9684     break;
9685   case UO_Real:
9686   case UO_Imag:
9687     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
9688     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
9689     // complex l-values to ordinary l-values and all other values to r-values.
9690     if (Input.isInvalid()) return ExprError();
9691     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
9692       if (Input.get()->getValueKind() != VK_RValue &&
9693           Input.get()->getObjectKind() == OK_Ordinary)
9694         VK = Input.get()->getValueKind();
9695     } else if (!getLangOpts().CPlusPlus) {
9696       // In C, a volatile scalar is read by __imag. In C++, it is not.
9697       Input = DefaultLvalueConversion(Input.take());
9698     }
9699     break;
9700   case UO_Extension:
9701     resultType = Input.get()->getType();
9702     VK = Input.get()->getValueKind();
9703     OK = Input.get()->getObjectKind();
9704     break;
9705   }
9706   if (resultType.isNull() || Input.isInvalid())
9707     return ExprError();
9708 
9709   // Check for array bounds violations in the operand of the UnaryOperator,
9710   // except for the '*' and '&' operators that have to be handled specially
9711   // by CheckArrayAccess (as there are special cases like &array[arraysize]
9712   // that are explicitly defined as valid by the standard).
9713   if (Opc != UO_AddrOf && Opc != UO_Deref)
9714     CheckArrayAccess(Input.get());
9715 
9716   return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
9717                                            VK, OK, OpLoc));
9718 }
9719 
9720 /// \brief Determine whether the given expression is a qualified member
9721 /// access expression, of a form that could be turned into a pointer to member
9722 /// with the address-of operator.
9723 static bool isQualifiedMemberAccess(Expr *E) {
9724   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9725     if (!DRE->getQualifier())
9726       return false;
9727 
9728     ValueDecl *VD = DRE->getDecl();
9729     if (!VD->isCXXClassMember())
9730       return false;
9731 
9732     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9733       return true;
9734     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9735       return Method->isInstance();
9736 
9737     return false;
9738   }
9739 
9740   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9741     if (!ULE->getQualifier())
9742       return false;
9743 
9744     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9745                                            DEnd = ULE->decls_end();
9746          D != DEnd; ++D) {
9747       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9748         if (Method->isInstance())
9749           return true;
9750       } else {
9751         // Overload set does not contain methods.
9752         break;
9753       }
9754     }
9755 
9756     return false;
9757   }
9758 
9759   return false;
9760 }
9761 
9762 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
9763                               UnaryOperatorKind Opc, Expr *Input) {
9764   // First things first: handle placeholders so that the
9765   // overloaded-operator check considers the right type.
9766   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
9767     // Increment and decrement of pseudo-object references.
9768     if (pty->getKind() == BuiltinType::PseudoObject &&
9769         UnaryOperator::isIncrementDecrementOp(Opc))
9770       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
9771 
9772     // extension is always a builtin operator.
9773     if (Opc == UO_Extension)
9774       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9775 
9776     // & gets special logic for several kinds of placeholder.
9777     // The builtin code knows what to do.
9778     if (Opc == UO_AddrOf &&
9779         (pty->getKind() == BuiltinType::Overload ||
9780          pty->getKind() == BuiltinType::UnknownAny ||
9781          pty->getKind() == BuiltinType::BoundMember))
9782       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9783 
9784     // Anything else needs to be handled now.
9785     ExprResult Result = CheckPlaceholderExpr(Input);
9786     if (Result.isInvalid()) return ExprError();
9787     Input = Result.take();
9788   }
9789 
9790   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
9791       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
9792       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
9793     // Find all of the overloaded operators visible from this
9794     // point. We perform both an operator-name lookup from the local
9795     // scope and an argument-dependent lookup based on the types of
9796     // the arguments.
9797     UnresolvedSet<16> Functions;
9798     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
9799     if (S && OverOp != OO_None)
9800       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9801                                    Functions);
9802 
9803     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
9804   }
9805 
9806   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9807 }
9808 
9809 // Unary Operators.  'Tok' is the token for the operator.
9810 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
9811                               tok::TokenKind Op, Expr *Input) {
9812   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
9813 }
9814 
9815 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
9816 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
9817                                 LabelDecl *TheDecl) {
9818   TheDecl->markUsed(Context);
9819   // Create the AST node.  The address of a label always has type 'void*'.
9820   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
9821                                        Context.getPointerType(Context.VoidTy)));
9822 }
9823 
9824 /// Given the last statement in a statement-expression, check whether
9825 /// the result is a producing expression (like a call to an
9826 /// ns_returns_retained function) and, if so, rebuild it to hoist the
9827 /// release out of the full-expression.  Otherwise, return null.
9828 /// Cannot fail.
9829 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
9830   // Should always be wrapped with one of these.
9831   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
9832   if (!cleanups) return 0;
9833 
9834   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
9835   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
9836     return 0;
9837 
9838   // Splice out the cast.  This shouldn't modify any interesting
9839   // features of the statement.
9840   Expr *producer = cast->getSubExpr();
9841   assert(producer->getType() == cast->getType());
9842   assert(producer->getValueKind() == cast->getValueKind());
9843   cleanups->setSubExpr(producer);
9844   return cleanups;
9845 }
9846 
9847 void Sema::ActOnStartStmtExpr() {
9848   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9849 }
9850 
9851 void Sema::ActOnStmtExprError() {
9852   // Note that function is also called by TreeTransform when leaving a
9853   // StmtExpr scope without rebuilding anything.
9854 
9855   DiscardCleanupsInEvaluationContext();
9856   PopExpressionEvaluationContext();
9857 }
9858 
9859 ExprResult
9860 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
9861                     SourceLocation RPLoc) { // "({..})"
9862   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9863   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9864 
9865   if (hasAnyUnrecoverableErrorsInThisFunction())
9866     DiscardCleanupsInEvaluationContext();
9867   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9868   PopExpressionEvaluationContext();
9869 
9870   bool isFileScope
9871     = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
9872   if (isFileScope)
9873     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
9874 
9875   // FIXME: there are a variety of strange constraints to enforce here, for
9876   // example, it is not possible to goto into a stmt expression apparently.
9877   // More semantic analysis is needed.
9878 
9879   // If there are sub stmts in the compound stmt, take the type of the last one
9880   // as the type of the stmtexpr.
9881   QualType Ty = Context.VoidTy;
9882   bool StmtExprMayBindToTemp = false;
9883   if (!Compound->body_empty()) {
9884     Stmt *LastStmt = Compound->body_back();
9885     LabelStmt *LastLabelStmt = 0;
9886     // If LastStmt is a label, skip down through into the body.
9887     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9888       LastLabelStmt = Label;
9889       LastStmt = Label->getSubStmt();
9890     }
9891 
9892     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
9893       // Do function/array conversion on the last expression, but not
9894       // lvalue-to-rvalue.  However, initialize an unqualified type.
9895       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9896       if (LastExpr.isInvalid())
9897         return ExprError();
9898       Ty = LastExpr.get()->getType().getUnqualifiedType();
9899 
9900       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9901         // In ARC, if the final expression ends in a consume, splice
9902         // the consume out and bind it later.  In the alternate case
9903         // (when dealing with a retainable type), the result
9904         // initialization will create a produce.  In both cases the
9905         // result will be +1, and we'll need to balance that out with
9906         // a bind.
9907         if (Expr *rebuiltLastStmt
9908               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9909           LastExpr = rebuiltLastStmt;
9910         } else {
9911           LastExpr = PerformCopyInitialization(
9912                             InitializedEntity::InitializeResult(LPLoc,
9913                                                                 Ty,
9914                                                                 false),
9915                                                    SourceLocation(),
9916                                                LastExpr);
9917         }
9918 
9919         if (LastExpr.isInvalid())
9920           return ExprError();
9921         if (LastExpr.get() != 0) {
9922           if (!LastLabelStmt)
9923             Compound->setLastStmt(LastExpr.take());
9924           else
9925             LastLabelStmt->setSubStmt(LastExpr.take());
9926           StmtExprMayBindToTemp = true;
9927         }
9928       }
9929     }
9930   }
9931 
9932   // FIXME: Check that expression type is complete/non-abstract; statement
9933   // expressions are not lvalues.
9934   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9935   if (StmtExprMayBindToTemp)
9936     return MaybeBindToTemporary(ResStmtExpr);
9937   return Owned(ResStmtExpr);
9938 }
9939 
9940 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
9941                                       TypeSourceInfo *TInfo,
9942                                       OffsetOfComponent *CompPtr,
9943                                       unsigned NumComponents,
9944                                       SourceLocation RParenLoc) {
9945   QualType ArgTy = TInfo->getType();
9946   bool Dependent = ArgTy->isDependentType();
9947   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
9948 
9949   // We must have at least one component that refers to the type, and the first
9950   // one is known to be a field designator.  Verify that the ArgTy represents
9951   // a struct/union/class.
9952   if (!Dependent && !ArgTy->isRecordType())
9953     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9954                        << ArgTy << TypeRange);
9955 
9956   // Type must be complete per C99 7.17p3 because a declaring a variable
9957   // with an incomplete type would be ill-formed.
9958   if (!Dependent
9959       && RequireCompleteType(BuiltinLoc, ArgTy,
9960                              diag::err_offsetof_incomplete_type, TypeRange))
9961     return ExprError();
9962 
9963   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9964   // GCC extension, diagnose them.
9965   // FIXME: This diagnostic isn't actually visible because the location is in
9966   // a system header!
9967   if (NumComponents != 1)
9968     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9969       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
9970 
9971   bool DidWarnAboutNonPOD = false;
9972   QualType CurrentType = ArgTy;
9973   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9974   SmallVector<OffsetOfNode, 4> Comps;
9975   SmallVector<Expr*, 4> Exprs;
9976   for (unsigned i = 0; i != NumComponents; ++i) {
9977     const OffsetOfComponent &OC = CompPtr[i];
9978     if (OC.isBrackets) {
9979       // Offset of an array sub-field.  TODO: Should we allow vector elements?
9980       if (!CurrentType->isDependentType()) {
9981         const ArrayType *AT = Context.getAsArrayType(CurrentType);
9982         if(!AT)
9983           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9984                            << CurrentType);
9985         CurrentType = AT->getElementType();
9986       } else
9987         CurrentType = Context.DependentTy;
9988 
9989       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9990       if (IdxRval.isInvalid())
9991         return ExprError();
9992       Expr *Idx = IdxRval.take();
9993 
9994       // The expression must be an integral expression.
9995       // FIXME: An integral constant expression?
9996       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9997           !Idx->getType()->isIntegerType())
9998         return ExprError(Diag(Idx->getLocStart(),
9999                               diag::err_typecheck_subscript_not_integer)
10000                          << Idx->getSourceRange());
10001 
10002       // Record this array index.
10003       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
10004       Exprs.push_back(Idx);
10005       continue;
10006     }
10007 
10008     // Offset of a field.
10009     if (CurrentType->isDependentType()) {
10010       // We have the offset of a field, but we can't look into the dependent
10011       // type. Just record the identifier of the field.
10012       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
10013       CurrentType = Context.DependentTy;
10014       continue;
10015     }
10016 
10017     // We need to have a complete type to look into.
10018     if (RequireCompleteType(OC.LocStart, CurrentType,
10019                             diag::err_offsetof_incomplete_type))
10020       return ExprError();
10021 
10022     // Look for the designated field.
10023     const RecordType *RC = CurrentType->getAs<RecordType>();
10024     if (!RC)
10025       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
10026                        << CurrentType);
10027     RecordDecl *RD = RC->getDecl();
10028 
10029     // C++ [lib.support.types]p5:
10030     //   The macro offsetof accepts a restricted set of type arguments in this
10031     //   International Standard. type shall be a POD structure or a POD union
10032     //   (clause 9).
10033     // C++11 [support.types]p4:
10034     //   If type is not a standard-layout class (Clause 9), the results are
10035     //   undefined.
10036     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10037       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
10038       unsigned DiagID =
10039         LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type
10040                             : diag::warn_offsetof_non_pod_type;
10041 
10042       if (!IsSafe && !DidWarnAboutNonPOD &&
10043           DiagRuntimeBehavior(BuiltinLoc, 0,
10044                               PDiag(DiagID)
10045                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
10046                               << CurrentType))
10047         DidWarnAboutNonPOD = true;
10048     }
10049 
10050     // Look for the field.
10051     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
10052     LookupQualifiedName(R, RD);
10053     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
10054     IndirectFieldDecl *IndirectMemberDecl = 0;
10055     if (!MemberDecl) {
10056       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
10057         MemberDecl = IndirectMemberDecl->getAnonField();
10058     }
10059 
10060     if (!MemberDecl)
10061       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
10062                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
10063                                                               OC.LocEnd));
10064 
10065     // C99 7.17p3:
10066     //   (If the specified member is a bit-field, the behavior is undefined.)
10067     //
10068     // We diagnose this as an error.
10069     if (MemberDecl->isBitField()) {
10070       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
10071         << MemberDecl->getDeclName()
10072         << SourceRange(BuiltinLoc, RParenLoc);
10073       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
10074       return ExprError();
10075     }
10076 
10077     RecordDecl *Parent = MemberDecl->getParent();
10078     if (IndirectMemberDecl)
10079       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
10080 
10081     // If the member was found in a base class, introduce OffsetOfNodes for
10082     // the base class indirections.
10083     CXXBasePaths Paths;
10084     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
10085       if (Paths.getDetectedVirtual()) {
10086         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
10087           << MemberDecl->getDeclName()
10088           << SourceRange(BuiltinLoc, RParenLoc);
10089         return ExprError();
10090       }
10091 
10092       CXXBasePath &Path = Paths.front();
10093       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
10094            B != BEnd; ++B)
10095         Comps.push_back(OffsetOfNode(B->Base));
10096     }
10097 
10098     if (IndirectMemberDecl) {
10099       for (IndirectFieldDecl::chain_iterator FI =
10100            IndirectMemberDecl->chain_begin(),
10101            FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
10102         assert(isa<FieldDecl>(*FI));
10103         Comps.push_back(OffsetOfNode(OC.LocStart,
10104                                      cast<FieldDecl>(*FI), OC.LocEnd));
10105       }
10106     } else
10107       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
10108 
10109     CurrentType = MemberDecl->getType().getNonReferenceType();
10110   }
10111 
10112   return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
10113                                     TInfo, Comps, Exprs, RParenLoc));
10114 }
10115 
10116 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
10117                                       SourceLocation BuiltinLoc,
10118                                       SourceLocation TypeLoc,
10119                                       ParsedType ParsedArgTy,
10120                                       OffsetOfComponent *CompPtr,
10121                                       unsigned NumComponents,
10122                                       SourceLocation RParenLoc) {
10123 
10124   TypeSourceInfo *ArgTInfo;
10125   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
10126   if (ArgTy.isNull())
10127     return ExprError();
10128 
10129   if (!ArgTInfo)
10130     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
10131 
10132   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
10133                               RParenLoc);
10134 }
10135 
10136 
10137 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
10138                                  Expr *CondExpr,
10139                                  Expr *LHSExpr, Expr *RHSExpr,
10140                                  SourceLocation RPLoc) {
10141   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
10142 
10143   ExprValueKind VK = VK_RValue;
10144   ExprObjectKind OK = OK_Ordinary;
10145   QualType resType;
10146   bool ValueDependent = false;
10147   bool CondIsTrue = false;
10148   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
10149     resType = Context.DependentTy;
10150     ValueDependent = true;
10151   } else {
10152     // The conditional expression is required to be a constant expression.
10153     llvm::APSInt condEval(32);
10154     ExprResult CondICE
10155       = VerifyIntegerConstantExpression(CondExpr, &condEval,
10156           diag::err_typecheck_choose_expr_requires_constant, false);
10157     if (CondICE.isInvalid())
10158       return ExprError();
10159     CondExpr = CondICE.take();
10160     CondIsTrue = condEval.getZExtValue();
10161 
10162     // If the condition is > zero, then the AST type is the same as the LSHExpr.
10163     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
10164 
10165     resType = ActiveExpr->getType();
10166     ValueDependent = ActiveExpr->isValueDependent();
10167     VK = ActiveExpr->getValueKind();
10168     OK = ActiveExpr->getObjectKind();
10169   }
10170 
10171   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
10172                                         resType, VK, OK, RPLoc, CondIsTrue,
10173                                         resType->isDependentType(),
10174                                         ValueDependent));
10175 }
10176 
10177 //===----------------------------------------------------------------------===//
10178 // Clang Extensions.
10179 //===----------------------------------------------------------------------===//
10180 
10181 /// ActOnBlockStart - This callback is invoked when a block literal is started.
10182 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
10183   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
10184 
10185   if (LangOpts.CPlusPlus) {
10186     Decl *ManglingContextDecl;
10187     if (MangleNumberingContext *MCtx =
10188             getCurrentMangleNumberContext(Block->getDeclContext(),
10189                                           ManglingContextDecl)) {
10190       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
10191       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
10192     }
10193   }
10194 
10195   PushBlockScope(CurScope, Block);
10196   CurContext->addDecl(Block);
10197   if (CurScope)
10198     PushDeclContext(CurScope, Block);
10199   else
10200     CurContext = Block;
10201 
10202   getCurBlock()->HasImplicitReturnType = true;
10203 
10204   // Enter a new evaluation context to insulate the block from any
10205   // cleanups from the enclosing full-expression.
10206   PushExpressionEvaluationContext(PotentiallyEvaluated);
10207 }
10208 
10209 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
10210                                Scope *CurScope) {
10211   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
10212   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
10213   BlockScopeInfo *CurBlock = getCurBlock();
10214 
10215   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
10216   QualType T = Sig->getType();
10217 
10218   // FIXME: We should allow unexpanded parameter packs here, but that would,
10219   // in turn, make the block expression contain unexpanded parameter packs.
10220   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
10221     // Drop the parameters.
10222     FunctionProtoType::ExtProtoInfo EPI;
10223     EPI.HasTrailingReturn = false;
10224     EPI.TypeQuals |= DeclSpec::TQ_const;
10225     T = Context.getFunctionType(Context.DependentTy, None, EPI);
10226     Sig = Context.getTrivialTypeSourceInfo(T);
10227   }
10228 
10229   // GetTypeForDeclarator always produces a function type for a block
10230   // literal signature.  Furthermore, it is always a FunctionProtoType
10231   // unless the function was written with a typedef.
10232   assert(T->isFunctionType() &&
10233          "GetTypeForDeclarator made a non-function block signature");
10234 
10235   // Look for an explicit signature in that function type.
10236   FunctionProtoTypeLoc ExplicitSignature;
10237 
10238   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
10239   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
10240 
10241     // Check whether that explicit signature was synthesized by
10242     // GetTypeForDeclarator.  If so, don't save that as part of the
10243     // written signature.
10244     if (ExplicitSignature.getLocalRangeBegin() ==
10245         ExplicitSignature.getLocalRangeEnd()) {
10246       // This would be much cheaper if we stored TypeLocs instead of
10247       // TypeSourceInfos.
10248       TypeLoc Result = ExplicitSignature.getResultLoc();
10249       unsigned Size = Result.getFullDataSize();
10250       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
10251       Sig->getTypeLoc().initializeFullCopy(Result, Size);
10252 
10253       ExplicitSignature = FunctionProtoTypeLoc();
10254     }
10255   }
10256 
10257   CurBlock->TheDecl->setSignatureAsWritten(Sig);
10258   CurBlock->FunctionType = T;
10259 
10260   const FunctionType *Fn = T->getAs<FunctionType>();
10261   QualType RetTy = Fn->getResultType();
10262   bool isVariadic =
10263     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
10264 
10265   CurBlock->TheDecl->setIsVariadic(isVariadic);
10266 
10267   // Context.DependentTy is used as a placeholder for a missing block
10268   // return type.  TODO:  what should we do with declarators like:
10269   //   ^ * { ... }
10270   // If the answer is "apply template argument deduction"....
10271   if (RetTy != Context.DependentTy) {
10272     CurBlock->ReturnType = RetTy;
10273     CurBlock->TheDecl->setBlockMissingReturnType(false);
10274     CurBlock->HasImplicitReturnType = false;
10275   }
10276 
10277   // Push block parameters from the declarator if we had them.
10278   SmallVector<ParmVarDecl*, 8> Params;
10279   if (ExplicitSignature) {
10280     for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
10281       ParmVarDecl *Param = ExplicitSignature.getArg(I);
10282       if (Param->getIdentifier() == 0 &&
10283           !Param->isImplicit() &&
10284           !Param->isInvalidDecl() &&
10285           !getLangOpts().CPlusPlus)
10286         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10287       Params.push_back(Param);
10288     }
10289 
10290   // Fake up parameter variables if we have a typedef, like
10291   //   ^ fntype { ... }
10292   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
10293     for (FunctionProtoType::arg_type_iterator
10294            I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
10295       ParmVarDecl *Param =
10296         BuildParmVarDeclForTypedef(CurBlock->TheDecl,
10297                                    ParamInfo.getLocStart(),
10298                                    *I);
10299       Params.push_back(Param);
10300     }
10301   }
10302 
10303   // Set the parameters on the block decl.
10304   if (!Params.empty()) {
10305     CurBlock->TheDecl->setParams(Params);
10306     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
10307                              CurBlock->TheDecl->param_end(),
10308                              /*CheckParameterNames=*/false);
10309   }
10310 
10311   // Finally we can process decl attributes.
10312   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
10313 
10314   // Put the parameter variables in scope.
10315   for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
10316          E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
10317     (*AI)->setOwningFunction(CurBlock->TheDecl);
10318 
10319     // If this has an identifier, add it to the scope stack.
10320     if ((*AI)->getIdentifier()) {
10321       CheckShadow(CurBlock->TheScope, *AI);
10322 
10323       PushOnScopeChains(*AI, CurBlock->TheScope);
10324     }
10325   }
10326 }
10327 
10328 /// ActOnBlockError - If there is an error parsing a block, this callback
10329 /// is invoked to pop the information about the block from the action impl.
10330 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
10331   // Leave the expression-evaluation context.
10332   DiscardCleanupsInEvaluationContext();
10333   PopExpressionEvaluationContext();
10334 
10335   // Pop off CurBlock, handle nested blocks.
10336   PopDeclContext();
10337   PopFunctionScopeInfo();
10338 }
10339 
10340 /// ActOnBlockStmtExpr - This is called when the body of a block statement
10341 /// literal was successfully completed.  ^(int x){...}
10342 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
10343                                     Stmt *Body, Scope *CurScope) {
10344   // If blocks are disabled, emit an error.
10345   if (!LangOpts.Blocks)
10346     Diag(CaretLoc, diag::err_blocks_disable);
10347 
10348   // Leave the expression-evaluation context.
10349   if (hasAnyUnrecoverableErrorsInThisFunction())
10350     DiscardCleanupsInEvaluationContext();
10351   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
10352   PopExpressionEvaluationContext();
10353 
10354   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
10355 
10356   if (BSI->HasImplicitReturnType)
10357     deduceClosureReturnType(*BSI);
10358 
10359   PopDeclContext();
10360 
10361   QualType RetTy = Context.VoidTy;
10362   if (!BSI->ReturnType.isNull())
10363     RetTy = BSI->ReturnType;
10364 
10365   bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
10366   QualType BlockTy;
10367 
10368   // Set the captured variables on the block.
10369   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
10370   SmallVector<BlockDecl::Capture, 4> Captures;
10371   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
10372     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
10373     if (Cap.isThisCapture())
10374       continue;
10375     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
10376                               Cap.isNested(), Cap.getInitExpr());
10377     Captures.push_back(NewCap);
10378   }
10379   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
10380                             BSI->CXXThisCaptureIndex != 0);
10381 
10382   // If the user wrote a function type in some form, try to use that.
10383   if (!BSI->FunctionType.isNull()) {
10384     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
10385 
10386     FunctionType::ExtInfo Ext = FTy->getExtInfo();
10387     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
10388 
10389     // Turn protoless block types into nullary block types.
10390     if (isa<FunctionNoProtoType>(FTy)) {
10391       FunctionProtoType::ExtProtoInfo EPI;
10392       EPI.ExtInfo = Ext;
10393       BlockTy = Context.getFunctionType(RetTy, None, EPI);
10394 
10395     // Otherwise, if we don't need to change anything about the function type,
10396     // preserve its sugar structure.
10397     } else if (FTy->getResultType() == RetTy &&
10398                (!NoReturn || FTy->getNoReturnAttr())) {
10399       BlockTy = BSI->FunctionType;
10400 
10401     // Otherwise, make the minimal modifications to the function type.
10402     } else {
10403       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
10404       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10405       EPI.TypeQuals = 0; // FIXME: silently?
10406       EPI.ExtInfo = Ext;
10407       BlockTy = Context.getFunctionType(RetTy, FPT->getArgTypes(), EPI);
10408     }
10409 
10410   // If we don't have a function type, just build one from nothing.
10411   } else {
10412     FunctionProtoType::ExtProtoInfo EPI;
10413     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
10414     BlockTy = Context.getFunctionType(RetTy, None, EPI);
10415   }
10416 
10417   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
10418                            BSI->TheDecl->param_end());
10419   BlockTy = Context.getBlockPointerType(BlockTy);
10420 
10421   // If needed, diagnose invalid gotos and switches in the block.
10422   if (getCurFunction()->NeedsScopeChecking() &&
10423       !hasAnyUnrecoverableErrorsInThisFunction() &&
10424       !PP.isCodeCompletionEnabled())
10425     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
10426 
10427   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
10428 
10429   // Try to apply the named return value optimization. We have to check again
10430   // if we can do this, though, because blocks keep return statements around
10431   // to deduce an implicit return type.
10432   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
10433       !BSI->TheDecl->isDependentContext())
10434     computeNRVO(Body, getCurBlock());
10435 
10436   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
10437   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10438   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
10439 
10440   // If the block isn't obviously global, i.e. it captures anything at
10441   // all, then we need to do a few things in the surrounding context:
10442   if (Result->getBlockDecl()->hasCaptures()) {
10443     // First, this expression has a new cleanup object.
10444     ExprCleanupObjects.push_back(Result->getBlockDecl());
10445     ExprNeedsCleanups = true;
10446 
10447     // It also gets a branch-protected scope if any of the captured
10448     // variables needs destruction.
10449     for (BlockDecl::capture_const_iterator
10450            ci = Result->getBlockDecl()->capture_begin(),
10451            ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
10452       const VarDecl *var = ci->getVariable();
10453       if (var->getType().isDestructedType() != QualType::DK_none) {
10454         getCurFunction()->setHasBranchProtectedScope();
10455         break;
10456       }
10457     }
10458   }
10459 
10460   return Owned(Result);
10461 }
10462 
10463 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
10464                                         Expr *E, ParsedType Ty,
10465                                         SourceLocation RPLoc) {
10466   TypeSourceInfo *TInfo;
10467   GetTypeFromParser(Ty, &TInfo);
10468   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
10469 }
10470 
10471 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
10472                                 Expr *E, TypeSourceInfo *TInfo,
10473                                 SourceLocation RPLoc) {
10474   Expr *OrigExpr = E;
10475 
10476   // Get the va_list type
10477   QualType VaListType = Context.getBuiltinVaListType();
10478   if (VaListType->isArrayType()) {
10479     // Deal with implicit array decay; for example, on x86-64,
10480     // va_list is an array, but it's supposed to decay to
10481     // a pointer for va_arg.
10482     VaListType = Context.getArrayDecayedType(VaListType);
10483     // Make sure the input expression also decays appropriately.
10484     ExprResult Result = UsualUnaryConversions(E);
10485     if (Result.isInvalid())
10486       return ExprError();
10487     E = Result.take();
10488   } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
10489     // If va_list is a record type and we are compiling in C++ mode,
10490     // check the argument using reference binding.
10491     InitializedEntity Entity
10492       = InitializedEntity::InitializeParameter(Context,
10493           Context.getLValueReferenceType(VaListType), false);
10494     ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
10495     if (Init.isInvalid())
10496       return ExprError();
10497     E = Init.takeAs<Expr>();
10498   } else {
10499     // Otherwise, the va_list argument must be an l-value because
10500     // it is modified by va_arg.
10501     if (!E->isTypeDependent() &&
10502         CheckForModifiableLvalue(E, BuiltinLoc, *this))
10503       return ExprError();
10504   }
10505 
10506   if (!E->isTypeDependent() &&
10507       !Context.hasSameType(VaListType, E->getType())) {
10508     return ExprError(Diag(E->getLocStart(),
10509                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
10510       << OrigExpr->getType() << E->getSourceRange());
10511   }
10512 
10513   if (!TInfo->getType()->isDependentType()) {
10514     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10515                             diag::err_second_parameter_to_va_arg_incomplete,
10516                             TInfo->getTypeLoc()))
10517       return ExprError();
10518 
10519     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10520                                TInfo->getType(),
10521                                diag::err_second_parameter_to_va_arg_abstract,
10522                                TInfo->getTypeLoc()))
10523       return ExprError();
10524 
10525     if (!TInfo->getType().isPODType(Context)) {
10526       Diag(TInfo->getTypeLoc().getBeginLoc(),
10527            TInfo->getType()->isObjCLifetimeType()
10528              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
10529              : diag::warn_second_parameter_to_va_arg_not_pod)
10530         << TInfo->getType()
10531         << TInfo->getTypeLoc().getSourceRange();
10532     }
10533 
10534     // Check for va_arg where arguments of the given type will be promoted
10535     // (i.e. this va_arg is guaranteed to have undefined behavior).
10536     QualType PromoteType;
10537     if (TInfo->getType()->isPromotableIntegerType()) {
10538       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
10539       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
10540         PromoteType = QualType();
10541     }
10542     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
10543       PromoteType = Context.DoubleTy;
10544     if (!PromoteType.isNull())
10545       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
10546                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
10547                           << TInfo->getType()
10548                           << PromoteType
10549                           << TInfo->getTypeLoc().getSourceRange());
10550   }
10551 
10552   QualType T = TInfo->getType().getNonLValueExprType(Context);
10553   return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
10554 }
10555 
10556 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
10557   // The type of __null will be int or long, depending on the size of
10558   // pointers on the target.
10559   QualType Ty;
10560   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
10561   if (pw == Context.getTargetInfo().getIntWidth())
10562     Ty = Context.IntTy;
10563   else if (pw == Context.getTargetInfo().getLongWidth())
10564     Ty = Context.LongTy;
10565   else if (pw == Context.getTargetInfo().getLongLongWidth())
10566     Ty = Context.LongLongTy;
10567   else {
10568     llvm_unreachable("I don't know size of pointer!");
10569   }
10570 
10571   return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
10572 }
10573 
10574 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
10575                                            Expr *SrcExpr, FixItHint &Hint,
10576                                            bool &IsNSString) {
10577   if (!SemaRef.getLangOpts().ObjC1)
10578     return;
10579 
10580   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10581   if (!PT)
10582     return;
10583 
10584   // Check if the destination is of type 'id'.
10585   if (!PT->isObjCIdType()) {
10586     // Check if the destination is the 'NSString' interface.
10587     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10588     if (!ID || !ID->getIdentifier()->isStr("NSString"))
10589       return;
10590     IsNSString = true;
10591   }
10592 
10593   // Ignore any parens, implicit casts (should only be
10594   // array-to-pointer decays), and not-so-opaque values.  The last is
10595   // important for making this trigger for property assignments.
10596   SrcExpr = SrcExpr->IgnoreParenImpCasts();
10597   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10598     if (OV->getSourceExpr())
10599       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10600 
10601   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
10602   if (!SL || !SL->isAscii())
10603     return;
10604 
10605   Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
10606 }
10607 
10608 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10609                                     SourceLocation Loc,
10610                                     QualType DstType, QualType SrcType,
10611                                     Expr *SrcExpr, AssignmentAction Action,
10612                                     bool *Complained) {
10613   if (Complained)
10614     *Complained = false;
10615 
10616   // Decode the result (notice that AST's are still created for extensions).
10617   bool CheckInferredResultType = false;
10618   bool isInvalid = false;
10619   unsigned DiagKind = 0;
10620   FixItHint Hint;
10621   ConversionFixItGenerator ConvHints;
10622   bool MayHaveConvFixit = false;
10623   bool MayHaveFunctionDiff = false;
10624   bool IsNSString = false;
10625 
10626   switch (ConvTy) {
10627   case Compatible:
10628       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10629       return false;
10630 
10631   case PointerToInt:
10632     DiagKind = diag::ext_typecheck_convert_pointer_int;
10633     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10634     MayHaveConvFixit = true;
10635     break;
10636   case IntToPointer:
10637     DiagKind = diag::ext_typecheck_convert_int_pointer;
10638     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10639     MayHaveConvFixit = true;
10640     break;
10641   case IncompatiblePointer:
10642     MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint, IsNSString);
10643       DiagKind =
10644         (Action == AA_Passing_CFAudited ?
10645           diag::err_arc_typecheck_convert_incompatible_pointer :
10646           diag::ext_typecheck_convert_incompatible_pointer);
10647     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10648       SrcType->isObjCObjectPointerType();
10649     if (Hint.isNull() && !CheckInferredResultType) {
10650       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10651     }
10652     else if (CheckInferredResultType) {
10653       SrcType = SrcType.getUnqualifiedType();
10654       DstType = DstType.getUnqualifiedType();
10655     }
10656     else if (IsNSString && !Hint.isNull())
10657       DiagKind = diag::warn_missing_atsign_prefix;
10658     MayHaveConvFixit = true;
10659     break;
10660   case IncompatiblePointerSign:
10661     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10662     break;
10663   case FunctionVoidPointer:
10664     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10665     break;
10666   case IncompatiblePointerDiscardsQualifiers: {
10667     // Perform array-to-pointer decay if necessary.
10668     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10669 
10670     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10671     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10672     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10673       DiagKind = diag::err_typecheck_incompatible_address_space;
10674       break;
10675 
10676 
10677     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10678       DiagKind = diag::err_typecheck_incompatible_ownership;
10679       break;
10680     }
10681 
10682     llvm_unreachable("unknown error case for discarding qualifiers!");
10683     // fallthrough
10684   }
10685   case CompatiblePointerDiscardsQualifiers:
10686     // If the qualifiers lost were because we were applying the
10687     // (deprecated) C++ conversion from a string literal to a char*
10688     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
10689     // Ideally, this check would be performed in
10690     // checkPointerTypesForAssignment. However, that would require a
10691     // bit of refactoring (so that the second argument is an
10692     // expression, rather than a type), which should be done as part
10693     // of a larger effort to fix checkPointerTypesForAssignment for
10694     // C++ semantics.
10695     if (getLangOpts().CPlusPlus &&
10696         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10697       return false;
10698     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10699     break;
10700   case IncompatibleNestedPointerQualifiers:
10701     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
10702     break;
10703   case IntToBlockPointer:
10704     DiagKind = diag::err_int_to_block_pointer;
10705     break;
10706   case IncompatibleBlockPointer:
10707     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
10708     break;
10709   case IncompatibleObjCQualifiedId:
10710     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
10711     // it can give a more specific diagnostic.
10712     DiagKind = diag::warn_incompatible_qualified_id;
10713     break;
10714   case IncompatibleVectors:
10715     DiagKind = diag::warn_incompatible_vectors;
10716     break;
10717   case IncompatibleObjCWeakRef:
10718     DiagKind = diag::err_arc_weak_unavailable_assign;
10719     break;
10720   case Incompatible:
10721     DiagKind = diag::err_typecheck_convert_incompatible;
10722     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10723     MayHaveConvFixit = true;
10724     isInvalid = true;
10725     MayHaveFunctionDiff = true;
10726     break;
10727   }
10728 
10729   QualType FirstType, SecondType;
10730   switch (Action) {
10731   case AA_Assigning:
10732   case AA_Initializing:
10733     // The destination type comes first.
10734     FirstType = DstType;
10735     SecondType = SrcType;
10736     break;
10737 
10738   case AA_Returning:
10739   case AA_Passing:
10740   case AA_Passing_CFAudited:
10741   case AA_Converting:
10742   case AA_Sending:
10743   case AA_Casting:
10744     // The source type comes first.
10745     FirstType = SrcType;
10746     SecondType = DstType;
10747     break;
10748   }
10749 
10750   PartialDiagnostic FDiag = PDiag(DiagKind);
10751   if (Action == AA_Passing_CFAudited)
10752     FDiag << FirstType << SecondType << SrcExpr->getSourceRange();
10753   else
10754     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
10755 
10756   // If we can fix the conversion, suggest the FixIts.
10757   assert(ConvHints.isNull() || Hint.isNull());
10758   if (!ConvHints.isNull()) {
10759     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
10760          HE = ConvHints.Hints.end(); HI != HE; ++HI)
10761       FDiag << *HI;
10762   } else {
10763     FDiag << Hint;
10764   }
10765   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
10766 
10767   if (MayHaveFunctionDiff)
10768     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
10769 
10770   Diag(Loc, FDiag);
10771 
10772   if (SecondType == Context.OverloadTy)
10773     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
10774                               FirstType);
10775 
10776   if (CheckInferredResultType)
10777     EmitRelatedResultTypeNote(SrcExpr);
10778 
10779   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
10780     EmitRelatedResultTypeNoteForReturn(DstType);
10781 
10782   if (Complained)
10783     *Complained = true;
10784   return isInvalid;
10785 }
10786 
10787 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10788                                                  llvm::APSInt *Result) {
10789   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
10790   public:
10791     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10792       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
10793     }
10794   } Diagnoser;
10795 
10796   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
10797 }
10798 
10799 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10800                                                  llvm::APSInt *Result,
10801                                                  unsigned DiagID,
10802                                                  bool AllowFold) {
10803   class IDDiagnoser : public VerifyICEDiagnoser {
10804     unsigned DiagID;
10805 
10806   public:
10807     IDDiagnoser(unsigned DiagID)
10808       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
10809 
10810     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10811       S.Diag(Loc, DiagID) << SR;
10812     }
10813   } Diagnoser(DiagID);
10814 
10815   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
10816 }
10817 
10818 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
10819                                             SourceRange SR) {
10820   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
10821 }
10822 
10823 ExprResult
10824 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10825                                       VerifyICEDiagnoser &Diagnoser,
10826                                       bool AllowFold) {
10827   SourceLocation DiagLoc = E->getLocStart();
10828 
10829   if (getLangOpts().CPlusPlus11) {
10830     // C++11 [expr.const]p5:
10831     //   If an expression of literal class type is used in a context where an
10832     //   integral constant expression is required, then that class type shall
10833     //   have a single non-explicit conversion function to an integral or
10834     //   unscoped enumeration type
10835     ExprResult Converted;
10836     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
10837     public:
10838       CXX11ConvertDiagnoser(bool Silent)
10839           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
10840                                 Silent, true) {}
10841 
10842       virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10843                                                    QualType T) {
10844         return S.Diag(Loc, diag::err_ice_not_integral) << T;
10845       }
10846 
10847       virtual SemaDiagnosticBuilder diagnoseIncomplete(
10848           Sema &S, SourceLocation Loc, QualType T) {
10849         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
10850       }
10851 
10852       virtual SemaDiagnosticBuilder diagnoseExplicitConv(
10853           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
10854         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10855       }
10856 
10857       virtual SemaDiagnosticBuilder noteExplicitConv(
10858           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
10859         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10860                  << ConvTy->isEnumeralType() << ConvTy;
10861       }
10862 
10863       virtual SemaDiagnosticBuilder diagnoseAmbiguous(
10864           Sema &S, SourceLocation Loc, QualType T) {
10865         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10866       }
10867 
10868       virtual SemaDiagnosticBuilder noteAmbiguous(
10869           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
10870         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10871                  << ConvTy->isEnumeralType() << ConvTy;
10872       }
10873 
10874       virtual SemaDiagnosticBuilder diagnoseConversion(
10875           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
10876         llvm_unreachable("conversion functions are permitted");
10877       }
10878     } ConvertDiagnoser(Diagnoser.Suppress);
10879 
10880     Converted = PerformContextualImplicitConversion(DiagLoc, E,
10881                                                     ConvertDiagnoser);
10882     if (Converted.isInvalid())
10883       return Converted;
10884     E = Converted.take();
10885     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10886       return ExprError();
10887   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10888     // An ICE must be of integral or unscoped enumeration type.
10889     if (!Diagnoser.Suppress)
10890       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10891     return ExprError();
10892   }
10893 
10894   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10895   // in the non-ICE case.
10896   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
10897     if (Result)
10898       *Result = E->EvaluateKnownConstInt(Context);
10899     return Owned(E);
10900   }
10901 
10902   Expr::EvalResult EvalResult;
10903   SmallVector<PartialDiagnosticAt, 8> Notes;
10904   EvalResult.Diag = &Notes;
10905 
10906   // Try to evaluate the expression, and produce diagnostics explaining why it's
10907   // not a constant expression as a side-effect.
10908   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10909                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10910 
10911   // In C++11, we can rely on diagnostics being produced for any expression
10912   // which is not a constant expression. If no diagnostics were produced, then
10913   // this is a constant expression.
10914   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
10915     if (Result)
10916       *Result = EvalResult.Val.getInt();
10917     return Owned(E);
10918   }
10919 
10920   // If our only note is the usual "invalid subexpression" note, just point
10921   // the caret at its location rather than producing an essentially
10922   // redundant note.
10923   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10924         diag::note_invalid_subexpr_in_const_expr) {
10925     DiagLoc = Notes[0].first;
10926     Notes.clear();
10927   }
10928 
10929   if (!Folded || !AllowFold) {
10930     if (!Diagnoser.Suppress) {
10931       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10932       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10933         Diag(Notes[I].first, Notes[I].second);
10934     }
10935 
10936     return ExprError();
10937   }
10938 
10939   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
10940   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10941     Diag(Notes[I].first, Notes[I].second);
10942 
10943   if (Result)
10944     *Result = EvalResult.Val.getInt();
10945   return Owned(E);
10946 }
10947 
10948 namespace {
10949   // Handle the case where we conclude a expression which we speculatively
10950   // considered to be unevaluated is actually evaluated.
10951   class TransformToPE : public TreeTransform<TransformToPE> {
10952     typedef TreeTransform<TransformToPE> BaseTransform;
10953 
10954   public:
10955     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10956 
10957     // Make sure we redo semantic analysis
10958     bool AlwaysRebuild() { return true; }
10959 
10960     // Make sure we handle LabelStmts correctly.
10961     // FIXME: This does the right thing, but maybe we need a more general
10962     // fix to TreeTransform?
10963     StmtResult TransformLabelStmt(LabelStmt *S) {
10964       S->getDecl()->setStmt(0);
10965       return BaseTransform::TransformLabelStmt(S);
10966     }
10967 
10968     // We need to special-case DeclRefExprs referring to FieldDecls which
10969     // are not part of a member pointer formation; normal TreeTransforming
10970     // doesn't catch this case because of the way we represent them in the AST.
10971     // FIXME: This is a bit ugly; is it really the best way to handle this
10972     // case?
10973     //
10974     // Error on DeclRefExprs referring to FieldDecls.
10975     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10976       if (isa<FieldDecl>(E->getDecl()) &&
10977           !SemaRef.isUnevaluatedContext())
10978         return SemaRef.Diag(E->getLocation(),
10979                             diag::err_invalid_non_static_member_use)
10980             << E->getDecl() << E->getSourceRange();
10981 
10982       return BaseTransform::TransformDeclRefExpr(E);
10983     }
10984 
10985     // Exception: filter out member pointer formation
10986     ExprResult TransformUnaryOperator(UnaryOperator *E) {
10987       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10988         return E;
10989 
10990       return BaseTransform::TransformUnaryOperator(E);
10991     }
10992 
10993     ExprResult TransformLambdaExpr(LambdaExpr *E) {
10994       // Lambdas never need to be transformed.
10995       return E;
10996     }
10997   };
10998 }
10999 
11000 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
11001   assert(isUnevaluatedContext() &&
11002          "Should only transform unevaluated expressions");
11003   ExprEvalContexts.back().Context =
11004       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
11005   if (isUnevaluatedContext())
11006     return E;
11007   return TransformToPE(*this).TransformExpr(E);
11008 }
11009 
11010 void
11011 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11012                                       Decl *LambdaContextDecl,
11013                                       bool IsDecltype) {
11014   ExprEvalContexts.push_back(
11015              ExpressionEvaluationContextRecord(NewContext,
11016                                                ExprCleanupObjects.size(),
11017                                                ExprNeedsCleanups,
11018                                                LambdaContextDecl,
11019                                                IsDecltype));
11020   ExprNeedsCleanups = false;
11021   if (!MaybeODRUseExprs.empty())
11022     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
11023 }
11024 
11025 void
11026 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11027                                       ReuseLambdaContextDecl_t,
11028                                       bool IsDecltype) {
11029   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
11030   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
11031 }
11032 
11033 void Sema::PopExpressionEvaluationContext() {
11034   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
11035 
11036   if (!Rec.Lambdas.empty()) {
11037     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11038       unsigned D;
11039       if (Rec.isUnevaluated()) {
11040         // C++11 [expr.prim.lambda]p2:
11041         //   A lambda-expression shall not appear in an unevaluated operand
11042         //   (Clause 5).
11043         D = diag::err_lambda_unevaluated_operand;
11044       } else {
11045         // C++1y [expr.const]p2:
11046         //   A conditional-expression e is a core constant expression unless the
11047         //   evaluation of e, following the rules of the abstract machine, would
11048         //   evaluate [...] a lambda-expression.
11049         D = diag::err_lambda_in_constant_expression;
11050       }
11051       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
11052         Diag(Rec.Lambdas[I]->getLocStart(), D);
11053     } else {
11054       // Mark the capture expressions odr-used. This was deferred
11055       // during lambda expression creation.
11056       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
11057         LambdaExpr *Lambda = Rec.Lambdas[I];
11058         for (LambdaExpr::capture_init_iterator
11059                   C = Lambda->capture_init_begin(),
11060                CEnd = Lambda->capture_init_end();
11061              C != CEnd; ++C) {
11062           MarkDeclarationsReferencedInExpr(*C);
11063         }
11064       }
11065     }
11066   }
11067 
11068   // When are coming out of an unevaluated context, clear out any
11069   // temporaries that we may have created as part of the evaluation of
11070   // the expression in that context: they aren't relevant because they
11071   // will never be constructed.
11072   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11073     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
11074                              ExprCleanupObjects.end());
11075     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
11076     CleanupVarDeclMarking();
11077     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
11078   // Otherwise, merge the contexts together.
11079   } else {
11080     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
11081     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
11082                             Rec.SavedMaybeODRUseExprs.end());
11083   }
11084 
11085   // Pop the current expression evaluation context off the stack.
11086   ExprEvalContexts.pop_back();
11087 }
11088 
11089 void Sema::DiscardCleanupsInEvaluationContext() {
11090   ExprCleanupObjects.erase(
11091          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
11092          ExprCleanupObjects.end());
11093   ExprNeedsCleanups = false;
11094   MaybeODRUseExprs.clear();
11095 }
11096 
11097 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
11098   if (!E->getType()->isVariablyModifiedType())
11099     return E;
11100   return TransformToPotentiallyEvaluated(E);
11101 }
11102 
11103 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
11104   // Do not mark anything as "used" within a dependent context; wait for
11105   // an instantiation.
11106   if (SemaRef.CurContext->isDependentContext())
11107     return false;
11108 
11109   switch (SemaRef.ExprEvalContexts.back().Context) {
11110     case Sema::Unevaluated:
11111     case Sema::UnevaluatedAbstract:
11112       // We are in an expression that is not potentially evaluated; do nothing.
11113       // (Depending on how you read the standard, we actually do need to do
11114       // something here for null pointer constants, but the standard's
11115       // definition of a null pointer constant is completely crazy.)
11116       return false;
11117 
11118     case Sema::ConstantEvaluated:
11119     case Sema::PotentiallyEvaluated:
11120       // We are in a potentially evaluated expression (or a constant-expression
11121       // in C++03); we need to do implicit template instantiation, implicitly
11122       // define class members, and mark most declarations as used.
11123       return true;
11124 
11125     case Sema::PotentiallyEvaluatedIfUsed:
11126       // Referenced declarations will only be used if the construct in the
11127       // containing expression is used.
11128       return false;
11129   }
11130   llvm_unreachable("Invalid context");
11131 }
11132 
11133 /// \brief Mark a function referenced, and check whether it is odr-used
11134 /// (C++ [basic.def.odr]p2, C99 6.9p3)
11135 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
11136   assert(Func && "No function?");
11137 
11138   Func->setReferenced();
11139 
11140   // C++11 [basic.def.odr]p3:
11141   //   A function whose name appears as a potentially-evaluated expression is
11142   //   odr-used if it is the unique lookup result or the selected member of a
11143   //   set of overloaded functions [...].
11144   //
11145   // We (incorrectly) mark overload resolution as an unevaluated context, so we
11146   // can just check that here. Skip the rest of this function if we've already
11147   // marked the function as used.
11148   if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
11149     // C++11 [temp.inst]p3:
11150     //   Unless a function template specialization has been explicitly
11151     //   instantiated or explicitly specialized, the function template
11152     //   specialization is implicitly instantiated when the specialization is
11153     //   referenced in a context that requires a function definition to exist.
11154     //
11155     // We consider constexpr function templates to be referenced in a context
11156     // that requires a definition to exist whenever they are referenced.
11157     //
11158     // FIXME: This instantiates constexpr functions too frequently. If this is
11159     // really an unevaluated context (and we're not just in the definition of a
11160     // function template or overload resolution or other cases which we
11161     // incorrectly consider to be unevaluated contexts), and we're not in a
11162     // subexpression which we actually need to evaluate (for instance, a
11163     // template argument, array bound or an expression in a braced-init-list),
11164     // we are not permitted to instantiate this constexpr function definition.
11165     //
11166     // FIXME: This also implicitly defines special members too frequently. They
11167     // are only supposed to be implicitly defined if they are odr-used, but they
11168     // are not odr-used from constant expressions in unevaluated contexts.
11169     // However, they cannot be referenced if they are deleted, and they are
11170     // deleted whenever the implicit definition of the special member would
11171     // fail.
11172     if (!Func->isConstexpr() || Func->getBody())
11173       return;
11174     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
11175     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
11176       return;
11177   }
11178 
11179   // Note that this declaration has been used.
11180   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
11181     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
11182       if (Constructor->isDefaultConstructor()) {
11183         if (Constructor->isTrivial())
11184           return;
11185         if (!Constructor->isUsed(false))
11186           DefineImplicitDefaultConstructor(Loc, Constructor);
11187       } else if (Constructor->isCopyConstructor()) {
11188         if (!Constructor->isUsed(false))
11189           DefineImplicitCopyConstructor(Loc, Constructor);
11190       } else if (Constructor->isMoveConstructor()) {
11191         if (!Constructor->isUsed(false))
11192           DefineImplicitMoveConstructor(Loc, Constructor);
11193       }
11194     } else if (Constructor->getInheritedConstructor()) {
11195       if (!Constructor->isUsed(false))
11196         DefineInheritingConstructor(Loc, Constructor);
11197     }
11198 
11199     MarkVTableUsed(Loc, Constructor->getParent());
11200   } else if (CXXDestructorDecl *Destructor =
11201                  dyn_cast<CXXDestructorDecl>(Func)) {
11202     if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
11203         !Destructor->isUsed(false))
11204       DefineImplicitDestructor(Loc, Destructor);
11205     if (Destructor->isVirtual())
11206       MarkVTableUsed(Loc, Destructor->getParent());
11207   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
11208     if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
11209         MethodDecl->isOverloadedOperator() &&
11210         MethodDecl->getOverloadedOperator() == OO_Equal) {
11211       if (!MethodDecl->isUsed(false)) {
11212         if (MethodDecl->isCopyAssignmentOperator())
11213           DefineImplicitCopyAssignment(Loc, MethodDecl);
11214         else
11215           DefineImplicitMoveAssignment(Loc, MethodDecl);
11216       }
11217     } else if (isa<CXXConversionDecl>(MethodDecl) &&
11218                MethodDecl->getParent()->isLambda()) {
11219       CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
11220       if (Conversion->isLambdaToBlockPointerConversion())
11221         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
11222       else
11223         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
11224     } else if (MethodDecl->isVirtual())
11225       MarkVTableUsed(Loc, MethodDecl->getParent());
11226   }
11227 
11228   // Recursive functions should be marked when used from another function.
11229   // FIXME: Is this really right?
11230   if (CurContext == Func) return;
11231 
11232   // Resolve the exception specification for any function which is
11233   // used: CodeGen will need it.
11234   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
11235   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
11236     ResolveExceptionSpec(Loc, FPT);
11237 
11238   // Implicit instantiation of function templates and member functions of
11239   // class templates.
11240   if (Func->isImplicitlyInstantiable()) {
11241     bool AlreadyInstantiated = false;
11242     SourceLocation PointOfInstantiation = Loc;
11243     if (FunctionTemplateSpecializationInfo *SpecInfo
11244                               = Func->getTemplateSpecializationInfo()) {
11245       if (SpecInfo->getPointOfInstantiation().isInvalid())
11246         SpecInfo->setPointOfInstantiation(Loc);
11247       else if (SpecInfo->getTemplateSpecializationKind()
11248                  == TSK_ImplicitInstantiation) {
11249         AlreadyInstantiated = true;
11250         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
11251       }
11252     } else if (MemberSpecializationInfo *MSInfo
11253                                 = Func->getMemberSpecializationInfo()) {
11254       if (MSInfo->getPointOfInstantiation().isInvalid())
11255         MSInfo->setPointOfInstantiation(Loc);
11256       else if (MSInfo->getTemplateSpecializationKind()
11257                  == TSK_ImplicitInstantiation) {
11258         AlreadyInstantiated = true;
11259         PointOfInstantiation = MSInfo->getPointOfInstantiation();
11260       }
11261     }
11262 
11263     if (!AlreadyInstantiated || Func->isConstexpr()) {
11264       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
11265           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
11266           ActiveTemplateInstantiations.size())
11267         PendingLocalImplicitInstantiations.push_back(
11268             std::make_pair(Func, PointOfInstantiation));
11269       else if (Func->isConstexpr())
11270         // Do not defer instantiations of constexpr functions, to avoid the
11271         // expression evaluator needing to call back into Sema if it sees a
11272         // call to such a function.
11273         InstantiateFunctionDefinition(PointOfInstantiation, Func);
11274       else {
11275         PendingInstantiations.push_back(std::make_pair(Func,
11276                                                        PointOfInstantiation));
11277         // Notify the consumer that a function was implicitly instantiated.
11278         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
11279       }
11280     }
11281   } else {
11282     // Walk redefinitions, as some of them may be instantiable.
11283     for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
11284          e(Func->redecls_end()); i != e; ++i) {
11285       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
11286         MarkFunctionReferenced(Loc, *i);
11287     }
11288   }
11289 
11290   // Keep track of used but undefined functions.
11291   if (!Func->isDefined()) {
11292     if (mightHaveNonExternalLinkage(Func))
11293       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11294     else if (Func->getMostRecentDecl()->isInlined() &&
11295              (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
11296              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
11297       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11298   }
11299 
11300   // Normally the most current decl is marked used while processing the use and
11301   // any subsequent decls are marked used by decl merging. This fails with
11302   // template instantiation since marking can happen at the end of the file
11303   // and, because of the two phase lookup, this function is called with at
11304   // decl in the middle of a decl chain. We loop to maintain the invariant
11305   // that once a decl is used, all decls after it are also used.
11306   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
11307     F->markUsed(Context);
11308     if (F == Func)
11309       break;
11310   }
11311 }
11312 
11313 static void
11314 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
11315                                    VarDecl *var, DeclContext *DC) {
11316   DeclContext *VarDC = var->getDeclContext();
11317 
11318   //  If the parameter still belongs to the translation unit, then
11319   //  we're actually just using one parameter in the declaration of
11320   //  the next.
11321   if (isa<ParmVarDecl>(var) &&
11322       isa<TranslationUnitDecl>(VarDC))
11323     return;
11324 
11325   // For C code, don't diagnose about capture if we're not actually in code
11326   // right now; it's impossible to write a non-constant expression outside of
11327   // function context, so we'll get other (more useful) diagnostics later.
11328   //
11329   // For C++, things get a bit more nasty... it would be nice to suppress this
11330   // diagnostic for certain cases like using a local variable in an array bound
11331   // for a member of a local class, but the correct predicate is not obvious.
11332   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
11333     return;
11334 
11335   if (isa<CXXMethodDecl>(VarDC) &&
11336       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
11337     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
11338       << var->getIdentifier();
11339   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
11340     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
11341       << var->getIdentifier() << fn->getDeclName();
11342   } else if (isa<BlockDecl>(VarDC)) {
11343     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
11344       << var->getIdentifier();
11345   } else {
11346     // FIXME: Is there any other context where a local variable can be
11347     // declared?
11348     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
11349       << var->getIdentifier();
11350   }
11351 
11352   S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
11353     << var->getIdentifier();
11354 
11355   // FIXME: Add additional diagnostic info about class etc. which prevents
11356   // capture.
11357 }
11358 
11359 
11360 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
11361                                       bool &SubCapturesAreNested,
11362                                       QualType &CaptureType,
11363                                       QualType &DeclRefType) {
11364    // Check whether we've already captured it.
11365   if (CSI->CaptureMap.count(Var)) {
11366     // If we found a capture, any subcaptures are nested.
11367     SubCapturesAreNested = true;
11368 
11369     // Retrieve the capture type for this variable.
11370     CaptureType = CSI->getCapture(Var).getCaptureType();
11371 
11372     // Compute the type of an expression that refers to this variable.
11373     DeclRefType = CaptureType.getNonReferenceType();
11374 
11375     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
11376     if (Cap.isCopyCapture() &&
11377         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
11378       DeclRefType.addConst();
11379     return true;
11380   }
11381   return false;
11382 }
11383 
11384 // Only block literals, captured statements, and lambda expressions can
11385 // capture; other scopes don't work.
11386 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
11387                                  SourceLocation Loc,
11388                                  const bool Diagnose, Sema &S) {
11389   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
11390     return getLambdaAwareParentOfDeclContext(DC);
11391   else {
11392     if (Diagnose)
11393        diagnoseUncapturableValueReference(S, Loc, Var, DC);
11394   }
11395   return 0;
11396 }
11397 
11398 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
11399 // certain types of variables (unnamed, variably modified types etc.)
11400 // so check for eligibility.
11401 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
11402                                  SourceLocation Loc,
11403                                  const bool Diagnose, Sema &S) {
11404 
11405   bool IsBlock = isa<BlockScopeInfo>(CSI);
11406   bool IsLambda = isa<LambdaScopeInfo>(CSI);
11407 
11408   // Lambdas are not allowed to capture unnamed variables
11409   // (e.g. anonymous unions).
11410   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
11411   // assuming that's the intent.
11412   if (IsLambda && !Var->getDeclName()) {
11413     if (Diagnose) {
11414       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
11415       S.Diag(Var->getLocation(), diag::note_declared_at);
11416     }
11417     return false;
11418   }
11419 
11420   // Prohibit variably-modified types; they're difficult to deal with.
11421   if (Var->getType()->isVariablyModifiedType()) {
11422     if (Diagnose) {
11423       if (IsBlock)
11424         S.Diag(Loc, diag::err_ref_vm_type);
11425       else
11426         S.Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
11427       S.Diag(Var->getLocation(), diag::note_previous_decl)
11428         << Var->getDeclName();
11429     }
11430     return false;
11431   }
11432   // Prohibit structs with flexible array members too.
11433   // We cannot capture what is in the tail end of the struct.
11434   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
11435     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
11436       if (Diagnose) {
11437         if (IsBlock)
11438           S.Diag(Loc, diag::err_ref_flexarray_type);
11439         else
11440           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
11441             << Var->getDeclName();
11442         S.Diag(Var->getLocation(), diag::note_previous_decl)
11443           << Var->getDeclName();
11444       }
11445       return false;
11446     }
11447   }
11448   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11449   // Lambdas and captured statements are not allowed to capture __block
11450   // variables; they don't support the expected semantics.
11451   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
11452     if (Diagnose) {
11453       S.Diag(Loc, diag::err_capture_block_variable)
11454         << Var->getDeclName() << !IsLambda;
11455       S.Diag(Var->getLocation(), diag::note_previous_decl)
11456         << Var->getDeclName();
11457     }
11458     return false;
11459   }
11460 
11461   return true;
11462 }
11463 
11464 // Returns true if the capture by block was successful.
11465 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
11466                                  SourceLocation Loc,
11467                                  const bool BuildAndDiagnose,
11468                                  QualType &CaptureType,
11469                                  QualType &DeclRefType,
11470                                  const bool Nested,
11471                                  Sema &S) {
11472   Expr *CopyExpr = 0;
11473   bool ByRef = false;
11474 
11475   // Blocks are not allowed to capture arrays.
11476   if (CaptureType->isArrayType()) {
11477     if (BuildAndDiagnose) {
11478       S.Diag(Loc, diag::err_ref_array_type);
11479       S.Diag(Var->getLocation(), diag::note_previous_decl)
11480       << Var->getDeclName();
11481     }
11482     return false;
11483   }
11484 
11485   // Forbid the block-capture of autoreleasing variables.
11486   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11487     if (BuildAndDiagnose) {
11488       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
11489         << /*block*/ 0;
11490       S.Diag(Var->getLocation(), diag::note_previous_decl)
11491         << Var->getDeclName();
11492     }
11493     return false;
11494   }
11495   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11496   if (HasBlocksAttr || CaptureType->isReferenceType()) {
11497     // Block capture by reference does not change the capture or
11498     // declaration reference types.
11499     ByRef = true;
11500   } else {
11501     // Block capture by copy introduces 'const'.
11502     CaptureType = CaptureType.getNonReferenceType().withConst();
11503     DeclRefType = CaptureType;
11504 
11505     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
11506       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11507         // The capture logic needs the destructor, so make sure we mark it.
11508         // Usually this is unnecessary because most local variables have
11509         // their destructors marked at declaration time, but parameters are
11510         // an exception because it's technically only the call site that
11511         // actually requires the destructor.
11512         if (isa<ParmVarDecl>(Var))
11513           S.FinalizeVarWithDestructor(Var, Record);
11514 
11515         // Enter a new evaluation context to insulate the copy
11516         // full-expression.
11517         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
11518 
11519         // According to the blocks spec, the capture of a variable from
11520         // the stack requires a const copy constructor.  This is not true
11521         // of the copy/move done to move a __block variable to the heap.
11522         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
11523                                                   DeclRefType.withConst(),
11524                                                   VK_LValue, Loc);
11525 
11526         ExprResult Result
11527           = S.PerformCopyInitialization(
11528               InitializedEntity::InitializeBlock(Var->getLocation(),
11529                                                   CaptureType, false),
11530               Loc, S.Owned(DeclRef));
11531 
11532         // Build a full-expression copy expression if initialization
11533         // succeeded and used a non-trivial constructor.  Recover from
11534         // errors by pretending that the copy isn't necessary.
11535         if (!Result.isInvalid() &&
11536             !cast<CXXConstructExpr>(Result.get())->getConstructor()
11537                 ->isTrivial()) {
11538           Result = S.MaybeCreateExprWithCleanups(Result);
11539           CopyExpr = Result.take();
11540         }
11541       }
11542     }
11543   }
11544 
11545   // Actually capture the variable.
11546   if (BuildAndDiagnose)
11547     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11548                     SourceLocation(), CaptureType, CopyExpr);
11549 
11550   return true;
11551 
11552 }
11553 
11554 
11555 /// \brief Capture the given variable in the captured region.
11556 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
11557                                     VarDecl *Var,
11558                                     SourceLocation Loc,
11559                                     const bool BuildAndDiagnose,
11560                                     QualType &CaptureType,
11561                                     QualType &DeclRefType,
11562                                     const bool RefersToEnclosingLocal,
11563                                     Sema &S) {
11564 
11565   // By default, capture variables by reference.
11566   bool ByRef = true;
11567   // Using an LValue reference type is consistent with Lambdas (see below).
11568   CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11569   Expr *CopyExpr = 0;
11570   if (BuildAndDiagnose) {
11571     // The current implementation assumes that all variables are captured
11572     // by references. Since there is no capture by copy, no expression evaluation
11573     // will be needed.
11574     //
11575     RecordDecl *RD = RSI->TheRecordDecl;
11576 
11577     FieldDecl *Field
11578       = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, CaptureType,
11579                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
11580                           0, false, ICIS_NoInit);
11581     Field->setImplicit(true);
11582     Field->setAccess(AS_private);
11583     RD->addDecl(Field);
11584 
11585     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11586                                             DeclRefType, VK_LValue, Loc);
11587     Var->setReferenced(true);
11588     Var->markUsed(S.Context);
11589   }
11590 
11591   // Actually capture the variable.
11592   if (BuildAndDiagnose)
11593     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc,
11594                     SourceLocation(), CaptureType, CopyExpr);
11595 
11596 
11597   return true;
11598 }
11599 
11600 /// \brief Create a field within the lambda class for the variable
11601 ///  being captured.  Handle Array captures.
11602 static ExprResult addAsFieldToClosureType(Sema &S,
11603                                  LambdaScopeInfo *LSI,
11604                                   VarDecl *Var, QualType FieldType,
11605                                   QualType DeclRefType,
11606                                   SourceLocation Loc,
11607                                   bool RefersToEnclosingLocal) {
11608   CXXRecordDecl *Lambda = LSI->Lambda;
11609 
11610   // Build the non-static data member.
11611   FieldDecl *Field
11612     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
11613                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
11614                         0, false, ICIS_NoInit);
11615   Field->setImplicit(true);
11616   Field->setAccess(AS_private);
11617   Lambda->addDecl(Field);
11618 
11619   // C++11 [expr.prim.lambda]p21:
11620   //   When the lambda-expression is evaluated, the entities that
11621   //   are captured by copy are used to direct-initialize each
11622   //   corresponding non-static data member of the resulting closure
11623   //   object. (For array members, the array elements are
11624   //   direct-initialized in increasing subscript order.) These
11625   //   initializations are performed in the (unspecified) order in
11626   //   which the non-static data members are declared.
11627 
11628   // Introduce a new evaluation context for the initialization, so
11629   // that temporaries introduced as part of the capture are retained
11630   // to be re-"exported" from the lambda expression itself.
11631   EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
11632 
11633   // C++ [expr.prim.labda]p12:
11634   //   An entity captured by a lambda-expression is odr-used (3.2) in
11635   //   the scope containing the lambda-expression.
11636   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11637                                           DeclRefType, VK_LValue, Loc);
11638   Var->setReferenced(true);
11639   Var->markUsed(S.Context);
11640 
11641   // When the field has array type, create index variables for each
11642   // dimension of the array. We use these index variables to subscript
11643   // the source array, and other clients (e.g., CodeGen) will perform
11644   // the necessary iteration with these index variables.
11645   SmallVector<VarDecl *, 4> IndexVariables;
11646   QualType BaseType = FieldType;
11647   QualType SizeType = S.Context.getSizeType();
11648   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
11649   while (const ConstantArrayType *Array
11650                         = S.Context.getAsConstantArrayType(BaseType)) {
11651     // Create the iteration variable for this array index.
11652     IdentifierInfo *IterationVarName = 0;
11653     {
11654       SmallString<8> Str;
11655       llvm::raw_svector_ostream OS(Str);
11656       OS << "__i" << IndexVariables.size();
11657       IterationVarName = &S.Context.Idents.get(OS.str());
11658     }
11659     VarDecl *IterationVar
11660       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11661                         IterationVarName, SizeType,
11662                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11663                         SC_None);
11664     IndexVariables.push_back(IterationVar);
11665     LSI->ArrayIndexVars.push_back(IterationVar);
11666 
11667     // Create a reference to the iteration variable.
11668     ExprResult IterationVarRef
11669       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
11670     assert(!IterationVarRef.isInvalid() &&
11671            "Reference to invented variable cannot fail!");
11672     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
11673     assert(!IterationVarRef.isInvalid() &&
11674            "Conversion of invented variable cannot fail!");
11675 
11676     // Subscript the array with this iteration variable.
11677     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
11678                              Ref, Loc, IterationVarRef.take(), Loc);
11679     if (Subscript.isInvalid()) {
11680       S.CleanupVarDeclMarking();
11681       S.DiscardCleanupsInEvaluationContext();
11682       return ExprError();
11683     }
11684 
11685     Ref = Subscript.take();
11686     BaseType = Array->getElementType();
11687   }
11688 
11689   // Construct the entity that we will be initializing. For an array, this
11690   // will be first element in the array, which may require several levels
11691   // of array-subscript entities.
11692   SmallVector<InitializedEntity, 4> Entities;
11693   Entities.reserve(1 + IndexVariables.size());
11694   Entities.push_back(
11695     InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(),
11696         Field->getType(), Loc));
11697   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
11698     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
11699                                                             0,
11700                                                             Entities.back()));
11701 
11702   InitializationKind InitKind
11703     = InitializationKind::CreateDirect(Loc, Loc, Loc);
11704   InitializationSequence Init(S, Entities.back(), InitKind, Ref);
11705   ExprResult Result(true);
11706   if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
11707     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
11708 
11709   // If this initialization requires any cleanups (e.g., due to a
11710   // default argument to a copy constructor), note that for the
11711   // lambda.
11712   if (S.ExprNeedsCleanups)
11713     LSI->ExprNeedsCleanups = true;
11714 
11715   // Exit the expression evaluation context used for the capture.
11716   S.CleanupVarDeclMarking();
11717   S.DiscardCleanupsInEvaluationContext();
11718   return Result;
11719 }
11720 
11721 
11722 
11723 /// \brief Capture the given variable in the lambda.
11724 static bool captureInLambda(LambdaScopeInfo *LSI,
11725                             VarDecl *Var,
11726                             SourceLocation Loc,
11727                             const bool BuildAndDiagnose,
11728                             QualType &CaptureType,
11729                             QualType &DeclRefType,
11730                             const bool RefersToEnclosingLocal,
11731                             const Sema::TryCaptureKind Kind,
11732                             SourceLocation EllipsisLoc,
11733                             const bool IsTopScope,
11734                             Sema &S) {
11735 
11736   // Determine whether we are capturing by reference or by value.
11737   bool ByRef = false;
11738   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
11739     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
11740   } else {
11741     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
11742   }
11743 
11744   // Compute the type of the field that will capture this variable.
11745   if (ByRef) {
11746     // C++11 [expr.prim.lambda]p15:
11747     //   An entity is captured by reference if it is implicitly or
11748     //   explicitly captured but not captured by copy. It is
11749     //   unspecified whether additional unnamed non-static data
11750     //   members are declared in the closure type for entities
11751     //   captured by reference.
11752     //
11753     // FIXME: It is not clear whether we want to build an lvalue reference
11754     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
11755     // to do the former, while EDG does the latter. Core issue 1249 will
11756     // clarify, but for now we follow GCC because it's a more permissive and
11757     // easily defensible position.
11758     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11759   } else {
11760     // C++11 [expr.prim.lambda]p14:
11761     //   For each entity captured by copy, an unnamed non-static
11762     //   data member is declared in the closure type. The
11763     //   declaration order of these members is unspecified. The type
11764     //   of such a data member is the type of the corresponding
11765     //   captured entity if the entity is not a reference to an
11766     //   object, or the referenced type otherwise. [Note: If the
11767     //   captured entity is a reference to a function, the
11768     //   corresponding data member is also a reference to a
11769     //   function. - end note ]
11770     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
11771       if (!RefType->getPointeeType()->isFunctionType())
11772         CaptureType = RefType->getPointeeType();
11773     }
11774 
11775     // Forbid the lambda copy-capture of autoreleasing variables.
11776     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11777       if (BuildAndDiagnose) {
11778         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
11779         S.Diag(Var->getLocation(), diag::note_previous_decl)
11780           << Var->getDeclName();
11781       }
11782       return false;
11783     }
11784 
11785     if (S.RequireNonAbstractType(Loc, CaptureType,
11786                                  diag::err_capture_of_abstract_type))
11787       return false;
11788   }
11789 
11790   // Capture this variable in the lambda.
11791   Expr *CopyExpr = 0;
11792   if (BuildAndDiagnose) {
11793     ExprResult Result = addAsFieldToClosureType(S, LSI, Var,
11794                                         CaptureType, DeclRefType, Loc,
11795                                         RefersToEnclosingLocal);
11796     if (!Result.isInvalid())
11797       CopyExpr = Result.take();
11798   }
11799 
11800   // Compute the type of a reference to this captured variable.
11801   if (ByRef)
11802     DeclRefType = CaptureType.getNonReferenceType();
11803   else {
11804     // C++ [expr.prim.lambda]p5:
11805     //   The closure type for a lambda-expression has a public inline
11806     //   function call operator [...]. This function call operator is
11807     //   declared const (9.3.1) if and only if the lambda-expression’s
11808     //   parameter-declaration-clause is not followed by mutable.
11809     DeclRefType = CaptureType.getNonReferenceType();
11810     if (!LSI->Mutable && !CaptureType->isReferenceType())
11811       DeclRefType.addConst();
11812   }
11813 
11814   // Add the capture.
11815   if (BuildAndDiagnose)
11816     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal,
11817                     Loc, EllipsisLoc, CaptureType, CopyExpr);
11818 
11819   return true;
11820 }
11821 
11822 
11823 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc,
11824                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
11825                               bool BuildAndDiagnose,
11826                               QualType &CaptureType,
11827                               QualType &DeclRefType,
11828 						                const unsigned *const FunctionScopeIndexToStopAt) {
11829   bool Nested = false;
11830 
11831   DeclContext *DC = CurContext;
11832   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
11833       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
11834   // We need to sync up the Declaration Context with the
11835   // FunctionScopeIndexToStopAt
11836   if (FunctionScopeIndexToStopAt) {
11837     unsigned FSIndex = FunctionScopes.size() - 1;
11838     while (FSIndex != MaxFunctionScopesIndex) {
11839       DC = getLambdaAwareParentOfDeclContext(DC);
11840       --FSIndex;
11841     }
11842   }
11843 
11844 
11845   // If the variable is declared in the current context (and is not an
11846   // init-capture), there is no need to capture it.
11847   if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true;
11848   if (!Var->hasLocalStorage()) return true;
11849 
11850   // Walk up the stack to determine whether we can capture the variable,
11851   // performing the "simple" checks that don't depend on type. We stop when
11852   // we've either hit the declared scope of the variable or find an existing
11853   // capture of that variable.  We start from the innermost capturing-entity
11854   // (the DC) and ensure that all intervening capturing-entities
11855   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
11856   // declcontext can either capture the variable or have already captured
11857   // the variable.
11858   CaptureType = Var->getType();
11859   DeclRefType = CaptureType.getNonReferenceType();
11860   bool Explicit = (Kind != TryCapture_Implicit);
11861   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
11862   do {
11863     // Only block literals, captured statements, and lambda expressions can
11864     // capture; other scopes don't work.
11865     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
11866                                                               ExprLoc,
11867                                                               BuildAndDiagnose,
11868                                                               *this);
11869     if (!ParentDC) return true;
11870 
11871     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
11872     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
11873 
11874 
11875     // Check whether we've already captured it.
11876     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
11877                                              DeclRefType))
11878       break;
11879     // If we are instantiating a generic lambda call operator body,
11880     // we do not want to capture new variables.  What was captured
11881     // during either a lambdas transformation or initial parsing
11882     // should be used.
11883     if (isGenericLambdaCallOperatorSpecialization(DC)) {
11884       if (BuildAndDiagnose) {
11885         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
11886         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
11887           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
11888           Diag(Var->getLocation(), diag::note_previous_decl)
11889              << Var->getDeclName();
11890           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
11891         } else
11892           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
11893       }
11894       return true;
11895     }
11896     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
11897     // certain types of variables (unnamed, variably modified types etc.)
11898     // so check for eligibility.
11899     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
11900        return true;
11901 
11902     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
11903       // No capture-default, and this is not an explicit capture
11904       // so cannot capture this variable.
11905       if (BuildAndDiagnose) {
11906         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
11907         Diag(Var->getLocation(), diag::note_previous_decl)
11908           << Var->getDeclName();
11909         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
11910              diag::note_lambda_decl);
11911         // FIXME: If we error out because an outer lambda can not implicitly
11912         // capture a variable that an inner lambda explicitly captures, we
11913         // should have the inner lambda do the explicit capture - because
11914         // it makes for cleaner diagnostics later.  This would purely be done
11915         // so that the diagnostic does not misleadingly claim that a variable
11916         // can not be captured by a lambda implicitly even though it is captured
11917         // explicitly.  Suggestion:
11918         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
11919         //    at the function head
11920         //  - cache the StartingDeclContext - this must be a lambda
11921         //  - captureInLambda in the innermost lambda the variable.
11922       }
11923       return true;
11924     }
11925 
11926     FunctionScopesIndex--;
11927     DC = ParentDC;
11928     Explicit = false;
11929   } while (!Var->getDeclContext()->Equals(DC));
11930 
11931   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
11932   // computing the type of the capture at each step, checking type-specific
11933   // requirements, and adding captures if requested.
11934   // If the variable had already been captured previously, we start capturing
11935   // at the lambda nested within that one.
11936   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
11937        ++I) {
11938     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
11939 
11940     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
11941       if (!captureInBlock(BSI, Var, ExprLoc,
11942                           BuildAndDiagnose, CaptureType,
11943                           DeclRefType, Nested, *this))
11944         return true;
11945       Nested = true;
11946     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
11947       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
11948                                    BuildAndDiagnose, CaptureType,
11949                                    DeclRefType, Nested, *this))
11950         return true;
11951       Nested = true;
11952     } else {
11953       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
11954       if (!captureInLambda(LSI, Var, ExprLoc,
11955                            BuildAndDiagnose, CaptureType,
11956                            DeclRefType, Nested, Kind, EllipsisLoc,
11957                             /*IsTopScope*/I == N - 1, *this))
11958         return true;
11959       Nested = true;
11960     }
11961   }
11962   return false;
11963 }
11964 
11965 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
11966                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
11967   QualType CaptureType;
11968   QualType DeclRefType;
11969   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
11970                             /*BuildAndDiagnose=*/true, CaptureType,
11971                             DeclRefType, 0);
11972 }
11973 
11974 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
11975   QualType CaptureType;
11976   QualType DeclRefType;
11977 
11978   // Determine whether we can capture this variable.
11979   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
11980                          /*BuildAndDiagnose=*/false, CaptureType,
11981                          DeclRefType, 0))
11982     return QualType();
11983 
11984   return DeclRefType;
11985 }
11986 
11987 
11988 
11989 // If either the type of the variable or the initializer is dependent,
11990 // return false. Otherwise, determine whether the variable is a constant
11991 // expression. Use this if you need to know if a variable that might or
11992 // might not be dependent is truly a constant expression.
11993 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
11994     ASTContext &Context) {
11995 
11996   if (Var->getType()->isDependentType())
11997     return false;
11998   const VarDecl *DefVD = 0;
11999   Var->getAnyInitializer(DefVD);
12000   if (!DefVD)
12001     return false;
12002   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
12003   Expr *Init = cast<Expr>(Eval->Value);
12004   if (Init->isValueDependent())
12005     return false;
12006   return IsVariableAConstantExpression(Var, Context);
12007 }
12008 
12009 
12010 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
12011   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
12012   // an object that satisfies the requirements for appearing in a
12013   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
12014   // is immediately applied."  This function handles the lvalue-to-rvalue
12015   // conversion part.
12016   MaybeODRUseExprs.erase(E->IgnoreParens());
12017 
12018   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
12019   // to a variable that is a constant expression, and if so, identify it as
12020   // a reference to a variable that does not involve an odr-use of that
12021   // variable.
12022   if (LambdaScopeInfo *LSI = getCurLambda()) {
12023     Expr *SansParensExpr = E->IgnoreParens();
12024     VarDecl *Var = 0;
12025     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
12026       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
12027     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
12028       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
12029 
12030     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
12031       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
12032   }
12033 }
12034 
12035 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
12036   if (!Res.isUsable())
12037     return Res;
12038 
12039   // If a constant-expression is a reference to a variable where we delay
12040   // deciding whether it is an odr-use, just assume we will apply the
12041   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
12042   // (a non-type template argument), we have special handling anyway.
12043   UpdateMarkingForLValueToRValue(Res.get());
12044   return Res;
12045 }
12046 
12047 void Sema::CleanupVarDeclMarking() {
12048   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
12049                                         e = MaybeODRUseExprs.end();
12050        i != e; ++i) {
12051     VarDecl *Var;
12052     SourceLocation Loc;
12053     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
12054       Var = cast<VarDecl>(DRE->getDecl());
12055       Loc = DRE->getLocation();
12056     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
12057       Var = cast<VarDecl>(ME->getMemberDecl());
12058       Loc = ME->getMemberLoc();
12059     } else {
12060       llvm_unreachable("Unexpcted expression");
12061     }
12062 
12063     MarkVarDeclODRUsed(Var, Loc, *this, /*MaxFunctionScopeIndex Pointer*/ 0);
12064   }
12065 
12066   MaybeODRUseExprs.clear();
12067 }
12068 
12069 
12070 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
12071                                     VarDecl *Var, Expr *E) {
12072   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
12073          "Invalid Expr argument to DoMarkVarDeclReferenced");
12074   Var->setReferenced();
12075 
12076   // If the context is not PotentiallyEvaluated and not Unevaluated
12077   // (i.e PotentiallyEvaluatedIfUsed) do not bother to consider variables
12078   // in this context for odr-use unless we are within a lambda.
12079   // If we don't know whether the context is potentially evaluated or not
12080   // (for e.g., if we're in a generic lambda), we want to add a potential
12081   // capture and eventually analyze for odr-use.
12082   // We should also be able to analyze certain constructs in a non-generic
12083   // lambda setting for potential odr-use and capture violation:
12084   // template<class T> void foo(T t) {
12085   //    auto L = [](int i) { return t; };
12086   // }
12087   //
12088   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
12089 
12090     if (SemaRef.isUnevaluatedContext()) return;
12091 
12092     const bool refersToEnclosingScope =
12093       (SemaRef.CurContext != Var->getDeclContext() &&
12094            Var->getDeclContext()->isFunctionOrMethod());
12095     if (!refersToEnclosingScope) return;
12096 
12097     if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
12098       // If a variable could potentially be odr-used, defer marking it so
12099       // until we finish analyzing the full expression for any lvalue-to-rvalue
12100       // or discarded value conversions that would obviate odr-use.
12101       // Add it to the list of potential captures that will be analyzed
12102       // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
12103       // unless the variable is a reference that was initialized by a constant
12104       // expression (this will never need to be captured or odr-used).
12105       const bool IsConstantExpr = IsVariableNonDependentAndAConstantExpression(
12106           Var, SemaRef.Context);
12107       assert(E && "Capture variable should be used in an expression.");
12108       if (!IsConstantExpr || !Var->getType()->isReferenceType())
12109         LSI->addPotentialCapture(E->IgnoreParens());
12110     }
12111     return;
12112   }
12113 
12114   VarTemplateSpecializationDecl *VarSpec =
12115       dyn_cast<VarTemplateSpecializationDecl>(Var);
12116   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
12117          "Can't instantiate a partial template specialization.");
12118 
12119   // Implicit instantiation of static data members, static data member
12120   // templates of class templates, and variable template specializations.
12121   // Delay instantiations of variable templates, except for those
12122   // that could be used in a constant expression.
12123   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
12124   if (isTemplateInstantiation(TSK)) {
12125     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
12126 
12127     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
12128       if (Var->getPointOfInstantiation().isInvalid()) {
12129         // This is a modification of an existing AST node. Notify listeners.
12130         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
12131           L->StaticDataMemberInstantiated(Var);
12132       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
12133         // Don't bother trying to instantiate it again, unless we might need
12134         // its initializer before we get to the end of the TU.
12135         TryInstantiating = false;
12136     }
12137 
12138     if (Var->getPointOfInstantiation().isInvalid())
12139       Var->setTemplateSpecializationKind(TSK, Loc);
12140 
12141     if (TryInstantiating) {
12142       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
12143       bool InstantiationDependent = false;
12144       bool IsNonDependent =
12145           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
12146                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
12147                   : true;
12148 
12149       // Do not instantiate specializations that are still type-dependent.
12150       if (IsNonDependent) {
12151         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
12152           // Do not defer instantiations of variables which could be used in a
12153           // constant expression.
12154           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
12155         } else {
12156           SemaRef.PendingInstantiations
12157               .push_back(std::make_pair(Var, PointOfInstantiation));
12158         }
12159       }
12160     }
12161   }
12162   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
12163   // the requirements for appearing in a constant expression (5.19) and, if
12164   // it is an object, the lvalue-to-rvalue conversion (4.1)
12165   // is immediately applied."  We check the first part here, and
12166   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
12167   // Note that we use the C++11 definition everywhere because nothing in
12168   // C++03 depends on whether we get the C++03 version correct. The second
12169   // part does not apply to references, since they are not objects.
12170   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
12171     // A reference initialized by a constant expression can never be
12172     // odr-used, so simply ignore it.
12173     // But a non-reference might get odr-used if it doesn't undergo
12174     // an lvalue-to-rvalue or is discarded, so track it.
12175     if (!Var->getType()->isReferenceType())
12176       SemaRef.MaybeODRUseExprs.insert(E);
12177   }
12178   else
12179     MarkVarDeclODRUsed(Var, Loc, SemaRef, /*MaxFunctionScopeIndex ptr*/0);
12180 }
12181 
12182 /// \brief Mark a variable referenced, and check whether it is odr-used
12183 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
12184 /// used directly for normal expressions referring to VarDecl.
12185 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
12186   DoMarkVarDeclReferenced(*this, Loc, Var, 0);
12187 }
12188 
12189 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
12190                                Decl *D, Expr *E, bool OdrUse) {
12191   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
12192     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
12193     return;
12194   }
12195 
12196   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
12197 
12198   // If this is a call to a method via a cast, also mark the method in the
12199   // derived class used in case codegen can devirtualize the call.
12200   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12201   if (!ME)
12202     return;
12203   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
12204   if (!MD)
12205     return;
12206   const Expr *Base = ME->getBase();
12207   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
12208   if (!MostDerivedClassDecl)
12209     return;
12210   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
12211   if (!DM || DM->isPure())
12212     return;
12213   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
12214 }
12215 
12216 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
12217 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
12218   // TODO: update this with DR# once a defect report is filed.
12219   // C++11 defect. The address of a pure member should not be an ODR use, even
12220   // if it's a qualified reference.
12221   bool OdrUse = true;
12222   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
12223     if (Method->isVirtual())
12224       OdrUse = false;
12225   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
12226 }
12227 
12228 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
12229 void Sema::MarkMemberReferenced(MemberExpr *E) {
12230   // C++11 [basic.def.odr]p2:
12231   //   A non-overloaded function whose name appears as a potentially-evaluated
12232   //   expression or a member of a set of candidate functions, if selected by
12233   //   overload resolution when referred to from a potentially-evaluated
12234   //   expression, is odr-used, unless it is a pure virtual function and its
12235   //   name is not explicitly qualified.
12236   bool OdrUse = true;
12237   if (!E->hasQualifier()) {
12238     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
12239       if (Method->isPure())
12240         OdrUse = false;
12241   }
12242   SourceLocation Loc = E->getMemberLoc().isValid() ?
12243                             E->getMemberLoc() : E->getLocStart();
12244   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
12245 }
12246 
12247 /// \brief Perform marking for a reference to an arbitrary declaration.  It
12248 /// marks the declaration referenced, and performs odr-use checking for functions
12249 /// and variables. This method should not be used when building an normal
12250 /// expression which refers to a variable.
12251 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
12252   if (OdrUse) {
12253     if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12254       MarkVariableReferenced(Loc, VD);
12255       return;
12256     }
12257     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
12258       MarkFunctionReferenced(Loc, FD);
12259       return;
12260     }
12261   }
12262   D->setReferenced();
12263 }
12264 
12265 namespace {
12266   // Mark all of the declarations referenced
12267   // FIXME: Not fully implemented yet! We need to have a better understanding
12268   // of when we're entering
12269   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
12270     Sema &S;
12271     SourceLocation Loc;
12272 
12273   public:
12274     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
12275 
12276     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
12277 
12278     bool TraverseTemplateArgument(const TemplateArgument &Arg);
12279     bool TraverseRecordType(RecordType *T);
12280   };
12281 }
12282 
12283 bool MarkReferencedDecls::TraverseTemplateArgument(
12284   const TemplateArgument &Arg) {
12285   if (Arg.getKind() == TemplateArgument::Declaration) {
12286     if (Decl *D = Arg.getAsDecl())
12287       S.MarkAnyDeclReferenced(Loc, D, true);
12288   }
12289 
12290   return Inherited::TraverseTemplateArgument(Arg);
12291 }
12292 
12293 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
12294   if (ClassTemplateSpecializationDecl *Spec
12295                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
12296     const TemplateArgumentList &Args = Spec->getTemplateArgs();
12297     return TraverseTemplateArguments(Args.data(), Args.size());
12298   }
12299 
12300   return true;
12301 }
12302 
12303 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
12304   MarkReferencedDecls Marker(*this, Loc);
12305   Marker.TraverseType(Context.getCanonicalType(T));
12306 }
12307 
12308 namespace {
12309   /// \brief Helper class that marks all of the declarations referenced by
12310   /// potentially-evaluated subexpressions as "referenced".
12311   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
12312     Sema &S;
12313     bool SkipLocalVariables;
12314 
12315   public:
12316     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
12317 
12318     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
12319       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
12320 
12321     void VisitDeclRefExpr(DeclRefExpr *E) {
12322       // If we were asked not to visit local variables, don't.
12323       if (SkipLocalVariables) {
12324         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
12325           if (VD->hasLocalStorage())
12326             return;
12327       }
12328 
12329       S.MarkDeclRefReferenced(E);
12330     }
12331 
12332     void VisitMemberExpr(MemberExpr *E) {
12333       S.MarkMemberReferenced(E);
12334       Inherited::VisitMemberExpr(E);
12335     }
12336 
12337     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12338       S.MarkFunctionReferenced(E->getLocStart(),
12339             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
12340       Visit(E->getSubExpr());
12341     }
12342 
12343     void VisitCXXNewExpr(CXXNewExpr *E) {
12344       if (E->getOperatorNew())
12345         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
12346       if (E->getOperatorDelete())
12347         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12348       Inherited::VisitCXXNewExpr(E);
12349     }
12350 
12351     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
12352       if (E->getOperatorDelete())
12353         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12354       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
12355       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12356         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12357         S.MarkFunctionReferenced(E->getLocStart(),
12358                                     S.LookupDestructor(Record));
12359       }
12360 
12361       Inherited::VisitCXXDeleteExpr(E);
12362     }
12363 
12364     void VisitCXXConstructExpr(CXXConstructExpr *E) {
12365       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
12366       Inherited::VisitCXXConstructExpr(E);
12367     }
12368 
12369     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12370       Visit(E->getExpr());
12371     }
12372 
12373     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12374       Inherited::VisitImplicitCastExpr(E);
12375 
12376       if (E->getCastKind() == CK_LValueToRValue)
12377         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
12378     }
12379   };
12380 }
12381 
12382 /// \brief Mark any declarations that appear within this expression or any
12383 /// potentially-evaluated subexpressions as "referenced".
12384 ///
12385 /// \param SkipLocalVariables If true, don't mark local variables as
12386 /// 'referenced'.
12387 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
12388                                             bool SkipLocalVariables) {
12389   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
12390 }
12391 
12392 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
12393 /// of the program being compiled.
12394 ///
12395 /// This routine emits the given diagnostic when the code currently being
12396 /// type-checked is "potentially evaluated", meaning that there is a
12397 /// possibility that the code will actually be executable. Code in sizeof()
12398 /// expressions, code used only during overload resolution, etc., are not
12399 /// potentially evaluated. This routine will suppress such diagnostics or,
12400 /// in the absolutely nutty case of potentially potentially evaluated
12401 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
12402 /// later.
12403 ///
12404 /// This routine should be used for all diagnostics that describe the run-time
12405 /// behavior of a program, such as passing a non-POD value through an ellipsis.
12406 /// Failure to do so will likely result in spurious diagnostics or failures
12407 /// during overload resolution or within sizeof/alignof/typeof/typeid.
12408 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
12409                                const PartialDiagnostic &PD) {
12410   switch (ExprEvalContexts.back().Context) {
12411   case Unevaluated:
12412   case UnevaluatedAbstract:
12413     // The argument will never be evaluated, so don't complain.
12414     break;
12415 
12416   case ConstantEvaluated:
12417     // Relevant diagnostics should be produced by constant evaluation.
12418     break;
12419 
12420   case PotentiallyEvaluated:
12421   case PotentiallyEvaluatedIfUsed:
12422     if (Statement && getCurFunctionOrMethodDecl()) {
12423       FunctionScopes.back()->PossiblyUnreachableDiags.
12424         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
12425     }
12426     else
12427       Diag(Loc, PD);
12428 
12429     return true;
12430   }
12431 
12432   return false;
12433 }
12434 
12435 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
12436                                CallExpr *CE, FunctionDecl *FD) {
12437   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
12438     return false;
12439 
12440   // If we're inside a decltype's expression, don't check for a valid return
12441   // type or construct temporaries until we know whether this is the last call.
12442   if (ExprEvalContexts.back().IsDecltype) {
12443     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
12444     return false;
12445   }
12446 
12447   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
12448     FunctionDecl *FD;
12449     CallExpr *CE;
12450 
12451   public:
12452     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
12453       : FD(FD), CE(CE) { }
12454 
12455     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
12456       if (!FD) {
12457         S.Diag(Loc, diag::err_call_incomplete_return)
12458           << T << CE->getSourceRange();
12459         return;
12460       }
12461 
12462       S.Diag(Loc, diag::err_call_function_incomplete_return)
12463         << CE->getSourceRange() << FD->getDeclName() << T;
12464       S.Diag(FD->getLocation(),
12465              diag::note_function_with_incomplete_return_type_declared_here)
12466         << FD->getDeclName();
12467     }
12468   } Diagnoser(FD, CE);
12469 
12470   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
12471     return true;
12472 
12473   return false;
12474 }
12475 
12476 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
12477 // will prevent this condition from triggering, which is what we want.
12478 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
12479   SourceLocation Loc;
12480 
12481   unsigned diagnostic = diag::warn_condition_is_assignment;
12482   bool IsOrAssign = false;
12483 
12484   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
12485     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
12486       return;
12487 
12488     IsOrAssign = Op->getOpcode() == BO_OrAssign;
12489 
12490     // Greylist some idioms by putting them into a warning subcategory.
12491     if (ObjCMessageExpr *ME
12492           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
12493       Selector Sel = ME->getSelector();
12494 
12495       // self = [<foo> init...]
12496       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
12497         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12498 
12499       // <foo> = [<bar> nextObject]
12500       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
12501         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12502     }
12503 
12504     Loc = Op->getOperatorLoc();
12505   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
12506     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
12507       return;
12508 
12509     IsOrAssign = Op->getOperator() == OO_PipeEqual;
12510     Loc = Op->getOperatorLoc();
12511   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
12512     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
12513   else {
12514     // Not an assignment.
12515     return;
12516   }
12517 
12518   Diag(Loc, diagnostic) << E->getSourceRange();
12519 
12520   SourceLocation Open = E->getLocStart();
12521   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
12522   Diag(Loc, diag::note_condition_assign_silence)
12523         << FixItHint::CreateInsertion(Open, "(")
12524         << FixItHint::CreateInsertion(Close, ")");
12525 
12526   if (IsOrAssign)
12527     Diag(Loc, diag::note_condition_or_assign_to_comparison)
12528       << FixItHint::CreateReplacement(Loc, "!=");
12529   else
12530     Diag(Loc, diag::note_condition_assign_to_comparison)
12531       << FixItHint::CreateReplacement(Loc, "==");
12532 }
12533 
12534 /// \brief Redundant parentheses over an equality comparison can indicate
12535 /// that the user intended an assignment used as condition.
12536 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
12537   // Don't warn if the parens came from a macro.
12538   SourceLocation parenLoc = ParenE->getLocStart();
12539   if (parenLoc.isInvalid() || parenLoc.isMacroID())
12540     return;
12541   // Don't warn for dependent expressions.
12542   if (ParenE->isTypeDependent())
12543     return;
12544 
12545   Expr *E = ParenE->IgnoreParens();
12546 
12547   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
12548     if (opE->getOpcode() == BO_EQ &&
12549         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
12550                                                            == Expr::MLV_Valid) {
12551       SourceLocation Loc = opE->getOperatorLoc();
12552 
12553       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
12554       SourceRange ParenERange = ParenE->getSourceRange();
12555       Diag(Loc, diag::note_equality_comparison_silence)
12556         << FixItHint::CreateRemoval(ParenERange.getBegin())
12557         << FixItHint::CreateRemoval(ParenERange.getEnd());
12558       Diag(Loc, diag::note_equality_comparison_to_assign)
12559         << FixItHint::CreateReplacement(Loc, "=");
12560     }
12561 }
12562 
12563 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
12564   DiagnoseAssignmentAsCondition(E);
12565   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
12566     DiagnoseEqualityWithExtraParens(parenE);
12567 
12568   ExprResult result = CheckPlaceholderExpr(E);
12569   if (result.isInvalid()) return ExprError();
12570   E = result.take();
12571 
12572   if (!E->isTypeDependent()) {
12573     if (getLangOpts().CPlusPlus)
12574       return CheckCXXBooleanCondition(E); // C++ 6.4p4
12575 
12576     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
12577     if (ERes.isInvalid())
12578       return ExprError();
12579     E = ERes.take();
12580 
12581     QualType T = E->getType();
12582     if (!T->isScalarType()) { // C99 6.8.4.1p1
12583       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
12584         << T << E->getSourceRange();
12585       return ExprError();
12586     }
12587   }
12588 
12589   return Owned(E);
12590 }
12591 
12592 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
12593                                        Expr *SubExpr) {
12594   if (!SubExpr)
12595     return ExprError();
12596 
12597   return CheckBooleanCondition(SubExpr, Loc);
12598 }
12599 
12600 namespace {
12601   /// A visitor for rebuilding a call to an __unknown_any expression
12602   /// to have an appropriate type.
12603   struct RebuildUnknownAnyFunction
12604     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
12605 
12606     Sema &S;
12607 
12608     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
12609 
12610     ExprResult VisitStmt(Stmt *S) {
12611       llvm_unreachable("unexpected statement!");
12612     }
12613 
12614     ExprResult VisitExpr(Expr *E) {
12615       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
12616         << E->getSourceRange();
12617       return ExprError();
12618     }
12619 
12620     /// Rebuild an expression which simply semantically wraps another
12621     /// expression which it shares the type and value kind of.
12622     template <class T> ExprResult rebuildSugarExpr(T *E) {
12623       ExprResult SubResult = Visit(E->getSubExpr());
12624       if (SubResult.isInvalid()) return ExprError();
12625 
12626       Expr *SubExpr = SubResult.take();
12627       E->setSubExpr(SubExpr);
12628       E->setType(SubExpr->getType());
12629       E->setValueKind(SubExpr->getValueKind());
12630       assert(E->getObjectKind() == OK_Ordinary);
12631       return E;
12632     }
12633 
12634     ExprResult VisitParenExpr(ParenExpr *E) {
12635       return rebuildSugarExpr(E);
12636     }
12637 
12638     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12639       return rebuildSugarExpr(E);
12640     }
12641 
12642     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12643       ExprResult SubResult = Visit(E->getSubExpr());
12644       if (SubResult.isInvalid()) return ExprError();
12645 
12646       Expr *SubExpr = SubResult.take();
12647       E->setSubExpr(SubExpr);
12648       E->setType(S.Context.getPointerType(SubExpr->getType()));
12649       assert(E->getValueKind() == VK_RValue);
12650       assert(E->getObjectKind() == OK_Ordinary);
12651       return E;
12652     }
12653 
12654     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
12655       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
12656 
12657       E->setType(VD->getType());
12658 
12659       assert(E->getValueKind() == VK_RValue);
12660       if (S.getLangOpts().CPlusPlus &&
12661           !(isa<CXXMethodDecl>(VD) &&
12662             cast<CXXMethodDecl>(VD)->isInstance()))
12663         E->setValueKind(VK_LValue);
12664 
12665       return E;
12666     }
12667 
12668     ExprResult VisitMemberExpr(MemberExpr *E) {
12669       return resolveDecl(E, E->getMemberDecl());
12670     }
12671 
12672     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12673       return resolveDecl(E, E->getDecl());
12674     }
12675   };
12676 }
12677 
12678 /// Given a function expression of unknown-any type, try to rebuild it
12679 /// to have a function type.
12680 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
12681   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
12682   if (Result.isInvalid()) return ExprError();
12683   return S.DefaultFunctionArrayConversion(Result.take());
12684 }
12685 
12686 namespace {
12687   /// A visitor for rebuilding an expression of type __unknown_anytype
12688   /// into one which resolves the type directly on the referring
12689   /// expression.  Strict preservation of the original source
12690   /// structure is not a goal.
12691   struct RebuildUnknownAnyExpr
12692     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
12693 
12694     Sema &S;
12695 
12696     /// The current destination type.
12697     QualType DestType;
12698 
12699     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
12700       : S(S), DestType(CastType) {}
12701 
12702     ExprResult VisitStmt(Stmt *S) {
12703       llvm_unreachable("unexpected statement!");
12704     }
12705 
12706     ExprResult VisitExpr(Expr *E) {
12707       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12708         << E->getSourceRange();
12709       return ExprError();
12710     }
12711 
12712     ExprResult VisitCallExpr(CallExpr *E);
12713     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
12714 
12715     /// Rebuild an expression which simply semantically wraps another
12716     /// expression which it shares the type and value kind of.
12717     template <class T> ExprResult rebuildSugarExpr(T *E) {
12718       ExprResult SubResult = Visit(E->getSubExpr());
12719       if (SubResult.isInvalid()) return ExprError();
12720       Expr *SubExpr = SubResult.take();
12721       E->setSubExpr(SubExpr);
12722       E->setType(SubExpr->getType());
12723       E->setValueKind(SubExpr->getValueKind());
12724       assert(E->getObjectKind() == OK_Ordinary);
12725       return E;
12726     }
12727 
12728     ExprResult VisitParenExpr(ParenExpr *E) {
12729       return rebuildSugarExpr(E);
12730     }
12731 
12732     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12733       return rebuildSugarExpr(E);
12734     }
12735 
12736     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12737       const PointerType *Ptr = DestType->getAs<PointerType>();
12738       if (!Ptr) {
12739         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
12740           << E->getSourceRange();
12741         return ExprError();
12742       }
12743       assert(E->getValueKind() == VK_RValue);
12744       assert(E->getObjectKind() == OK_Ordinary);
12745       E->setType(DestType);
12746 
12747       // Build the sub-expression as if it were an object of the pointee type.
12748       DestType = Ptr->getPointeeType();
12749       ExprResult SubResult = Visit(E->getSubExpr());
12750       if (SubResult.isInvalid()) return ExprError();
12751       E->setSubExpr(SubResult.take());
12752       return E;
12753     }
12754 
12755     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
12756 
12757     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
12758 
12759     ExprResult VisitMemberExpr(MemberExpr *E) {
12760       return resolveDecl(E, E->getMemberDecl());
12761     }
12762 
12763     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12764       return resolveDecl(E, E->getDecl());
12765     }
12766   };
12767 }
12768 
12769 /// Rebuilds a call expression which yielded __unknown_anytype.
12770 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
12771   Expr *CalleeExpr = E->getCallee();
12772 
12773   enum FnKind {
12774     FK_MemberFunction,
12775     FK_FunctionPointer,
12776     FK_BlockPointer
12777   };
12778 
12779   FnKind Kind;
12780   QualType CalleeType = CalleeExpr->getType();
12781   if (CalleeType == S.Context.BoundMemberTy) {
12782     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
12783     Kind = FK_MemberFunction;
12784     CalleeType = Expr::findBoundMemberType(CalleeExpr);
12785   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
12786     CalleeType = Ptr->getPointeeType();
12787     Kind = FK_FunctionPointer;
12788   } else {
12789     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
12790     Kind = FK_BlockPointer;
12791   }
12792   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
12793 
12794   // Verify that this is a legal result type of a function.
12795   if (DestType->isArrayType() || DestType->isFunctionType()) {
12796     unsigned diagID = diag::err_func_returning_array_function;
12797     if (Kind == FK_BlockPointer)
12798       diagID = diag::err_block_returning_array_function;
12799 
12800     S.Diag(E->getExprLoc(), diagID)
12801       << DestType->isFunctionType() << DestType;
12802     return ExprError();
12803   }
12804 
12805   // Otherwise, go ahead and set DestType as the call's result.
12806   E->setType(DestType.getNonLValueExprType(S.Context));
12807   E->setValueKind(Expr::getValueKindForType(DestType));
12808   assert(E->getObjectKind() == OK_Ordinary);
12809 
12810   // Rebuild the function type, replacing the result type with DestType.
12811   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
12812   if (Proto) {
12813     // __unknown_anytype(...) is a special case used by the debugger when
12814     // it has no idea what a function's signature is.
12815     //
12816     // We want to build this call essentially under the K&R
12817     // unprototyped rules, but making a FunctionNoProtoType in C++
12818     // would foul up all sorts of assumptions.  However, we cannot
12819     // simply pass all arguments as variadic arguments, nor can we
12820     // portably just call the function under a non-variadic type; see
12821     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
12822     // However, it turns out that in practice it is generally safe to
12823     // call a function declared as "A foo(B,C,D);" under the prototype
12824     // "A foo(B,C,D,...);".  The only known exception is with the
12825     // Windows ABI, where any variadic function is implicitly cdecl
12826     // regardless of its normal CC.  Therefore we change the parameter
12827     // types to match the types of the arguments.
12828     //
12829     // This is a hack, but it is far superior to moving the
12830     // corresponding target-specific code from IR-gen to Sema/AST.
12831 
12832     ArrayRef<QualType> ParamTypes = Proto->getArgTypes();
12833     SmallVector<QualType, 8> ArgTypes;
12834     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
12835       ArgTypes.reserve(E->getNumArgs());
12836       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
12837         Expr *Arg = E->getArg(i);
12838         QualType ArgType = Arg->getType();
12839         if (E->isLValue()) {
12840           ArgType = S.Context.getLValueReferenceType(ArgType);
12841         } else if (E->isXValue()) {
12842           ArgType = S.Context.getRValueReferenceType(ArgType);
12843         }
12844         ArgTypes.push_back(ArgType);
12845       }
12846       ParamTypes = ArgTypes;
12847     }
12848     DestType = S.Context.getFunctionType(DestType, ParamTypes,
12849                                          Proto->getExtProtoInfo());
12850   } else {
12851     DestType = S.Context.getFunctionNoProtoType(DestType,
12852                                                 FnType->getExtInfo());
12853   }
12854 
12855   // Rebuild the appropriate pointer-to-function type.
12856   switch (Kind) {
12857   case FK_MemberFunction:
12858     // Nothing to do.
12859     break;
12860 
12861   case FK_FunctionPointer:
12862     DestType = S.Context.getPointerType(DestType);
12863     break;
12864 
12865   case FK_BlockPointer:
12866     DestType = S.Context.getBlockPointerType(DestType);
12867     break;
12868   }
12869 
12870   // Finally, we can recurse.
12871   ExprResult CalleeResult = Visit(CalleeExpr);
12872   if (!CalleeResult.isUsable()) return ExprError();
12873   E->setCallee(CalleeResult.take());
12874 
12875   // Bind a temporary if necessary.
12876   return S.MaybeBindToTemporary(E);
12877 }
12878 
12879 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
12880   // Verify that this is a legal result type of a call.
12881   if (DestType->isArrayType() || DestType->isFunctionType()) {
12882     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
12883       << DestType->isFunctionType() << DestType;
12884     return ExprError();
12885   }
12886 
12887   // Rewrite the method result type if available.
12888   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
12889     assert(Method->getResultType() == S.Context.UnknownAnyTy);
12890     Method->setResultType(DestType);
12891   }
12892 
12893   // Change the type of the message.
12894   E->setType(DestType.getNonReferenceType());
12895   E->setValueKind(Expr::getValueKindForType(DestType));
12896 
12897   return S.MaybeBindToTemporary(E);
12898 }
12899 
12900 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
12901   // The only case we should ever see here is a function-to-pointer decay.
12902   if (E->getCastKind() == CK_FunctionToPointerDecay) {
12903     assert(E->getValueKind() == VK_RValue);
12904     assert(E->getObjectKind() == OK_Ordinary);
12905 
12906     E->setType(DestType);
12907 
12908     // Rebuild the sub-expression as the pointee (function) type.
12909     DestType = DestType->castAs<PointerType>()->getPointeeType();
12910 
12911     ExprResult Result = Visit(E->getSubExpr());
12912     if (!Result.isUsable()) return ExprError();
12913 
12914     E->setSubExpr(Result.take());
12915     return S.Owned(E);
12916   } else if (E->getCastKind() == CK_LValueToRValue) {
12917     assert(E->getValueKind() == VK_RValue);
12918     assert(E->getObjectKind() == OK_Ordinary);
12919 
12920     assert(isa<BlockPointerType>(E->getType()));
12921 
12922     E->setType(DestType);
12923 
12924     // The sub-expression has to be a lvalue reference, so rebuild it as such.
12925     DestType = S.Context.getLValueReferenceType(DestType);
12926 
12927     ExprResult Result = Visit(E->getSubExpr());
12928     if (!Result.isUsable()) return ExprError();
12929 
12930     E->setSubExpr(Result.take());
12931     return S.Owned(E);
12932   } else {
12933     llvm_unreachable("Unhandled cast type!");
12934   }
12935 }
12936 
12937 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
12938   ExprValueKind ValueKind = VK_LValue;
12939   QualType Type = DestType;
12940 
12941   // We know how to make this work for certain kinds of decls:
12942 
12943   //  - functions
12944   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
12945     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
12946       DestType = Ptr->getPointeeType();
12947       ExprResult Result = resolveDecl(E, VD);
12948       if (Result.isInvalid()) return ExprError();
12949       return S.ImpCastExprToType(Result.take(), Type,
12950                                  CK_FunctionToPointerDecay, VK_RValue);
12951     }
12952 
12953     if (!Type->isFunctionType()) {
12954       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
12955         << VD << E->getSourceRange();
12956       return ExprError();
12957     }
12958 
12959     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
12960       if (MD->isInstance()) {
12961         ValueKind = VK_RValue;
12962         Type = S.Context.BoundMemberTy;
12963       }
12964 
12965     // Function references aren't l-values in C.
12966     if (!S.getLangOpts().CPlusPlus)
12967       ValueKind = VK_RValue;
12968 
12969   //  - variables
12970   } else if (isa<VarDecl>(VD)) {
12971     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
12972       Type = RefTy->getPointeeType();
12973     } else if (Type->isFunctionType()) {
12974       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
12975         << VD << E->getSourceRange();
12976       return ExprError();
12977     }
12978 
12979   //  - nothing else
12980   } else {
12981     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
12982       << VD << E->getSourceRange();
12983     return ExprError();
12984   }
12985 
12986   // Modifying the declaration like this is friendly to IR-gen but
12987   // also really dangerous.
12988   VD->setType(DestType);
12989   E->setType(Type);
12990   E->setValueKind(ValueKind);
12991   return S.Owned(E);
12992 }
12993 
12994 /// Check a cast of an unknown-any type.  We intentionally only
12995 /// trigger this for C-style casts.
12996 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
12997                                      Expr *CastExpr, CastKind &CastKind,
12998                                      ExprValueKind &VK, CXXCastPath &Path) {
12999   // Rewrite the casted expression from scratch.
13000   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
13001   if (!result.isUsable()) return ExprError();
13002 
13003   CastExpr = result.take();
13004   VK = CastExpr->getValueKind();
13005   CastKind = CK_NoOp;
13006 
13007   return CastExpr;
13008 }
13009 
13010 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
13011   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
13012 }
13013 
13014 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
13015                                     Expr *arg, QualType &paramType) {
13016   // If the syntactic form of the argument is not an explicit cast of
13017   // any sort, just do default argument promotion.
13018   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
13019   if (!castArg) {
13020     ExprResult result = DefaultArgumentPromotion(arg);
13021     if (result.isInvalid()) return ExprError();
13022     paramType = result.get()->getType();
13023     return result;
13024   }
13025 
13026   // Otherwise, use the type that was written in the explicit cast.
13027   assert(!arg->hasPlaceholderType());
13028   paramType = castArg->getTypeAsWritten();
13029 
13030   // Copy-initialize a parameter of that type.
13031   InitializedEntity entity =
13032     InitializedEntity::InitializeParameter(Context, paramType,
13033                                            /*consumed*/ false);
13034   return PerformCopyInitialization(entity, callLoc, Owned(arg));
13035 }
13036 
13037 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
13038   Expr *orig = E;
13039   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
13040   while (true) {
13041     E = E->IgnoreParenImpCasts();
13042     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
13043       E = call->getCallee();
13044       diagID = diag::err_uncasted_call_of_unknown_any;
13045     } else {
13046       break;
13047     }
13048   }
13049 
13050   SourceLocation loc;
13051   NamedDecl *d;
13052   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
13053     loc = ref->getLocation();
13054     d = ref->getDecl();
13055   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
13056     loc = mem->getMemberLoc();
13057     d = mem->getMemberDecl();
13058   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
13059     diagID = diag::err_uncasted_call_of_unknown_any;
13060     loc = msg->getSelectorStartLoc();
13061     d = msg->getMethodDecl();
13062     if (!d) {
13063       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
13064         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
13065         << orig->getSourceRange();
13066       return ExprError();
13067     }
13068   } else {
13069     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13070       << E->getSourceRange();
13071     return ExprError();
13072   }
13073 
13074   S.Diag(loc, diagID) << d << orig->getSourceRange();
13075 
13076   // Never recoverable.
13077   return ExprError();
13078 }
13079 
13080 /// Check for operands with placeholder types and complain if found.
13081 /// Returns true if there was an error and no recovery was possible.
13082 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
13083   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
13084   if (!placeholderType) return Owned(E);
13085 
13086   switch (placeholderType->getKind()) {
13087 
13088   // Overloaded expressions.
13089   case BuiltinType::Overload: {
13090     // Try to resolve a single function template specialization.
13091     // This is obligatory.
13092     ExprResult result = Owned(E);
13093     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
13094       return result;
13095 
13096     // If that failed, try to recover with a call.
13097     } else {
13098       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
13099                            /*complain*/ true);
13100       return result;
13101     }
13102   }
13103 
13104   // Bound member functions.
13105   case BuiltinType::BoundMember: {
13106     ExprResult result = Owned(E);
13107     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
13108                          /*complain*/ true);
13109     return result;
13110   }
13111 
13112   // ARC unbridged casts.
13113   case BuiltinType::ARCUnbridgedCast: {
13114     Expr *realCast = stripARCUnbridgedCast(E);
13115     diagnoseARCUnbridgedCast(realCast);
13116     return Owned(realCast);
13117   }
13118 
13119   // Expressions of unknown type.
13120   case BuiltinType::UnknownAny:
13121     return diagnoseUnknownAnyExpr(*this, E);
13122 
13123   // Pseudo-objects.
13124   case BuiltinType::PseudoObject:
13125     return checkPseudoObjectRValue(E);
13126 
13127   case BuiltinType::BuiltinFn:
13128     Diag(E->getLocStart(), diag::err_builtin_fn_use);
13129     return ExprError();
13130 
13131   // Everything else should be impossible.
13132 #define BUILTIN_TYPE(Id, SingletonId) \
13133   case BuiltinType::Id:
13134 #define PLACEHOLDER_TYPE(Id, SingletonId)
13135 #include "clang/AST/BuiltinTypes.def"
13136     break;
13137   }
13138 
13139   llvm_unreachable("invalid placeholder type!");
13140 }
13141 
13142 bool Sema::CheckCaseExpression(Expr *E) {
13143   if (E->isTypeDependent())
13144     return true;
13145   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
13146     return E->getType()->isIntegralOrEnumerationType();
13147   return false;
13148 }
13149 
13150 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
13151 ExprResult
13152 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
13153   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
13154          "Unknown Objective-C Boolean value!");
13155   QualType BoolT = Context.ObjCBuiltinBoolTy;
13156   if (!Context.getBOOLDecl()) {
13157     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
13158                         Sema::LookupOrdinaryName);
13159     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
13160       NamedDecl *ND = Result.getFoundDecl();
13161       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
13162         Context.setBOOLDecl(TD);
13163     }
13164   }
13165   if (Context.getBOOLDecl())
13166     BoolT = Context.getBOOLType();
13167   return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
13168                                         BoolT, OpLoc));
13169 }
13170