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->getReturnType()->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.EmitAvailabilityWarning(Sema::AD_Deprecation,
116                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl);
117       break;
118 
119     case AR_Unavailable:
120       if (S.getCurContextAvailability() != AR_Unavailable)
121         S.EmitAvailabilityWarning(Sema::AD_Unavailable,
122                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl);
123       break;
124 
125     }
126     return Result;
127 }
128 
129 /// \brief Emit a note explaining that this function is deleted.
130 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
131   assert(Decl->isDeleted());
132 
133   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
134 
135   if (Method && Method->isDeleted() && Method->isDefaulted()) {
136     // If the method was explicitly defaulted, point at that declaration.
137     if (!Method->isImplicit())
138       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
139 
140     // Try to diagnose why this special member function was implicitly
141     // deleted. This might fail, if that reason no longer applies.
142     CXXSpecialMember CSM = getSpecialMember(Method);
143     if (CSM != CXXInvalid)
144       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
145 
146     return;
147   }
148 
149   if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
150     if (CXXConstructorDecl *BaseCD =
151             const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
152       Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
153       if (BaseCD->isDeleted()) {
154         NoteDeletedFunction(BaseCD);
155       } else {
156         // FIXME: An explanation of why exactly it can't be inherited
157         // would be nice.
158         Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
159       }
160       return;
161     }
162   }
163 
164   Diag(Decl->getLocation(), diag::note_availability_specified_here)
165     << Decl << true;
166 }
167 
168 /// \brief Determine whether a FunctionDecl was ever declared with an
169 /// explicit storage class.
170 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
171   for (auto I : D->redecls()) {
172     if (I->getStorageClass() != SC_None)
173       return true;
174   }
175   return false;
176 }
177 
178 /// \brief Check whether we're in an extern inline function and referring to a
179 /// variable or function with internal linkage (C11 6.7.4p3).
180 ///
181 /// This is only a warning because we used to silently accept this code, but
182 /// in many cases it will not behave correctly. This is not enabled in C++ mode
183 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
184 /// and so while there may still be user mistakes, most of the time we can't
185 /// prove that there are errors.
186 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
187                                                       const NamedDecl *D,
188                                                       SourceLocation Loc) {
189   // This is disabled under C++; there are too many ways for this to fire in
190   // contexts where the warning is a false positive, or where it is technically
191   // correct but benign.
192   if (S.getLangOpts().CPlusPlus)
193     return;
194 
195   // Check if this is an inlined function or method.
196   FunctionDecl *Current = S.getCurFunctionDecl();
197   if (!Current)
198     return;
199   if (!Current->isInlined())
200     return;
201   if (!Current->isExternallyVisible())
202     return;
203 
204   // Check if the decl has internal linkage.
205   if (D->getFormalLinkage() != InternalLinkage)
206     return;
207 
208   // Downgrade from ExtWarn to Extension if
209   //  (1) the supposedly external inline function is in the main file,
210   //      and probably won't be included anywhere else.
211   //  (2) the thing we're referencing is a pure function.
212   //  (3) the thing we're referencing is another inline function.
213   // This last can give us false negatives, but it's better than warning on
214   // wrappers for simple C library functions.
215   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
216   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
217   if (!DowngradeWarning && UsedFn)
218     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
219 
220   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
221                                : diag::warn_internal_in_extern_inline)
222     << /*IsVar=*/!UsedFn << D;
223 
224   S.MaybeSuggestAddingStaticToDecl(Current);
225 
226   S.Diag(D->getCanonicalDecl()->getLocation(),
227          diag::note_internal_decl_declared_here)
228     << D;
229 }
230 
231 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
232   const FunctionDecl *First = Cur->getFirstDecl();
233 
234   // Suggest "static" on the function, if possible.
235   if (!hasAnyExplicitStorageClass(First)) {
236     SourceLocation DeclBegin = First->getSourceRange().getBegin();
237     Diag(DeclBegin, diag::note_convert_inline_to_static)
238       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
239   }
240 }
241 
242 /// \brief Determine whether the use of this declaration is valid, and
243 /// emit any corresponding diagnostics.
244 ///
245 /// This routine diagnoses various problems with referencing
246 /// declarations that can occur when using a declaration. For example,
247 /// it might warn if a deprecated or unavailable declaration is being
248 /// used, or produce an error (and return true) if a C++0x deleted
249 /// function is being used.
250 ///
251 /// \returns true if there was an error (this declaration cannot be
252 /// referenced), false otherwise.
253 ///
254 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
255                              const ObjCInterfaceDecl *UnknownObjCClass) {
256   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
257     // If there were any diagnostics suppressed by template argument deduction,
258     // emit them now.
259     SuppressedDiagnosticsMap::iterator
260       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
261     if (Pos != SuppressedDiagnostics.end()) {
262       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
263       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
264         Diag(Suppressed[I].first, Suppressed[I].second);
265 
266       // Clear out the list of suppressed diagnostics, so that we don't emit
267       // them again for this specialization. However, we don't obsolete this
268       // entry from the table, because we want to avoid ever emitting these
269       // diagnostics again.
270       Suppressed.clear();
271     }
272 
273     // C++ [basic.start.main]p3:
274     //   The function 'main' shall not be used within a program.
275     if (cast<FunctionDecl>(D)->isMain())
276       Diag(Loc, diag::ext_main_used);
277   }
278 
279   // See if this is an auto-typed variable whose initializer we are parsing.
280   if (ParsingInitForAutoVars.count(D)) {
281     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
282       << D->getDeclName();
283     return true;
284   }
285 
286   // See if this is a deleted function.
287   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
288     if (FD->isDeleted()) {
289       Diag(Loc, diag::err_deleted_function_use);
290       NoteDeletedFunction(FD);
291       return true;
292     }
293 
294     // If the function has a deduced return type, and we can't deduce it,
295     // then we can't use it either.
296     if (getLangOpts().CPlusPlus1y && FD->getReturnType()->isUndeducedType() &&
297         DeduceReturnType(FD, Loc))
298       return true;
299   }
300   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
301 
302   DiagnoseUnusedOfDecl(*this, D, Loc);
303 
304   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
305 
306   return false;
307 }
308 
309 /// \brief Retrieve the message suffix that should be added to a
310 /// diagnostic complaining about the given function being deleted or
311 /// unavailable.
312 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
313   std::string Message;
314   if (FD->getAvailability(&Message))
315     return ": " + Message;
316 
317   return std::string();
318 }
319 
320 /// DiagnoseSentinelCalls - This routine checks whether a call or
321 /// message-send is to a declaration with the sentinel attribute, and
322 /// if so, it checks that the requirements of the sentinel are
323 /// satisfied.
324 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
325                                  ArrayRef<Expr *> Args) {
326   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
327   if (!attr)
328     return;
329 
330   // The number of formal parameters of the declaration.
331   unsigned numFormalParams;
332 
333   // The kind of declaration.  This is also an index into a %select in
334   // the diagnostic.
335   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
336 
337   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
338     numFormalParams = MD->param_size();
339     calleeType = CT_Method;
340   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
341     numFormalParams = FD->param_size();
342     calleeType = CT_Function;
343   } else if (isa<VarDecl>(D)) {
344     QualType type = cast<ValueDecl>(D)->getType();
345     const FunctionType *fn = 0;
346     if (const PointerType *ptr = type->getAs<PointerType>()) {
347       fn = ptr->getPointeeType()->getAs<FunctionType>();
348       if (!fn) return;
349       calleeType = CT_Function;
350     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
351       fn = ptr->getPointeeType()->castAs<FunctionType>();
352       calleeType = CT_Block;
353     } else {
354       return;
355     }
356 
357     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
358       numFormalParams = proto->getNumParams();
359     } else {
360       numFormalParams = 0;
361     }
362   } else {
363     return;
364   }
365 
366   // "nullPos" is the number of formal parameters at the end which
367   // effectively count as part of the variadic arguments.  This is
368   // useful if you would prefer to not have *any* formal parameters,
369   // but the language forces you to have at least one.
370   unsigned nullPos = attr->getNullPos();
371   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
372   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
373 
374   // The number of arguments which should follow the sentinel.
375   unsigned numArgsAfterSentinel = attr->getSentinel();
376 
377   // If there aren't enough arguments for all the formal parameters,
378   // the sentinel, and the args after the sentinel, complain.
379   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
380     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
381     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
382     return;
383   }
384 
385   // Otherwise, find the sentinel expression.
386   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
387   if (!sentinelExpr) return;
388   if (sentinelExpr->isValueDependent()) return;
389   if (Context.isSentinelNullExpr(sentinelExpr)) return;
390 
391   // Pick a reasonable string to insert.  Optimistically use 'nil' or
392   // 'NULL' if those are actually defined in the context.  Only use
393   // 'nil' for ObjC methods, where it's much more likely that the
394   // variadic arguments form a list of object pointers.
395   SourceLocation MissingNilLoc
396     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
397   std::string NullValue;
398   if (calleeType == CT_Method &&
399       PP.getIdentifierInfo("nil")->hasMacroDefinition())
400     NullValue = "nil";
401   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
402     NullValue = "NULL";
403   else
404     NullValue = "(void*) 0";
405 
406   if (MissingNilLoc.isInvalid())
407     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
408   else
409     Diag(MissingNilLoc, diag::warn_missing_sentinel)
410       << int(calleeType)
411       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
412   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
413 }
414 
415 SourceRange Sema::getExprRange(Expr *E) const {
416   return E ? E->getSourceRange() : SourceRange();
417 }
418 
419 //===----------------------------------------------------------------------===//
420 //  Standard Promotions and Conversions
421 //===----------------------------------------------------------------------===//
422 
423 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
424 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
425   // Handle any placeholder expressions which made it here.
426   if (E->getType()->isPlaceholderType()) {
427     ExprResult result = CheckPlaceholderExpr(E);
428     if (result.isInvalid()) return ExprError();
429     E = result.take();
430   }
431 
432   QualType Ty = E->getType();
433   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
434 
435   if (Ty->isFunctionType()) {
436     // If we are here, we are not calling a function but taking
437     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
438     if (getLangOpts().OpenCL) {
439       Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
440       return ExprError();
441     }
442     E = ImpCastExprToType(E, Context.getPointerType(Ty),
443                           CK_FunctionToPointerDecay).take();
444   } else if (Ty->isArrayType()) {
445     // In C90 mode, arrays only promote to pointers if the array expression is
446     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
447     // type 'array of type' is converted to an expression that has type 'pointer
448     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
449     // that has type 'array of type' ...".  The relevant change is "an lvalue"
450     // (C90) to "an expression" (C99).
451     //
452     // C++ 4.2p1:
453     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
454     // T" can be converted to an rvalue of type "pointer to T".
455     //
456     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
457       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
458                             CK_ArrayToPointerDecay).take();
459   }
460   return Owned(E);
461 }
462 
463 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
464   // Check to see if we are dereferencing a null pointer.  If so,
465   // and if not volatile-qualified, this is undefined behavior that the
466   // optimizer will delete, so warn about it.  People sometimes try to use this
467   // to get a deterministic trap and are surprised by clang's behavior.  This
468   // only handles the pattern "*null", which is a very syntactic check.
469   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
470     if (UO->getOpcode() == UO_Deref &&
471         UO->getSubExpr()->IgnoreParenCasts()->
472           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
473         !UO->getType().isVolatileQualified()) {
474     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
475                           S.PDiag(diag::warn_indirection_through_null)
476                             << UO->getSubExpr()->getSourceRange());
477     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
478                         S.PDiag(diag::note_indirection_through_null));
479   }
480 }
481 
482 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
483                                     SourceLocation AssignLoc,
484                                     const Expr* RHS) {
485   const ObjCIvarDecl *IV = OIRE->getDecl();
486   if (!IV)
487     return;
488 
489   DeclarationName MemberName = IV->getDeclName();
490   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
491   if (!Member || !Member->isStr("isa"))
492     return;
493 
494   const Expr *Base = OIRE->getBase();
495   QualType BaseType = Base->getType();
496   if (OIRE->isArrow())
497     BaseType = BaseType->getPointeeType();
498   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
499     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
500       ObjCInterfaceDecl *ClassDeclared = 0;
501       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
502       if (!ClassDeclared->getSuperClass()
503           && (*ClassDeclared->ivar_begin()) == IV) {
504         if (RHS) {
505           NamedDecl *ObjectSetClass =
506             S.LookupSingleName(S.TUScope,
507                                &S.Context.Idents.get("object_setClass"),
508                                SourceLocation(), S.LookupOrdinaryName);
509           if (ObjectSetClass) {
510             SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
511             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
512             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
513             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
514                                                      AssignLoc), ",") <<
515             FixItHint::CreateInsertion(RHSLocEnd, ")");
516           }
517           else
518             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
519         } else {
520           NamedDecl *ObjectGetClass =
521             S.LookupSingleName(S.TUScope,
522                                &S.Context.Idents.get("object_getClass"),
523                                SourceLocation(), S.LookupOrdinaryName);
524           if (ObjectGetClass)
525             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
526             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
527             FixItHint::CreateReplacement(
528                                          SourceRange(OIRE->getOpLoc(),
529                                                      OIRE->getLocEnd()), ")");
530           else
531             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
532         }
533         S.Diag(IV->getLocation(), diag::note_ivar_decl);
534       }
535     }
536 }
537 
538 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
539   // Handle any placeholder expressions which made it here.
540   if (E->getType()->isPlaceholderType()) {
541     ExprResult result = CheckPlaceholderExpr(E);
542     if (result.isInvalid()) return ExprError();
543     E = result.take();
544   }
545 
546   // C++ [conv.lval]p1:
547   //   A glvalue of a non-function, non-array type T can be
548   //   converted to a prvalue.
549   if (!E->isGLValue()) return Owned(E);
550 
551   QualType T = E->getType();
552   assert(!T.isNull() && "r-value conversion on typeless expression?");
553 
554   // We don't want to throw lvalue-to-rvalue casts on top of
555   // expressions of certain types in C++.
556   if (getLangOpts().CPlusPlus &&
557       (E->getType() == Context.OverloadTy ||
558        T->isDependentType() ||
559        T->isRecordType()))
560     return Owned(E);
561 
562   // The C standard is actually really unclear on this point, and
563   // DR106 tells us what the result should be but not why.  It's
564   // generally best to say that void types just doesn't undergo
565   // lvalue-to-rvalue at all.  Note that expressions of unqualified
566   // 'void' type are never l-values, but qualified void can be.
567   if (T->isVoidType())
568     return Owned(E);
569 
570   // OpenCL usually rejects direct accesses to values of 'half' type.
571   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
572       T->isHalfType()) {
573     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
574       << 0 << T;
575     return ExprError();
576   }
577 
578   CheckForNullPointerDereference(*this, E);
579   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
580     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
581                                      &Context.Idents.get("object_getClass"),
582                                      SourceLocation(), LookupOrdinaryName);
583     if (ObjectGetClass)
584       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
585         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
586         FixItHint::CreateReplacement(
587                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
588     else
589       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
590   }
591   else if (const ObjCIvarRefExpr *OIRE =
592             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
593     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0);
594 
595   // C++ [conv.lval]p1:
596   //   [...] If T is a non-class type, the type of the prvalue is the
597   //   cv-unqualified version of T. Otherwise, the type of the
598   //   rvalue is T.
599   //
600   // C99 6.3.2.1p2:
601   //   If the lvalue has qualified type, the value has the unqualified
602   //   version of the type of the lvalue; otherwise, the value has the
603   //   type of the lvalue.
604   if (T.hasQualifiers())
605     T = T.getUnqualifiedType();
606 
607   UpdateMarkingForLValueToRValue(E);
608 
609   // Loading a __weak object implicitly retains the value, so we need a cleanup to
610   // balance that.
611   if (getLangOpts().ObjCAutoRefCount &&
612       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
613     ExprNeedsCleanups = true;
614 
615   ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
616                                                   E, 0, VK_RValue));
617 
618   // C11 6.3.2.1p2:
619   //   ... if the lvalue has atomic type, the value has the non-atomic version
620   //   of the type of the lvalue ...
621   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
622     T = Atomic->getValueType().getUnqualifiedType();
623     Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
624                                          Res.get(), 0, VK_RValue));
625   }
626 
627   return Res;
628 }
629 
630 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
631   ExprResult Res = DefaultFunctionArrayConversion(E);
632   if (Res.isInvalid())
633     return ExprError();
634   Res = DefaultLvalueConversion(Res.take());
635   if (Res.isInvalid())
636     return ExprError();
637   return Res;
638 }
639 
640 /// CallExprUnaryConversions - a special case of an unary conversion
641 /// performed on a function designator of a call expression.
642 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
643   QualType Ty = E->getType();
644   ExprResult Res = E;
645   // Only do implicit cast for a function type, but not for a pointer
646   // to function type.
647   if (Ty->isFunctionType()) {
648     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
649                             CK_FunctionToPointerDecay).take();
650     if (Res.isInvalid())
651       return ExprError();
652   }
653   Res = DefaultLvalueConversion(Res.take());
654   if (Res.isInvalid())
655     return ExprError();
656   return Owned(Res.take());
657 }
658 
659 /// UsualUnaryConversions - Performs various conversions that are common to most
660 /// operators (C99 6.3). The conversions of array and function types are
661 /// sometimes suppressed. For example, the array->pointer conversion doesn't
662 /// apply if the array is an argument to the sizeof or address (&) operators.
663 /// In these instances, this routine should *not* be called.
664 ExprResult Sema::UsualUnaryConversions(Expr *E) {
665   // First, convert to an r-value.
666   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
667   if (Res.isInvalid())
668     return ExprError();
669   E = Res.take();
670 
671   QualType Ty = E->getType();
672   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
673 
674   // Half FP have to be promoted to float unless it is natively supported
675   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
676     return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
677 
678   // Try to perform integral promotions if the object has a theoretically
679   // promotable type.
680   if (Ty->isIntegralOrUnscopedEnumerationType()) {
681     // C99 6.3.1.1p2:
682     //
683     //   The following may be used in an expression wherever an int or
684     //   unsigned int may be used:
685     //     - an object or expression with an integer type whose integer
686     //       conversion rank is less than or equal to the rank of int
687     //       and unsigned int.
688     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
689     //
690     //   If an int can represent all values of the original type, the
691     //   value is converted to an int; otherwise, it is converted to an
692     //   unsigned int. These are called the integer promotions. All
693     //   other types are unchanged by the integer promotions.
694 
695     QualType PTy = Context.isPromotableBitField(E);
696     if (!PTy.isNull()) {
697       E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
698       return Owned(E);
699     }
700     if (Ty->isPromotableIntegerType()) {
701       QualType PT = Context.getPromotedIntegerType(Ty);
702       E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
703       return Owned(E);
704     }
705   }
706   return Owned(E);
707 }
708 
709 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
710 /// do not have a prototype. Arguments that have type float or __fp16
711 /// are promoted to double. All other argument types are converted by
712 /// UsualUnaryConversions().
713 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
714   QualType Ty = E->getType();
715   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
716 
717   ExprResult Res = UsualUnaryConversions(E);
718   if (Res.isInvalid())
719     return ExprError();
720   E = Res.take();
721 
722   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
723   // double.
724   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
725   if (BTy && (BTy->getKind() == BuiltinType::Half ||
726               BTy->getKind() == BuiltinType::Float))
727     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
728 
729   // C++ performs lvalue-to-rvalue conversion as a default argument
730   // promotion, even on class types, but note:
731   //   C++11 [conv.lval]p2:
732   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
733   //     operand or a subexpression thereof the value contained in the
734   //     referenced object is not accessed. Otherwise, if the glvalue
735   //     has a class type, the conversion copy-initializes a temporary
736   //     of type T from the glvalue and the result of the conversion
737   //     is a prvalue for the temporary.
738   // FIXME: add some way to gate this entire thing for correctness in
739   // potentially potentially evaluated contexts.
740   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
741     ExprResult Temp = PerformCopyInitialization(
742                        InitializedEntity::InitializeTemporary(E->getType()),
743                                                 E->getExprLoc(),
744                                                 Owned(E));
745     if (Temp.isInvalid())
746       return ExprError();
747     E = Temp.get();
748   }
749 
750   return Owned(E);
751 }
752 
753 /// Determine the degree of POD-ness for an expression.
754 /// Incomplete types are considered POD, since this check can be performed
755 /// when we're in an unevaluated context.
756 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
757   if (Ty->isIncompleteType()) {
758     // C++11 [expr.call]p7:
759     //   After these conversions, if the argument does not have arithmetic,
760     //   enumeration, pointer, pointer to member, or class type, the program
761     //   is ill-formed.
762     //
763     // Since we've already performed array-to-pointer and function-to-pointer
764     // decay, the only such type in C++ is cv void. This also handles
765     // initializer lists as variadic arguments.
766     if (Ty->isVoidType())
767       return VAK_Invalid;
768 
769     if (Ty->isObjCObjectType())
770       return VAK_Invalid;
771     return VAK_Valid;
772   }
773 
774   if (Ty.isCXX98PODType(Context))
775     return VAK_Valid;
776 
777   // C++11 [expr.call]p7:
778   //   Passing a potentially-evaluated argument of class type (Clause 9)
779   //   having a non-trivial copy constructor, a non-trivial move constructor,
780   //   or a non-trivial destructor, with no corresponding parameter,
781   //   is conditionally-supported with implementation-defined semantics.
782   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
783     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
784       if (!Record->hasNonTrivialCopyConstructor() &&
785           !Record->hasNonTrivialMoveConstructor() &&
786           !Record->hasNonTrivialDestructor())
787         return VAK_ValidInCXX11;
788 
789   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
790     return VAK_Valid;
791 
792   if (Ty->isObjCObjectType())
793     return VAK_Invalid;
794 
795   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
796   // permitted to reject them. We should consider doing so.
797   return VAK_Undefined;
798 }
799 
800 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
801   // Don't allow one to pass an Objective-C interface to a vararg.
802   const QualType &Ty = E->getType();
803   VarArgKind VAK = isValidVarArgType(Ty);
804 
805   // Complain about passing non-POD types through varargs.
806   switch (VAK) {
807   case VAK_ValidInCXX11:
808     DiagRuntimeBehavior(
809         E->getLocStart(), 0,
810         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
811           << Ty << CT);
812     // Fall through.
813   case VAK_Valid:
814     if (Ty->isRecordType()) {
815       // This is unlikely to be what the user intended. If the class has a
816       // 'c_str' member function, the user probably meant to call that.
817       DiagRuntimeBehavior(E->getLocStart(), 0,
818                           PDiag(diag::warn_pass_class_arg_to_vararg)
819                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
820     }
821     break;
822 
823   case VAK_Undefined:
824     DiagRuntimeBehavior(
825         E->getLocStart(), 0,
826         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
827           << getLangOpts().CPlusPlus11 << Ty << CT);
828     break;
829 
830   case VAK_Invalid:
831     if (Ty->isObjCObjectType())
832       DiagRuntimeBehavior(
833           E->getLocStart(), 0,
834           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
835             << Ty << CT);
836     else
837       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
838         << isa<InitListExpr>(E) << Ty << CT;
839     break;
840   }
841 }
842 
843 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
844 /// will create a trap if the resulting type is not a POD type.
845 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
846                                                   FunctionDecl *FDecl) {
847   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
848     // Strip the unbridged-cast placeholder expression off, if applicable.
849     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
850         (CT == VariadicMethod ||
851          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
852       E = stripARCUnbridgedCast(E);
853 
854     // Otherwise, do normal placeholder checking.
855     } else {
856       ExprResult ExprRes = CheckPlaceholderExpr(E);
857       if (ExprRes.isInvalid())
858         return ExprError();
859       E = ExprRes.take();
860     }
861   }
862 
863   ExprResult ExprRes = DefaultArgumentPromotion(E);
864   if (ExprRes.isInvalid())
865     return ExprError();
866   E = ExprRes.take();
867 
868   // Diagnostics regarding non-POD argument types are
869   // emitted along with format string checking in Sema::CheckFunctionCall().
870   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
871     // Turn this into a trap.
872     CXXScopeSpec SS;
873     SourceLocation TemplateKWLoc;
874     UnqualifiedId Name;
875     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
876                        E->getLocStart());
877     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
878                                           Name, true, false);
879     if (TrapFn.isInvalid())
880       return ExprError();
881 
882     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
883                                     E->getLocStart(), None,
884                                     E->getLocEnd());
885     if (Call.isInvalid())
886       return ExprError();
887 
888     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
889                                   Call.get(), E);
890     if (Comma.isInvalid())
891       return ExprError();
892     return Comma.get();
893   }
894 
895   if (!getLangOpts().CPlusPlus &&
896       RequireCompleteType(E->getExprLoc(), E->getType(),
897                           diag::err_call_incomplete_argument))
898     return ExprError();
899 
900   return Owned(E);
901 }
902 
903 /// \brief Converts an integer to complex float type.  Helper function of
904 /// UsualArithmeticConversions()
905 ///
906 /// \return false if the integer expression is an integer type and is
907 /// successfully converted to the complex type.
908 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
909                                                   ExprResult &ComplexExpr,
910                                                   QualType IntTy,
911                                                   QualType ComplexTy,
912                                                   bool SkipCast) {
913   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
914   if (SkipCast) return false;
915   if (IntTy->isIntegerType()) {
916     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
917     IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
918     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
919                                   CK_FloatingRealToComplex);
920   } else {
921     assert(IntTy->isComplexIntegerType());
922     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
923                                   CK_IntegralComplexToFloatingComplex);
924   }
925   return false;
926 }
927 
928 /// \brief Takes two complex float types and converts them to the same type.
929 /// Helper function of UsualArithmeticConversions()
930 static QualType
931 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
932                                             ExprResult &RHS, QualType LHSType,
933                                             QualType RHSType,
934                                             bool IsCompAssign) {
935   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
936 
937   if (order < 0) {
938     // _Complex float -> _Complex double
939     if (!IsCompAssign)
940       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
941     return RHSType;
942   }
943   if (order > 0)
944     // _Complex float -> _Complex double
945     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
946   return LHSType;
947 }
948 
949 /// \brief Converts otherExpr to complex float and promotes complexExpr if
950 /// necessary.  Helper function of UsualArithmeticConversions()
951 static QualType handleOtherComplexFloatConversion(Sema &S,
952                                                   ExprResult &ComplexExpr,
953                                                   ExprResult &OtherExpr,
954                                                   QualType ComplexTy,
955                                                   QualType OtherTy,
956                                                   bool ConvertComplexExpr,
957                                                   bool ConvertOtherExpr) {
958   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
959 
960   // If just the complexExpr is complex, the otherExpr needs to be converted,
961   // and the complexExpr might need to be promoted.
962   if (order > 0) { // complexExpr is wider
963     // float -> _Complex double
964     if (ConvertOtherExpr) {
965       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
966       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
967       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
968                                       CK_FloatingRealToComplex);
969     }
970     return ComplexTy;
971   }
972 
973   // otherTy is at least as wide.  Find its corresponding complex type.
974   QualType result = (order == 0 ? ComplexTy :
975                                   S.Context.getComplexType(OtherTy));
976 
977   // double -> _Complex double
978   if (ConvertOtherExpr)
979     OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
980                                     CK_FloatingRealToComplex);
981 
982   // _Complex float -> _Complex double
983   if (ConvertComplexExpr && order < 0)
984     ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
985                                       CK_FloatingComplexCast);
986 
987   return result;
988 }
989 
990 /// \brief Handle arithmetic conversion with complex types.  Helper function of
991 /// UsualArithmeticConversions()
992 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
993                                              ExprResult &RHS, QualType LHSType,
994                                              QualType RHSType,
995                                              bool IsCompAssign) {
996   // if we have an integer operand, the result is the complex type.
997   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
998                                              /*skipCast*/false))
999     return LHSType;
1000   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1001                                              /*skipCast*/IsCompAssign))
1002     return RHSType;
1003 
1004   // This handles complex/complex, complex/float, or float/complex.
1005   // When both operands are complex, the shorter operand is converted to the
1006   // type of the longer, and that is the type of the result. This corresponds
1007   // to what is done when combining two real floating-point operands.
1008   // The fun begins when size promotion occur across type domains.
1009   // From H&S 6.3.4: When one operand is complex and the other is a real
1010   // floating-point type, the less precise type is converted, within it's
1011   // real or complex domain, to the precision of the other type. For example,
1012   // when combining a "long double" with a "double _Complex", the
1013   // "double _Complex" is promoted to "long double _Complex".
1014 
1015   bool LHSComplexFloat = LHSType->isComplexType();
1016   bool RHSComplexFloat = RHSType->isComplexType();
1017 
1018   // If both are complex, just cast to the more precise type.
1019   if (LHSComplexFloat && RHSComplexFloat)
1020     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
1021                                                        LHSType, RHSType,
1022                                                        IsCompAssign);
1023 
1024   // If only one operand is complex, promote it if necessary and convert the
1025   // other operand to complex.
1026   if (LHSComplexFloat)
1027     return handleOtherComplexFloatConversion(
1028         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
1029         /*convertOtherExpr*/ true);
1030 
1031   assert(RHSComplexFloat);
1032   return handleOtherComplexFloatConversion(
1033       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
1034       /*convertOtherExpr*/ !IsCompAssign);
1035 }
1036 
1037 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1038 /// of UsualArithmeticConversions()
1039 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1040                                            ExprResult &IntExpr,
1041                                            QualType FloatTy, QualType IntTy,
1042                                            bool ConvertFloat, bool ConvertInt) {
1043   if (IntTy->isIntegerType()) {
1044     if (ConvertInt)
1045       // Convert intExpr to the lhs floating point type.
1046       IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
1047                                     CK_IntegralToFloating);
1048     return FloatTy;
1049   }
1050 
1051   // Convert both sides to the appropriate complex float.
1052   assert(IntTy->isComplexIntegerType());
1053   QualType result = S.Context.getComplexType(FloatTy);
1054 
1055   // _Complex int -> _Complex float
1056   if (ConvertInt)
1057     IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
1058                                   CK_IntegralComplexToFloatingComplex);
1059 
1060   // float -> _Complex float
1061   if (ConvertFloat)
1062     FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
1063                                     CK_FloatingRealToComplex);
1064 
1065   return result;
1066 }
1067 
1068 /// \brief Handle arithmethic conversion with floating point types.  Helper
1069 /// function of UsualArithmeticConversions()
1070 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1071                                       ExprResult &RHS, QualType LHSType,
1072                                       QualType RHSType, bool IsCompAssign) {
1073   bool LHSFloat = LHSType->isRealFloatingType();
1074   bool RHSFloat = RHSType->isRealFloatingType();
1075 
1076   // If we have two real floating types, convert the smaller operand
1077   // to the bigger result.
1078   if (LHSFloat && RHSFloat) {
1079     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1080     if (order > 0) {
1081       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
1082       return LHSType;
1083     }
1084 
1085     assert(order < 0 && "illegal float comparison");
1086     if (!IsCompAssign)
1087       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
1088     return RHSType;
1089   }
1090 
1091   if (LHSFloat)
1092     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1093                                       /*convertFloat=*/!IsCompAssign,
1094                                       /*convertInt=*/ true);
1095   assert(RHSFloat);
1096   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1097                                     /*convertInt=*/ true,
1098                                     /*convertFloat=*/!IsCompAssign);
1099 }
1100 
1101 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1102 
1103 namespace {
1104 /// These helper callbacks are placed in an anonymous namespace to
1105 /// permit their use as function template parameters.
1106 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1107   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1108 }
1109 
1110 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1111   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1112                              CK_IntegralComplexCast);
1113 }
1114 }
1115 
1116 /// \brief Handle integer arithmetic conversions.  Helper function of
1117 /// UsualArithmeticConversions()
1118 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1119 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1120                                         ExprResult &RHS, QualType LHSType,
1121                                         QualType RHSType, bool IsCompAssign) {
1122   // The rules for this case are in C99 6.3.1.8
1123   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1124   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1125   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1126   if (LHSSigned == RHSSigned) {
1127     // Same signedness; use the higher-ranked type
1128     if (order >= 0) {
1129       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1130       return LHSType;
1131     } else if (!IsCompAssign)
1132       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1133     return RHSType;
1134   } else if (order != (LHSSigned ? 1 : -1)) {
1135     // The unsigned type has greater than or equal rank to the
1136     // signed type, so use the unsigned type
1137     if (RHSSigned) {
1138       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1139       return LHSType;
1140     } else if (!IsCompAssign)
1141       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1142     return RHSType;
1143   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1144     // The two types are different widths; if we are here, that
1145     // means the signed type is larger than the unsigned type, so
1146     // use the signed type.
1147     if (LHSSigned) {
1148       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1149       return LHSType;
1150     } else if (!IsCompAssign)
1151       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1152     return RHSType;
1153   } else {
1154     // The signed type is higher-ranked than the unsigned type,
1155     // but isn't actually any bigger (like unsigned int and long
1156     // on most 32-bit systems).  Use the unsigned type corresponding
1157     // to the signed type.
1158     QualType result =
1159       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1160     RHS = (*doRHSCast)(S, RHS.take(), result);
1161     if (!IsCompAssign)
1162       LHS = (*doLHSCast)(S, LHS.take(), result);
1163     return result;
1164   }
1165 }
1166 
1167 /// \brief Handle conversions with GCC complex int extension.  Helper function
1168 /// of UsualArithmeticConversions()
1169 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1170                                            ExprResult &RHS, QualType LHSType,
1171                                            QualType RHSType,
1172                                            bool IsCompAssign) {
1173   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1174   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1175 
1176   if (LHSComplexInt && RHSComplexInt) {
1177     QualType LHSEltType = LHSComplexInt->getElementType();
1178     QualType RHSEltType = RHSComplexInt->getElementType();
1179     QualType ScalarType =
1180       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1181         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1182 
1183     return S.Context.getComplexType(ScalarType);
1184   }
1185 
1186   if (LHSComplexInt) {
1187     QualType LHSEltType = LHSComplexInt->getElementType();
1188     QualType ScalarType =
1189       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1190         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1191     QualType ComplexType = S.Context.getComplexType(ScalarType);
1192     RHS = S.ImpCastExprToType(RHS.take(), ComplexType,
1193                               CK_IntegralRealToComplex);
1194 
1195     return ComplexType;
1196   }
1197 
1198   assert(RHSComplexInt);
1199 
1200   QualType RHSEltType = RHSComplexInt->getElementType();
1201   QualType ScalarType =
1202     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1203       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1204   QualType ComplexType = S.Context.getComplexType(ScalarType);
1205 
1206   if (!IsCompAssign)
1207     LHS = S.ImpCastExprToType(LHS.take(), ComplexType,
1208                               CK_IntegralRealToComplex);
1209   return ComplexType;
1210 }
1211 
1212 /// UsualArithmeticConversions - Performs various conversions that are common to
1213 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1214 /// routine returns the first non-arithmetic type found. The client is
1215 /// responsible for emitting appropriate error diagnostics.
1216 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1217                                           bool IsCompAssign) {
1218   if (!IsCompAssign) {
1219     LHS = UsualUnaryConversions(LHS.take());
1220     if (LHS.isInvalid())
1221       return QualType();
1222   }
1223 
1224   RHS = UsualUnaryConversions(RHS.take());
1225   if (RHS.isInvalid())
1226     return QualType();
1227 
1228   // For conversion purposes, we ignore any qualifiers.
1229   // For example, "const float" and "float" are equivalent.
1230   QualType LHSType =
1231     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1232   QualType RHSType =
1233     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1234 
1235   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1236   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1237     LHSType = AtomicLHS->getValueType();
1238 
1239   // If both types are identical, no conversion is needed.
1240   if (LHSType == RHSType)
1241     return LHSType;
1242 
1243   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1244   // The caller can deal with this (e.g. pointer + int).
1245   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1246     return QualType();
1247 
1248   // Apply unary and bitfield promotions to the LHS's type.
1249   QualType LHSUnpromotedType = LHSType;
1250   if (LHSType->isPromotableIntegerType())
1251     LHSType = Context.getPromotedIntegerType(LHSType);
1252   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1253   if (!LHSBitfieldPromoteTy.isNull())
1254     LHSType = LHSBitfieldPromoteTy;
1255   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1256     LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
1257 
1258   // If both types are identical, no conversion is needed.
1259   if (LHSType == RHSType)
1260     return LHSType;
1261 
1262   // At this point, we have two different arithmetic types.
1263 
1264   // Handle complex types first (C99 6.3.1.8p1).
1265   if (LHSType->isComplexType() || RHSType->isComplexType())
1266     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1267                                         IsCompAssign);
1268 
1269   // Now handle "real" floating types (i.e. float, double, long double).
1270   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1271     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1272                                  IsCompAssign);
1273 
1274   // Handle GCC complex int extension.
1275   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1276     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1277                                       IsCompAssign);
1278 
1279   // Finally, we have two differing integer types.
1280   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1281            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1282 }
1283 
1284 
1285 //===----------------------------------------------------------------------===//
1286 //  Semantic Analysis for various Expression Types
1287 //===----------------------------------------------------------------------===//
1288 
1289 
1290 ExprResult
1291 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1292                                 SourceLocation DefaultLoc,
1293                                 SourceLocation RParenLoc,
1294                                 Expr *ControllingExpr,
1295                                 ArrayRef<ParsedType> ArgTypes,
1296                                 ArrayRef<Expr *> ArgExprs) {
1297   unsigned NumAssocs = ArgTypes.size();
1298   assert(NumAssocs == ArgExprs.size());
1299 
1300   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1301   for (unsigned i = 0; i < NumAssocs; ++i) {
1302     if (ArgTypes[i])
1303       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1304     else
1305       Types[i] = 0;
1306   }
1307 
1308   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1309                                              ControllingExpr,
1310                                              llvm::makeArrayRef(Types, NumAssocs),
1311                                              ArgExprs);
1312   delete [] Types;
1313   return ER;
1314 }
1315 
1316 ExprResult
1317 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1318                                  SourceLocation DefaultLoc,
1319                                  SourceLocation RParenLoc,
1320                                  Expr *ControllingExpr,
1321                                  ArrayRef<TypeSourceInfo *> Types,
1322                                  ArrayRef<Expr *> Exprs) {
1323   unsigned NumAssocs = Types.size();
1324   assert(NumAssocs == Exprs.size());
1325   if (ControllingExpr->getType()->isPlaceholderType()) {
1326     ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1327     if (result.isInvalid()) return ExprError();
1328     ControllingExpr = result.take();
1329   }
1330 
1331   bool TypeErrorFound = false,
1332        IsResultDependent = ControllingExpr->isTypeDependent(),
1333        ContainsUnexpandedParameterPack
1334          = ControllingExpr->containsUnexpandedParameterPack();
1335 
1336   for (unsigned i = 0; i < NumAssocs; ++i) {
1337     if (Exprs[i]->containsUnexpandedParameterPack())
1338       ContainsUnexpandedParameterPack = true;
1339 
1340     if (Types[i]) {
1341       if (Types[i]->getType()->containsUnexpandedParameterPack())
1342         ContainsUnexpandedParameterPack = true;
1343 
1344       if (Types[i]->getType()->isDependentType()) {
1345         IsResultDependent = true;
1346       } else {
1347         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1348         // complete object type other than a variably modified type."
1349         unsigned D = 0;
1350         if (Types[i]->getType()->isIncompleteType())
1351           D = diag::err_assoc_type_incomplete;
1352         else if (!Types[i]->getType()->isObjectType())
1353           D = diag::err_assoc_type_nonobject;
1354         else if (Types[i]->getType()->isVariablyModifiedType())
1355           D = diag::err_assoc_type_variably_modified;
1356 
1357         if (D != 0) {
1358           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1359             << Types[i]->getTypeLoc().getSourceRange()
1360             << Types[i]->getType();
1361           TypeErrorFound = true;
1362         }
1363 
1364         // C11 6.5.1.1p2 "No two generic associations in the same generic
1365         // selection shall specify compatible types."
1366         for (unsigned j = i+1; j < NumAssocs; ++j)
1367           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1368               Context.typesAreCompatible(Types[i]->getType(),
1369                                          Types[j]->getType())) {
1370             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1371                  diag::err_assoc_compatible_types)
1372               << Types[j]->getTypeLoc().getSourceRange()
1373               << Types[j]->getType()
1374               << Types[i]->getType();
1375             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1376                  diag::note_compat_assoc)
1377               << Types[i]->getTypeLoc().getSourceRange()
1378               << Types[i]->getType();
1379             TypeErrorFound = true;
1380           }
1381       }
1382     }
1383   }
1384   if (TypeErrorFound)
1385     return ExprError();
1386 
1387   // If we determined that the generic selection is result-dependent, don't
1388   // try to compute the result expression.
1389   if (IsResultDependent)
1390     return Owned(new (Context) GenericSelectionExpr(
1391                    Context, KeyLoc, ControllingExpr,
1392                    Types, Exprs,
1393                    DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
1394 
1395   SmallVector<unsigned, 1> CompatIndices;
1396   unsigned DefaultIndex = -1U;
1397   for (unsigned i = 0; i < NumAssocs; ++i) {
1398     if (!Types[i])
1399       DefaultIndex = i;
1400     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1401                                         Types[i]->getType()))
1402       CompatIndices.push_back(i);
1403   }
1404 
1405   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1406   // type compatible with at most one of the types named in its generic
1407   // association list."
1408   if (CompatIndices.size() > 1) {
1409     // We strip parens here because the controlling expression is typically
1410     // parenthesized in macro definitions.
1411     ControllingExpr = ControllingExpr->IgnoreParens();
1412     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1413       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1414       << (unsigned) CompatIndices.size();
1415     for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
1416          E = CompatIndices.end(); I != E; ++I) {
1417       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1418            diag::note_compat_assoc)
1419         << Types[*I]->getTypeLoc().getSourceRange()
1420         << Types[*I]->getType();
1421     }
1422     return ExprError();
1423   }
1424 
1425   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1426   // its controlling expression shall have type compatible with exactly one of
1427   // the types named in its generic association list."
1428   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1429     // We strip parens here because the controlling expression is typically
1430     // parenthesized in macro definitions.
1431     ControllingExpr = ControllingExpr->IgnoreParens();
1432     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1433       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1434     return ExprError();
1435   }
1436 
1437   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1438   // type name that is compatible with the type of the controlling expression,
1439   // then the result expression of the generic selection is the expression
1440   // in that generic association. Otherwise, the result expression of the
1441   // generic selection is the expression in the default generic association."
1442   unsigned ResultIndex =
1443     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1444 
1445   return Owned(new (Context) GenericSelectionExpr(
1446                  Context, KeyLoc, ControllingExpr,
1447                  Types, Exprs,
1448                  DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
1449                  ResultIndex));
1450 }
1451 
1452 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1453 /// location of the token and the offset of the ud-suffix within it.
1454 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1455                                      unsigned Offset) {
1456   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1457                                         S.getLangOpts());
1458 }
1459 
1460 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1461 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1462 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1463                                                  IdentifierInfo *UDSuffix,
1464                                                  SourceLocation UDSuffixLoc,
1465                                                  ArrayRef<Expr*> Args,
1466                                                  SourceLocation LitEndLoc) {
1467   assert(Args.size() <= 2 && "too many arguments for literal operator");
1468 
1469   QualType ArgTy[2];
1470   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1471     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1472     if (ArgTy[ArgIdx]->isArrayType())
1473       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1474   }
1475 
1476   DeclarationName OpName =
1477     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1478   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1479   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1480 
1481   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1482   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1483                               /*AllowRaw*/false, /*AllowTemplate*/false,
1484                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1485     return ExprError();
1486 
1487   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1488 }
1489 
1490 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1491 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1492 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1493 /// multiple tokens.  However, the common case is that StringToks points to one
1494 /// string.
1495 ///
1496 ExprResult
1497 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1498                          Scope *UDLScope) {
1499   assert(NumStringToks && "Must have at least one string!");
1500 
1501   StringLiteralParser Literal(StringToks, NumStringToks, PP);
1502   if (Literal.hadError)
1503     return ExprError();
1504 
1505   SmallVector<SourceLocation, 4> StringTokLocs;
1506   for (unsigned i = 0; i != NumStringToks; ++i)
1507     StringTokLocs.push_back(StringToks[i].getLocation());
1508 
1509   QualType CharTy = Context.CharTy;
1510   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1511   if (Literal.isWide()) {
1512     CharTy = Context.getWideCharType();
1513     Kind = StringLiteral::Wide;
1514   } else if (Literal.isUTF8()) {
1515     Kind = StringLiteral::UTF8;
1516   } else if (Literal.isUTF16()) {
1517     CharTy = Context.Char16Ty;
1518     Kind = StringLiteral::UTF16;
1519   } else if (Literal.isUTF32()) {
1520     CharTy = Context.Char32Ty;
1521     Kind = StringLiteral::UTF32;
1522   } else if (Literal.isPascal()) {
1523     CharTy = Context.UnsignedCharTy;
1524   }
1525 
1526   QualType CharTyConst = CharTy;
1527   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1528   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1529     CharTyConst.addConst();
1530 
1531   // Get an array type for the string, according to C99 6.4.5.  This includes
1532   // the nul terminator character as well as the string length for pascal
1533   // strings.
1534   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1535                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1536                                  ArrayType::Normal, 0);
1537 
1538   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1539   if (getLangOpts().OpenCL) {
1540     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1541   }
1542 
1543   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1544   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1545                                              Kind, Literal.Pascal, StrTy,
1546                                              &StringTokLocs[0],
1547                                              StringTokLocs.size());
1548   if (Literal.getUDSuffix().empty())
1549     return Owned(Lit);
1550 
1551   // We're building a user-defined literal.
1552   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1553   SourceLocation UDSuffixLoc =
1554     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1555                    Literal.getUDSuffixOffset());
1556 
1557   // Make sure we're allowed user-defined literals here.
1558   if (!UDLScope)
1559     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1560 
1561   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1562   //   operator "" X (str, len)
1563   QualType SizeType = Context.getSizeType();
1564 
1565   DeclarationName OpName =
1566     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1567   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1568   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1569 
1570   QualType ArgTy[] = {
1571     Context.getArrayDecayedType(StrTy), SizeType
1572   };
1573 
1574   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1575   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1576                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1577                                 /*AllowStringTemplate*/true)) {
1578 
1579   case LOLR_Cooked: {
1580     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1581     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1582                                                     StringTokLocs[0]);
1583     Expr *Args[] = { Lit, LenArg };
1584 
1585     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1586   }
1587 
1588   case LOLR_StringTemplate: {
1589     TemplateArgumentListInfo ExplicitArgs;
1590 
1591     unsigned CharBits = Context.getIntWidth(CharTy);
1592     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1593     llvm::APSInt Value(CharBits, CharIsUnsigned);
1594 
1595     TemplateArgument TypeArg(CharTy);
1596     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1597     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1598 
1599     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1600       Value = Lit->getCodeUnit(I);
1601       TemplateArgument Arg(Context, Value, CharTy);
1602       TemplateArgumentLocInfo ArgInfo;
1603       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1604     }
1605     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1606                                     &ExplicitArgs);
1607   }
1608   case LOLR_Raw:
1609   case LOLR_Template:
1610     llvm_unreachable("unexpected literal operator lookup result");
1611   case LOLR_Error:
1612     return ExprError();
1613   }
1614   llvm_unreachable("unexpected literal operator lookup result");
1615 }
1616 
1617 ExprResult
1618 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1619                        SourceLocation Loc,
1620                        const CXXScopeSpec *SS) {
1621   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1622   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1623 }
1624 
1625 /// BuildDeclRefExpr - Build an expression that references a
1626 /// declaration that does not require a closure capture.
1627 ExprResult
1628 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1629                        const DeclarationNameInfo &NameInfo,
1630                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1631                        const TemplateArgumentListInfo *TemplateArgs) {
1632   if (getLangOpts().CUDA)
1633     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1634       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1635         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1636                            CalleeTarget = IdentifyCUDATarget(Callee);
1637         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1638           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1639             << CalleeTarget << D->getIdentifier() << CallerTarget;
1640           Diag(D->getLocation(), diag::note_previous_decl)
1641             << D->getIdentifier();
1642           return ExprError();
1643         }
1644       }
1645 
1646   bool refersToEnclosingScope =
1647     (CurContext != D->getDeclContext() &&
1648      D->getDeclContext()->isFunctionOrMethod()) ||
1649     (isa<VarDecl>(D) &&
1650      cast<VarDecl>(D)->isInitCapture());
1651 
1652   DeclRefExpr *E;
1653   if (isa<VarTemplateSpecializationDecl>(D)) {
1654     VarTemplateSpecializationDecl *VarSpec =
1655         cast<VarTemplateSpecializationDecl>(D);
1656 
1657     E = DeclRefExpr::Create(
1658         Context,
1659         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1660         VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope,
1661         NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs);
1662   } else {
1663     assert(!TemplateArgs && "No template arguments for non-variable"
1664                             " template specialization references");
1665     E = DeclRefExpr::Create(
1666         Context,
1667         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1668         SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD);
1669   }
1670 
1671   MarkDeclRefReferenced(E);
1672 
1673   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1674       Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1675     DiagnosticsEngine::Level Level =
1676       Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1677                                E->getLocStart());
1678     if (Level != DiagnosticsEngine::Ignored)
1679       recordUseOfEvaluatedWeak(E);
1680   }
1681 
1682   // Just in case we're building an illegal pointer-to-member.
1683   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1684   if (FD && FD->isBitField())
1685     E->setObjectKind(OK_BitField);
1686 
1687   return Owned(E);
1688 }
1689 
1690 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1691 /// possibly a list of template arguments.
1692 ///
1693 /// If this produces template arguments, it is permitted to call
1694 /// DecomposeTemplateName.
1695 ///
1696 /// This actually loses a lot of source location information for
1697 /// non-standard name kinds; we should consider preserving that in
1698 /// some way.
1699 void
1700 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1701                              TemplateArgumentListInfo &Buffer,
1702                              DeclarationNameInfo &NameInfo,
1703                              const TemplateArgumentListInfo *&TemplateArgs) {
1704   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1705     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1706     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1707 
1708     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1709                                        Id.TemplateId->NumArgs);
1710     translateTemplateArguments(TemplateArgsPtr, Buffer);
1711 
1712     TemplateName TName = Id.TemplateId->Template.get();
1713     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1714     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1715     TemplateArgs = &Buffer;
1716   } else {
1717     NameInfo = GetNameFromUnqualifiedId(Id);
1718     TemplateArgs = 0;
1719   }
1720 }
1721 
1722 /// Diagnose an empty lookup.
1723 ///
1724 /// \return false if new lookup candidates were found
1725 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1726                                CorrectionCandidateCallback &CCC,
1727                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1728                                ArrayRef<Expr *> Args) {
1729   DeclarationName Name = R.getLookupName();
1730 
1731   unsigned diagnostic = diag::err_undeclared_var_use;
1732   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1733   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1734       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1735       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1736     diagnostic = diag::err_undeclared_use;
1737     diagnostic_suggest = diag::err_undeclared_use_suggest;
1738   }
1739 
1740   // If the original lookup was an unqualified lookup, fake an
1741   // unqualified lookup.  This is useful when (for example) the
1742   // original lookup would not have found something because it was a
1743   // dependent name.
1744   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1745     ? CurContext : 0;
1746   while (DC) {
1747     if (isa<CXXRecordDecl>(DC)) {
1748       LookupQualifiedName(R, DC);
1749 
1750       if (!R.empty()) {
1751         // Don't give errors about ambiguities in this lookup.
1752         R.suppressDiagnostics();
1753 
1754         // During a default argument instantiation the CurContext points
1755         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1756         // function parameter list, hence add an explicit check.
1757         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1758                               ActiveTemplateInstantiations.back().Kind ==
1759             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1760         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1761         bool isInstance = CurMethod &&
1762                           CurMethod->isInstance() &&
1763                           DC == CurMethod->getParent() && !isDefaultArgument;
1764 
1765 
1766         // Give a code modification hint to insert 'this->'.
1767         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1768         // Actually quite difficult!
1769         if (getLangOpts().MSVCCompat)
1770           diagnostic = diag::warn_found_via_dependent_bases_lookup;
1771         if (isInstance) {
1772           Diag(R.getNameLoc(), diagnostic) << Name
1773             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1774           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1775               CallsUndergoingInstantiation.back()->getCallee());
1776 
1777           CXXMethodDecl *DepMethod;
1778           if (CurMethod->isDependentContext())
1779             DepMethod = CurMethod;
1780           else if (CurMethod->getTemplatedKind() ==
1781               FunctionDecl::TK_FunctionTemplateSpecialization)
1782             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1783                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1784           else
1785             DepMethod = cast<CXXMethodDecl>(
1786                 CurMethod->getInstantiatedFromMemberFunction());
1787           assert(DepMethod && "No template pattern found");
1788 
1789           QualType DepThisType = DepMethod->getThisType(Context);
1790           CheckCXXThisCapture(R.getNameLoc());
1791           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1792                                      R.getNameLoc(), DepThisType, false);
1793           TemplateArgumentListInfo TList;
1794           if (ULE->hasExplicitTemplateArgs())
1795             ULE->copyTemplateArgumentsInto(TList);
1796 
1797           CXXScopeSpec SS;
1798           SS.Adopt(ULE->getQualifierLoc());
1799           CXXDependentScopeMemberExpr *DepExpr =
1800               CXXDependentScopeMemberExpr::Create(
1801                   Context, DepThis, DepThisType, true, SourceLocation(),
1802                   SS.getWithLocInContext(Context),
1803                   ULE->getTemplateKeywordLoc(), 0,
1804                   R.getLookupNameInfo(),
1805                   ULE->hasExplicitTemplateArgs() ? &TList : 0);
1806           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1807         } else {
1808           Diag(R.getNameLoc(), diagnostic) << Name;
1809         }
1810 
1811         // Do we really want to note all of these?
1812         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1813           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1814 
1815         // Return true if we are inside a default argument instantiation
1816         // and the found name refers to an instance member function, otherwise
1817         // the function calling DiagnoseEmptyLookup will try to create an
1818         // implicit member call and this is wrong for default argument.
1819         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1820           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1821           return true;
1822         }
1823 
1824         // Tell the callee to try to recover.
1825         return false;
1826       }
1827 
1828       R.clear();
1829     }
1830 
1831     // In Microsoft mode, if we are performing lookup from within a friend
1832     // function definition declared at class scope then we must set
1833     // DC to the lexical parent to be able to search into the parent
1834     // class.
1835     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1836         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1837         DC->getLexicalParent()->isRecord())
1838       DC = DC->getLexicalParent();
1839     else
1840       DC = DC->getParent();
1841   }
1842 
1843   // We didn't find anything, so try to correct for a typo.
1844   TypoCorrection Corrected;
1845   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1846                                     S, &SS, CCC))) {
1847     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1848     bool DroppedSpecifier =
1849         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1850     R.setLookupName(Corrected.getCorrection());
1851 
1852     bool AcceptableWithRecovery = false;
1853     bool AcceptableWithoutRecovery = false;
1854     NamedDecl *ND = Corrected.getCorrectionDecl();
1855     if (ND) {
1856       if (Corrected.isOverloaded()) {
1857         OverloadCandidateSet OCS(R.getNameLoc());
1858         OverloadCandidateSet::iterator Best;
1859         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1860                                         CDEnd = Corrected.end();
1861              CD != CDEnd; ++CD) {
1862           if (FunctionTemplateDecl *FTD =
1863                    dyn_cast<FunctionTemplateDecl>(*CD))
1864             AddTemplateOverloadCandidate(
1865                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1866                 Args, OCS);
1867           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1868             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1869               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1870                                    Args, OCS);
1871         }
1872         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1873         case OR_Success:
1874           ND = Best->Function;
1875           Corrected.setCorrectionDecl(ND);
1876           break;
1877         default:
1878           // FIXME: Arbitrarily pick the first declaration for the note.
1879           Corrected.setCorrectionDecl(ND);
1880           break;
1881         }
1882       }
1883       R.addDecl(ND);
1884 
1885       AcceptableWithRecovery =
1886           isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1887       // FIXME: If we ended up with a typo for a type name or
1888       // Objective-C class name, we're in trouble because the parser
1889       // is in the wrong place to recover. Suggest the typo
1890       // correction, but don't make it a fix-it since we're not going
1891       // to recover well anyway.
1892       AcceptableWithoutRecovery =
1893           isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1894     } else {
1895       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1896       // because we aren't able to recover.
1897       AcceptableWithoutRecovery = true;
1898     }
1899 
1900     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1901       unsigned NoteID = (Corrected.getCorrectionDecl() &&
1902                          isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1903                             ? diag::note_implicit_param_decl
1904                             : diag::note_previous_decl;
1905       if (SS.isEmpty())
1906         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1907                      PDiag(NoteID), AcceptableWithRecovery);
1908       else
1909         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1910                                   << Name << computeDeclContext(SS, false)
1911                                   << DroppedSpecifier << SS.getRange(),
1912                      PDiag(NoteID), AcceptableWithRecovery);
1913 
1914       // Tell the callee whether to try to recover.
1915       return !AcceptableWithRecovery;
1916     }
1917   }
1918   R.clear();
1919 
1920   // Emit a special diagnostic for failed member lookups.
1921   // FIXME: computing the declaration context might fail here (?)
1922   if (!SS.isEmpty()) {
1923     Diag(R.getNameLoc(), diag::err_no_member)
1924       << Name << computeDeclContext(SS, false)
1925       << SS.getRange();
1926     return true;
1927   }
1928 
1929   // Give up, we can't recover.
1930   Diag(R.getNameLoc(), diagnostic) << Name;
1931   return true;
1932 }
1933 
1934 ExprResult Sema::ActOnIdExpression(Scope *S,
1935                                    CXXScopeSpec &SS,
1936                                    SourceLocation TemplateKWLoc,
1937                                    UnqualifiedId &Id,
1938                                    bool HasTrailingLParen,
1939                                    bool IsAddressOfOperand,
1940                                    CorrectionCandidateCallback *CCC,
1941                                    bool IsInlineAsmIdentifier) {
1942   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1943          "cannot be direct & operand and have a trailing lparen");
1944   if (SS.isInvalid())
1945     return ExprError();
1946 
1947   TemplateArgumentListInfo TemplateArgsBuffer;
1948 
1949   // Decompose the UnqualifiedId into the following data.
1950   DeclarationNameInfo NameInfo;
1951   const TemplateArgumentListInfo *TemplateArgs;
1952   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1953 
1954   DeclarationName Name = NameInfo.getName();
1955   IdentifierInfo *II = Name.getAsIdentifierInfo();
1956   SourceLocation NameLoc = NameInfo.getLoc();
1957 
1958   // C++ [temp.dep.expr]p3:
1959   //   An id-expression is type-dependent if it contains:
1960   //     -- an identifier that was declared with a dependent type,
1961   //        (note: handled after lookup)
1962   //     -- a template-id that is dependent,
1963   //        (note: handled in BuildTemplateIdExpr)
1964   //     -- a conversion-function-id that specifies a dependent type,
1965   //     -- a nested-name-specifier that contains a class-name that
1966   //        names a dependent type.
1967   // Determine whether this is a member of an unknown specialization;
1968   // we need to handle these differently.
1969   bool DependentID = false;
1970   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1971       Name.getCXXNameType()->isDependentType()) {
1972     DependentID = true;
1973   } else if (SS.isSet()) {
1974     if (DeclContext *DC = computeDeclContext(SS, false)) {
1975       if (RequireCompleteDeclContext(SS, DC))
1976         return ExprError();
1977     } else {
1978       DependentID = true;
1979     }
1980   }
1981 
1982   if (DependentID)
1983     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1984                                       IsAddressOfOperand, TemplateArgs);
1985 
1986   // Perform the required lookup.
1987   LookupResult R(*this, NameInfo,
1988                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1989                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1990   if (TemplateArgs) {
1991     // Lookup the template name again to correctly establish the context in
1992     // which it was found. This is really unfortunate as we already did the
1993     // lookup to determine that it was a template name in the first place. If
1994     // this becomes a performance hit, we can work harder to preserve those
1995     // results until we get here but it's likely not worth it.
1996     bool MemberOfUnknownSpecialization;
1997     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1998                        MemberOfUnknownSpecialization);
1999 
2000     if (MemberOfUnknownSpecialization ||
2001         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2002       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2003                                         IsAddressOfOperand, TemplateArgs);
2004   } else {
2005     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2006     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2007 
2008     // If the result might be in a dependent base class, this is a dependent
2009     // id-expression.
2010     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2011       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2012                                         IsAddressOfOperand, TemplateArgs);
2013 
2014     // If this reference is in an Objective-C method, then we need to do
2015     // some special Objective-C lookup, too.
2016     if (IvarLookupFollowUp) {
2017       ExprResult E(LookupInObjCMethod(R, S, II, true));
2018       if (E.isInvalid())
2019         return ExprError();
2020 
2021       if (Expr *Ex = E.takeAs<Expr>())
2022         return Owned(Ex);
2023     }
2024   }
2025 
2026   if (R.isAmbiguous())
2027     return ExprError();
2028 
2029   // Determine whether this name might be a candidate for
2030   // argument-dependent lookup.
2031   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2032 
2033   if (R.empty() && !ADL) {
2034 
2035     // Otherwise, this could be an implicitly declared function reference (legal
2036     // in C90, extension in C99, forbidden in C++).
2037     if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2038       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2039       if (D) R.addDecl(D);
2040     }
2041 
2042     // If this name wasn't predeclared and if this is not a function
2043     // call, diagnose the problem.
2044     if (R.empty()) {
2045       // In Microsoft mode, if we are inside a template class member function
2046       // whose parent class has dependent base classes, and we can't resolve
2047       // an unqualified identifier, then assume the identifier is a member of a
2048       // dependent base class.  The goal is to postpone name lookup to
2049       // instantiation time to be able to search into the type dependent base
2050       // classes.
2051       // FIXME: If we want 100% compatibility with MSVC, we will have delay all
2052       // unqualified name lookup.  Any name lookup during template parsing means
2053       // clang might find something that MSVC doesn't.  For now, we only handle
2054       // the common case of members of a dependent base class.
2055       if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2056         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2057         if (MD && MD->isInstance() && MD->getParent()->hasAnyDependentBases()) {
2058           QualType ThisType = MD->getThisType(Context);
2059           // Since the 'this' expression is synthesized, we don't need to
2060           // perform the double-lookup check.
2061           NamedDecl *FirstQualifierInScope = 0;
2062           return Owned(CXXDependentScopeMemberExpr::Create(
2063               Context, /*This=*/0, ThisType, /*IsArrow=*/true,
2064               /*Op=*/SourceLocation(), SS.getWithLocInContext(Context),
2065               TemplateKWLoc, FirstQualifierInScope, NameInfo, TemplateArgs));
2066         }
2067       }
2068 
2069       // Don't diagnose an empty lookup for inline assmebly.
2070       if (IsInlineAsmIdentifier)
2071         return ExprError();
2072 
2073       CorrectionCandidateCallback DefaultValidator;
2074       if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
2075         return ExprError();
2076 
2077       assert(!R.empty() &&
2078              "DiagnoseEmptyLookup returned false but added no results");
2079 
2080       // If we found an Objective-C instance variable, let
2081       // LookupInObjCMethod build the appropriate expression to
2082       // reference the ivar.
2083       if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2084         R.clear();
2085         ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2086         // In a hopelessly buggy code, Objective-C instance variable
2087         // lookup fails and no expression will be built to reference it.
2088         if (!E.isInvalid() && !E.get())
2089           return ExprError();
2090         return E;
2091       }
2092     }
2093   }
2094 
2095   // This is guaranteed from this point on.
2096   assert(!R.empty() || ADL);
2097 
2098   // Check whether this might be a C++ implicit instance member access.
2099   // C++ [class.mfct.non-static]p3:
2100   //   When an id-expression that is not part of a class member access
2101   //   syntax and not used to form a pointer to member is used in the
2102   //   body of a non-static member function of class X, if name lookup
2103   //   resolves the name in the id-expression to a non-static non-type
2104   //   member of some class C, the id-expression is transformed into a
2105   //   class member access expression using (*this) as the
2106   //   postfix-expression to the left of the . operator.
2107   //
2108   // But we don't actually need to do this for '&' operands if R
2109   // resolved to a function or overloaded function set, because the
2110   // expression is ill-formed if it actually works out to be a
2111   // non-static member function:
2112   //
2113   // C++ [expr.ref]p4:
2114   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2115   //   [t]he expression can be used only as the left-hand operand of a
2116   //   member function call.
2117   //
2118   // There are other safeguards against such uses, but it's important
2119   // to get this right here so that we don't end up making a
2120   // spuriously dependent expression if we're inside a dependent
2121   // instance method.
2122   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2123     bool MightBeImplicitMember;
2124     if (!IsAddressOfOperand)
2125       MightBeImplicitMember = true;
2126     else if (!SS.isEmpty())
2127       MightBeImplicitMember = false;
2128     else if (R.isOverloadedResult())
2129       MightBeImplicitMember = false;
2130     else if (R.isUnresolvableResult())
2131       MightBeImplicitMember = true;
2132     else
2133       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2134                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2135                               isa<MSPropertyDecl>(R.getFoundDecl());
2136 
2137     if (MightBeImplicitMember)
2138       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2139                                              R, TemplateArgs);
2140   }
2141 
2142   if (TemplateArgs || TemplateKWLoc.isValid()) {
2143 
2144     // In C++1y, if this is a variable template id, then check it
2145     // in BuildTemplateIdExpr().
2146     // The single lookup result must be a variable template declaration.
2147     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2148         Id.TemplateId->Kind == TNK_Var_template) {
2149       assert(R.getAsSingle<VarTemplateDecl>() &&
2150              "There should only be one declaration found.");
2151     }
2152 
2153     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2154   }
2155 
2156   return BuildDeclarationNameExpr(SS, R, ADL);
2157 }
2158 
2159 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2160 /// declaration name, generally during template instantiation.
2161 /// There's a large number of things which don't need to be done along
2162 /// this path.
2163 ExprResult
2164 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2165                                         const DeclarationNameInfo &NameInfo,
2166                                         bool IsAddressOfOperand) {
2167   DeclContext *DC = computeDeclContext(SS, false);
2168   if (!DC)
2169     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2170                                      NameInfo, /*TemplateArgs=*/0);
2171 
2172   if (RequireCompleteDeclContext(SS, DC))
2173     return ExprError();
2174 
2175   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2176   LookupQualifiedName(R, DC);
2177 
2178   if (R.isAmbiguous())
2179     return ExprError();
2180 
2181   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2182     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2183                                      NameInfo, /*TemplateArgs=*/0);
2184 
2185   if (R.empty()) {
2186     Diag(NameInfo.getLoc(), diag::err_no_member)
2187       << NameInfo.getName() << DC << SS.getRange();
2188     return ExprError();
2189   }
2190 
2191   // Defend against this resolving to an implicit member access. We usually
2192   // won't get here if this might be a legitimate a class member (we end up in
2193   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2194   // a pointer-to-member or in an unevaluated context in C++11.
2195   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2196     return BuildPossibleImplicitMemberExpr(SS,
2197                                            /*TemplateKWLoc=*/SourceLocation(),
2198                                            R, /*TemplateArgs=*/0);
2199 
2200   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2201 }
2202 
2203 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2204 /// detected that we're currently inside an ObjC method.  Perform some
2205 /// additional lookup.
2206 ///
2207 /// Ideally, most of this would be done by lookup, but there's
2208 /// actually quite a lot of extra work involved.
2209 ///
2210 /// Returns a null sentinel to indicate trivial success.
2211 ExprResult
2212 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2213                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2214   SourceLocation Loc = Lookup.getNameLoc();
2215   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2216 
2217   // Check for error condition which is already reported.
2218   if (!CurMethod)
2219     return ExprError();
2220 
2221   // There are two cases to handle here.  1) scoped lookup could have failed,
2222   // in which case we should look for an ivar.  2) scoped lookup could have
2223   // found a decl, but that decl is outside the current instance method (i.e.
2224   // a global variable).  In these two cases, we do a lookup for an ivar with
2225   // this name, if the lookup sucedes, we replace it our current decl.
2226 
2227   // If we're in a class method, we don't normally want to look for
2228   // ivars.  But if we don't find anything else, and there's an
2229   // ivar, that's an error.
2230   bool IsClassMethod = CurMethod->isClassMethod();
2231 
2232   bool LookForIvars;
2233   if (Lookup.empty())
2234     LookForIvars = true;
2235   else if (IsClassMethod)
2236     LookForIvars = false;
2237   else
2238     LookForIvars = (Lookup.isSingleResult() &&
2239                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2240   ObjCInterfaceDecl *IFace = 0;
2241   if (LookForIvars) {
2242     IFace = CurMethod->getClassInterface();
2243     ObjCInterfaceDecl *ClassDeclared;
2244     ObjCIvarDecl *IV = 0;
2245     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2246       // Diagnose using an ivar in a class method.
2247       if (IsClassMethod)
2248         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2249                          << IV->getDeclName());
2250 
2251       // If we're referencing an invalid decl, just return this as a silent
2252       // error node.  The error diagnostic was already emitted on the decl.
2253       if (IV->isInvalidDecl())
2254         return ExprError();
2255 
2256       // Check if referencing a field with __attribute__((deprecated)).
2257       if (DiagnoseUseOfDecl(IV, Loc))
2258         return ExprError();
2259 
2260       // Diagnose the use of an ivar outside of the declaring class.
2261       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2262           !declaresSameEntity(ClassDeclared, IFace) &&
2263           !getLangOpts().DebuggerSupport)
2264         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2265 
2266       // FIXME: This should use a new expr for a direct reference, don't
2267       // turn this into Self->ivar, just return a BareIVarExpr or something.
2268       IdentifierInfo &II = Context.Idents.get("self");
2269       UnqualifiedId SelfName;
2270       SelfName.setIdentifier(&II, SourceLocation());
2271       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2272       CXXScopeSpec SelfScopeSpec;
2273       SourceLocation TemplateKWLoc;
2274       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2275                                               SelfName, false, false);
2276       if (SelfExpr.isInvalid())
2277         return ExprError();
2278 
2279       SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2280       if (SelfExpr.isInvalid())
2281         return ExprError();
2282 
2283       MarkAnyDeclReferenced(Loc, IV, true);
2284 
2285       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2286       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2287           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2288         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2289 
2290       ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2291                                                               Loc, IV->getLocation(),
2292                                                               SelfExpr.take(),
2293                                                               true, true);
2294 
2295       if (getLangOpts().ObjCAutoRefCount) {
2296         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2297           DiagnosticsEngine::Level Level =
2298             Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2299           if (Level != DiagnosticsEngine::Ignored)
2300             recordUseOfEvaluatedWeak(Result);
2301         }
2302         if (CurContext->isClosure())
2303           Diag(Loc, diag::warn_implicitly_retains_self)
2304             << FixItHint::CreateInsertion(Loc, "self->");
2305       }
2306 
2307       return Owned(Result);
2308     }
2309   } else if (CurMethod->isInstanceMethod()) {
2310     // We should warn if a local variable hides an ivar.
2311     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2312       ObjCInterfaceDecl *ClassDeclared;
2313       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2314         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2315             declaresSameEntity(IFace, ClassDeclared))
2316           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2317       }
2318     }
2319   } else if (Lookup.isSingleResult() &&
2320              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2321     // If accessing a stand-alone ivar in a class method, this is an error.
2322     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2323       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2324                        << IV->getDeclName());
2325   }
2326 
2327   if (Lookup.empty() && II && AllowBuiltinCreation) {
2328     // FIXME. Consolidate this with similar code in LookupName.
2329     if (unsigned BuiltinID = II->getBuiltinID()) {
2330       if (!(getLangOpts().CPlusPlus &&
2331             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2332         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2333                                            S, Lookup.isForRedeclaration(),
2334                                            Lookup.getNameLoc());
2335         if (D) Lookup.addDecl(D);
2336       }
2337     }
2338   }
2339   // Sentinel value saying that we didn't do anything special.
2340   return Owned((Expr*) 0);
2341 }
2342 
2343 /// \brief Cast a base object to a member's actual type.
2344 ///
2345 /// Logically this happens in three phases:
2346 ///
2347 /// * First we cast from the base type to the naming class.
2348 ///   The naming class is the class into which we were looking
2349 ///   when we found the member;  it's the qualifier type if a
2350 ///   qualifier was provided, and otherwise it's the base type.
2351 ///
2352 /// * Next we cast from the naming class to the declaring class.
2353 ///   If the member we found was brought into a class's scope by
2354 ///   a using declaration, this is that class;  otherwise it's
2355 ///   the class declaring the member.
2356 ///
2357 /// * Finally we cast from the declaring class to the "true"
2358 ///   declaring class of the member.  This conversion does not
2359 ///   obey access control.
2360 ExprResult
2361 Sema::PerformObjectMemberConversion(Expr *From,
2362                                     NestedNameSpecifier *Qualifier,
2363                                     NamedDecl *FoundDecl,
2364                                     NamedDecl *Member) {
2365   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2366   if (!RD)
2367     return Owned(From);
2368 
2369   QualType DestRecordType;
2370   QualType DestType;
2371   QualType FromRecordType;
2372   QualType FromType = From->getType();
2373   bool PointerConversions = false;
2374   if (isa<FieldDecl>(Member)) {
2375     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2376 
2377     if (FromType->getAs<PointerType>()) {
2378       DestType = Context.getPointerType(DestRecordType);
2379       FromRecordType = FromType->getPointeeType();
2380       PointerConversions = true;
2381     } else {
2382       DestType = DestRecordType;
2383       FromRecordType = FromType;
2384     }
2385   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2386     if (Method->isStatic())
2387       return Owned(From);
2388 
2389     DestType = Method->getThisType(Context);
2390     DestRecordType = DestType->getPointeeType();
2391 
2392     if (FromType->getAs<PointerType>()) {
2393       FromRecordType = FromType->getPointeeType();
2394       PointerConversions = true;
2395     } else {
2396       FromRecordType = FromType;
2397       DestType = DestRecordType;
2398     }
2399   } else {
2400     // No conversion necessary.
2401     return Owned(From);
2402   }
2403 
2404   if (DestType->isDependentType() || FromType->isDependentType())
2405     return Owned(From);
2406 
2407   // If the unqualified types are the same, no conversion is necessary.
2408   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2409     return Owned(From);
2410 
2411   SourceRange FromRange = From->getSourceRange();
2412   SourceLocation FromLoc = FromRange.getBegin();
2413 
2414   ExprValueKind VK = From->getValueKind();
2415 
2416   // C++ [class.member.lookup]p8:
2417   //   [...] Ambiguities can often be resolved by qualifying a name with its
2418   //   class name.
2419   //
2420   // If the member was a qualified name and the qualified referred to a
2421   // specific base subobject type, we'll cast to that intermediate type
2422   // first and then to the object in which the member is declared. That allows
2423   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2424   //
2425   //   class Base { public: int x; };
2426   //   class Derived1 : public Base { };
2427   //   class Derived2 : public Base { };
2428   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2429   //
2430   //   void VeryDerived::f() {
2431   //     x = 17; // error: ambiguous base subobjects
2432   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2433   //   }
2434   if (Qualifier && Qualifier->getAsType()) {
2435     QualType QType = QualType(Qualifier->getAsType(), 0);
2436     assert(QType->isRecordType() && "lookup done with non-record type");
2437 
2438     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2439 
2440     // In C++98, the qualifier type doesn't actually have to be a base
2441     // type of the object type, in which case we just ignore it.
2442     // Otherwise build the appropriate casts.
2443     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2444       CXXCastPath BasePath;
2445       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2446                                        FromLoc, FromRange, &BasePath))
2447         return ExprError();
2448 
2449       if (PointerConversions)
2450         QType = Context.getPointerType(QType);
2451       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2452                                VK, &BasePath).take();
2453 
2454       FromType = QType;
2455       FromRecordType = QRecordType;
2456 
2457       // If the qualifier type was the same as the destination type,
2458       // we're done.
2459       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2460         return Owned(From);
2461     }
2462   }
2463 
2464   bool IgnoreAccess = false;
2465 
2466   // If we actually found the member through a using declaration, cast
2467   // down to the using declaration's type.
2468   //
2469   // Pointer equality is fine here because only one declaration of a
2470   // class ever has member declarations.
2471   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2472     assert(isa<UsingShadowDecl>(FoundDecl));
2473     QualType URecordType = Context.getTypeDeclType(
2474                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2475 
2476     // We only need to do this if the naming-class to declaring-class
2477     // conversion is non-trivial.
2478     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2479       assert(IsDerivedFrom(FromRecordType, URecordType));
2480       CXXCastPath BasePath;
2481       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2482                                        FromLoc, FromRange, &BasePath))
2483         return ExprError();
2484 
2485       QualType UType = URecordType;
2486       if (PointerConversions)
2487         UType = Context.getPointerType(UType);
2488       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2489                                VK, &BasePath).take();
2490       FromType = UType;
2491       FromRecordType = URecordType;
2492     }
2493 
2494     // We don't do access control for the conversion from the
2495     // declaring class to the true declaring class.
2496     IgnoreAccess = true;
2497   }
2498 
2499   CXXCastPath BasePath;
2500   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2501                                    FromLoc, FromRange, &BasePath,
2502                                    IgnoreAccess))
2503     return ExprError();
2504 
2505   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2506                            VK, &BasePath);
2507 }
2508 
2509 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2510                                       const LookupResult &R,
2511                                       bool HasTrailingLParen) {
2512   // Only when used directly as the postfix-expression of a call.
2513   if (!HasTrailingLParen)
2514     return false;
2515 
2516   // Never if a scope specifier was provided.
2517   if (SS.isSet())
2518     return false;
2519 
2520   // Only in C++ or ObjC++.
2521   if (!getLangOpts().CPlusPlus)
2522     return false;
2523 
2524   // Turn off ADL when we find certain kinds of declarations during
2525   // normal lookup:
2526   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2527     NamedDecl *D = *I;
2528 
2529     // C++0x [basic.lookup.argdep]p3:
2530     //     -- a declaration of a class member
2531     // Since using decls preserve this property, we check this on the
2532     // original decl.
2533     if (D->isCXXClassMember())
2534       return false;
2535 
2536     // C++0x [basic.lookup.argdep]p3:
2537     //     -- a block-scope function declaration that is not a
2538     //        using-declaration
2539     // NOTE: we also trigger this for function templates (in fact, we
2540     // don't check the decl type at all, since all other decl types
2541     // turn off ADL anyway).
2542     if (isa<UsingShadowDecl>(D))
2543       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2544     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2545       return false;
2546 
2547     // C++0x [basic.lookup.argdep]p3:
2548     //     -- a declaration that is neither a function or a function
2549     //        template
2550     // And also for builtin functions.
2551     if (isa<FunctionDecl>(D)) {
2552       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2553 
2554       // But also builtin functions.
2555       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2556         return false;
2557     } else if (!isa<FunctionTemplateDecl>(D))
2558       return false;
2559   }
2560 
2561   return true;
2562 }
2563 
2564 
2565 /// Diagnoses obvious problems with the use of the given declaration
2566 /// as an expression.  This is only actually called for lookups that
2567 /// were not overloaded, and it doesn't promise that the declaration
2568 /// will in fact be used.
2569 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2570   if (isa<TypedefNameDecl>(D)) {
2571     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2572     return true;
2573   }
2574 
2575   if (isa<ObjCInterfaceDecl>(D)) {
2576     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2577     return true;
2578   }
2579 
2580   if (isa<NamespaceDecl>(D)) {
2581     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2582     return true;
2583   }
2584 
2585   return false;
2586 }
2587 
2588 ExprResult
2589 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2590                                LookupResult &R,
2591                                bool NeedsADL) {
2592   // If this is a single, fully-resolved result and we don't need ADL,
2593   // just build an ordinary singleton decl ref.
2594   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2595     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2596                                     R.getRepresentativeDecl());
2597 
2598   // We only need to check the declaration if there's exactly one
2599   // result, because in the overloaded case the results can only be
2600   // functions and function templates.
2601   if (R.isSingleResult() &&
2602       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2603     return ExprError();
2604 
2605   // Otherwise, just build an unresolved lookup expression.  Suppress
2606   // any lookup-related diagnostics; we'll hash these out later, when
2607   // we've picked a target.
2608   R.suppressDiagnostics();
2609 
2610   UnresolvedLookupExpr *ULE
2611     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2612                                    SS.getWithLocInContext(Context),
2613                                    R.getLookupNameInfo(),
2614                                    NeedsADL, R.isOverloadedResult(),
2615                                    R.begin(), R.end());
2616 
2617   return Owned(ULE);
2618 }
2619 
2620 /// \brief Complete semantic analysis for a reference to the given declaration.
2621 ExprResult Sema::BuildDeclarationNameExpr(
2622     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2623     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) {
2624   assert(D && "Cannot refer to a NULL declaration");
2625   assert(!isa<FunctionTemplateDecl>(D) &&
2626          "Cannot refer unambiguously to a function template");
2627 
2628   SourceLocation Loc = NameInfo.getLoc();
2629   if (CheckDeclInExpr(*this, Loc, D))
2630     return ExprError();
2631 
2632   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2633     // Specifically diagnose references to class templates that are missing
2634     // a template argument list.
2635     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2636                                            << Template << SS.getRange();
2637     Diag(Template->getLocation(), diag::note_template_decl_here);
2638     return ExprError();
2639   }
2640 
2641   // Make sure that we're referring to a value.
2642   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2643   if (!VD) {
2644     Diag(Loc, diag::err_ref_non_value)
2645       << D << SS.getRange();
2646     Diag(D->getLocation(), diag::note_declared_at);
2647     return ExprError();
2648   }
2649 
2650   // Check whether this declaration can be used. Note that we suppress
2651   // this check when we're going to perform argument-dependent lookup
2652   // on this function name, because this might not be the function
2653   // that overload resolution actually selects.
2654   if (DiagnoseUseOfDecl(VD, Loc))
2655     return ExprError();
2656 
2657   // Only create DeclRefExpr's for valid Decl's.
2658   if (VD->isInvalidDecl())
2659     return ExprError();
2660 
2661   // Handle members of anonymous structs and unions.  If we got here,
2662   // and the reference is to a class member indirect field, then this
2663   // must be the subject of a pointer-to-member expression.
2664   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2665     if (!indirectField->isCXXClassMember())
2666       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2667                                                       indirectField);
2668 
2669   {
2670     QualType type = VD->getType();
2671     ExprValueKind valueKind = VK_RValue;
2672 
2673     switch (D->getKind()) {
2674     // Ignore all the non-ValueDecl kinds.
2675 #define ABSTRACT_DECL(kind)
2676 #define VALUE(type, base)
2677 #define DECL(type, base) \
2678     case Decl::type:
2679 #include "clang/AST/DeclNodes.inc"
2680       llvm_unreachable("invalid value decl kind");
2681 
2682     // These shouldn't make it here.
2683     case Decl::ObjCAtDefsField:
2684     case Decl::ObjCIvar:
2685       llvm_unreachable("forming non-member reference to ivar?");
2686 
2687     // Enum constants are always r-values and never references.
2688     // Unresolved using declarations are dependent.
2689     case Decl::EnumConstant:
2690     case Decl::UnresolvedUsingValue:
2691       valueKind = VK_RValue;
2692       break;
2693 
2694     // Fields and indirect fields that got here must be for
2695     // pointer-to-member expressions; we just call them l-values for
2696     // internal consistency, because this subexpression doesn't really
2697     // exist in the high-level semantics.
2698     case Decl::Field:
2699     case Decl::IndirectField:
2700       assert(getLangOpts().CPlusPlus &&
2701              "building reference to field in C?");
2702 
2703       // These can't have reference type in well-formed programs, but
2704       // for internal consistency we do this anyway.
2705       type = type.getNonReferenceType();
2706       valueKind = VK_LValue;
2707       break;
2708 
2709     // Non-type template parameters are either l-values or r-values
2710     // depending on the type.
2711     case Decl::NonTypeTemplateParm: {
2712       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2713         type = reftype->getPointeeType();
2714         valueKind = VK_LValue; // even if the parameter is an r-value reference
2715         break;
2716       }
2717 
2718       // For non-references, we need to strip qualifiers just in case
2719       // the template parameter was declared as 'const int' or whatever.
2720       valueKind = VK_RValue;
2721       type = type.getUnqualifiedType();
2722       break;
2723     }
2724 
2725     case Decl::Var:
2726     case Decl::VarTemplateSpecialization:
2727     case Decl::VarTemplatePartialSpecialization:
2728       // In C, "extern void blah;" is valid and is an r-value.
2729       if (!getLangOpts().CPlusPlus &&
2730           !type.hasQualifiers() &&
2731           type->isVoidType()) {
2732         valueKind = VK_RValue;
2733         break;
2734       }
2735       // fallthrough
2736 
2737     case Decl::ImplicitParam:
2738     case Decl::ParmVar: {
2739       // These are always l-values.
2740       valueKind = VK_LValue;
2741       type = type.getNonReferenceType();
2742 
2743       // FIXME: Does the addition of const really only apply in
2744       // potentially-evaluated contexts? Since the variable isn't actually
2745       // captured in an unevaluated context, it seems that the answer is no.
2746       if (!isUnevaluatedContext()) {
2747         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2748         if (!CapturedType.isNull())
2749           type = CapturedType;
2750       }
2751 
2752       break;
2753     }
2754 
2755     case Decl::Function: {
2756       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2757         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2758           type = Context.BuiltinFnTy;
2759           valueKind = VK_RValue;
2760           break;
2761         }
2762       }
2763 
2764       const FunctionType *fty = type->castAs<FunctionType>();
2765 
2766       // If we're referring to a function with an __unknown_anytype
2767       // result type, make the entire expression __unknown_anytype.
2768       if (fty->getReturnType() == Context.UnknownAnyTy) {
2769         type = Context.UnknownAnyTy;
2770         valueKind = VK_RValue;
2771         break;
2772       }
2773 
2774       // Functions are l-values in C++.
2775       if (getLangOpts().CPlusPlus) {
2776         valueKind = VK_LValue;
2777         break;
2778       }
2779 
2780       // C99 DR 316 says that, if a function type comes from a
2781       // function definition (without a prototype), that type is only
2782       // used for checking compatibility. Therefore, when referencing
2783       // the function, we pretend that we don't have the full function
2784       // type.
2785       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2786           isa<FunctionProtoType>(fty))
2787         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2788                                               fty->getExtInfo());
2789 
2790       // Functions are r-values in C.
2791       valueKind = VK_RValue;
2792       break;
2793     }
2794 
2795     case Decl::MSProperty:
2796       valueKind = VK_LValue;
2797       break;
2798 
2799     case Decl::CXXMethod:
2800       // If we're referring to a method with an __unknown_anytype
2801       // result type, make the entire expression __unknown_anytype.
2802       // This should only be possible with a type written directly.
2803       if (const FunctionProtoType *proto
2804             = dyn_cast<FunctionProtoType>(VD->getType()))
2805         if (proto->getReturnType() == Context.UnknownAnyTy) {
2806           type = Context.UnknownAnyTy;
2807           valueKind = VK_RValue;
2808           break;
2809         }
2810 
2811       // C++ methods are l-values if static, r-values if non-static.
2812       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2813         valueKind = VK_LValue;
2814         break;
2815       }
2816       // fallthrough
2817 
2818     case Decl::CXXConversion:
2819     case Decl::CXXDestructor:
2820     case Decl::CXXConstructor:
2821       valueKind = VK_RValue;
2822       break;
2823     }
2824 
2825     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2826                             TemplateArgs);
2827   }
2828 }
2829 
2830 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2831                                      PredefinedExpr::IdentType IT) {
2832   // Pick the current block, lambda, captured statement or function.
2833   Decl *currentDecl = 0;
2834   if (const BlockScopeInfo *BSI = getCurBlock())
2835     currentDecl = BSI->TheDecl;
2836   else if (const LambdaScopeInfo *LSI = getCurLambda())
2837     currentDecl = LSI->CallOperator;
2838   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
2839     currentDecl = CSI->TheCapturedDecl;
2840   else
2841     currentDecl = getCurFunctionOrMethodDecl();
2842 
2843   if (!currentDecl) {
2844     Diag(Loc, diag::ext_predef_outside_function);
2845     currentDecl = Context.getTranslationUnitDecl();
2846   }
2847 
2848   QualType ResTy;
2849   if (cast<DeclContext>(currentDecl)->isDependentContext())
2850     ResTy = Context.DependentTy;
2851   else {
2852     // Pre-defined identifiers are of type char[x], where x is the length of
2853     // the string.
2854     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2855 
2856     llvm::APInt LengthI(32, Length + 1);
2857     if (IT == PredefinedExpr::LFunction)
2858       ResTy = Context.WideCharTy.withConst();
2859     else
2860       ResTy = Context.CharTy.withConst();
2861     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2862   }
2863 
2864   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2865 }
2866 
2867 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2868   PredefinedExpr::IdentType IT;
2869 
2870   switch (Kind) {
2871   default: llvm_unreachable("Unknown simple primary expr!");
2872   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2873   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2874   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
2875   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2876   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2877   }
2878 
2879   return BuildPredefinedExpr(Loc, IT);
2880 }
2881 
2882 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2883   SmallString<16> CharBuffer;
2884   bool Invalid = false;
2885   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2886   if (Invalid)
2887     return ExprError();
2888 
2889   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2890                             PP, Tok.getKind());
2891   if (Literal.hadError())
2892     return ExprError();
2893 
2894   QualType Ty;
2895   if (Literal.isWide())
2896     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
2897   else if (Literal.isUTF16())
2898     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2899   else if (Literal.isUTF32())
2900     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2901   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2902     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2903   else
2904     Ty = Context.CharTy;  // 'x' -> char in C++
2905 
2906   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2907   if (Literal.isWide())
2908     Kind = CharacterLiteral::Wide;
2909   else if (Literal.isUTF16())
2910     Kind = CharacterLiteral::UTF16;
2911   else if (Literal.isUTF32())
2912     Kind = CharacterLiteral::UTF32;
2913 
2914   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2915                                              Tok.getLocation());
2916 
2917   if (Literal.getUDSuffix().empty())
2918     return Owned(Lit);
2919 
2920   // We're building a user-defined literal.
2921   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2922   SourceLocation UDSuffixLoc =
2923     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2924 
2925   // Make sure we're allowed user-defined literals here.
2926   if (!UDLScope)
2927     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2928 
2929   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2930   //   operator "" X (ch)
2931   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2932                                         Lit, Tok.getLocation());
2933 }
2934 
2935 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2936   unsigned IntSize = Context.getTargetInfo().getIntWidth();
2937   return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2938                                       Context.IntTy, Loc));
2939 }
2940 
2941 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2942                                   QualType Ty, SourceLocation Loc) {
2943   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2944 
2945   using llvm::APFloat;
2946   APFloat Val(Format);
2947 
2948   APFloat::opStatus result = Literal.GetFloatValue(Val);
2949 
2950   // Overflow is always an error, but underflow is only an error if
2951   // we underflowed to zero (APFloat reports denormals as underflow).
2952   if ((result & APFloat::opOverflow) ||
2953       ((result & APFloat::opUnderflow) && Val.isZero())) {
2954     unsigned diagnostic;
2955     SmallString<20> buffer;
2956     if (result & APFloat::opOverflow) {
2957       diagnostic = diag::warn_float_overflow;
2958       APFloat::getLargest(Format).toString(buffer);
2959     } else {
2960       diagnostic = diag::warn_float_underflow;
2961       APFloat::getSmallest(Format).toString(buffer);
2962     }
2963 
2964     S.Diag(Loc, diagnostic)
2965       << Ty
2966       << StringRef(buffer.data(), buffer.size());
2967   }
2968 
2969   bool isExact = (result == APFloat::opOK);
2970   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2971 }
2972 
2973 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
2974   // Fast path for a single digit (which is quite common).  A single digit
2975   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
2976   if (Tok.getLength() == 1) {
2977     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2978     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
2979   }
2980 
2981   SmallString<128> SpellingBuffer;
2982   // NumericLiteralParser wants to overread by one character.  Add padding to
2983   // the buffer in case the token is copied to the buffer.  If getSpelling()
2984   // returns a StringRef to the memory buffer, it should have a null char at
2985   // the EOF, so it is also safe.
2986   SpellingBuffer.resize(Tok.getLength() + 1);
2987 
2988   // Get the spelling of the token, which eliminates trigraphs, etc.
2989   bool Invalid = false;
2990   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
2991   if (Invalid)
2992     return ExprError();
2993 
2994   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
2995   if (Literal.hadError)
2996     return ExprError();
2997 
2998   if (Literal.hasUDSuffix()) {
2999     // We're building a user-defined literal.
3000     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3001     SourceLocation UDSuffixLoc =
3002       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3003 
3004     // Make sure we're allowed user-defined literals here.
3005     if (!UDLScope)
3006       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3007 
3008     QualType CookedTy;
3009     if (Literal.isFloatingLiteral()) {
3010       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3011       // long double, the literal is treated as a call of the form
3012       //   operator "" X (f L)
3013       CookedTy = Context.LongDoubleTy;
3014     } else {
3015       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3016       // unsigned long long, the literal is treated as a call of the form
3017       //   operator "" X (n ULL)
3018       CookedTy = Context.UnsignedLongLongTy;
3019     }
3020 
3021     DeclarationName OpName =
3022       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3023     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3024     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3025 
3026     SourceLocation TokLoc = Tok.getLocation();
3027 
3028     // Perform literal operator lookup to determine if we're building a raw
3029     // literal or a cooked one.
3030     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3031     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3032                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3033                                   /*AllowStringTemplate*/false)) {
3034     case LOLR_Error:
3035       return ExprError();
3036 
3037     case LOLR_Cooked: {
3038       Expr *Lit;
3039       if (Literal.isFloatingLiteral()) {
3040         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3041       } else {
3042         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3043         if (Literal.GetIntegerValue(ResultVal))
3044           Diag(Tok.getLocation(), diag::err_integer_too_large);
3045         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3046                                      Tok.getLocation());
3047       }
3048       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3049     }
3050 
3051     case LOLR_Raw: {
3052       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3053       // literal is treated as a call of the form
3054       //   operator "" X ("n")
3055       unsigned Length = Literal.getUDSuffixOffset();
3056       QualType StrTy = Context.getConstantArrayType(
3057           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3058           ArrayType::Normal, 0);
3059       Expr *Lit = StringLiteral::Create(
3060           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3061           /*Pascal*/false, StrTy, &TokLoc, 1);
3062       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3063     }
3064 
3065     case LOLR_Template: {
3066       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3067       // template), L is treated as a call fo the form
3068       //   operator "" X <'c1', 'c2', ... 'ck'>()
3069       // where n is the source character sequence c1 c2 ... ck.
3070       TemplateArgumentListInfo ExplicitArgs;
3071       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3072       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3073       llvm::APSInt Value(CharBits, CharIsUnsigned);
3074       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3075         Value = TokSpelling[I];
3076         TemplateArgument Arg(Context, Value, Context.CharTy);
3077         TemplateArgumentLocInfo ArgInfo;
3078         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3079       }
3080       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3081                                       &ExplicitArgs);
3082     }
3083     case LOLR_StringTemplate:
3084       llvm_unreachable("unexpected literal operator lookup result");
3085     }
3086   }
3087 
3088   Expr *Res;
3089 
3090   if (Literal.isFloatingLiteral()) {
3091     QualType Ty;
3092     if (Literal.isFloat)
3093       Ty = Context.FloatTy;
3094     else if (!Literal.isLong)
3095       Ty = Context.DoubleTy;
3096     else
3097       Ty = Context.LongDoubleTy;
3098 
3099     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3100 
3101     if (Ty == Context.DoubleTy) {
3102       if (getLangOpts().SinglePrecisionConstants) {
3103         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
3104       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
3105         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3106         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
3107       }
3108     }
3109   } else if (!Literal.isIntegerLiteral()) {
3110     return ExprError();
3111   } else {
3112     QualType Ty;
3113 
3114     // 'long long' is a C99 or C++11 feature.
3115     if (!getLangOpts().C99 && Literal.isLongLong) {
3116       if (getLangOpts().CPlusPlus)
3117         Diag(Tok.getLocation(),
3118              getLangOpts().CPlusPlus11 ?
3119              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3120       else
3121         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3122     }
3123 
3124     // Get the value in the widest-possible width.
3125     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3126     // The microsoft literal suffix extensions support 128-bit literals, which
3127     // may be wider than [u]intmax_t.
3128     // FIXME: Actually, they don't. We seem to have accidentally invented the
3129     //        i128 suffix.
3130     if (Literal.isMicrosoftInteger && MaxWidth < 128 &&
3131         PP.getTargetInfo().hasInt128Type())
3132       MaxWidth = 128;
3133     llvm::APInt ResultVal(MaxWidth, 0);
3134 
3135     if (Literal.GetIntegerValue(ResultVal)) {
3136       // If this value didn't fit into uintmax_t, error and force to ull.
3137       Diag(Tok.getLocation(), diag::err_integer_too_large);
3138       Ty = Context.UnsignedLongLongTy;
3139       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3140              "long long is not intmax_t?");
3141     } else {
3142       // If this value fits into a ULL, try to figure out what else it fits into
3143       // according to the rules of C99 6.4.4.1p5.
3144 
3145       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3146       // be an unsigned int.
3147       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3148 
3149       // Check from smallest to largest, picking the smallest type we can.
3150       unsigned Width = 0;
3151       if (!Literal.isLong && !Literal.isLongLong) {
3152         // Are int/unsigned possibilities?
3153         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3154 
3155         // Does it fit in a unsigned int?
3156         if (ResultVal.isIntN(IntSize)) {
3157           // Does it fit in a signed int?
3158           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3159             Ty = Context.IntTy;
3160           else if (AllowUnsigned)
3161             Ty = Context.UnsignedIntTy;
3162           Width = IntSize;
3163         }
3164       }
3165 
3166       // Are long/unsigned long possibilities?
3167       if (Ty.isNull() && !Literal.isLongLong) {
3168         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3169 
3170         // Does it fit in a unsigned long?
3171         if (ResultVal.isIntN(LongSize)) {
3172           // Does it fit in a signed long?
3173           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3174             Ty = Context.LongTy;
3175           else if (AllowUnsigned)
3176             Ty = Context.UnsignedLongTy;
3177           Width = LongSize;
3178         }
3179       }
3180 
3181       // Check long long if needed.
3182       if (Ty.isNull()) {
3183         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3184 
3185         // Does it fit in a unsigned long long?
3186         if (ResultVal.isIntN(LongLongSize)) {
3187           // Does it fit in a signed long long?
3188           // To be compatible with MSVC, hex integer literals ending with the
3189           // LL or i64 suffix are always signed in Microsoft mode.
3190           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3191               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3192             Ty = Context.LongLongTy;
3193           else if (AllowUnsigned)
3194             Ty = Context.UnsignedLongLongTy;
3195           Width = LongLongSize;
3196         }
3197       }
3198 
3199       // If it doesn't fit in unsigned long long, and we're using Microsoft
3200       // extensions, then its a 128-bit integer literal.
3201       if (Ty.isNull() && Literal.isMicrosoftInteger &&
3202           PP.getTargetInfo().hasInt128Type()) {
3203         if (Literal.isUnsigned)
3204           Ty = Context.UnsignedInt128Ty;
3205         else
3206           Ty = Context.Int128Ty;
3207         Width = 128;
3208       }
3209 
3210       // If we still couldn't decide a type, we probably have something that
3211       // does not fit in a signed long long, but has no U suffix.
3212       if (Ty.isNull()) {
3213         Diag(Tok.getLocation(), diag::ext_integer_too_large_for_signed);
3214         Ty = Context.UnsignedLongLongTy;
3215         Width = Context.getTargetInfo().getLongLongWidth();
3216       }
3217 
3218       if (ResultVal.getBitWidth() != Width)
3219         ResultVal = ResultVal.trunc(Width);
3220     }
3221     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3222   }
3223 
3224   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3225   if (Literal.isImaginary)
3226     Res = new (Context) ImaginaryLiteral(Res,
3227                                         Context.getComplexType(Res->getType()));
3228 
3229   return Owned(Res);
3230 }
3231 
3232 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3233   assert((E != 0) && "ActOnParenExpr() missing expr");
3234   return Owned(new (Context) ParenExpr(L, R, E));
3235 }
3236 
3237 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3238                                          SourceLocation Loc,
3239                                          SourceRange ArgRange) {
3240   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3241   // scalar or vector data type argument..."
3242   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3243   // type (C99 6.2.5p18) or void.
3244   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3245     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3246       << T << ArgRange;
3247     return true;
3248   }
3249 
3250   assert((T->isVoidType() || !T->isIncompleteType()) &&
3251          "Scalar types should always be complete");
3252   return false;
3253 }
3254 
3255 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3256                                            SourceLocation Loc,
3257                                            SourceRange ArgRange,
3258                                            UnaryExprOrTypeTrait TraitKind) {
3259   // Invalid types must be hard errors for SFINAE in C++.
3260   if (S.LangOpts.CPlusPlus)
3261     return true;
3262 
3263   // C99 6.5.3.4p1:
3264   if (T->isFunctionType() &&
3265       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3266     // sizeof(function)/alignof(function) is allowed as an extension.
3267     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3268       << TraitKind << ArgRange;
3269     return false;
3270   }
3271 
3272   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3273   // this is an error (OpenCL v1.1 s6.3.k)
3274   if (T->isVoidType()) {
3275     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3276                                         : diag::ext_sizeof_alignof_void_type;
3277     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3278     return false;
3279   }
3280 
3281   return true;
3282 }
3283 
3284 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3285                                              SourceLocation Loc,
3286                                              SourceRange ArgRange,
3287                                              UnaryExprOrTypeTrait TraitKind) {
3288   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3289   // runtime doesn't allow it.
3290   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3291     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3292       << T << (TraitKind == UETT_SizeOf)
3293       << ArgRange;
3294     return true;
3295   }
3296 
3297   return false;
3298 }
3299 
3300 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3301 /// pointer type is equal to T) and emit a warning if it is.
3302 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3303                                      Expr *E) {
3304   // Don't warn if the operation changed the type.
3305   if (T != E->getType())
3306     return;
3307 
3308   // Now look for array decays.
3309   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3310   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3311     return;
3312 
3313   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3314                                              << ICE->getType()
3315                                              << ICE->getSubExpr()->getType();
3316 }
3317 
3318 /// \brief Check the constraints on expression operands to unary type expression
3319 /// and type traits.
3320 ///
3321 /// Completes any types necessary and validates the constraints on the operand
3322 /// expression. The logic mostly mirrors the type-based overload, but may modify
3323 /// the expression as it completes the type for that expression through template
3324 /// instantiation, etc.
3325 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3326                                             UnaryExprOrTypeTrait ExprKind) {
3327   QualType ExprTy = E->getType();
3328   assert(!ExprTy->isReferenceType());
3329 
3330   if (ExprKind == UETT_VecStep)
3331     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3332                                         E->getSourceRange());
3333 
3334   // Whitelist some types as extensions
3335   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3336                                       E->getSourceRange(), ExprKind))
3337     return false;
3338 
3339   if (RequireCompleteExprType(E,
3340                               diag::err_sizeof_alignof_incomplete_type,
3341                               ExprKind, E->getSourceRange()))
3342     return true;
3343 
3344   // Completing the expression's type may have changed it.
3345   ExprTy = E->getType();
3346   assert(!ExprTy->isReferenceType());
3347 
3348   if (ExprTy->isFunctionType()) {
3349     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3350       << ExprKind << E->getSourceRange();
3351     return true;
3352   }
3353 
3354   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3355                                        E->getSourceRange(), ExprKind))
3356     return true;
3357 
3358   if (ExprKind == UETT_SizeOf) {
3359     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3360       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3361         QualType OType = PVD->getOriginalType();
3362         QualType Type = PVD->getType();
3363         if (Type->isPointerType() && OType->isArrayType()) {
3364           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3365             << Type << OType;
3366           Diag(PVD->getLocation(), diag::note_declared_at);
3367         }
3368       }
3369     }
3370 
3371     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3372     // decays into a pointer and returns an unintended result. This is most
3373     // likely a typo for "sizeof(array) op x".
3374     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3375       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3376                                BO->getLHS());
3377       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3378                                BO->getRHS());
3379     }
3380   }
3381 
3382   return false;
3383 }
3384 
3385 /// \brief Check the constraints on operands to unary expression and type
3386 /// traits.
3387 ///
3388 /// This will complete any types necessary, and validate the various constraints
3389 /// on those operands.
3390 ///
3391 /// The UsualUnaryConversions() function is *not* called by this routine.
3392 /// C99 6.3.2.1p[2-4] all state:
3393 ///   Except when it is the operand of the sizeof operator ...
3394 ///
3395 /// C++ [expr.sizeof]p4
3396 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3397 ///   standard conversions are not applied to the operand of sizeof.
3398 ///
3399 /// This policy is followed for all of the unary trait expressions.
3400 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3401                                             SourceLocation OpLoc,
3402                                             SourceRange ExprRange,
3403                                             UnaryExprOrTypeTrait ExprKind) {
3404   if (ExprType->isDependentType())
3405     return false;
3406 
3407   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3408   //   the result is the size of the referenced type."
3409   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3410   //   result shall be the alignment of the referenced type."
3411   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3412     ExprType = Ref->getPointeeType();
3413 
3414   if (ExprKind == UETT_VecStep)
3415     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3416 
3417   // Whitelist some types as extensions
3418   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3419                                       ExprKind))
3420     return false;
3421 
3422   if (RequireCompleteType(OpLoc, ExprType,
3423                           diag::err_sizeof_alignof_incomplete_type,
3424                           ExprKind, ExprRange))
3425     return true;
3426 
3427   if (ExprType->isFunctionType()) {
3428     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3429       << ExprKind << ExprRange;
3430     return true;
3431   }
3432 
3433   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3434                                        ExprKind))
3435     return true;
3436 
3437   return false;
3438 }
3439 
3440 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3441   E = E->IgnoreParens();
3442 
3443   // Cannot know anything else if the expression is dependent.
3444   if (E->isTypeDependent())
3445     return false;
3446 
3447   if (E->getObjectKind() == OK_BitField) {
3448     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3449        << 1 << E->getSourceRange();
3450     return true;
3451   }
3452 
3453   ValueDecl *D = 0;
3454   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3455     D = DRE->getDecl();
3456   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3457     D = ME->getMemberDecl();
3458   }
3459 
3460   // If it's a field, require the containing struct to have a
3461   // complete definition so that we can compute the layout.
3462   //
3463   // This requires a very particular set of circumstances.  For a
3464   // field to be contained within an incomplete type, we must in the
3465   // process of parsing that type.  To have an expression refer to a
3466   // field, it must be an id-expression or a member-expression, but
3467   // the latter are always ill-formed when the base type is
3468   // incomplete, including only being partially complete.  An
3469   // id-expression can never refer to a field in C because fields
3470   // are not in the ordinary namespace.  In C++, an id-expression
3471   // can implicitly be a member access, but only if there's an
3472   // implicit 'this' value, and all such contexts are subject to
3473   // delayed parsing --- except for trailing return types in C++11.
3474   // And if an id-expression referring to a field occurs in a
3475   // context that lacks a 'this' value, it's ill-formed --- except,
3476   // again, in C++11, where such references are allowed in an
3477   // unevaluated context.  So C++11 introduces some new complexity.
3478   //
3479   // For the record, since __alignof__ on expressions is a GCC
3480   // extension, GCC seems to permit this but always gives the
3481   // nonsensical answer 0.
3482   //
3483   // We don't really need the layout here --- we could instead just
3484   // directly check for all the appropriate alignment-lowing
3485   // attributes --- but that would require duplicating a lot of
3486   // logic that just isn't worth duplicating for such a marginal
3487   // use-case.
3488   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3489     // Fast path this check, since we at least know the record has a
3490     // definition if we can find a member of it.
3491     if (!FD->getParent()->isCompleteDefinition()) {
3492       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3493         << E->getSourceRange();
3494       return true;
3495     }
3496 
3497     // Otherwise, if it's a field, and the field doesn't have
3498     // reference type, then it must have a complete type (or be a
3499     // flexible array member, which we explicitly want to
3500     // white-list anyway), which makes the following checks trivial.
3501     if (!FD->getType()->isReferenceType())
3502       return false;
3503   }
3504 
3505   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3506 }
3507 
3508 bool Sema::CheckVecStepExpr(Expr *E) {
3509   E = E->IgnoreParens();
3510 
3511   // Cannot know anything else if the expression is dependent.
3512   if (E->isTypeDependent())
3513     return false;
3514 
3515   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3516 }
3517 
3518 /// \brief Build a sizeof or alignof expression given a type operand.
3519 ExprResult
3520 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3521                                      SourceLocation OpLoc,
3522                                      UnaryExprOrTypeTrait ExprKind,
3523                                      SourceRange R) {
3524   if (!TInfo)
3525     return ExprError();
3526 
3527   QualType T = TInfo->getType();
3528 
3529   if (!T->isDependentType() &&
3530       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3531     return ExprError();
3532 
3533   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3534   return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3535                                                       Context.getSizeType(),
3536                                                       OpLoc, R.getEnd()));
3537 }
3538 
3539 /// \brief Build a sizeof or alignof expression given an expression
3540 /// operand.
3541 ExprResult
3542 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3543                                      UnaryExprOrTypeTrait ExprKind) {
3544   ExprResult PE = CheckPlaceholderExpr(E);
3545   if (PE.isInvalid())
3546     return ExprError();
3547 
3548   E = PE.get();
3549 
3550   // Verify that the operand is valid.
3551   bool isInvalid = false;
3552   if (E->isTypeDependent()) {
3553     // Delay type-checking for type-dependent expressions.
3554   } else if (ExprKind == UETT_AlignOf) {
3555     isInvalid = CheckAlignOfExpr(*this, E);
3556   } else if (ExprKind == UETT_VecStep) {
3557     isInvalid = CheckVecStepExpr(E);
3558   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3559     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3560     isInvalid = true;
3561   } else {
3562     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3563   }
3564 
3565   if (isInvalid)
3566     return ExprError();
3567 
3568   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3569     PE = TransformToPotentiallyEvaluated(E);
3570     if (PE.isInvalid()) return ExprError();
3571     E = PE.take();
3572   }
3573 
3574   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3575   return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3576       ExprKind, E, Context.getSizeType(), OpLoc,
3577       E->getSourceRange().getEnd()));
3578 }
3579 
3580 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3581 /// expr and the same for @c alignof and @c __alignof
3582 /// Note that the ArgRange is invalid if isType is false.
3583 ExprResult
3584 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3585                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3586                                     void *TyOrEx, const SourceRange &ArgRange) {
3587   // If error parsing type, ignore.
3588   if (TyOrEx == 0) return ExprError();
3589 
3590   if (IsType) {
3591     TypeSourceInfo *TInfo;
3592     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3593     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3594   }
3595 
3596   Expr *ArgEx = (Expr *)TyOrEx;
3597   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3598   return Result;
3599 }
3600 
3601 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3602                                      bool IsReal) {
3603   if (V.get()->isTypeDependent())
3604     return S.Context.DependentTy;
3605 
3606   // _Real and _Imag are only l-values for normal l-values.
3607   if (V.get()->getObjectKind() != OK_Ordinary) {
3608     V = S.DefaultLvalueConversion(V.take());
3609     if (V.isInvalid())
3610       return QualType();
3611   }
3612 
3613   // These operators return the element type of a complex type.
3614   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3615     return CT->getElementType();
3616 
3617   // Otherwise they pass through real integer and floating point types here.
3618   if (V.get()->getType()->isArithmeticType())
3619     return V.get()->getType();
3620 
3621   // Test for placeholders.
3622   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3623   if (PR.isInvalid()) return QualType();
3624   if (PR.get() != V.get()) {
3625     V = PR;
3626     return CheckRealImagOperand(S, V, Loc, IsReal);
3627   }
3628 
3629   // Reject anything else.
3630   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3631     << (IsReal ? "__real" : "__imag");
3632   return QualType();
3633 }
3634 
3635 
3636 
3637 ExprResult
3638 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3639                           tok::TokenKind Kind, Expr *Input) {
3640   UnaryOperatorKind Opc;
3641   switch (Kind) {
3642   default: llvm_unreachable("Unknown unary op!");
3643   case tok::plusplus:   Opc = UO_PostInc; break;
3644   case tok::minusminus: Opc = UO_PostDec; break;
3645   }
3646 
3647   // Since this might is a postfix expression, get rid of ParenListExprs.
3648   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3649   if (Result.isInvalid()) return ExprError();
3650   Input = Result.take();
3651 
3652   return BuildUnaryOp(S, OpLoc, Opc, Input);
3653 }
3654 
3655 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3656 ///
3657 /// \return true on error
3658 static bool checkArithmeticOnObjCPointer(Sema &S,
3659                                          SourceLocation opLoc,
3660                                          Expr *op) {
3661   assert(op->getType()->isObjCObjectPointerType());
3662   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
3663       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
3664     return false;
3665 
3666   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3667     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3668     << op->getSourceRange();
3669   return true;
3670 }
3671 
3672 ExprResult
3673 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3674                               Expr *idx, SourceLocation rbLoc) {
3675   // Since this might be a postfix expression, get rid of ParenListExprs.
3676   if (isa<ParenListExpr>(base)) {
3677     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3678     if (result.isInvalid()) return ExprError();
3679     base = result.take();
3680   }
3681 
3682   // Handle any non-overload placeholder types in the base and index
3683   // expressions.  We can't handle overloads here because the other
3684   // operand might be an overloadable type, in which case the overload
3685   // resolution for the operator overload should get the first crack
3686   // at the overload.
3687   if (base->getType()->isNonOverloadPlaceholderType()) {
3688     ExprResult result = CheckPlaceholderExpr(base);
3689     if (result.isInvalid()) return ExprError();
3690     base = result.take();
3691   }
3692   if (idx->getType()->isNonOverloadPlaceholderType()) {
3693     ExprResult result = CheckPlaceholderExpr(idx);
3694     if (result.isInvalid()) return ExprError();
3695     idx = result.take();
3696   }
3697 
3698   // Build an unanalyzed expression if either operand is type-dependent.
3699   if (getLangOpts().CPlusPlus &&
3700       (base->isTypeDependent() || idx->isTypeDependent())) {
3701     return Owned(new (Context) ArraySubscriptExpr(base, idx,
3702                                                   Context.DependentTy,
3703                                                   VK_LValue, OK_Ordinary,
3704                                                   rbLoc));
3705   }
3706 
3707   // Use C++ overloaded-operator rules if either operand has record
3708   // type.  The spec says to do this if either type is *overloadable*,
3709   // but enum types can't declare subscript operators or conversion
3710   // operators, so there's nothing interesting for overload resolution
3711   // to do if there aren't any record types involved.
3712   //
3713   // ObjC pointers have their own subscripting logic that is not tied
3714   // to overload resolution and so should not take this path.
3715   if (getLangOpts().CPlusPlus &&
3716       (base->getType()->isRecordType() ||
3717        (!base->getType()->isObjCObjectPointerType() &&
3718         idx->getType()->isRecordType()))) {
3719     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3720   }
3721 
3722   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3723 }
3724 
3725 ExprResult
3726 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3727                                       Expr *Idx, SourceLocation RLoc) {
3728   Expr *LHSExp = Base;
3729   Expr *RHSExp = Idx;
3730 
3731   // Perform default conversions.
3732   if (!LHSExp->getType()->getAs<VectorType>()) {
3733     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3734     if (Result.isInvalid())
3735       return ExprError();
3736     LHSExp = Result.take();
3737   }
3738   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3739   if (Result.isInvalid())
3740     return ExprError();
3741   RHSExp = Result.take();
3742 
3743   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3744   ExprValueKind VK = VK_LValue;
3745   ExprObjectKind OK = OK_Ordinary;
3746 
3747   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3748   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3749   // in the subscript position. As a result, we need to derive the array base
3750   // and index from the expression types.
3751   Expr *BaseExpr, *IndexExpr;
3752   QualType ResultType;
3753   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3754     BaseExpr = LHSExp;
3755     IndexExpr = RHSExp;
3756     ResultType = Context.DependentTy;
3757   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3758     BaseExpr = LHSExp;
3759     IndexExpr = RHSExp;
3760     ResultType = PTy->getPointeeType();
3761   } else if (const ObjCObjectPointerType *PTy =
3762                LHSTy->getAs<ObjCObjectPointerType>()) {
3763     BaseExpr = LHSExp;
3764     IndexExpr = RHSExp;
3765 
3766     // Use custom logic if this should be the pseudo-object subscript
3767     // expression.
3768     if (!LangOpts.isSubscriptPointerArithmetic())
3769       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3770 
3771     ResultType = PTy->getPointeeType();
3772   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3773      // Handle the uncommon case of "123[Ptr]".
3774     BaseExpr = RHSExp;
3775     IndexExpr = LHSExp;
3776     ResultType = PTy->getPointeeType();
3777   } else if (const ObjCObjectPointerType *PTy =
3778                RHSTy->getAs<ObjCObjectPointerType>()) {
3779      // Handle the uncommon case of "123[Ptr]".
3780     BaseExpr = RHSExp;
3781     IndexExpr = LHSExp;
3782     ResultType = PTy->getPointeeType();
3783     if (!LangOpts.isSubscriptPointerArithmetic()) {
3784       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3785         << ResultType << BaseExpr->getSourceRange();
3786       return ExprError();
3787     }
3788   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3789     BaseExpr = LHSExp;    // vectors: V[123]
3790     IndexExpr = RHSExp;
3791     VK = LHSExp->getValueKind();
3792     if (VK != VK_RValue)
3793       OK = OK_VectorComponent;
3794 
3795     // FIXME: need to deal with const...
3796     ResultType = VTy->getElementType();
3797   } else if (LHSTy->isArrayType()) {
3798     // If we see an array that wasn't promoted by
3799     // DefaultFunctionArrayLvalueConversion, it must be an array that
3800     // wasn't promoted because of the C90 rule that doesn't
3801     // allow promoting non-lvalue arrays.  Warn, then
3802     // force the promotion here.
3803     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3804         LHSExp->getSourceRange();
3805     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3806                                CK_ArrayToPointerDecay).take();
3807     LHSTy = LHSExp->getType();
3808 
3809     BaseExpr = LHSExp;
3810     IndexExpr = RHSExp;
3811     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3812   } else if (RHSTy->isArrayType()) {
3813     // Same as previous, except for 123[f().a] case
3814     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3815         RHSExp->getSourceRange();
3816     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3817                                CK_ArrayToPointerDecay).take();
3818     RHSTy = RHSExp->getType();
3819 
3820     BaseExpr = RHSExp;
3821     IndexExpr = LHSExp;
3822     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3823   } else {
3824     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3825        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3826   }
3827   // C99 6.5.2.1p1
3828   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3829     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3830                      << IndexExpr->getSourceRange());
3831 
3832   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3833        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3834          && !IndexExpr->isTypeDependent())
3835     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3836 
3837   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3838   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3839   // type. Note that Functions are not objects, and that (in C99 parlance)
3840   // incomplete types are not object types.
3841   if (ResultType->isFunctionType()) {
3842     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3843       << ResultType << BaseExpr->getSourceRange();
3844     return ExprError();
3845   }
3846 
3847   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3848     // GNU extension: subscripting on pointer to void
3849     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3850       << BaseExpr->getSourceRange();
3851 
3852     // C forbids expressions of unqualified void type from being l-values.
3853     // See IsCForbiddenLValueType.
3854     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3855   } else if (!ResultType->isDependentType() &&
3856       RequireCompleteType(LLoc, ResultType,
3857                           diag::err_subscript_incomplete_type, BaseExpr))
3858     return ExprError();
3859 
3860   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3861          !ResultType.isCForbiddenLValueType());
3862 
3863   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3864                                                 ResultType, VK, OK, RLoc));
3865 }
3866 
3867 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3868                                         FunctionDecl *FD,
3869                                         ParmVarDecl *Param) {
3870   if (Param->hasUnparsedDefaultArg()) {
3871     Diag(CallLoc,
3872          diag::err_use_of_default_argument_to_function_declared_later) <<
3873       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3874     Diag(UnparsedDefaultArgLocs[Param],
3875          diag::note_default_argument_declared_here);
3876     return ExprError();
3877   }
3878 
3879   if (Param->hasUninstantiatedDefaultArg()) {
3880     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3881 
3882     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3883                                                  Param);
3884 
3885     // Instantiate the expression.
3886     MultiLevelTemplateArgumentList MutiLevelArgList
3887       = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3888 
3889     InstantiatingTemplate Inst(*this, CallLoc, Param,
3890                                MutiLevelArgList.getInnermost());
3891     if (Inst.isInvalid())
3892       return ExprError();
3893 
3894     ExprResult Result;
3895     {
3896       // C++ [dcl.fct.default]p5:
3897       //   The names in the [default argument] expression are bound, and
3898       //   the semantic constraints are checked, at the point where the
3899       //   default argument expression appears.
3900       ContextRAII SavedContext(*this, FD);
3901       LocalInstantiationScope Local(*this);
3902       Result = SubstExpr(UninstExpr, MutiLevelArgList);
3903     }
3904     if (Result.isInvalid())
3905       return ExprError();
3906 
3907     // Check the expression as an initializer for the parameter.
3908     InitializedEntity Entity
3909       = InitializedEntity::InitializeParameter(Context, Param);
3910     InitializationKind Kind
3911       = InitializationKind::CreateCopy(Param->getLocation(),
3912              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3913     Expr *ResultE = Result.takeAs<Expr>();
3914 
3915     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3916     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3917     if (Result.isInvalid())
3918       return ExprError();
3919 
3920     Expr *Arg = Result.takeAs<Expr>();
3921     CheckCompletedExpr(Arg, Param->getOuterLocStart());
3922     // Build the default argument expression.
3923     return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
3924   }
3925 
3926   // If the default expression creates temporaries, we need to
3927   // push them to the current stack of expression temporaries so they'll
3928   // be properly destroyed.
3929   // FIXME: We should really be rebuilding the default argument with new
3930   // bound temporaries; see the comment in PR5810.
3931   // We don't need to do that with block decls, though, because
3932   // blocks in default argument expression can never capture anything.
3933   if (isa<ExprWithCleanups>(Param->getInit())) {
3934     // Set the "needs cleanups" bit regardless of whether there are
3935     // any explicit objects.
3936     ExprNeedsCleanups = true;
3937 
3938     // Append all the objects to the cleanup list.  Right now, this
3939     // should always be a no-op, because blocks in default argument
3940     // expressions should never be able to capture anything.
3941     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3942            "default argument expression has capturing blocks?");
3943   }
3944 
3945   // We already type-checked the argument, so we know it works.
3946   // Just mark all of the declarations in this potentially-evaluated expression
3947   // as being "referenced".
3948   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3949                                    /*SkipLocalVariables=*/true);
3950   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3951 }
3952 
3953 
3954 Sema::VariadicCallType
3955 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3956                           Expr *Fn) {
3957   if (Proto && Proto->isVariadic()) {
3958     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3959       return VariadicConstructor;
3960     else if (Fn && Fn->getType()->isBlockPointerType())
3961       return VariadicBlock;
3962     else if (FDecl) {
3963       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3964         if (Method->isInstance())
3965           return VariadicMethod;
3966     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
3967       return VariadicMethod;
3968     return VariadicFunction;
3969   }
3970   return VariadicDoesNotApply;
3971 }
3972 
3973 namespace {
3974 class FunctionCallCCC : public FunctionCallFilterCCC {
3975 public:
3976   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
3977                   unsigned NumArgs, bool HasExplicitTemplateArgs)
3978       : FunctionCallFilterCCC(SemaRef, NumArgs, HasExplicitTemplateArgs),
3979         FunctionName(FuncName) {}
3980 
3981   bool ValidateCandidate(const TypoCorrection &candidate) override {
3982     if (!candidate.getCorrectionSpecifier() ||
3983         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
3984       return false;
3985     }
3986 
3987     return FunctionCallFilterCCC::ValidateCandidate(candidate);
3988   }
3989 
3990 private:
3991   const IdentifierInfo *const FunctionName;
3992 };
3993 }
3994 
3995 static TypoCorrection TryTypoCorrectionForCall(Sema &S,
3996                                                DeclarationNameInfo FuncName,
3997                                                ArrayRef<Expr *> Args) {
3998   FunctionCallCCC CCC(S, FuncName.getName().getAsIdentifierInfo(),
3999                       Args.size(), false);
4000   if (TypoCorrection Corrected =
4001           S.CorrectTypo(FuncName, Sema::LookupOrdinaryName,
4002                         S.getScopeForContext(S.CurContext), NULL, CCC)) {
4003     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
4004       if (Corrected.isOverloaded()) {
4005         OverloadCandidateSet OCS(FuncName.getLoc());
4006         OverloadCandidateSet::iterator Best;
4007         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
4008                                            CDEnd = Corrected.end();
4009              CD != CDEnd; ++CD) {
4010           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
4011             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4012                                    OCS);
4013         }
4014         switch (OCS.BestViableFunction(S, FuncName.getLoc(), Best)) {
4015         case OR_Success:
4016           ND = Best->Function;
4017           Corrected.setCorrectionDecl(ND);
4018           break;
4019         default:
4020           break;
4021         }
4022       }
4023       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
4024         return Corrected;
4025       }
4026     }
4027   }
4028   return TypoCorrection();
4029 }
4030 
4031 /// ConvertArgumentsForCall - Converts the arguments specified in
4032 /// Args/NumArgs to the parameter types of the function FDecl with
4033 /// function prototype Proto. Call is the call expression itself, and
4034 /// Fn is the function expression. For a C++ member function, this
4035 /// routine does not attempt to convert the object argument. Returns
4036 /// true if the call is ill-formed.
4037 bool
4038 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4039                               FunctionDecl *FDecl,
4040                               const FunctionProtoType *Proto,
4041                               ArrayRef<Expr *> Args,
4042                               SourceLocation RParenLoc,
4043                               bool IsExecConfig) {
4044   // Bail out early if calling a builtin with custom typechecking.
4045   // We don't need to do this in the
4046   if (FDecl)
4047     if (unsigned ID = FDecl->getBuiltinID())
4048       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4049         return false;
4050 
4051   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4052   // assignment, to the types of the corresponding parameter, ...
4053   unsigned NumParams = Proto->getNumParams();
4054   bool Invalid = false;
4055   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4056   unsigned FnKind = Fn->getType()->isBlockPointerType()
4057                        ? 1 /* block */
4058                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4059                                        : 0 /* function */);
4060 
4061   // If too few arguments are available (and we don't have default
4062   // arguments for the remaining parameters), don't make the call.
4063   if (Args.size() < NumParams) {
4064     if (Args.size() < MinArgs) {
4065       MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4066       TypoCorrection TC;
4067       if (FDecl && (TC = TryTypoCorrectionForCall(
4068                         *this, DeclarationNameInfo(FDecl->getDeclName(),
4069                                                    (ME ? ME->getMemberLoc()
4070                                                        : Fn->getLocStart())),
4071                         Args))) {
4072         unsigned diag_id =
4073             MinArgs == NumParams && !Proto->isVariadic()
4074                 ? diag::err_typecheck_call_too_few_args_suggest
4075                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4076         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4077                                         << static_cast<unsigned>(Args.size())
4078                                         << TC.getCorrectionRange());
4079       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4080         Diag(RParenLoc,
4081              MinArgs == NumParams && !Proto->isVariadic()
4082                  ? diag::err_typecheck_call_too_few_args_one
4083                  : diag::err_typecheck_call_too_few_args_at_least_one)
4084             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4085       else
4086         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4087                             ? diag::err_typecheck_call_too_few_args
4088                             : diag::err_typecheck_call_too_few_args_at_least)
4089             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4090             << Fn->getSourceRange();
4091 
4092       // Emit the location of the prototype.
4093       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4094         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4095           << FDecl;
4096 
4097       return true;
4098     }
4099     Call->setNumArgs(Context, NumParams);
4100   }
4101 
4102   // If too many are passed and not variadic, error on the extras and drop
4103   // them.
4104   if (Args.size() > NumParams) {
4105     if (!Proto->isVariadic()) {
4106       MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4107       TypoCorrection TC;
4108       if (FDecl && (TC = TryTypoCorrectionForCall(
4109                         *this, DeclarationNameInfo(FDecl->getDeclName(),
4110                                                    (ME ? ME->getMemberLoc()
4111                                                        : Fn->getLocStart())),
4112                         Args))) {
4113         unsigned diag_id =
4114             MinArgs == NumParams && !Proto->isVariadic()
4115                 ? diag::err_typecheck_call_too_many_args_suggest
4116                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4117         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4118                                         << static_cast<unsigned>(Args.size())
4119                                         << TC.getCorrectionRange());
4120       } else if (NumParams == 1 && FDecl &&
4121                  FDecl->getParamDecl(0)->getDeclName())
4122         Diag(Args[NumParams]->getLocStart(),
4123              MinArgs == NumParams
4124                  ? diag::err_typecheck_call_too_many_args_one
4125                  : diag::err_typecheck_call_too_many_args_at_most_one)
4126             << FnKind << FDecl->getParamDecl(0)
4127             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4128             << SourceRange(Args[NumParams]->getLocStart(),
4129                            Args.back()->getLocEnd());
4130       else
4131         Diag(Args[NumParams]->getLocStart(),
4132              MinArgs == NumParams
4133                  ? diag::err_typecheck_call_too_many_args
4134                  : diag::err_typecheck_call_too_many_args_at_most)
4135             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4136             << Fn->getSourceRange()
4137             << SourceRange(Args[NumParams]->getLocStart(),
4138                            Args.back()->getLocEnd());
4139 
4140       // Emit the location of the prototype.
4141       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4142         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4143           << FDecl;
4144 
4145       // This deletes the extra arguments.
4146       Call->setNumArgs(Context, NumParams);
4147       return true;
4148     }
4149   }
4150   SmallVector<Expr *, 8> AllArgs;
4151   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4152 
4153   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4154                                    Proto, 0, Args, AllArgs, CallType);
4155   if (Invalid)
4156     return true;
4157   unsigned TotalNumArgs = AllArgs.size();
4158   for (unsigned i = 0; i < TotalNumArgs; ++i)
4159     Call->setArg(i, AllArgs[i]);
4160 
4161   return false;
4162 }
4163 
4164 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4165                                   const FunctionProtoType *Proto,
4166                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4167                                   SmallVectorImpl<Expr *> &AllArgs,
4168                                   VariadicCallType CallType, bool AllowExplicit,
4169                                   bool IsListInitialization) {
4170   unsigned NumParams = Proto->getNumParams();
4171   unsigned NumArgsToCheck = Args.size();
4172   bool Invalid = false;
4173   if (Args.size() != NumParams)
4174     // Use default arguments for missing arguments
4175     NumArgsToCheck = NumParams;
4176   unsigned ArgIx = 0;
4177   // Continue to check argument types (even if we have too few/many args).
4178   for (unsigned i = FirstParam; i != NumArgsToCheck; i++) {
4179     QualType ProtoArgType = Proto->getParamType(i);
4180 
4181     Expr *Arg;
4182     ParmVarDecl *Param;
4183     if (ArgIx < Args.size()) {
4184       Arg = Args[ArgIx++];
4185 
4186       if (RequireCompleteType(Arg->getLocStart(),
4187                               ProtoArgType,
4188                               diag::err_call_incomplete_argument, Arg))
4189         return true;
4190 
4191       // Pass the argument
4192       Param = 0;
4193       if (FDecl && i < FDecl->getNumParams())
4194         Param = FDecl->getParamDecl(i);
4195 
4196       // Strip the unbridged-cast placeholder expression off, if applicable.
4197       bool CFAudited = false;
4198       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4199           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4200           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4201         Arg = stripARCUnbridgedCast(Arg);
4202       else if (getLangOpts().ObjCAutoRefCount &&
4203                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4204                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4205         CFAudited = true;
4206 
4207       InitializedEntity Entity =
4208           Param ? InitializedEntity::InitializeParameter(Context, Param,
4209                                                          ProtoArgType)
4210                 : InitializedEntity::InitializeParameter(
4211                       Context, ProtoArgType, Proto->isParamConsumed(i));
4212 
4213       // Remember that parameter belongs to a CF audited API.
4214       if (CFAudited)
4215         Entity.setParameterCFAudited();
4216 
4217       ExprResult ArgE = PerformCopyInitialization(Entity,
4218                                                   SourceLocation(),
4219                                                   Owned(Arg),
4220                                                   IsListInitialization,
4221                                                   AllowExplicit);
4222       if (ArgE.isInvalid())
4223         return true;
4224 
4225       Arg = ArgE.takeAs<Expr>();
4226     } else {
4227       assert(FDecl && "can't use default arguments without a known callee");
4228       Param = FDecl->getParamDecl(i);
4229 
4230       ExprResult ArgExpr =
4231         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4232       if (ArgExpr.isInvalid())
4233         return true;
4234 
4235       Arg = ArgExpr.takeAs<Expr>();
4236     }
4237 
4238     // Check for array bounds violations for each argument to the call. This
4239     // check only triggers warnings when the argument isn't a more complex Expr
4240     // with its own checking, such as a BinaryOperator.
4241     CheckArrayAccess(Arg);
4242 
4243     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4244     CheckStaticArrayArgument(CallLoc, Param, Arg);
4245 
4246     AllArgs.push_back(Arg);
4247   }
4248 
4249   // If this is a variadic call, handle args passed through "...".
4250   if (CallType != VariadicDoesNotApply) {
4251     // Assume that extern "C" functions with variadic arguments that
4252     // return __unknown_anytype aren't *really* variadic.
4253     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4254         FDecl->isExternC()) {
4255       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4256         QualType paramType; // ignored
4257         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
4258         Invalid |= arg.isInvalid();
4259         AllArgs.push_back(arg.take());
4260       }
4261 
4262     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4263     } else {
4264       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4265         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4266                                                           FDecl);
4267         Invalid |= Arg.isInvalid();
4268         AllArgs.push_back(Arg.take());
4269       }
4270     }
4271 
4272     // Check for array bounds violations.
4273     for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4274       CheckArrayAccess(Args[i]);
4275   }
4276   return Invalid;
4277 }
4278 
4279 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4280   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4281   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4282     TL = DTL.getOriginalLoc();
4283   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4284     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4285       << ATL.getLocalSourceRange();
4286 }
4287 
4288 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4289 /// array parameter, check that it is non-null, and that if it is formed by
4290 /// array-to-pointer decay, the underlying array is sufficiently large.
4291 ///
4292 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4293 /// array type derivation, then for each call to the function, the value of the
4294 /// corresponding actual argument shall provide access to the first element of
4295 /// an array with at least as many elements as specified by the size expression.
4296 void
4297 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4298                                ParmVarDecl *Param,
4299                                const Expr *ArgExpr) {
4300   // Static array parameters are not supported in C++.
4301   if (!Param || getLangOpts().CPlusPlus)
4302     return;
4303 
4304   QualType OrigTy = Param->getOriginalType();
4305 
4306   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4307   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4308     return;
4309 
4310   if (ArgExpr->isNullPointerConstant(Context,
4311                                      Expr::NPC_NeverValueDependent)) {
4312     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4313     DiagnoseCalleeStaticArrayParam(*this, Param);
4314     return;
4315   }
4316 
4317   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4318   if (!CAT)
4319     return;
4320 
4321   const ConstantArrayType *ArgCAT =
4322     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4323   if (!ArgCAT)
4324     return;
4325 
4326   if (ArgCAT->getSize().ult(CAT->getSize())) {
4327     Diag(CallLoc, diag::warn_static_array_too_small)
4328       << ArgExpr->getSourceRange()
4329       << (unsigned) ArgCAT->getSize().getZExtValue()
4330       << (unsigned) CAT->getSize().getZExtValue();
4331     DiagnoseCalleeStaticArrayParam(*this, Param);
4332   }
4333 }
4334 
4335 /// Given a function expression of unknown-any type, try to rebuild it
4336 /// to have a function type.
4337 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4338 
4339 /// Is the given type a placeholder that we need to lower out
4340 /// immediately during argument processing?
4341 static bool isPlaceholderToRemoveAsArg(QualType type) {
4342   // Placeholders are never sugared.
4343   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4344   if (!placeholder) return false;
4345 
4346   switch (placeholder->getKind()) {
4347   // Ignore all the non-placeholder types.
4348 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4349 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4350 #include "clang/AST/BuiltinTypes.def"
4351     return false;
4352 
4353   // We cannot lower out overload sets; they might validly be resolved
4354   // by the call machinery.
4355   case BuiltinType::Overload:
4356     return false;
4357 
4358   // Unbridged casts in ARC can be handled in some call positions and
4359   // should be left in place.
4360   case BuiltinType::ARCUnbridgedCast:
4361     return false;
4362 
4363   // Pseudo-objects should be converted as soon as possible.
4364   case BuiltinType::PseudoObject:
4365     return true;
4366 
4367   // The debugger mode could theoretically but currently does not try
4368   // to resolve unknown-typed arguments based on known parameter types.
4369   case BuiltinType::UnknownAny:
4370     return true;
4371 
4372   // These are always invalid as call arguments and should be reported.
4373   case BuiltinType::BoundMember:
4374   case BuiltinType::BuiltinFn:
4375     return true;
4376   }
4377   llvm_unreachable("bad builtin type kind");
4378 }
4379 
4380 /// Check an argument list for placeholders that we won't try to
4381 /// handle later.
4382 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4383   // Apply this processing to all the arguments at once instead of
4384   // dying at the first failure.
4385   bool hasInvalid = false;
4386   for (size_t i = 0, e = args.size(); i != e; i++) {
4387     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4388       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4389       if (result.isInvalid()) hasInvalid = true;
4390       else args[i] = result.take();
4391     }
4392   }
4393   return hasInvalid;
4394 }
4395 
4396 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4397 /// This provides the location of the left/right parens and a list of comma
4398 /// locations.
4399 ExprResult
4400 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4401                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
4402                     Expr *ExecConfig, bool IsExecConfig) {
4403   // Since this might be a postfix expression, get rid of ParenListExprs.
4404   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4405   if (Result.isInvalid()) return ExprError();
4406   Fn = Result.take();
4407 
4408   if (checkArgsForPlaceholders(*this, ArgExprs))
4409     return ExprError();
4410 
4411   if (getLangOpts().CPlusPlus) {
4412     // If this is a pseudo-destructor expression, build the call immediately.
4413     if (isa<CXXPseudoDestructorExpr>(Fn)) {
4414       if (!ArgExprs.empty()) {
4415         // Pseudo-destructor calls should not have any arguments.
4416         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4417           << FixItHint::CreateRemoval(
4418                                     SourceRange(ArgExprs[0]->getLocStart(),
4419                                                 ArgExprs.back()->getLocEnd()));
4420       }
4421 
4422       return Owned(new (Context) CallExpr(Context, Fn, None,
4423                                           Context.VoidTy, VK_RValue,
4424                                           RParenLoc));
4425     }
4426     if (Fn->getType() == Context.PseudoObjectTy) {
4427       ExprResult result = CheckPlaceholderExpr(Fn);
4428       if (result.isInvalid()) return ExprError();
4429       Fn = result.take();
4430     }
4431 
4432     // Determine whether this is a dependent call inside a C++ template,
4433     // in which case we won't do any semantic analysis now.
4434     // FIXME: Will need to cache the results of name lookup (including ADL) in
4435     // Fn.
4436     bool Dependent = false;
4437     if (Fn->isTypeDependent())
4438       Dependent = true;
4439     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4440       Dependent = true;
4441 
4442     if (Dependent) {
4443       if (ExecConfig) {
4444         return Owned(new (Context) CUDAKernelCallExpr(
4445             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4446             Context.DependentTy, VK_RValue, RParenLoc));
4447       } else {
4448         return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
4449                                             Context.DependentTy, VK_RValue,
4450                                             RParenLoc));
4451       }
4452     }
4453 
4454     // Determine whether this is a call to an object (C++ [over.call.object]).
4455     if (Fn->getType()->isRecordType())
4456       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
4457                                                 ArgExprs, RParenLoc));
4458 
4459     if (Fn->getType() == Context.UnknownAnyTy) {
4460       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4461       if (result.isInvalid()) return ExprError();
4462       Fn = result.take();
4463     }
4464 
4465     if (Fn->getType() == Context.BoundMemberTy) {
4466       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4467     }
4468   }
4469 
4470   // Check for overloaded calls.  This can happen even in C due to extensions.
4471   if (Fn->getType() == Context.OverloadTy) {
4472     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4473 
4474     // We aren't supposed to apply this logic for if there's an '&' involved.
4475     if (!find.HasFormOfMemberPointer) {
4476       OverloadExpr *ovl = find.Expression;
4477       if (isa<UnresolvedLookupExpr>(ovl)) {
4478         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4479         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4480                                        RParenLoc, ExecConfig);
4481       } else {
4482         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4483                                          RParenLoc);
4484       }
4485     }
4486   }
4487 
4488   // If we're directly calling a function, get the appropriate declaration.
4489   if (Fn->getType() == Context.UnknownAnyTy) {
4490     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4491     if (result.isInvalid()) return ExprError();
4492     Fn = result.take();
4493   }
4494 
4495   Expr *NakedFn = Fn->IgnoreParens();
4496 
4497   NamedDecl *NDecl = 0;
4498   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4499     if (UnOp->getOpcode() == UO_AddrOf)
4500       NakedFn = UnOp->getSubExpr()->IgnoreParens();
4501 
4502   if (isa<DeclRefExpr>(NakedFn))
4503     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4504   else if (isa<MemberExpr>(NakedFn))
4505     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4506 
4507   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
4508     if (FD->hasAttr<EnableIfAttr>()) {
4509       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
4510         Diag(Fn->getLocStart(),
4511              isa<CXXMethodDecl>(FD) ?
4512                  diag::err_ovl_no_viable_member_function_in_call :
4513                  diag::err_ovl_no_viable_function_in_call)
4514           << FD << FD->getSourceRange();
4515         Diag(FD->getLocation(),
4516              diag::note_ovl_candidate_disabled_by_enable_if_attr)
4517             << Attr->getCond()->getSourceRange() << Attr->getMessage();
4518       }
4519     }
4520   }
4521 
4522   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4523                                ExecConfig, IsExecConfig);
4524 }
4525 
4526 ExprResult
4527 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4528                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
4529   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4530   if (!ConfigDecl)
4531     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4532                           << "cudaConfigureCall");
4533   QualType ConfigQTy = ConfigDecl->getType();
4534 
4535   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4536       ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
4537   MarkFunctionReferenced(LLLLoc, ConfigDecl);
4538 
4539   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
4540                        /*IsExecConfig=*/true);
4541 }
4542 
4543 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4544 ///
4545 /// __builtin_astype( value, dst type )
4546 ///
4547 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4548                                  SourceLocation BuiltinLoc,
4549                                  SourceLocation RParenLoc) {
4550   ExprValueKind VK = VK_RValue;
4551   ExprObjectKind OK = OK_Ordinary;
4552   QualType DstTy = GetTypeFromParser(ParsedDestTy);
4553   QualType SrcTy = E->getType();
4554   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4555     return ExprError(Diag(BuiltinLoc,
4556                           diag::err_invalid_astype_of_different_size)
4557                      << DstTy
4558                      << SrcTy
4559                      << E->getSourceRange());
4560   return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
4561                RParenLoc));
4562 }
4563 
4564 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
4565 /// provided arguments.
4566 ///
4567 /// __builtin_convertvector( value, dst type )
4568 ///
4569 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4570                                         SourceLocation BuiltinLoc,
4571                                         SourceLocation RParenLoc) {
4572   TypeSourceInfo *TInfo;
4573   GetTypeFromParser(ParsedDestTy, &TInfo);
4574   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
4575 }
4576 
4577 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4578 /// i.e. an expression not of \p OverloadTy.  The expression should
4579 /// unary-convert to an expression of function-pointer or
4580 /// block-pointer type.
4581 ///
4582 /// \param NDecl the declaration being called, if available
4583 ExprResult
4584 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4585                             SourceLocation LParenLoc,
4586                             ArrayRef<Expr *> Args,
4587                             SourceLocation RParenLoc,
4588                             Expr *Config, bool IsExecConfig) {
4589   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4590   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4591 
4592   // Promote the function operand.
4593   // We special-case function promotion here because we only allow promoting
4594   // builtin functions to function pointers in the callee of a call.
4595   ExprResult Result;
4596   if (BuiltinID &&
4597       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4598     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4599                                CK_BuiltinFnToFnPtr).take();
4600   } else {
4601     Result = CallExprUnaryConversions(Fn);
4602   }
4603   if (Result.isInvalid())
4604     return ExprError();
4605   Fn = Result.take();
4606 
4607   // Make the call expr early, before semantic checks.  This guarantees cleanup
4608   // of arguments and function on error.
4609   CallExpr *TheCall;
4610   if (Config)
4611     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4612                                                cast<CallExpr>(Config), Args,
4613                                                Context.BoolTy, VK_RValue,
4614                                                RParenLoc);
4615   else
4616     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4617                                      VK_RValue, RParenLoc);
4618 
4619   // Bail out early if calling a builtin with custom typechecking.
4620   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4621     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4622 
4623  retry:
4624   const FunctionType *FuncT;
4625   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4626     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4627     // have type pointer to function".
4628     FuncT = PT->getPointeeType()->getAs<FunctionType>();
4629     if (FuncT == 0)
4630       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4631                          << Fn->getType() << Fn->getSourceRange());
4632   } else if (const BlockPointerType *BPT =
4633                Fn->getType()->getAs<BlockPointerType>()) {
4634     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4635   } else {
4636     // Handle calls to expressions of unknown-any type.
4637     if (Fn->getType() == Context.UnknownAnyTy) {
4638       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4639       if (rewrite.isInvalid()) return ExprError();
4640       Fn = rewrite.take();
4641       TheCall->setCallee(Fn);
4642       goto retry;
4643     }
4644 
4645     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4646       << Fn->getType() << Fn->getSourceRange());
4647   }
4648 
4649   if (getLangOpts().CUDA) {
4650     if (Config) {
4651       // CUDA: Kernel calls must be to global functions
4652       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4653         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4654             << FDecl->getName() << Fn->getSourceRange());
4655 
4656       // CUDA: Kernel function must have 'void' return type
4657       if (!FuncT->getReturnType()->isVoidType())
4658         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4659             << Fn->getType() << Fn->getSourceRange());
4660     } else {
4661       // CUDA: Calls to global functions must be configured
4662       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4663         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4664             << FDecl->getName() << Fn->getSourceRange());
4665     }
4666   }
4667 
4668   // Check for a valid return type
4669   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
4670                           FDecl))
4671     return ExprError();
4672 
4673   // We know the result type of the call, set it.
4674   TheCall->setType(FuncT->getCallResultType(Context));
4675   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
4676 
4677   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4678   if (Proto) {
4679     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4680                                 IsExecConfig))
4681       return ExprError();
4682   } else {
4683     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4684 
4685     if (FDecl) {
4686       // Check if we have too few/too many template arguments, based
4687       // on our knowledge of the function definition.
4688       const FunctionDecl *Def = 0;
4689       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
4690         Proto = Def->getType()->getAs<FunctionProtoType>();
4691        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
4692           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4693           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
4694       }
4695 
4696       // If the function we're calling isn't a function prototype, but we have
4697       // a function prototype from a prior declaratiom, use that prototype.
4698       if (!FDecl->hasPrototype())
4699         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4700     }
4701 
4702     // Promote the arguments (C99 6.5.2.2p6).
4703     for (unsigned i = 0, e = Args.size(); i != e; i++) {
4704       Expr *Arg = Args[i];
4705 
4706       if (Proto && i < Proto->getNumParams()) {
4707         InitializedEntity Entity = InitializedEntity::InitializeParameter(
4708             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
4709         ExprResult ArgE = PerformCopyInitialization(Entity,
4710                                                     SourceLocation(),
4711                                                     Owned(Arg));
4712         if (ArgE.isInvalid())
4713           return true;
4714 
4715         Arg = ArgE.takeAs<Expr>();
4716 
4717       } else {
4718         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4719 
4720         if (ArgE.isInvalid())
4721           return true;
4722 
4723         Arg = ArgE.takeAs<Expr>();
4724       }
4725 
4726       if (RequireCompleteType(Arg->getLocStart(),
4727                               Arg->getType(),
4728                               diag::err_call_incomplete_argument, Arg))
4729         return ExprError();
4730 
4731       TheCall->setArg(i, Arg);
4732     }
4733   }
4734 
4735   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4736     if (!Method->isStatic())
4737       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4738         << Fn->getSourceRange());
4739 
4740   // Check for sentinels
4741   if (NDecl)
4742     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
4743 
4744   // Do special checking on direct calls to functions.
4745   if (FDecl) {
4746     if (CheckFunctionCall(FDecl, TheCall, Proto))
4747       return ExprError();
4748 
4749     if (BuiltinID)
4750       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4751   } else if (NDecl) {
4752     if (CheckPointerCall(NDecl, TheCall, Proto))
4753       return ExprError();
4754   } else {
4755     if (CheckOtherCall(TheCall, Proto))
4756       return ExprError();
4757   }
4758 
4759   return MaybeBindToTemporary(TheCall);
4760 }
4761 
4762 ExprResult
4763 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4764                            SourceLocation RParenLoc, Expr *InitExpr) {
4765   assert(Ty && "ActOnCompoundLiteral(): missing type");
4766   // FIXME: put back this assert when initializers are worked out.
4767   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4768 
4769   TypeSourceInfo *TInfo;
4770   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4771   if (!TInfo)
4772     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4773 
4774   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4775 }
4776 
4777 ExprResult
4778 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4779                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4780   QualType literalType = TInfo->getType();
4781 
4782   if (literalType->isArrayType()) {
4783     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4784           diag::err_illegal_decl_array_incomplete_type,
4785           SourceRange(LParenLoc,
4786                       LiteralExpr->getSourceRange().getEnd())))
4787       return ExprError();
4788     if (literalType->isVariableArrayType())
4789       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4790         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4791   } else if (!literalType->isDependentType() &&
4792              RequireCompleteType(LParenLoc, literalType,
4793                diag::err_typecheck_decl_incomplete_type,
4794                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4795     return ExprError();
4796 
4797   InitializedEntity Entity
4798     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
4799   InitializationKind Kind
4800     = InitializationKind::CreateCStyleCast(LParenLoc,
4801                                            SourceRange(LParenLoc, RParenLoc),
4802                                            /*InitList=*/true);
4803   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
4804   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4805                                       &literalType);
4806   if (Result.isInvalid())
4807     return ExprError();
4808   LiteralExpr = Result.get();
4809 
4810   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4811   if (isFileScope &&
4812       !LiteralExpr->isTypeDependent() &&
4813       !LiteralExpr->isValueDependent() &&
4814       !literalType->isDependentType()) { // 6.5.2.5p3
4815     if (CheckForConstantInitializer(LiteralExpr, literalType))
4816       return ExprError();
4817   }
4818 
4819   // In C, compound literals are l-values for some reason.
4820   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4821 
4822   return MaybeBindToTemporary(
4823            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4824                                              VK, LiteralExpr, isFileScope));
4825 }
4826 
4827 ExprResult
4828 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4829                     SourceLocation RBraceLoc) {
4830   // Immediately handle non-overload placeholders.  Overloads can be
4831   // resolved contextually, but everything else here can't.
4832   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4833     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4834       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4835 
4836       // Ignore failures; dropping the entire initializer list because
4837       // of one failure would be terrible for indexing/etc.
4838       if (result.isInvalid()) continue;
4839 
4840       InitArgList[I] = result.take();
4841     }
4842   }
4843 
4844   // Semantic analysis for initializers is done by ActOnDeclarator() and
4845   // CheckInitializer() - it requires knowledge of the object being intialized.
4846 
4847   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4848                                                RBraceLoc);
4849   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4850   return Owned(E);
4851 }
4852 
4853 /// Do an explicit extend of the given block pointer if we're in ARC.
4854 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4855   assert(E.get()->getType()->isBlockPointerType());
4856   assert(E.get()->isRValue());
4857 
4858   // Only do this in an r-value context.
4859   if (!S.getLangOpts().ObjCAutoRefCount) return;
4860 
4861   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4862                                CK_ARCExtendBlockObject, E.get(),
4863                                /*base path*/ 0, VK_RValue);
4864   S.ExprNeedsCleanups = true;
4865 }
4866 
4867 /// Prepare a conversion of the given expression to an ObjC object
4868 /// pointer type.
4869 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4870   QualType type = E.get()->getType();
4871   if (type->isObjCObjectPointerType()) {
4872     return CK_BitCast;
4873   } else if (type->isBlockPointerType()) {
4874     maybeExtendBlockObject(*this, E);
4875     return CK_BlockPointerToObjCPointerCast;
4876   } else {
4877     assert(type->isPointerType());
4878     return CK_CPointerToObjCPointerCast;
4879   }
4880 }
4881 
4882 /// Prepares for a scalar cast, performing all the necessary stages
4883 /// except the final cast and returning the kind required.
4884 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4885   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4886   // Also, callers should have filtered out the invalid cases with
4887   // pointers.  Everything else should be possible.
4888 
4889   QualType SrcTy = Src.get()->getType();
4890   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4891     return CK_NoOp;
4892 
4893   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4894   case Type::STK_MemberPointer:
4895     llvm_unreachable("member pointer type in C");
4896 
4897   case Type::STK_CPointer:
4898   case Type::STK_BlockPointer:
4899   case Type::STK_ObjCObjectPointer:
4900     switch (DestTy->getScalarTypeKind()) {
4901     case Type::STK_CPointer: {
4902       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
4903       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
4904       if (SrcAS != DestAS)
4905         return CK_AddressSpaceConversion;
4906       return CK_BitCast;
4907     }
4908     case Type::STK_BlockPointer:
4909       return (SrcKind == Type::STK_BlockPointer
4910                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4911     case Type::STK_ObjCObjectPointer:
4912       if (SrcKind == Type::STK_ObjCObjectPointer)
4913         return CK_BitCast;
4914       if (SrcKind == Type::STK_CPointer)
4915         return CK_CPointerToObjCPointerCast;
4916       maybeExtendBlockObject(*this, Src);
4917       return CK_BlockPointerToObjCPointerCast;
4918     case Type::STK_Bool:
4919       return CK_PointerToBoolean;
4920     case Type::STK_Integral:
4921       return CK_PointerToIntegral;
4922     case Type::STK_Floating:
4923     case Type::STK_FloatingComplex:
4924     case Type::STK_IntegralComplex:
4925     case Type::STK_MemberPointer:
4926       llvm_unreachable("illegal cast from pointer");
4927     }
4928     llvm_unreachable("Should have returned before this");
4929 
4930   case Type::STK_Bool: // casting from bool is like casting from an integer
4931   case Type::STK_Integral:
4932     switch (DestTy->getScalarTypeKind()) {
4933     case Type::STK_CPointer:
4934     case Type::STK_ObjCObjectPointer:
4935     case Type::STK_BlockPointer:
4936       if (Src.get()->isNullPointerConstant(Context,
4937                                            Expr::NPC_ValueDependentIsNull))
4938         return CK_NullToPointer;
4939       return CK_IntegralToPointer;
4940     case Type::STK_Bool:
4941       return CK_IntegralToBoolean;
4942     case Type::STK_Integral:
4943       return CK_IntegralCast;
4944     case Type::STK_Floating:
4945       return CK_IntegralToFloating;
4946     case Type::STK_IntegralComplex:
4947       Src = ImpCastExprToType(Src.take(),
4948                               DestTy->castAs<ComplexType>()->getElementType(),
4949                               CK_IntegralCast);
4950       return CK_IntegralRealToComplex;
4951     case Type::STK_FloatingComplex:
4952       Src = ImpCastExprToType(Src.take(),
4953                               DestTy->castAs<ComplexType>()->getElementType(),
4954                               CK_IntegralToFloating);
4955       return CK_FloatingRealToComplex;
4956     case Type::STK_MemberPointer:
4957       llvm_unreachable("member pointer type in C");
4958     }
4959     llvm_unreachable("Should have returned before this");
4960 
4961   case Type::STK_Floating:
4962     switch (DestTy->getScalarTypeKind()) {
4963     case Type::STK_Floating:
4964       return CK_FloatingCast;
4965     case Type::STK_Bool:
4966       return CK_FloatingToBoolean;
4967     case Type::STK_Integral:
4968       return CK_FloatingToIntegral;
4969     case Type::STK_FloatingComplex:
4970       Src = ImpCastExprToType(Src.take(),
4971                               DestTy->castAs<ComplexType>()->getElementType(),
4972                               CK_FloatingCast);
4973       return CK_FloatingRealToComplex;
4974     case Type::STK_IntegralComplex:
4975       Src = ImpCastExprToType(Src.take(),
4976                               DestTy->castAs<ComplexType>()->getElementType(),
4977                               CK_FloatingToIntegral);
4978       return CK_IntegralRealToComplex;
4979     case Type::STK_CPointer:
4980     case Type::STK_ObjCObjectPointer:
4981     case Type::STK_BlockPointer:
4982       llvm_unreachable("valid float->pointer cast?");
4983     case Type::STK_MemberPointer:
4984       llvm_unreachable("member pointer type in C");
4985     }
4986     llvm_unreachable("Should have returned before this");
4987 
4988   case Type::STK_FloatingComplex:
4989     switch (DestTy->getScalarTypeKind()) {
4990     case Type::STK_FloatingComplex:
4991       return CK_FloatingComplexCast;
4992     case Type::STK_IntegralComplex:
4993       return CK_FloatingComplexToIntegralComplex;
4994     case Type::STK_Floating: {
4995       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4996       if (Context.hasSameType(ET, DestTy))
4997         return CK_FloatingComplexToReal;
4998       Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4999       return CK_FloatingCast;
5000     }
5001     case Type::STK_Bool:
5002       return CK_FloatingComplexToBoolean;
5003     case Type::STK_Integral:
5004       Src = ImpCastExprToType(Src.take(),
5005                               SrcTy->castAs<ComplexType>()->getElementType(),
5006                               CK_FloatingComplexToReal);
5007       return CK_FloatingToIntegral;
5008     case Type::STK_CPointer:
5009     case Type::STK_ObjCObjectPointer:
5010     case Type::STK_BlockPointer:
5011       llvm_unreachable("valid complex float->pointer cast?");
5012     case Type::STK_MemberPointer:
5013       llvm_unreachable("member pointer type in C");
5014     }
5015     llvm_unreachable("Should have returned before this");
5016 
5017   case Type::STK_IntegralComplex:
5018     switch (DestTy->getScalarTypeKind()) {
5019     case Type::STK_FloatingComplex:
5020       return CK_IntegralComplexToFloatingComplex;
5021     case Type::STK_IntegralComplex:
5022       return CK_IntegralComplexCast;
5023     case Type::STK_Integral: {
5024       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5025       if (Context.hasSameType(ET, DestTy))
5026         return CK_IntegralComplexToReal;
5027       Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
5028       return CK_IntegralCast;
5029     }
5030     case Type::STK_Bool:
5031       return CK_IntegralComplexToBoolean;
5032     case Type::STK_Floating:
5033       Src = ImpCastExprToType(Src.take(),
5034                               SrcTy->castAs<ComplexType>()->getElementType(),
5035                               CK_IntegralComplexToReal);
5036       return CK_IntegralToFloating;
5037     case Type::STK_CPointer:
5038     case Type::STK_ObjCObjectPointer:
5039     case Type::STK_BlockPointer:
5040       llvm_unreachable("valid complex int->pointer cast?");
5041     case Type::STK_MemberPointer:
5042       llvm_unreachable("member pointer type in C");
5043     }
5044     llvm_unreachable("Should have returned before this");
5045   }
5046 
5047   llvm_unreachable("Unhandled scalar cast");
5048 }
5049 
5050 static bool breakDownVectorType(QualType type, uint64_t &len,
5051                                 QualType &eltType) {
5052   // Vectors are simple.
5053   if (const VectorType *vecType = type->getAs<VectorType>()) {
5054     len = vecType->getNumElements();
5055     eltType = vecType->getElementType();
5056     assert(eltType->isScalarType());
5057     return true;
5058   }
5059 
5060   // We allow lax conversion to and from non-vector types, but only if
5061   // they're real types (i.e. non-complex, non-pointer scalar types).
5062   if (!type->isRealType()) return false;
5063 
5064   len = 1;
5065   eltType = type;
5066   return true;
5067 }
5068 
5069 static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) {
5070   uint64_t srcLen, destLen;
5071   QualType srcElt, destElt;
5072   if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false;
5073   if (!breakDownVectorType(destTy, destLen, destElt)) return false;
5074 
5075   // ASTContext::getTypeSize will return the size rounded up to a
5076   // power of 2, so instead of using that, we need to use the raw
5077   // element size multiplied by the element count.
5078   uint64_t srcEltSize = S.Context.getTypeSize(srcElt);
5079   uint64_t destEltSize = S.Context.getTypeSize(destElt);
5080 
5081   return (srcLen * srcEltSize == destLen * destEltSize);
5082 }
5083 
5084 /// Is this a legal conversion between two known vector types?
5085 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5086   assert(destTy->isVectorType() || srcTy->isVectorType());
5087 
5088   if (!Context.getLangOpts().LaxVectorConversions)
5089     return false;
5090   return VectorTypesMatch(*this, srcTy, destTy);
5091 }
5092 
5093 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5094                            CastKind &Kind) {
5095   assert(VectorTy->isVectorType() && "Not a vector type!");
5096 
5097   if (Ty->isVectorType() || Ty->isIntegerType()) {
5098     if (!VectorTypesMatch(*this, Ty, VectorTy))
5099       return Diag(R.getBegin(),
5100                   Ty->isVectorType() ?
5101                   diag::err_invalid_conversion_between_vectors :
5102                   diag::err_invalid_conversion_between_vector_and_integer)
5103         << VectorTy << Ty << R;
5104   } else
5105     return Diag(R.getBegin(),
5106                 diag::err_invalid_conversion_between_vector_and_scalar)
5107       << VectorTy << Ty << R;
5108 
5109   Kind = CK_BitCast;
5110   return false;
5111 }
5112 
5113 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5114                                     Expr *CastExpr, CastKind &Kind) {
5115   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5116 
5117   QualType SrcTy = CastExpr->getType();
5118 
5119   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5120   // an ExtVectorType.
5121   // In OpenCL, casts between vectors of different types are not allowed.
5122   // (See OpenCL 6.2).
5123   if (SrcTy->isVectorType()) {
5124     if (!VectorTypesMatch(*this, SrcTy, DestTy)
5125         || (getLangOpts().OpenCL &&
5126             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5127       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5128         << DestTy << SrcTy << R;
5129       return ExprError();
5130     }
5131     Kind = CK_BitCast;
5132     return Owned(CastExpr);
5133   }
5134 
5135   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5136   // conversion will take place first from scalar to elt type, and then
5137   // splat from elt type to vector.
5138   if (SrcTy->isPointerType())
5139     return Diag(R.getBegin(),
5140                 diag::err_invalid_conversion_between_vector_and_scalar)
5141       << DestTy << SrcTy << R;
5142 
5143   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5144   ExprResult CastExprRes = Owned(CastExpr);
5145   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
5146   if (CastExprRes.isInvalid())
5147     return ExprError();
5148   CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
5149 
5150   Kind = CK_VectorSplat;
5151   return Owned(CastExpr);
5152 }
5153 
5154 ExprResult
5155 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5156                     Declarator &D, ParsedType &Ty,
5157                     SourceLocation RParenLoc, Expr *CastExpr) {
5158   assert(!D.isInvalidType() && (CastExpr != 0) &&
5159          "ActOnCastExpr(): missing type or expr");
5160 
5161   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5162   if (D.isInvalidType())
5163     return ExprError();
5164 
5165   if (getLangOpts().CPlusPlus) {
5166     // Check that there are no default arguments (C++ only).
5167     CheckExtraCXXDefaultArguments(D);
5168   }
5169 
5170   checkUnusedDeclAttributes(D);
5171 
5172   QualType castType = castTInfo->getType();
5173   Ty = CreateParsedType(castType, castTInfo);
5174 
5175   bool isVectorLiteral = false;
5176 
5177   // Check for an altivec or OpenCL literal,
5178   // i.e. all the elements are integer constants.
5179   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5180   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5181   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
5182        && castType->isVectorType() && (PE || PLE)) {
5183     if (PLE && PLE->getNumExprs() == 0) {
5184       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5185       return ExprError();
5186     }
5187     if (PE || PLE->getNumExprs() == 1) {
5188       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5189       if (!E->getType()->isVectorType())
5190         isVectorLiteral = true;
5191     }
5192     else
5193       isVectorLiteral = true;
5194   }
5195 
5196   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5197   // then handle it as such.
5198   if (isVectorLiteral)
5199     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5200 
5201   // If the Expr being casted is a ParenListExpr, handle it specially.
5202   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5203   // sequence of BinOp comma operators.
5204   if (isa<ParenListExpr>(CastExpr)) {
5205     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5206     if (Result.isInvalid()) return ExprError();
5207     CastExpr = Result.take();
5208   }
5209 
5210   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5211       !getSourceManager().isInSystemMacro(LParenLoc))
5212     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
5213 
5214   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5215 }
5216 
5217 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5218                                     SourceLocation RParenLoc, Expr *E,
5219                                     TypeSourceInfo *TInfo) {
5220   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5221          "Expected paren or paren list expression");
5222 
5223   Expr **exprs;
5224   unsigned numExprs;
5225   Expr *subExpr;
5226   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5227   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5228     LiteralLParenLoc = PE->getLParenLoc();
5229     LiteralRParenLoc = PE->getRParenLoc();
5230     exprs = PE->getExprs();
5231     numExprs = PE->getNumExprs();
5232   } else { // isa<ParenExpr> by assertion at function entrance
5233     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5234     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5235     subExpr = cast<ParenExpr>(E)->getSubExpr();
5236     exprs = &subExpr;
5237     numExprs = 1;
5238   }
5239 
5240   QualType Ty = TInfo->getType();
5241   assert(Ty->isVectorType() && "Expected vector type");
5242 
5243   SmallVector<Expr *, 8> initExprs;
5244   const VectorType *VTy = Ty->getAs<VectorType>();
5245   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5246 
5247   // '(...)' form of vector initialization in AltiVec: the number of
5248   // initializers must be one or must match the size of the vector.
5249   // If a single value is specified in the initializer then it will be
5250   // replicated to all the components of the vector
5251   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5252     // The number of initializers must be one or must match the size of the
5253     // vector. If a single value is specified in the initializer then it will
5254     // be replicated to all the components of the vector
5255     if (numExprs == 1) {
5256       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5257       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5258       if (Literal.isInvalid())
5259         return ExprError();
5260       Literal = ImpCastExprToType(Literal.take(), ElemTy,
5261                                   PrepareScalarCast(Literal, ElemTy));
5262       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
5263     }
5264     else if (numExprs < numElems) {
5265       Diag(E->getExprLoc(),
5266            diag::err_incorrect_number_of_vector_initializers);
5267       return ExprError();
5268     }
5269     else
5270       initExprs.append(exprs, exprs + numExprs);
5271   }
5272   else {
5273     // For OpenCL, when the number of initializers is a single value,
5274     // it will be replicated to all components of the vector.
5275     if (getLangOpts().OpenCL &&
5276         VTy->getVectorKind() == VectorType::GenericVector &&
5277         numExprs == 1) {
5278         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5279         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5280         if (Literal.isInvalid())
5281           return ExprError();
5282         Literal = ImpCastExprToType(Literal.take(), ElemTy,
5283                                     PrepareScalarCast(Literal, ElemTy));
5284         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
5285     }
5286 
5287     initExprs.append(exprs, exprs + numExprs);
5288   }
5289   // FIXME: This means that pretty-printing the final AST will produce curly
5290   // braces instead of the original commas.
5291   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5292                                                    initExprs, LiteralRParenLoc);
5293   initE->setType(Ty);
5294   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5295 }
5296 
5297 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5298 /// the ParenListExpr into a sequence of comma binary operators.
5299 ExprResult
5300 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5301   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5302   if (!E)
5303     return Owned(OrigExpr);
5304 
5305   ExprResult Result(E->getExpr(0));
5306 
5307   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5308     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5309                         E->getExpr(i));
5310 
5311   if (Result.isInvalid()) return ExprError();
5312 
5313   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5314 }
5315 
5316 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5317                                     SourceLocation R,
5318                                     MultiExprArg Val) {
5319   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5320   return Owned(expr);
5321 }
5322 
5323 /// \brief Emit a specialized diagnostic when one expression is a null pointer
5324 /// constant and the other is not a pointer.  Returns true if a diagnostic is
5325 /// emitted.
5326 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5327                                       SourceLocation QuestionLoc) {
5328   Expr *NullExpr = LHSExpr;
5329   Expr *NonPointerExpr = RHSExpr;
5330   Expr::NullPointerConstantKind NullKind =
5331       NullExpr->isNullPointerConstant(Context,
5332                                       Expr::NPC_ValueDependentIsNotNull);
5333 
5334   if (NullKind == Expr::NPCK_NotNull) {
5335     NullExpr = RHSExpr;
5336     NonPointerExpr = LHSExpr;
5337     NullKind =
5338         NullExpr->isNullPointerConstant(Context,
5339                                         Expr::NPC_ValueDependentIsNotNull);
5340   }
5341 
5342   if (NullKind == Expr::NPCK_NotNull)
5343     return false;
5344 
5345   if (NullKind == Expr::NPCK_ZeroExpression)
5346     return false;
5347 
5348   if (NullKind == Expr::NPCK_ZeroLiteral) {
5349     // In this case, check to make sure that we got here from a "NULL"
5350     // string in the source code.
5351     NullExpr = NullExpr->IgnoreParenImpCasts();
5352     SourceLocation loc = NullExpr->getExprLoc();
5353     if (!findMacroSpelling(loc, "NULL"))
5354       return false;
5355   }
5356 
5357   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5358   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5359       << NonPointerExpr->getType() << DiagType
5360       << NonPointerExpr->getSourceRange();
5361   return true;
5362 }
5363 
5364 /// \brief Return false if the condition expression is valid, true otherwise.
5365 static bool checkCondition(Sema &S, Expr *Cond) {
5366   QualType CondTy = Cond->getType();
5367 
5368   // C99 6.5.15p2
5369   if (CondTy->isScalarType()) return false;
5370 
5371   // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
5372   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
5373     return false;
5374 
5375   // Emit the proper error message.
5376   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
5377                               diag::err_typecheck_cond_expect_scalar :
5378                               diag::err_typecheck_cond_expect_scalar_or_vector)
5379     << CondTy;
5380   return true;
5381 }
5382 
5383 /// \brief Return false if the two expressions can be converted to a vector,
5384 /// true otherwise
5385 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
5386                                                     ExprResult &RHS,
5387                                                     QualType CondTy) {
5388   // Both operands should be of scalar type.
5389   if (!LHS.get()->getType()->isScalarType()) {
5390     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5391       << CondTy;
5392     return true;
5393   }
5394   if (!RHS.get()->getType()->isScalarType()) {
5395     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5396       << CondTy;
5397     return true;
5398   }
5399 
5400   // Implicity convert these scalars to the type of the condition.
5401   LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5402   RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
5403   return false;
5404 }
5405 
5406 /// \brief Handle when one or both operands are void type.
5407 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5408                                          ExprResult &RHS) {
5409     Expr *LHSExpr = LHS.get();
5410     Expr *RHSExpr = RHS.get();
5411 
5412     if (!LHSExpr->getType()->isVoidType())
5413       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5414         << RHSExpr->getSourceRange();
5415     if (!RHSExpr->getType()->isVoidType())
5416       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5417         << LHSExpr->getSourceRange();
5418     LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
5419     RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
5420     return S.Context.VoidTy;
5421 }
5422 
5423 /// \brief Return false if the NullExpr can be promoted to PointerTy,
5424 /// true otherwise.
5425 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5426                                         QualType PointerTy) {
5427   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5428       !NullExpr.get()->isNullPointerConstant(S.Context,
5429                                             Expr::NPC_ValueDependentIsNull))
5430     return true;
5431 
5432   NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
5433   return false;
5434 }
5435 
5436 /// \brief Checks compatibility between two pointers and return the resulting
5437 /// type.
5438 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5439                                                      ExprResult &RHS,
5440                                                      SourceLocation Loc) {
5441   QualType LHSTy = LHS.get()->getType();
5442   QualType RHSTy = RHS.get()->getType();
5443 
5444   if (S.Context.hasSameType(LHSTy, RHSTy)) {
5445     // Two identical pointers types are always compatible.
5446     return LHSTy;
5447   }
5448 
5449   QualType lhptee, rhptee;
5450 
5451   // Get the pointee types.
5452   bool IsBlockPointer = false;
5453   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5454     lhptee = LHSBTy->getPointeeType();
5455     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5456     IsBlockPointer = true;
5457   } else {
5458     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5459     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5460   }
5461 
5462   // C99 6.5.15p6: If both operands are pointers to compatible types or to
5463   // differently qualified versions of compatible types, the result type is
5464   // a pointer to an appropriately qualified version of the composite
5465   // type.
5466 
5467   // Only CVR-qualifiers exist in the standard, and the differently-qualified
5468   // clause doesn't make sense for our extensions. E.g. address space 2 should
5469   // be incompatible with address space 3: they may live on different devices or
5470   // anything.
5471   Qualifiers lhQual = lhptee.getQualifiers();
5472   Qualifiers rhQual = rhptee.getQualifiers();
5473 
5474   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5475   lhQual.removeCVRQualifiers();
5476   rhQual.removeCVRQualifiers();
5477 
5478   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5479   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5480 
5481   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5482 
5483   if (CompositeTy.isNull()) {
5484     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
5485       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5486       << RHS.get()->getSourceRange();
5487     // In this situation, we assume void* type. No especially good
5488     // reason, but this is what gcc does, and we do have to pick
5489     // to get a consistent AST.
5490     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5491     LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5492     RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5493     return incompatTy;
5494   }
5495 
5496   // The pointer types are compatible.
5497   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5498   if (IsBlockPointer)
5499     ResultTy = S.Context.getBlockPointerType(ResultTy);
5500   else
5501     ResultTy = S.Context.getPointerType(ResultTy);
5502 
5503   LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
5504   RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
5505   return ResultTy;
5506 }
5507 
5508 /// \brief Return the resulting type when the operands are both block pointers.
5509 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5510                                                           ExprResult &LHS,
5511                                                           ExprResult &RHS,
5512                                                           SourceLocation Loc) {
5513   QualType LHSTy = LHS.get()->getType();
5514   QualType RHSTy = RHS.get()->getType();
5515 
5516   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5517     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5518       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5519       LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5520       RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5521       return destType;
5522     }
5523     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5524       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5525       << RHS.get()->getSourceRange();
5526     return QualType();
5527   }
5528 
5529   // We have 2 block pointer types.
5530   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5531 }
5532 
5533 /// \brief Return the resulting type when the operands are both pointers.
5534 static QualType
5535 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5536                                             ExprResult &RHS,
5537                                             SourceLocation Loc) {
5538   // get the pointer types
5539   QualType LHSTy = LHS.get()->getType();
5540   QualType RHSTy = RHS.get()->getType();
5541 
5542   // get the "pointed to" types
5543   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5544   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5545 
5546   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5547   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5548     // Figure out necessary qualifiers (C99 6.5.15p6)
5549     QualType destPointee
5550       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5551     QualType destType = S.Context.getPointerType(destPointee);
5552     // Add qualifiers if necessary.
5553     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5554     // Promote to void*.
5555     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5556     return destType;
5557   }
5558   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5559     QualType destPointee
5560       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5561     QualType destType = S.Context.getPointerType(destPointee);
5562     // Add qualifiers if necessary.
5563     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5564     // Promote to void*.
5565     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5566     return destType;
5567   }
5568 
5569   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5570 }
5571 
5572 /// \brief Return false if the first expression is not an integer and the second
5573 /// expression is not a pointer, true otherwise.
5574 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5575                                         Expr* PointerExpr, SourceLocation Loc,
5576                                         bool IsIntFirstExpr) {
5577   if (!PointerExpr->getType()->isPointerType() ||
5578       !Int.get()->getType()->isIntegerType())
5579     return false;
5580 
5581   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5582   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5583 
5584   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5585     << Expr1->getType() << Expr2->getType()
5586     << Expr1->getSourceRange() << Expr2->getSourceRange();
5587   Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
5588                             CK_IntegralToPointer);
5589   return true;
5590 }
5591 
5592 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5593 /// In that case, LHS = cond.
5594 /// C99 6.5.15
5595 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5596                                         ExprResult &RHS, ExprValueKind &VK,
5597                                         ExprObjectKind &OK,
5598                                         SourceLocation QuestionLoc) {
5599 
5600   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5601   if (!LHSResult.isUsable()) return QualType();
5602   LHS = LHSResult;
5603 
5604   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5605   if (!RHSResult.isUsable()) return QualType();
5606   RHS = RHSResult;
5607 
5608   // C++ is sufficiently different to merit its own checker.
5609   if (getLangOpts().CPlusPlus)
5610     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5611 
5612   VK = VK_RValue;
5613   OK = OK_Ordinary;
5614 
5615   // First, check the condition.
5616   Cond = UsualUnaryConversions(Cond.take());
5617   if (Cond.isInvalid())
5618     return QualType();
5619   if (checkCondition(*this, Cond.get()))
5620     return QualType();
5621 
5622   // Now check the two expressions.
5623   if (LHS.get()->getType()->isVectorType() ||
5624       RHS.get()->getType()->isVectorType())
5625     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5626 
5627   UsualArithmeticConversions(LHS, RHS);
5628   if (LHS.isInvalid() || RHS.isInvalid())
5629     return QualType();
5630 
5631   QualType CondTy = Cond.get()->getType();
5632   QualType LHSTy = LHS.get()->getType();
5633   QualType RHSTy = RHS.get()->getType();
5634 
5635   // If the condition is a vector, and both operands are scalar,
5636   // attempt to implicity convert them to the vector type to act like the
5637   // built in select. (OpenCL v1.1 s6.3.i)
5638   if (getLangOpts().OpenCL && CondTy->isVectorType())
5639     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5640       return QualType();
5641 
5642   // If both operands have arithmetic type, do the usual arithmetic conversions
5643   // to find a common type: C99 6.5.15p3,5.
5644   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType())
5645     return LHS.get()->getType();
5646 
5647   // If both operands are the same structure or union type, the result is that
5648   // type.
5649   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5650     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5651       if (LHSRT->getDecl() == RHSRT->getDecl())
5652         // "If both the operands have structure or union type, the result has
5653         // that type."  This implies that CV qualifiers are dropped.
5654         return LHSTy.getUnqualifiedType();
5655     // FIXME: Type of conditional expression must be complete in C mode.
5656   }
5657 
5658   // C99 6.5.15p5: "If both operands have void type, the result has void type."
5659   // The following || allows only one side to be void (a GCC-ism).
5660   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5661     return checkConditionalVoidType(*this, LHS, RHS);
5662   }
5663 
5664   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5665   // the type of the other operand."
5666   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5667   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5668 
5669   // All objective-c pointer type analysis is done here.
5670   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5671                                                         QuestionLoc);
5672   if (LHS.isInvalid() || RHS.isInvalid())
5673     return QualType();
5674   if (!compositeType.isNull())
5675     return compositeType;
5676 
5677 
5678   // Handle block pointer types.
5679   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5680     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5681                                                      QuestionLoc);
5682 
5683   // Check constraints for C object pointers types (C99 6.5.15p3,6).
5684   if (LHSTy->isPointerType() && RHSTy->isPointerType())
5685     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5686                                                        QuestionLoc);
5687 
5688   // GCC compatibility: soften pointer/integer mismatch.  Note that
5689   // null pointers have been filtered out by this point.
5690   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5691       /*isIntFirstExpr=*/true))
5692     return RHSTy;
5693   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5694       /*isIntFirstExpr=*/false))
5695     return LHSTy;
5696 
5697   // Emit a better diagnostic if one of the expressions is a null pointer
5698   // constant and the other is not a pointer type. In this case, the user most
5699   // likely forgot to take the address of the other expression.
5700   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5701     return QualType();
5702 
5703   // Otherwise, the operands are not compatible.
5704   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5705     << LHSTy << RHSTy << LHS.get()->getSourceRange()
5706     << RHS.get()->getSourceRange();
5707   return QualType();
5708 }
5709 
5710 /// FindCompositeObjCPointerType - Helper method to find composite type of
5711 /// two objective-c pointer types of the two input expressions.
5712 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5713                                             SourceLocation QuestionLoc) {
5714   QualType LHSTy = LHS.get()->getType();
5715   QualType RHSTy = RHS.get()->getType();
5716 
5717   // Handle things like Class and struct objc_class*.  Here we case the result
5718   // to the pseudo-builtin, because that will be implicitly cast back to the
5719   // redefinition type if an attempt is made to access its fields.
5720   if (LHSTy->isObjCClassType() &&
5721       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5722     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5723     return LHSTy;
5724   }
5725   if (RHSTy->isObjCClassType() &&
5726       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5727     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5728     return RHSTy;
5729   }
5730   // And the same for struct objc_object* / id
5731   if (LHSTy->isObjCIdType() &&
5732       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5733     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5734     return LHSTy;
5735   }
5736   if (RHSTy->isObjCIdType() &&
5737       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5738     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5739     return RHSTy;
5740   }
5741   // And the same for struct objc_selector* / SEL
5742   if (Context.isObjCSelType(LHSTy) &&
5743       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5744     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
5745     return LHSTy;
5746   }
5747   if (Context.isObjCSelType(RHSTy) &&
5748       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5749     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
5750     return RHSTy;
5751   }
5752   // Check constraints for Objective-C object pointers types.
5753   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5754 
5755     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5756       // Two identical object pointer types are always compatible.
5757       return LHSTy;
5758     }
5759     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5760     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5761     QualType compositeType = LHSTy;
5762 
5763     // If both operands are interfaces and either operand can be
5764     // assigned to the other, use that type as the composite
5765     // type. This allows
5766     //   xxx ? (A*) a : (B*) b
5767     // where B is a subclass of A.
5768     //
5769     // Additionally, as for assignment, if either type is 'id'
5770     // allow silent coercion. Finally, if the types are
5771     // incompatible then make sure to use 'id' as the composite
5772     // type so the result is acceptable for sending messages to.
5773 
5774     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5775     // It could return the composite type.
5776     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5777       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5778     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5779       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5780     } else if ((LHSTy->isObjCQualifiedIdType() ||
5781                 RHSTy->isObjCQualifiedIdType()) &&
5782                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5783       // Need to handle "id<xx>" explicitly.
5784       // GCC allows qualified id and any Objective-C type to devolve to
5785       // id. Currently localizing to here until clear this should be
5786       // part of ObjCQualifiedIdTypesAreCompatible.
5787       compositeType = Context.getObjCIdType();
5788     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5789       compositeType = Context.getObjCIdType();
5790     } else if (!(compositeType =
5791                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5792       ;
5793     else {
5794       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5795       << LHSTy << RHSTy
5796       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5797       QualType incompatTy = Context.getObjCIdType();
5798       LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5799       RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5800       return incompatTy;
5801     }
5802     // The object pointer types are compatible.
5803     LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5804     RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
5805     return compositeType;
5806   }
5807   // Check Objective-C object pointer types and 'void *'
5808   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5809     if (getLangOpts().ObjCAutoRefCount) {
5810       // ARC forbids the implicit conversion of object pointers to 'void *',
5811       // so these types are not compatible.
5812       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5813           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5814       LHS = RHS = true;
5815       return QualType();
5816     }
5817     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5818     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5819     QualType destPointee
5820     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5821     QualType destType = Context.getPointerType(destPointee);
5822     // Add qualifiers if necessary.
5823     LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5824     // Promote to void*.
5825     RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5826     return destType;
5827   }
5828   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5829     if (getLangOpts().ObjCAutoRefCount) {
5830       // ARC forbids the implicit conversion of object pointers to 'void *',
5831       // so these types are not compatible.
5832       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5833           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5834       LHS = RHS = true;
5835       return QualType();
5836     }
5837     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5838     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5839     QualType destPointee
5840     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5841     QualType destType = Context.getPointerType(destPointee);
5842     // Add qualifiers if necessary.
5843     RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5844     // Promote to void*.
5845     LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5846     return destType;
5847   }
5848   return QualType();
5849 }
5850 
5851 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5852 /// ParenRange in parentheses.
5853 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5854                                const PartialDiagnostic &Note,
5855                                SourceRange ParenRange) {
5856   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5857   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5858       EndLoc.isValid()) {
5859     Self.Diag(Loc, Note)
5860       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5861       << FixItHint::CreateInsertion(EndLoc, ")");
5862   } else {
5863     // We can't display the parentheses, so just show the bare note.
5864     Self.Diag(Loc, Note) << ParenRange;
5865   }
5866 }
5867 
5868 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5869   return Opc >= BO_Mul && Opc <= BO_Shr;
5870 }
5871 
5872 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5873 /// expression, either using a built-in or overloaded operator,
5874 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5875 /// expression.
5876 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5877                                    Expr **RHSExprs) {
5878   // Don't strip parenthesis: we should not warn if E is in parenthesis.
5879   E = E->IgnoreImpCasts();
5880   E = E->IgnoreConversionOperator();
5881   E = E->IgnoreImpCasts();
5882 
5883   // Built-in binary operator.
5884   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5885     if (IsArithmeticOp(OP->getOpcode())) {
5886       *Opcode = OP->getOpcode();
5887       *RHSExprs = OP->getRHS();
5888       return true;
5889     }
5890   }
5891 
5892   // Overloaded operator.
5893   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5894     if (Call->getNumArgs() != 2)
5895       return false;
5896 
5897     // Make sure this is really a binary operator that is safe to pass into
5898     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5899     OverloadedOperatorKind OO = Call->getOperator();
5900     if (OO < OO_Plus || OO > OO_Arrow ||
5901         OO == OO_PlusPlus || OO == OO_MinusMinus)
5902       return false;
5903 
5904     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5905     if (IsArithmeticOp(OpKind)) {
5906       *Opcode = OpKind;
5907       *RHSExprs = Call->getArg(1);
5908       return true;
5909     }
5910   }
5911 
5912   return false;
5913 }
5914 
5915 static bool IsLogicOp(BinaryOperatorKind Opc) {
5916   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5917 }
5918 
5919 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5920 /// or is a logical expression such as (x==y) which has int type, but is
5921 /// commonly interpreted as boolean.
5922 static bool ExprLooksBoolean(Expr *E) {
5923   E = E->IgnoreParenImpCasts();
5924 
5925   if (E->getType()->isBooleanType())
5926     return true;
5927   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5928     return IsLogicOp(OP->getOpcode());
5929   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5930     return OP->getOpcode() == UO_LNot;
5931 
5932   return false;
5933 }
5934 
5935 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5936 /// and binary operator are mixed in a way that suggests the programmer assumed
5937 /// the conditional operator has higher precedence, for example:
5938 /// "int x = a + someBinaryCondition ? 1 : 2".
5939 static void DiagnoseConditionalPrecedence(Sema &Self,
5940                                           SourceLocation OpLoc,
5941                                           Expr *Condition,
5942                                           Expr *LHSExpr,
5943                                           Expr *RHSExpr) {
5944   BinaryOperatorKind CondOpcode;
5945   Expr *CondRHS;
5946 
5947   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5948     return;
5949   if (!ExprLooksBoolean(CondRHS))
5950     return;
5951 
5952   // The condition is an arithmetic binary expression, with a right-
5953   // hand side that looks boolean, so warn.
5954 
5955   Self.Diag(OpLoc, diag::warn_precedence_conditional)
5956       << Condition->getSourceRange()
5957       << BinaryOperator::getOpcodeStr(CondOpcode);
5958 
5959   SuggestParentheses(Self, OpLoc,
5960     Self.PDiag(diag::note_precedence_silence)
5961       << BinaryOperator::getOpcodeStr(CondOpcode),
5962     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5963 
5964   SuggestParentheses(Self, OpLoc,
5965     Self.PDiag(diag::note_precedence_conditional_first),
5966     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5967 }
5968 
5969 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5970 /// in the case of a the GNU conditional expr extension.
5971 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5972                                     SourceLocation ColonLoc,
5973                                     Expr *CondExpr, Expr *LHSExpr,
5974                                     Expr *RHSExpr) {
5975   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5976   // was the condition.
5977   OpaqueValueExpr *opaqueValue = 0;
5978   Expr *commonExpr = 0;
5979   if (LHSExpr == 0) {
5980     commonExpr = CondExpr;
5981     // Lower out placeholder types first.  This is important so that we don't
5982     // try to capture a placeholder. This happens in few cases in C++; such
5983     // as Objective-C++'s dictionary subscripting syntax.
5984     if (commonExpr->hasPlaceholderType()) {
5985       ExprResult result = CheckPlaceholderExpr(commonExpr);
5986       if (!result.isUsable()) return ExprError();
5987       commonExpr = result.take();
5988     }
5989     // We usually want to apply unary conversions *before* saving, except
5990     // in the special case of a C++ l-value conditional.
5991     if (!(getLangOpts().CPlusPlus
5992           && !commonExpr->isTypeDependent()
5993           && commonExpr->getValueKind() == RHSExpr->getValueKind()
5994           && commonExpr->isGLValue()
5995           && commonExpr->isOrdinaryOrBitFieldObject()
5996           && RHSExpr->isOrdinaryOrBitFieldObject()
5997           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5998       ExprResult commonRes = UsualUnaryConversions(commonExpr);
5999       if (commonRes.isInvalid())
6000         return ExprError();
6001       commonExpr = commonRes.take();
6002     }
6003 
6004     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6005                                                 commonExpr->getType(),
6006                                                 commonExpr->getValueKind(),
6007                                                 commonExpr->getObjectKind(),
6008                                                 commonExpr);
6009     LHSExpr = CondExpr = opaqueValue;
6010   }
6011 
6012   ExprValueKind VK = VK_RValue;
6013   ExprObjectKind OK = OK_Ordinary;
6014   ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
6015   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
6016                                              VK, OK, QuestionLoc);
6017   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6018       RHS.isInvalid())
6019     return ExprError();
6020 
6021   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6022                                 RHS.get());
6023 
6024   if (!commonExpr)
6025     return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
6026                                                    LHS.take(), ColonLoc,
6027                                                    RHS.take(), result, VK, OK));
6028 
6029   return Owned(new (Context)
6030     BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
6031                               RHS.take(), QuestionLoc, ColonLoc, result, VK,
6032                               OK));
6033 }
6034 
6035 // checkPointerTypesForAssignment - This is a very tricky routine (despite
6036 // being closely modeled after the C99 spec:-). The odd characteristic of this
6037 // routine is it effectively iqnores the qualifiers on the top level pointee.
6038 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6039 // FIXME: add a couple examples in this comment.
6040 static Sema::AssignConvertType
6041 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
6042   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6043   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6044 
6045   // get the "pointed to" type (ignoring qualifiers at the top level)
6046   const Type *lhptee, *rhptee;
6047   Qualifiers lhq, rhq;
6048   std::tie(lhptee, lhq) =
6049       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
6050   std::tie(rhptee, rhq) =
6051       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
6052 
6053   Sema::AssignConvertType ConvTy = Sema::Compatible;
6054 
6055   // C99 6.5.16.1p1: This following citation is common to constraints
6056   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6057   // qualifiers of the type *pointed to* by the right;
6058 
6059   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6060   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6061       lhq.compatiblyIncludesObjCLifetime(rhq)) {
6062     // Ignore lifetime for further calculation.
6063     lhq.removeObjCLifetime();
6064     rhq.removeObjCLifetime();
6065   }
6066 
6067   if (!lhq.compatiblyIncludes(rhq)) {
6068     // Treat address-space mismatches as fatal.  TODO: address subspaces
6069     if (lhq.getAddressSpace() != rhq.getAddressSpace())
6070       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6071 
6072     // It's okay to add or remove GC or lifetime qualifiers when converting to
6073     // and from void*.
6074     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
6075                         .compatiblyIncludes(
6076                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
6077              && (lhptee->isVoidType() || rhptee->isVoidType()))
6078       ; // keep old
6079 
6080     // Treat lifetime mismatches as fatal.
6081     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6082       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6083 
6084     // For GCC compatibility, other qualifier mismatches are treated
6085     // as still compatible in C.
6086     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6087   }
6088 
6089   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6090   // incomplete type and the other is a pointer to a qualified or unqualified
6091   // version of void...
6092   if (lhptee->isVoidType()) {
6093     if (rhptee->isIncompleteOrObjectType())
6094       return ConvTy;
6095 
6096     // As an extension, we allow cast to/from void* to function pointer.
6097     assert(rhptee->isFunctionType());
6098     return Sema::FunctionVoidPointer;
6099   }
6100 
6101   if (rhptee->isVoidType()) {
6102     if (lhptee->isIncompleteOrObjectType())
6103       return ConvTy;
6104 
6105     // As an extension, we allow cast to/from void* to function pointer.
6106     assert(lhptee->isFunctionType());
6107     return Sema::FunctionVoidPointer;
6108   }
6109 
6110   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6111   // unqualified versions of compatible types, ...
6112   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6113   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6114     // Check if the pointee types are compatible ignoring the sign.
6115     // We explicitly check for char so that we catch "char" vs
6116     // "unsigned char" on systems where "char" is unsigned.
6117     if (lhptee->isCharType())
6118       ltrans = S.Context.UnsignedCharTy;
6119     else if (lhptee->hasSignedIntegerRepresentation())
6120       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6121 
6122     if (rhptee->isCharType())
6123       rtrans = S.Context.UnsignedCharTy;
6124     else if (rhptee->hasSignedIntegerRepresentation())
6125       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6126 
6127     if (ltrans == rtrans) {
6128       // Types are compatible ignoring the sign. Qualifier incompatibility
6129       // takes priority over sign incompatibility because the sign
6130       // warning can be disabled.
6131       if (ConvTy != Sema::Compatible)
6132         return ConvTy;
6133 
6134       return Sema::IncompatiblePointerSign;
6135     }
6136 
6137     // If we are a multi-level pointer, it's possible that our issue is simply
6138     // one of qualification - e.g. char ** -> const char ** is not allowed. If
6139     // the eventual target type is the same and the pointers have the same
6140     // level of indirection, this must be the issue.
6141     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6142       do {
6143         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6144         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6145       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6146 
6147       if (lhptee == rhptee)
6148         return Sema::IncompatibleNestedPointerQualifiers;
6149     }
6150 
6151     // General pointer incompatibility takes priority over qualifiers.
6152     return Sema::IncompatiblePointer;
6153   }
6154   if (!S.getLangOpts().CPlusPlus &&
6155       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6156     return Sema::IncompatiblePointer;
6157   return ConvTy;
6158 }
6159 
6160 /// checkBlockPointerTypesForAssignment - This routine determines whether two
6161 /// block pointer types are compatible or whether a block and normal pointer
6162 /// are compatible. It is more restrict than comparing two function pointer
6163 // types.
6164 static Sema::AssignConvertType
6165 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6166                                     QualType RHSType) {
6167   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6168   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6169 
6170   QualType lhptee, rhptee;
6171 
6172   // get the "pointed to" type (ignoring qualifiers at the top level)
6173   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6174   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6175 
6176   // In C++, the types have to match exactly.
6177   if (S.getLangOpts().CPlusPlus)
6178     return Sema::IncompatibleBlockPointer;
6179 
6180   Sema::AssignConvertType ConvTy = Sema::Compatible;
6181 
6182   // For blocks we enforce that qualifiers are identical.
6183   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6184     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6185 
6186   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6187     return Sema::IncompatibleBlockPointer;
6188 
6189   return ConvTy;
6190 }
6191 
6192 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6193 /// for assignment compatibility.
6194 static Sema::AssignConvertType
6195 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6196                                    QualType RHSType) {
6197   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6198   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6199 
6200   if (LHSType->isObjCBuiltinType()) {
6201     // Class is not compatible with ObjC object pointers.
6202     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6203         !RHSType->isObjCQualifiedClassType())
6204       return Sema::IncompatiblePointer;
6205     return Sema::Compatible;
6206   }
6207   if (RHSType->isObjCBuiltinType()) {
6208     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6209         !LHSType->isObjCQualifiedClassType())
6210       return Sema::IncompatiblePointer;
6211     return Sema::Compatible;
6212   }
6213   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6214   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6215 
6216   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6217       // make an exception for id<P>
6218       !LHSType->isObjCQualifiedIdType())
6219     return Sema::CompatiblePointerDiscardsQualifiers;
6220 
6221   if (S.Context.typesAreCompatible(LHSType, RHSType))
6222     return Sema::Compatible;
6223   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6224     return Sema::IncompatibleObjCQualifiedId;
6225   return Sema::IncompatiblePointer;
6226 }
6227 
6228 Sema::AssignConvertType
6229 Sema::CheckAssignmentConstraints(SourceLocation Loc,
6230                                  QualType LHSType, QualType RHSType) {
6231   // Fake up an opaque expression.  We don't actually care about what
6232   // cast operations are required, so if CheckAssignmentConstraints
6233   // adds casts to this they'll be wasted, but fortunately that doesn't
6234   // usually happen on valid code.
6235   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6236   ExprResult RHSPtr = &RHSExpr;
6237   CastKind K = CK_Invalid;
6238 
6239   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
6240 }
6241 
6242 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6243 /// has code to accommodate several GCC extensions when type checking
6244 /// pointers. Here are some objectionable examples that GCC considers warnings:
6245 ///
6246 ///  int a, *pint;
6247 ///  short *pshort;
6248 ///  struct foo *pfoo;
6249 ///
6250 ///  pint = pshort; // warning: assignment from incompatible pointer type
6251 ///  a = pint; // warning: assignment makes integer from pointer without a cast
6252 ///  pint = a; // warning: assignment makes pointer from integer without a cast
6253 ///  pint = pfoo; // warning: assignment from incompatible pointer type
6254 ///
6255 /// As a result, the code for dealing with pointers is more complex than the
6256 /// C99 spec dictates.
6257 ///
6258 /// Sets 'Kind' for any result kind except Incompatible.
6259 Sema::AssignConvertType
6260 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6261                                  CastKind &Kind) {
6262   QualType RHSType = RHS.get()->getType();
6263   QualType OrigLHSType = LHSType;
6264 
6265   // Get canonical types.  We're not formatting these types, just comparing
6266   // them.
6267   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6268   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6269 
6270   // Common case: no conversion required.
6271   if (LHSType == RHSType) {
6272     Kind = CK_NoOp;
6273     return Compatible;
6274   }
6275 
6276   // If we have an atomic type, try a non-atomic assignment, then just add an
6277   // atomic qualification step.
6278   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6279     Sema::AssignConvertType result =
6280       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6281     if (result != Compatible)
6282       return result;
6283     if (Kind != CK_NoOp)
6284       RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
6285     Kind = CK_NonAtomicToAtomic;
6286     return Compatible;
6287   }
6288 
6289   // If the left-hand side is a reference type, then we are in a
6290   // (rare!) case where we've allowed the use of references in C,
6291   // e.g., as a parameter type in a built-in function. In this case,
6292   // just make sure that the type referenced is compatible with the
6293   // right-hand side type. The caller is responsible for adjusting
6294   // LHSType so that the resulting expression does not have reference
6295   // type.
6296   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6297     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6298       Kind = CK_LValueBitCast;
6299       return Compatible;
6300     }
6301     return Incompatible;
6302   }
6303 
6304   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6305   // to the same ExtVector type.
6306   if (LHSType->isExtVectorType()) {
6307     if (RHSType->isExtVectorType())
6308       return Incompatible;
6309     if (RHSType->isArithmeticType()) {
6310       // CK_VectorSplat does T -> vector T, so first cast to the
6311       // element type.
6312       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6313       if (elType != RHSType) {
6314         Kind = PrepareScalarCast(RHS, elType);
6315         RHS = ImpCastExprToType(RHS.take(), elType, Kind);
6316       }
6317       Kind = CK_VectorSplat;
6318       return Compatible;
6319     }
6320   }
6321 
6322   // Conversions to or from vector type.
6323   if (LHSType->isVectorType() || RHSType->isVectorType()) {
6324     if (LHSType->isVectorType() && RHSType->isVectorType()) {
6325       // Allow assignments of an AltiVec vector type to an equivalent GCC
6326       // vector type and vice versa
6327       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6328         Kind = CK_BitCast;
6329         return Compatible;
6330       }
6331 
6332       // If we are allowing lax vector conversions, and LHS and RHS are both
6333       // vectors, the total size only needs to be the same. This is a bitcast;
6334       // no bits are changed but the result type is different.
6335       if (isLaxVectorConversion(RHSType, LHSType)) {
6336         Kind = CK_BitCast;
6337         return IncompatibleVectors;
6338       }
6339     }
6340     return Incompatible;
6341   }
6342 
6343   // Arithmetic conversions.
6344   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
6345       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
6346     Kind = PrepareScalarCast(RHS, LHSType);
6347     return Compatible;
6348   }
6349 
6350   // Conversions to normal pointers.
6351   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
6352     // U* -> T*
6353     if (isa<PointerType>(RHSType)) {
6354       Kind = CK_BitCast;
6355       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
6356     }
6357 
6358     // int -> T*
6359     if (RHSType->isIntegerType()) {
6360       Kind = CK_IntegralToPointer; // FIXME: null?
6361       return IntToPointer;
6362     }
6363 
6364     // C pointers are not compatible with ObjC object pointers,
6365     // with two exceptions:
6366     if (isa<ObjCObjectPointerType>(RHSType)) {
6367       //  - conversions to void*
6368       if (LHSPointer->getPointeeType()->isVoidType()) {
6369         Kind = CK_BitCast;
6370         return Compatible;
6371       }
6372 
6373       //  - conversions from 'Class' to the redefinition type
6374       if (RHSType->isObjCClassType() &&
6375           Context.hasSameType(LHSType,
6376                               Context.getObjCClassRedefinitionType())) {
6377         Kind = CK_BitCast;
6378         return Compatible;
6379       }
6380 
6381       Kind = CK_BitCast;
6382       return IncompatiblePointer;
6383     }
6384 
6385     // U^ -> void*
6386     if (RHSType->getAs<BlockPointerType>()) {
6387       if (LHSPointer->getPointeeType()->isVoidType()) {
6388         Kind = CK_BitCast;
6389         return Compatible;
6390       }
6391     }
6392 
6393     return Incompatible;
6394   }
6395 
6396   // Conversions to block pointers.
6397   if (isa<BlockPointerType>(LHSType)) {
6398     // U^ -> T^
6399     if (RHSType->isBlockPointerType()) {
6400       Kind = CK_BitCast;
6401       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
6402     }
6403 
6404     // int or null -> T^
6405     if (RHSType->isIntegerType()) {
6406       Kind = CK_IntegralToPointer; // FIXME: null
6407       return IntToBlockPointer;
6408     }
6409 
6410     // id -> T^
6411     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
6412       Kind = CK_AnyPointerToBlockPointerCast;
6413       return Compatible;
6414     }
6415 
6416     // void* -> T^
6417     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
6418       if (RHSPT->getPointeeType()->isVoidType()) {
6419         Kind = CK_AnyPointerToBlockPointerCast;
6420         return Compatible;
6421       }
6422 
6423     return Incompatible;
6424   }
6425 
6426   // Conversions to Objective-C pointers.
6427   if (isa<ObjCObjectPointerType>(LHSType)) {
6428     // A* -> B*
6429     if (RHSType->isObjCObjectPointerType()) {
6430       Kind = CK_BitCast;
6431       Sema::AssignConvertType result =
6432         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
6433       if (getLangOpts().ObjCAutoRefCount &&
6434           result == Compatible &&
6435           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
6436         result = IncompatibleObjCWeakRef;
6437       return result;
6438     }
6439 
6440     // int or null -> A*
6441     if (RHSType->isIntegerType()) {
6442       Kind = CK_IntegralToPointer; // FIXME: null
6443       return IntToPointer;
6444     }
6445 
6446     // In general, C pointers are not compatible with ObjC object pointers,
6447     // with two exceptions:
6448     if (isa<PointerType>(RHSType)) {
6449       Kind = CK_CPointerToObjCPointerCast;
6450 
6451       //  - conversions from 'void*'
6452       if (RHSType->isVoidPointerType()) {
6453         return Compatible;
6454       }
6455 
6456       //  - conversions to 'Class' from its redefinition type
6457       if (LHSType->isObjCClassType() &&
6458           Context.hasSameType(RHSType,
6459                               Context.getObjCClassRedefinitionType())) {
6460         return Compatible;
6461       }
6462 
6463       return IncompatiblePointer;
6464     }
6465 
6466     // T^ -> A*
6467     if (RHSType->isBlockPointerType()) {
6468       maybeExtendBlockObject(*this, RHS);
6469       Kind = CK_BlockPointerToObjCPointerCast;
6470       return Compatible;
6471     }
6472 
6473     return Incompatible;
6474   }
6475 
6476   // Conversions from pointers that are not covered by the above.
6477   if (isa<PointerType>(RHSType)) {
6478     // T* -> _Bool
6479     if (LHSType == Context.BoolTy) {
6480       Kind = CK_PointerToBoolean;
6481       return Compatible;
6482     }
6483 
6484     // T* -> int
6485     if (LHSType->isIntegerType()) {
6486       Kind = CK_PointerToIntegral;
6487       return PointerToInt;
6488     }
6489 
6490     return Incompatible;
6491   }
6492 
6493   // Conversions from Objective-C pointers that are not covered by the above.
6494   if (isa<ObjCObjectPointerType>(RHSType)) {
6495     // T* -> _Bool
6496     if (LHSType == Context.BoolTy) {
6497       Kind = CK_PointerToBoolean;
6498       return Compatible;
6499     }
6500 
6501     // T* -> int
6502     if (LHSType->isIntegerType()) {
6503       Kind = CK_PointerToIntegral;
6504       return PointerToInt;
6505     }
6506 
6507     return Incompatible;
6508   }
6509 
6510   // struct A -> struct B
6511   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6512     if (Context.typesAreCompatible(LHSType, RHSType)) {
6513       Kind = CK_NoOp;
6514       return Compatible;
6515     }
6516   }
6517 
6518   return Incompatible;
6519 }
6520 
6521 /// \brief Constructs a transparent union from an expression that is
6522 /// used to initialize the transparent union.
6523 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6524                                       ExprResult &EResult, QualType UnionType,
6525                                       FieldDecl *Field) {
6526   // Build an initializer list that designates the appropriate member
6527   // of the transparent union.
6528   Expr *E = EResult.take();
6529   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6530                                                    E, SourceLocation());
6531   Initializer->setType(UnionType);
6532   Initializer->setInitializedFieldInUnion(Field);
6533 
6534   // Build a compound literal constructing a value of the transparent
6535   // union type from this initializer list.
6536   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6537   EResult = S.Owned(
6538     new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6539                                 VK_RValue, Initializer, false));
6540 }
6541 
6542 Sema::AssignConvertType
6543 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
6544                                                ExprResult &RHS) {
6545   QualType RHSType = RHS.get()->getType();
6546 
6547   // If the ArgType is a Union type, we want to handle a potential
6548   // transparent_union GCC extension.
6549   const RecordType *UT = ArgType->getAsUnionType();
6550   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6551     return Incompatible;
6552 
6553   // The field to initialize within the transparent union.
6554   RecordDecl *UD = UT->getDecl();
6555   FieldDecl *InitField = 0;
6556   // It's compatible if the expression matches any of the fields.
6557   for (auto *it : UD->fields()) {
6558     if (it->getType()->isPointerType()) {
6559       // If the transparent union contains a pointer type, we allow:
6560       // 1) void pointer
6561       // 2) null pointer constant
6562       if (RHSType->isPointerType())
6563         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6564           RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
6565           InitField = it;
6566           break;
6567         }
6568 
6569       if (RHS.get()->isNullPointerConstant(Context,
6570                                            Expr::NPC_ValueDependentIsNull)) {
6571         RHS = ImpCastExprToType(RHS.take(), it->getType(),
6572                                 CK_NullToPointer);
6573         InitField = it;
6574         break;
6575       }
6576     }
6577 
6578     CastKind Kind = CK_Invalid;
6579     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6580           == Compatible) {
6581       RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
6582       InitField = it;
6583       break;
6584     }
6585   }
6586 
6587   if (!InitField)
6588     return Incompatible;
6589 
6590   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6591   return Compatible;
6592 }
6593 
6594 Sema::AssignConvertType
6595 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6596                                        bool Diagnose,
6597                                        bool DiagnoseCFAudited) {
6598   if (getLangOpts().CPlusPlus) {
6599     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6600       // C++ 5.17p3: If the left operand is not of class type, the
6601       // expression is implicitly converted (C++ 4) to the
6602       // cv-unqualified type of the left operand.
6603       ExprResult Res;
6604       if (Diagnose) {
6605         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6606                                         AA_Assigning);
6607       } else {
6608         ImplicitConversionSequence ICS =
6609             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6610                                   /*SuppressUserConversions=*/false,
6611                                   /*AllowExplicit=*/false,
6612                                   /*InOverloadResolution=*/false,
6613                                   /*CStyle=*/false,
6614                                   /*AllowObjCWritebackConversion=*/false);
6615         if (ICS.isFailure())
6616           return Incompatible;
6617         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6618                                         ICS, AA_Assigning);
6619       }
6620       if (Res.isInvalid())
6621         return Incompatible;
6622       Sema::AssignConvertType result = Compatible;
6623       if (getLangOpts().ObjCAutoRefCount &&
6624           !CheckObjCARCUnavailableWeakConversion(LHSType,
6625                                                  RHS.get()->getType()))
6626         result = IncompatibleObjCWeakRef;
6627       RHS = Res;
6628       return result;
6629     }
6630 
6631     // FIXME: Currently, we fall through and treat C++ classes like C
6632     // structures.
6633     // FIXME: We also fall through for atomics; not sure what should
6634     // happen there, though.
6635   }
6636 
6637   // C99 6.5.16.1p1: the left operand is a pointer and the right is
6638   // a null pointer constant.
6639   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
6640        LHSType->isBlockPointerType()) &&
6641       RHS.get()->isNullPointerConstant(Context,
6642                                        Expr::NPC_ValueDependentIsNull)) {
6643     CastKind Kind;
6644     CXXCastPath Path;
6645     CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
6646     RHS = ImpCastExprToType(RHS.take(), LHSType, Kind, VK_RValue, &Path);
6647     return Compatible;
6648   }
6649 
6650   // This check seems unnatural, however it is necessary to ensure the proper
6651   // conversion of functions/arrays. If the conversion were done for all
6652   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6653   // expressions that suppress this implicit conversion (&, sizeof).
6654   //
6655   // Suppress this for references: C++ 8.5.3p5.
6656   if (!LHSType->isReferenceType()) {
6657     RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6658     if (RHS.isInvalid())
6659       return Incompatible;
6660   }
6661 
6662   CastKind Kind = CK_Invalid;
6663   Sema::AssignConvertType result =
6664     CheckAssignmentConstraints(LHSType, RHS, Kind);
6665 
6666   // C99 6.5.16.1p2: The value of the right operand is converted to the
6667   // type of the assignment expression.
6668   // CheckAssignmentConstraints allows the left-hand side to be a reference,
6669   // so that we can use references in built-in functions even in C.
6670   // The getNonReferenceType() call makes sure that the resulting expression
6671   // does not have reference type.
6672   if (result != Incompatible && RHS.get()->getType() != LHSType) {
6673     QualType Ty = LHSType.getNonLValueExprType(Context);
6674     Expr *E = RHS.take();
6675     if (getLangOpts().ObjCAutoRefCount)
6676       CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
6677                              DiagnoseCFAudited);
6678     if (getLangOpts().ObjC1 &&
6679         (CheckObjCBridgeRelatedConversions(E->getLocStart(),
6680                                           LHSType, E->getType(), E) ||
6681          ConversionToObjCStringLiteralCheck(LHSType, E))) {
6682       RHS = Owned(E);
6683       return Compatible;
6684     }
6685 
6686     RHS = ImpCastExprToType(E, Ty, Kind);
6687   }
6688   return result;
6689 }
6690 
6691 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6692                                ExprResult &RHS) {
6693   Diag(Loc, diag::err_typecheck_invalid_operands)
6694     << LHS.get()->getType() << RHS.get()->getType()
6695     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6696   return QualType();
6697 }
6698 
6699 /// Try to convert a value of non-vector type to a vector type by
6700 /// promoting (and only promoting) the type to the element type of the
6701 /// vector and then performing a vector splat.
6702 ///
6703 /// \param scalar - if non-null, actually perform the conversions
6704 /// \return true if the operation fails (but without diagnosing the failure)
6705 static bool tryVectorPromoteAndSplat(Sema &S, ExprResult *scalar,
6706                                      QualType scalarTy,
6707                                      QualType vectorEltTy,
6708                                      QualType vectorTy) {
6709   // The conversion to apply to the scalar before splatting it,
6710   // if necessary.
6711   CastKind scalarCast = CK_Invalid;
6712 
6713   if (vectorEltTy->isIntegralType(S.Context)) {
6714     if (!scalarTy->isIntegralType(S.Context)) return true;
6715     int order = S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy);
6716     if (order < 0) return true;
6717     if (order > 0) scalarCast = CK_IntegralCast;
6718   } else if (vectorEltTy->isRealFloatingType()) {
6719     if (scalarTy->isRealFloatingType()) {
6720       int order = S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy);
6721       if (order < 0) return true;
6722       if (order > 0) scalarCast = CK_FloatingCast;
6723     } else if (scalarTy->isIntegralType(S.Context)) {
6724       scalarCast = CK_IntegralToFloating;
6725     } else {
6726       return true;
6727     }
6728   } else {
6729     return true;
6730   }
6731 
6732   // Adjust scalar if desired.
6733   if (scalar) {
6734     if (scalarCast != CK_Invalid)
6735        *scalar = S.ImpCastExprToType(scalar->take(), vectorEltTy, scalarCast);
6736     *scalar = S.ImpCastExprToType(scalar->take(), vectorTy, CK_VectorSplat);
6737   }
6738   return false;
6739 }
6740 
6741 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6742                                    SourceLocation Loc, bool IsCompAssign) {
6743   if (!IsCompAssign) {
6744     LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6745     if (LHS.isInvalid())
6746       return QualType();
6747   }
6748   RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6749   if (RHS.isInvalid())
6750     return QualType();
6751 
6752   // For conversion purposes, we ignore any qualifiers.
6753   // For example, "const float" and "float" are equivalent.
6754   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
6755   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
6756 
6757   // If the vector types are identical, return.
6758   if (Context.hasSameType(LHSType, RHSType))
6759     return LHSType;
6760 
6761   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
6762   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
6763   assert(LHSVecType || RHSVecType);
6764 
6765   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
6766   if (LHSVecType && RHSVecType &&
6767       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6768     if (isa<ExtVectorType>(LHSVecType)) {
6769       RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6770       return LHSType;
6771     }
6772 
6773     if (!IsCompAssign)
6774       LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6775     return RHSType;
6776   }
6777 
6778   // If we're allowing lax vector conversions, only the total (data) size
6779   // needs to be the same.
6780   // FIXME: Should we really be allowing this?
6781   // FIXME: We really just pick the LHS type arbitrarily?
6782   if (isLaxVectorConversion(RHSType, LHSType)) {
6783     QualType resultType = LHSType;
6784     RHS = ImpCastExprToType(RHS.take(), resultType, CK_BitCast);
6785     return resultType;
6786   }
6787 
6788   // If there's an ext-vector type and a scalar, try to promote (and
6789   // only promote) and splat the scalar to the vector type.
6790   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
6791     if (!tryVectorPromoteAndSplat(*this, &RHS, RHSType,
6792                                   LHSVecType->getElementType(), LHSType))
6793       return LHSType;
6794   }
6795   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
6796     if (!tryVectorPromoteAndSplat(*this, (IsCompAssign ? 0 : &LHS), LHSType,
6797                                   RHSVecType->getElementType(), RHSType))
6798       return RHSType;
6799   }
6800 
6801   // Okay, the expression is invalid.
6802 
6803   // If there's a non-vector, non-real operand, diagnose that.
6804   if ((!RHSVecType && !RHSType->isRealType()) ||
6805       (!LHSVecType && !LHSType->isRealType())) {
6806     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
6807       << LHSType << RHSType
6808       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6809     return QualType();
6810   }
6811 
6812   // Otherwise, use the generic diagnostic.
6813   Diag(Loc, diag::err_typecheck_vector_not_convertable)
6814     << LHSType << RHSType
6815     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6816   return QualType();
6817 }
6818 
6819 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6820 // expression.  These are mainly cases where the null pointer is used as an
6821 // integer instead of a pointer.
6822 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6823                                 SourceLocation Loc, bool IsCompare) {
6824   // The canonical way to check for a GNU null is with isNullPointerConstant,
6825   // but we use a bit of a hack here for speed; this is a relatively
6826   // hot path, and isNullPointerConstant is slow.
6827   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6828   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6829 
6830   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6831 
6832   // Avoid analyzing cases where the result will either be invalid (and
6833   // diagnosed as such) or entirely valid and not something to warn about.
6834   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6835       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6836     return;
6837 
6838   // Comparison operations would not make sense with a null pointer no matter
6839   // what the other expression is.
6840   if (!IsCompare) {
6841     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6842         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6843         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6844     return;
6845   }
6846 
6847   // The rest of the operations only make sense with a null pointer
6848   // if the other expression is a pointer.
6849   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6850       NonNullType->canDecayToPointerType())
6851     return;
6852 
6853   S.Diag(Loc, diag::warn_null_in_comparison_operation)
6854       << LHSNull /* LHS is NULL */ << NonNullType
6855       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6856 }
6857 
6858 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6859                                            SourceLocation Loc,
6860                                            bool IsCompAssign, bool IsDiv) {
6861   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6862 
6863   if (LHS.get()->getType()->isVectorType() ||
6864       RHS.get()->getType()->isVectorType())
6865     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6866 
6867   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6868   if (LHS.isInvalid() || RHS.isInvalid())
6869     return QualType();
6870 
6871 
6872   if (compType.isNull() || !compType->isArithmeticType())
6873     return InvalidOperands(Loc, LHS, RHS);
6874 
6875   // Check for division by zero.
6876   llvm::APSInt RHSValue;
6877   if (IsDiv && !RHS.get()->isValueDependent() &&
6878       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6879     DiagRuntimeBehavior(Loc, RHS.get(),
6880                         PDiag(diag::warn_division_by_zero)
6881                           << RHS.get()->getSourceRange());
6882 
6883   return compType;
6884 }
6885 
6886 QualType Sema::CheckRemainderOperands(
6887   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6888   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6889 
6890   if (LHS.get()->getType()->isVectorType() ||
6891       RHS.get()->getType()->isVectorType()) {
6892     if (LHS.get()->getType()->hasIntegerRepresentation() &&
6893         RHS.get()->getType()->hasIntegerRepresentation())
6894       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6895     return InvalidOperands(Loc, LHS, RHS);
6896   }
6897 
6898   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6899   if (LHS.isInvalid() || RHS.isInvalid())
6900     return QualType();
6901 
6902   if (compType.isNull() || !compType->isIntegerType())
6903     return InvalidOperands(Loc, LHS, RHS);
6904 
6905   // Check for remainder by zero.
6906   llvm::APSInt RHSValue;
6907   if (!RHS.get()->isValueDependent() &&
6908       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6909     DiagRuntimeBehavior(Loc, RHS.get(),
6910                         PDiag(diag::warn_remainder_by_zero)
6911                           << RHS.get()->getSourceRange());
6912 
6913   return compType;
6914 }
6915 
6916 /// \brief Diagnose invalid arithmetic on two void pointers.
6917 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
6918                                                 Expr *LHSExpr, Expr *RHSExpr) {
6919   S.Diag(Loc, S.getLangOpts().CPlusPlus
6920                 ? diag::err_typecheck_pointer_arith_void_type
6921                 : diag::ext_gnu_void_ptr)
6922     << 1 /* two pointers */ << LHSExpr->getSourceRange()
6923                             << RHSExpr->getSourceRange();
6924 }
6925 
6926 /// \brief Diagnose invalid arithmetic on a void pointer.
6927 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6928                                             Expr *Pointer) {
6929   S.Diag(Loc, S.getLangOpts().CPlusPlus
6930                 ? diag::err_typecheck_pointer_arith_void_type
6931                 : diag::ext_gnu_void_ptr)
6932     << 0 /* one pointer */ << Pointer->getSourceRange();
6933 }
6934 
6935 /// \brief Diagnose invalid arithmetic on two function pointers.
6936 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6937                                                     Expr *LHS, Expr *RHS) {
6938   assert(LHS->getType()->isAnyPointerType());
6939   assert(RHS->getType()->isAnyPointerType());
6940   S.Diag(Loc, S.getLangOpts().CPlusPlus
6941                 ? diag::err_typecheck_pointer_arith_function_type
6942                 : diag::ext_gnu_ptr_func_arith)
6943     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6944     // We only show the second type if it differs from the first.
6945     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6946                                                    RHS->getType())
6947     << RHS->getType()->getPointeeType()
6948     << LHS->getSourceRange() << RHS->getSourceRange();
6949 }
6950 
6951 /// \brief Diagnose invalid arithmetic on a function pointer.
6952 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6953                                                 Expr *Pointer) {
6954   assert(Pointer->getType()->isAnyPointerType());
6955   S.Diag(Loc, S.getLangOpts().CPlusPlus
6956                 ? diag::err_typecheck_pointer_arith_function_type
6957                 : diag::ext_gnu_ptr_func_arith)
6958     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6959     << 0 /* one pointer, so only one type */
6960     << Pointer->getSourceRange();
6961 }
6962 
6963 /// \brief Emit error if Operand is incomplete pointer type
6964 ///
6965 /// \returns True if pointer has incomplete type
6966 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6967                                                  Expr *Operand) {
6968   assert(Operand->getType()->isAnyPointerType() &&
6969          !Operand->getType()->isDependentType());
6970   QualType PointeeTy = Operand->getType()->getPointeeType();
6971   return S.RequireCompleteType(Loc, PointeeTy,
6972                                diag::err_typecheck_arithmetic_incomplete_type,
6973                                PointeeTy, Operand->getSourceRange());
6974 }
6975 
6976 /// \brief Check the validity of an arithmetic pointer operand.
6977 ///
6978 /// If the operand has pointer type, this code will check for pointer types
6979 /// which are invalid in arithmetic operations. These will be diagnosed
6980 /// appropriately, including whether or not the use is supported as an
6981 /// extension.
6982 ///
6983 /// \returns True when the operand is valid to use (even if as an extension).
6984 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6985                                             Expr *Operand) {
6986   if (!Operand->getType()->isAnyPointerType()) return true;
6987 
6988   QualType PointeeTy = Operand->getType()->getPointeeType();
6989   if (PointeeTy->isVoidType()) {
6990     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6991     return !S.getLangOpts().CPlusPlus;
6992   }
6993   if (PointeeTy->isFunctionType()) {
6994     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6995     return !S.getLangOpts().CPlusPlus;
6996   }
6997 
6998   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
6999 
7000   return true;
7001 }
7002 
7003 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
7004 /// operands.
7005 ///
7006 /// This routine will diagnose any invalid arithmetic on pointer operands much
7007 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
7008 /// for emitting a single diagnostic even for operations where both LHS and RHS
7009 /// are (potentially problematic) pointers.
7010 ///
7011 /// \returns True when the operand is valid to use (even if as an extension).
7012 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
7013                                                 Expr *LHSExpr, Expr *RHSExpr) {
7014   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
7015   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
7016   if (!isLHSPointer && !isRHSPointer) return true;
7017 
7018   QualType LHSPointeeTy, RHSPointeeTy;
7019   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
7020   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
7021 
7022   // Check for arithmetic on pointers to incomplete types.
7023   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
7024   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
7025   if (isLHSVoidPtr || isRHSVoidPtr) {
7026     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
7027     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
7028     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
7029 
7030     return !S.getLangOpts().CPlusPlus;
7031   }
7032 
7033   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
7034   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
7035   if (isLHSFuncPtr || isRHSFuncPtr) {
7036     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
7037     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
7038                                                                 RHSExpr);
7039     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
7040 
7041     return !S.getLangOpts().CPlusPlus;
7042   }
7043 
7044   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
7045     return false;
7046   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
7047     return false;
7048 
7049   return true;
7050 }
7051 
7052 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
7053 /// literal.
7054 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
7055                                   Expr *LHSExpr, Expr *RHSExpr) {
7056   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
7057   Expr* IndexExpr = RHSExpr;
7058   if (!StrExpr) {
7059     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
7060     IndexExpr = LHSExpr;
7061   }
7062 
7063   bool IsStringPlusInt = StrExpr &&
7064       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
7065   if (!IsStringPlusInt)
7066     return;
7067 
7068   llvm::APSInt index;
7069   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
7070     unsigned StrLenWithNull = StrExpr->getLength() + 1;
7071     if (index.isNonNegative() &&
7072         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
7073                               index.isUnsigned()))
7074       return;
7075   }
7076 
7077   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7078   Self.Diag(OpLoc, diag::warn_string_plus_int)
7079       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
7080 
7081   // Only print a fixit for "str" + int, not for int + "str".
7082   if (IndexExpr == RHSExpr) {
7083     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7084     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7085         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7086         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7087         << FixItHint::CreateInsertion(EndLoc, "]");
7088   } else
7089     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7090 }
7091 
7092 /// \brief Emit a warning when adding a char literal to a string.
7093 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
7094                                    Expr *LHSExpr, Expr *RHSExpr) {
7095   const DeclRefExpr *StringRefExpr =
7096       dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts());
7097   const CharacterLiteral *CharExpr =
7098       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
7099   if (!StringRefExpr) {
7100     StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts());
7101     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
7102   }
7103 
7104   if (!CharExpr || !StringRefExpr)
7105     return;
7106 
7107   const QualType StringType = StringRefExpr->getType();
7108 
7109   // Return if not a PointerType.
7110   if (!StringType->isAnyPointerType())
7111     return;
7112 
7113   // Return if not a CharacterType.
7114   if (!StringType->getPointeeType()->isAnyCharacterType())
7115     return;
7116 
7117   ASTContext &Ctx = Self.getASTContext();
7118   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7119 
7120   const QualType CharType = CharExpr->getType();
7121   if (!CharType->isAnyCharacterType() &&
7122       CharType->isIntegerType() &&
7123       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
7124     Self.Diag(OpLoc, diag::warn_string_plus_char)
7125         << DiagRange << Ctx.CharTy;
7126   } else {
7127     Self.Diag(OpLoc, diag::warn_string_plus_char)
7128         << DiagRange << CharExpr->getType();
7129   }
7130 
7131   // Only print a fixit for str + char, not for char + str.
7132   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
7133     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7134     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7135         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7136         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7137         << FixItHint::CreateInsertion(EndLoc, "]");
7138   } else {
7139     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7140   }
7141 }
7142 
7143 /// \brief Emit error when two pointers are incompatible.
7144 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
7145                                            Expr *LHSExpr, Expr *RHSExpr) {
7146   assert(LHSExpr->getType()->isAnyPointerType());
7147   assert(RHSExpr->getType()->isAnyPointerType());
7148   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7149     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
7150     << RHSExpr->getSourceRange();
7151 }
7152 
7153 QualType Sema::CheckAdditionOperands( // C99 6.5.6
7154     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7155     QualType* CompLHSTy) {
7156   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7157 
7158   if (LHS.get()->getType()->isVectorType() ||
7159       RHS.get()->getType()->isVectorType()) {
7160     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7161     if (CompLHSTy) *CompLHSTy = compType;
7162     return compType;
7163   }
7164 
7165   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7166   if (LHS.isInvalid() || RHS.isInvalid())
7167     return QualType();
7168 
7169   // Diagnose "string literal" '+' int and string '+' "char literal".
7170   if (Opc == BO_Add) {
7171     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
7172     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
7173   }
7174 
7175   // handle the common case first (both operands are arithmetic).
7176   if (!compType.isNull() && compType->isArithmeticType()) {
7177     if (CompLHSTy) *CompLHSTy = compType;
7178     return compType;
7179   }
7180 
7181   // Type-checking.  Ultimately the pointer's going to be in PExp;
7182   // note that we bias towards the LHS being the pointer.
7183   Expr *PExp = LHS.get(), *IExp = RHS.get();
7184 
7185   bool isObjCPointer;
7186   if (PExp->getType()->isPointerType()) {
7187     isObjCPointer = false;
7188   } else if (PExp->getType()->isObjCObjectPointerType()) {
7189     isObjCPointer = true;
7190   } else {
7191     std::swap(PExp, IExp);
7192     if (PExp->getType()->isPointerType()) {
7193       isObjCPointer = false;
7194     } else if (PExp->getType()->isObjCObjectPointerType()) {
7195       isObjCPointer = true;
7196     } else {
7197       return InvalidOperands(Loc, LHS, RHS);
7198     }
7199   }
7200   assert(PExp->getType()->isAnyPointerType());
7201 
7202   if (!IExp->getType()->isIntegerType())
7203     return InvalidOperands(Loc, LHS, RHS);
7204 
7205   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
7206     return QualType();
7207 
7208   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
7209     return QualType();
7210 
7211   // Check array bounds for pointer arithemtic
7212   CheckArrayAccess(PExp, IExp);
7213 
7214   if (CompLHSTy) {
7215     QualType LHSTy = Context.isPromotableBitField(LHS.get());
7216     if (LHSTy.isNull()) {
7217       LHSTy = LHS.get()->getType();
7218       if (LHSTy->isPromotableIntegerType())
7219         LHSTy = Context.getPromotedIntegerType(LHSTy);
7220     }
7221     *CompLHSTy = LHSTy;
7222   }
7223 
7224   return PExp->getType();
7225 }
7226 
7227 // C99 6.5.6
7228 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
7229                                         SourceLocation Loc,
7230                                         QualType* CompLHSTy) {
7231   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7232 
7233   if (LHS.get()->getType()->isVectorType() ||
7234       RHS.get()->getType()->isVectorType()) {
7235     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7236     if (CompLHSTy) *CompLHSTy = compType;
7237     return compType;
7238   }
7239 
7240   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7241   if (LHS.isInvalid() || RHS.isInvalid())
7242     return QualType();
7243 
7244   // Enforce type constraints: C99 6.5.6p3.
7245 
7246   // Handle the common case first (both operands are arithmetic).
7247   if (!compType.isNull() && compType->isArithmeticType()) {
7248     if (CompLHSTy) *CompLHSTy = compType;
7249     return compType;
7250   }
7251 
7252   // Either ptr - int   or   ptr - ptr.
7253   if (LHS.get()->getType()->isAnyPointerType()) {
7254     QualType lpointee = LHS.get()->getType()->getPointeeType();
7255 
7256     // Diagnose bad cases where we step over interface counts.
7257     if (LHS.get()->getType()->isObjCObjectPointerType() &&
7258         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
7259       return QualType();
7260 
7261     // The result type of a pointer-int computation is the pointer type.
7262     if (RHS.get()->getType()->isIntegerType()) {
7263       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
7264         return QualType();
7265 
7266       // Check array bounds for pointer arithemtic
7267       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
7268                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
7269 
7270       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7271       return LHS.get()->getType();
7272     }
7273 
7274     // Handle pointer-pointer subtractions.
7275     if (const PointerType *RHSPTy
7276           = RHS.get()->getType()->getAs<PointerType>()) {
7277       QualType rpointee = RHSPTy->getPointeeType();
7278 
7279       if (getLangOpts().CPlusPlus) {
7280         // Pointee types must be the same: C++ [expr.add]
7281         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7282           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7283         }
7284       } else {
7285         // Pointee types must be compatible C99 6.5.6p3
7286         if (!Context.typesAreCompatible(
7287                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7288                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7289           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7290           return QualType();
7291         }
7292       }
7293 
7294       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
7295                                                LHS.get(), RHS.get()))
7296         return QualType();
7297 
7298       // The pointee type may have zero size.  As an extension, a structure or
7299       // union may have zero size or an array may have zero length.  In this
7300       // case subtraction does not make sense.
7301       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
7302         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
7303         if (ElementSize.isZero()) {
7304           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
7305             << rpointee.getUnqualifiedType()
7306             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7307         }
7308       }
7309 
7310       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7311       return Context.getPointerDiffType();
7312     }
7313   }
7314 
7315   return InvalidOperands(Loc, LHS, RHS);
7316 }
7317 
7318 static bool isScopedEnumerationType(QualType T) {
7319   if (const EnumType *ET = dyn_cast<EnumType>(T))
7320     return ET->getDecl()->isScoped();
7321   return false;
7322 }
7323 
7324 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
7325                                    SourceLocation Loc, unsigned Opc,
7326                                    QualType LHSType) {
7327   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
7328   // so skip remaining warnings as we don't want to modify values within Sema.
7329   if (S.getLangOpts().OpenCL)
7330     return;
7331 
7332   llvm::APSInt Right;
7333   // Check right/shifter operand
7334   if (RHS.get()->isValueDependent() ||
7335       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
7336     return;
7337 
7338   if (Right.isNegative()) {
7339     S.DiagRuntimeBehavior(Loc, RHS.get(),
7340                           S.PDiag(diag::warn_shift_negative)
7341                             << RHS.get()->getSourceRange());
7342     return;
7343   }
7344   llvm::APInt LeftBits(Right.getBitWidth(),
7345                        S.Context.getTypeSize(LHS.get()->getType()));
7346   if (Right.uge(LeftBits)) {
7347     S.DiagRuntimeBehavior(Loc, RHS.get(),
7348                           S.PDiag(diag::warn_shift_gt_typewidth)
7349                             << RHS.get()->getSourceRange());
7350     return;
7351   }
7352   if (Opc != BO_Shl)
7353     return;
7354 
7355   // When left shifting an ICE which is signed, we can check for overflow which
7356   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7357   // integers have defined behavior modulo one more than the maximum value
7358   // representable in the result type, so never warn for those.
7359   llvm::APSInt Left;
7360   if (LHS.get()->isValueDependent() ||
7361       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
7362       LHSType->hasUnsignedIntegerRepresentation())
7363     return;
7364   llvm::APInt ResultBits =
7365       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7366   if (LeftBits.uge(ResultBits))
7367     return;
7368   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7369   Result = Result.shl(Right);
7370 
7371   // Print the bit representation of the signed integer as an unsigned
7372   // hexadecimal number.
7373   SmallString<40> HexResult;
7374   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7375 
7376   // If we are only missing a sign bit, this is less likely to result in actual
7377   // bugs -- if the result is cast back to an unsigned type, it will have the
7378   // expected value. Thus we place this behind a different warning that can be
7379   // turned off separately if needed.
7380   if (LeftBits == ResultBits - 1) {
7381     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7382         << HexResult.str() << LHSType
7383         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7384     return;
7385   }
7386 
7387   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7388     << HexResult.str() << Result.getMinSignedBits() << LHSType
7389     << Left.getBitWidth() << LHS.get()->getSourceRange()
7390     << RHS.get()->getSourceRange();
7391 }
7392 
7393 // C99 6.5.7
7394 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
7395                                   SourceLocation Loc, unsigned Opc,
7396                                   bool IsCompAssign) {
7397   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7398 
7399   // Vector shifts promote their scalar inputs to vector type.
7400   if (LHS.get()->getType()->isVectorType() ||
7401       RHS.get()->getType()->isVectorType())
7402     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7403 
7404   // Shifts don't perform usual arithmetic conversions, they just do integer
7405   // promotions on each operand. C99 6.5.7p3
7406 
7407   // For the LHS, do usual unary conversions, but then reset them away
7408   // if this is a compound assignment.
7409   ExprResult OldLHS = LHS;
7410   LHS = UsualUnaryConversions(LHS.take());
7411   if (LHS.isInvalid())
7412     return QualType();
7413   QualType LHSType = LHS.get()->getType();
7414   if (IsCompAssign) LHS = OldLHS;
7415 
7416   // The RHS is simpler.
7417   RHS = UsualUnaryConversions(RHS.take());
7418   if (RHS.isInvalid())
7419     return QualType();
7420   QualType RHSType = RHS.get()->getType();
7421 
7422   // C99 6.5.7p2: Each of the operands shall have integer type.
7423   if (!LHSType->hasIntegerRepresentation() ||
7424       !RHSType->hasIntegerRepresentation())
7425     return InvalidOperands(Loc, LHS, RHS);
7426 
7427   // C++0x: Don't allow scoped enums. FIXME: Use something better than
7428   // hasIntegerRepresentation() above instead of this.
7429   if (isScopedEnumerationType(LHSType) ||
7430       isScopedEnumerationType(RHSType)) {
7431     return InvalidOperands(Loc, LHS, RHS);
7432   }
7433   // Sanity-check shift operands
7434   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
7435 
7436   // "The type of the result is that of the promoted left operand."
7437   return LHSType;
7438 }
7439 
7440 static bool IsWithinTemplateSpecialization(Decl *D) {
7441   if (DeclContext *DC = D->getDeclContext()) {
7442     if (isa<ClassTemplateSpecializationDecl>(DC))
7443       return true;
7444     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7445       return FD->isFunctionTemplateSpecialization();
7446   }
7447   return false;
7448 }
7449 
7450 /// If two different enums are compared, raise a warning.
7451 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
7452                                 Expr *RHS) {
7453   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
7454   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
7455 
7456   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
7457   if (!LHSEnumType)
7458     return;
7459   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
7460   if (!RHSEnumType)
7461     return;
7462 
7463   // Ignore anonymous enums.
7464   if (!LHSEnumType->getDecl()->getIdentifier())
7465     return;
7466   if (!RHSEnumType->getDecl()->getIdentifier())
7467     return;
7468 
7469   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
7470     return;
7471 
7472   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7473       << LHSStrippedType << RHSStrippedType
7474       << LHS->getSourceRange() << RHS->getSourceRange();
7475 }
7476 
7477 /// \brief Diagnose bad pointer comparisons.
7478 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
7479                                               ExprResult &LHS, ExprResult &RHS,
7480                                               bool IsError) {
7481   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
7482                       : diag::ext_typecheck_comparison_of_distinct_pointers)
7483     << LHS.get()->getType() << RHS.get()->getType()
7484     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7485 }
7486 
7487 /// \brief Returns false if the pointers are converted to a composite type,
7488 /// true otherwise.
7489 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
7490                                            ExprResult &LHS, ExprResult &RHS) {
7491   // C++ [expr.rel]p2:
7492   //   [...] Pointer conversions (4.10) and qualification
7493   //   conversions (4.4) are performed on pointer operands (or on
7494   //   a pointer operand and a null pointer constant) to bring
7495   //   them to their composite pointer type. [...]
7496   //
7497   // C++ [expr.eq]p1 uses the same notion for (in)equality
7498   // comparisons of pointers.
7499 
7500   // C++ [expr.eq]p2:
7501   //   In addition, pointers to members can be compared, or a pointer to
7502   //   member and a null pointer constant. Pointer to member conversions
7503   //   (4.11) and qualification conversions (4.4) are performed to bring
7504   //   them to a common type. If one operand is a null pointer constant,
7505   //   the common type is the type of the other operand. Otherwise, the
7506   //   common type is a pointer to member type similar (4.4) to the type
7507   //   of one of the operands, with a cv-qualification signature (4.4)
7508   //   that is the union of the cv-qualification signatures of the operand
7509   //   types.
7510 
7511   QualType LHSType = LHS.get()->getType();
7512   QualType RHSType = RHS.get()->getType();
7513   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
7514          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
7515 
7516   bool NonStandardCompositeType = false;
7517   bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
7518   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
7519   if (T.isNull()) {
7520     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
7521     return true;
7522   }
7523 
7524   if (NonStandardCompositeType)
7525     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
7526       << LHSType << RHSType << T << LHS.get()->getSourceRange()
7527       << RHS.get()->getSourceRange();
7528 
7529   LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
7530   RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
7531   return false;
7532 }
7533 
7534 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
7535                                                     ExprResult &LHS,
7536                                                     ExprResult &RHS,
7537                                                     bool IsError) {
7538   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
7539                       : diag::ext_typecheck_comparison_of_fptr_to_void)
7540     << LHS.get()->getType() << RHS.get()->getType()
7541     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7542 }
7543 
7544 static bool isObjCObjectLiteral(ExprResult &E) {
7545   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
7546   case Stmt::ObjCArrayLiteralClass:
7547   case Stmt::ObjCDictionaryLiteralClass:
7548   case Stmt::ObjCStringLiteralClass:
7549   case Stmt::ObjCBoxedExprClass:
7550     return true;
7551   default:
7552     // Note that ObjCBoolLiteral is NOT an object literal!
7553     return false;
7554   }
7555 }
7556 
7557 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
7558   const ObjCObjectPointerType *Type =
7559     LHS->getType()->getAs<ObjCObjectPointerType>();
7560 
7561   // If this is not actually an Objective-C object, bail out.
7562   if (!Type)
7563     return false;
7564 
7565   // Get the LHS object's interface type.
7566   QualType InterfaceType = Type->getPointeeType();
7567   if (const ObjCObjectType *iQFaceTy =
7568       InterfaceType->getAsObjCQualifiedInterfaceType())
7569     InterfaceType = iQFaceTy->getBaseType();
7570 
7571   // If the RHS isn't an Objective-C object, bail out.
7572   if (!RHS->getType()->isObjCObjectPointerType())
7573     return false;
7574 
7575   // Try to find the -isEqual: method.
7576   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
7577   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
7578                                                       InterfaceType,
7579                                                       /*instance=*/true);
7580   if (!Method) {
7581     if (Type->isObjCIdType()) {
7582       // For 'id', just check the global pool.
7583       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
7584                                                   /*receiverId=*/true,
7585                                                   /*warn=*/false);
7586     } else {
7587       // Check protocols.
7588       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
7589                                              /*instance=*/true);
7590     }
7591   }
7592 
7593   if (!Method)
7594     return false;
7595 
7596   QualType T = Method->param_begin()[0]->getType();
7597   if (!T->isObjCObjectPointerType())
7598     return false;
7599 
7600   QualType R = Method->getReturnType();
7601   if (!R->isScalarType())
7602     return false;
7603 
7604   return true;
7605 }
7606 
7607 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
7608   FromE = FromE->IgnoreParenImpCasts();
7609   switch (FromE->getStmtClass()) {
7610     default:
7611       break;
7612     case Stmt::ObjCStringLiteralClass:
7613       // "string literal"
7614       return LK_String;
7615     case Stmt::ObjCArrayLiteralClass:
7616       // "array literal"
7617       return LK_Array;
7618     case Stmt::ObjCDictionaryLiteralClass:
7619       // "dictionary literal"
7620       return LK_Dictionary;
7621     case Stmt::BlockExprClass:
7622       return LK_Block;
7623     case Stmt::ObjCBoxedExprClass: {
7624       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
7625       switch (Inner->getStmtClass()) {
7626         case Stmt::IntegerLiteralClass:
7627         case Stmt::FloatingLiteralClass:
7628         case Stmt::CharacterLiteralClass:
7629         case Stmt::ObjCBoolLiteralExprClass:
7630         case Stmt::CXXBoolLiteralExprClass:
7631           // "numeric literal"
7632           return LK_Numeric;
7633         case Stmt::ImplicitCastExprClass: {
7634           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
7635           // Boolean literals can be represented by implicit casts.
7636           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
7637             return LK_Numeric;
7638           break;
7639         }
7640         default:
7641           break;
7642       }
7643       return LK_Boxed;
7644     }
7645   }
7646   return LK_None;
7647 }
7648 
7649 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
7650                                           ExprResult &LHS, ExprResult &RHS,
7651                                           BinaryOperator::Opcode Opc){
7652   Expr *Literal;
7653   Expr *Other;
7654   if (isObjCObjectLiteral(LHS)) {
7655     Literal = LHS.get();
7656     Other = RHS.get();
7657   } else {
7658     Literal = RHS.get();
7659     Other = LHS.get();
7660   }
7661 
7662   // Don't warn on comparisons against nil.
7663   Other = Other->IgnoreParenCasts();
7664   if (Other->isNullPointerConstant(S.getASTContext(),
7665                                    Expr::NPC_ValueDependentIsNotNull))
7666     return;
7667 
7668   // This should be kept in sync with warn_objc_literal_comparison.
7669   // LK_String should always be after the other literals, since it has its own
7670   // warning flag.
7671   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
7672   assert(LiteralKind != Sema::LK_Block);
7673   if (LiteralKind == Sema::LK_None) {
7674     llvm_unreachable("Unknown Objective-C object literal kind");
7675   }
7676 
7677   if (LiteralKind == Sema::LK_String)
7678     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7679       << Literal->getSourceRange();
7680   else
7681     S.Diag(Loc, diag::warn_objc_literal_comparison)
7682       << LiteralKind << Literal->getSourceRange();
7683 
7684   if (BinaryOperator::isEqualityOp(Opc) &&
7685       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7686     SourceLocation Start = LHS.get()->getLocStart();
7687     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
7688     CharSourceRange OpRange =
7689       CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
7690 
7691     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7692       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
7693       << FixItHint::CreateReplacement(OpRange, " isEqual:")
7694       << FixItHint::CreateInsertion(End, "]");
7695   }
7696 }
7697 
7698 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
7699                                                 ExprResult &RHS,
7700                                                 SourceLocation Loc,
7701                                                 unsigned OpaqueOpc) {
7702   // This checking requires bools.
7703   if (!S.getLangOpts().Bool) return;
7704 
7705   // Check that left hand side is !something.
7706   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
7707   if (!UO || UO->getOpcode() != UO_LNot) return;
7708 
7709   // Only check if the right hand side is non-bool arithmetic type.
7710   if (RHS.get()->getType()->isBooleanType()) return;
7711 
7712   // Make sure that the something in !something is not bool.
7713   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
7714   if (SubExpr->getType()->isBooleanType()) return;
7715 
7716   // Emit warning.
7717   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
7718       << Loc;
7719 
7720   // First note suggest !(x < y)
7721   SourceLocation FirstOpen = SubExpr->getLocStart();
7722   SourceLocation FirstClose = RHS.get()->getLocEnd();
7723   FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
7724   if (FirstClose.isInvalid())
7725     FirstOpen = SourceLocation();
7726   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
7727       << FixItHint::CreateInsertion(FirstOpen, "(")
7728       << FixItHint::CreateInsertion(FirstClose, ")");
7729 
7730   // Second note suggests (!x) < y
7731   SourceLocation SecondOpen = LHS.get()->getLocStart();
7732   SourceLocation SecondClose = LHS.get()->getLocEnd();
7733   SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
7734   if (SecondClose.isInvalid())
7735     SecondOpen = SourceLocation();
7736   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
7737       << FixItHint::CreateInsertion(SecondOpen, "(")
7738       << FixItHint::CreateInsertion(SecondClose, ")");
7739 }
7740 
7741 // Get the decl for a simple expression: a reference to a variable,
7742 // an implicit C++ field reference, or an implicit ObjC ivar reference.
7743 static ValueDecl *getCompareDecl(Expr *E) {
7744   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
7745     return DR->getDecl();
7746   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
7747     if (Ivar->isFreeIvar())
7748       return Ivar->getDecl();
7749   }
7750   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
7751     if (Mem->isImplicitAccess())
7752       return Mem->getMemberDecl();
7753   }
7754   return 0;
7755 }
7756 
7757 // C99 6.5.8, C++ [expr.rel]
7758 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
7759                                     SourceLocation Loc, unsigned OpaqueOpc,
7760                                     bool IsRelational) {
7761   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7762 
7763   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7764 
7765   // Handle vector comparisons separately.
7766   if (LHS.get()->getType()->isVectorType() ||
7767       RHS.get()->getType()->isVectorType())
7768     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
7769 
7770   QualType LHSType = LHS.get()->getType();
7771   QualType RHSType = RHS.get()->getType();
7772 
7773   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7774   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
7775 
7776   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
7777   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
7778 
7779   if (!LHSType->hasFloatingRepresentation() &&
7780       !(LHSType->isBlockPointerType() && IsRelational) &&
7781       !LHS.get()->getLocStart().isMacroID() &&
7782       !RHS.get()->getLocStart().isMacroID() &&
7783       ActiveTemplateInstantiations.empty()) {
7784     // For non-floating point types, check for self-comparisons of the form
7785     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7786     // often indicate logic errors in the program.
7787     //
7788     // NOTE: Don't warn about comparison expressions resulting from macro
7789     // expansion. Also don't warn about comparisons which are only self
7790     // comparisons within a template specialization. The warnings should catch
7791     // obvious cases in the definition of the template anyways. The idea is to
7792     // warn when the typed comparison operator will always evaluate to the same
7793     // result.
7794     ValueDecl *DL = getCompareDecl(LHSStripped);
7795     ValueDecl *DR = getCompareDecl(RHSStripped);
7796     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
7797       DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7798                           << 0 // self-
7799                           << (Opc == BO_EQ
7800                               || Opc == BO_LE
7801                               || Opc == BO_GE));
7802     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
7803                !DL->getType()->isReferenceType() &&
7804                !DR->getType()->isReferenceType()) {
7805         // what is it always going to eval to?
7806         char always_evals_to;
7807         switch(Opc) {
7808         case BO_EQ: // e.g. array1 == array2
7809           always_evals_to = 0; // false
7810           break;
7811         case BO_NE: // e.g. array1 != array2
7812           always_evals_to = 1; // true
7813           break;
7814         default:
7815           // best we can say is 'a constant'
7816           always_evals_to = 2; // e.g. array1 <= array2
7817           break;
7818         }
7819         DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7820                             << 1 // array
7821                             << always_evals_to);
7822     }
7823 
7824     if (isa<CastExpr>(LHSStripped))
7825       LHSStripped = LHSStripped->IgnoreParenCasts();
7826     if (isa<CastExpr>(RHSStripped))
7827       RHSStripped = RHSStripped->IgnoreParenCasts();
7828 
7829     // Warn about comparisons against a string constant (unless the other
7830     // operand is null), the user probably wants strcmp.
7831     Expr *literalString = 0;
7832     Expr *literalStringStripped = 0;
7833     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7834         !RHSStripped->isNullPointerConstant(Context,
7835                                             Expr::NPC_ValueDependentIsNull)) {
7836       literalString = LHS.get();
7837       literalStringStripped = LHSStripped;
7838     } else if ((isa<StringLiteral>(RHSStripped) ||
7839                 isa<ObjCEncodeExpr>(RHSStripped)) &&
7840                !LHSStripped->isNullPointerConstant(Context,
7841                                             Expr::NPC_ValueDependentIsNull)) {
7842       literalString = RHS.get();
7843       literalStringStripped = RHSStripped;
7844     }
7845 
7846     if (literalString) {
7847       DiagRuntimeBehavior(Loc, 0,
7848         PDiag(diag::warn_stringcompare)
7849           << isa<ObjCEncodeExpr>(literalStringStripped)
7850           << literalString->getSourceRange());
7851     }
7852   }
7853 
7854   // C99 6.5.8p3 / C99 6.5.9p4
7855   UsualArithmeticConversions(LHS, RHS);
7856   if (LHS.isInvalid() || RHS.isInvalid())
7857     return QualType();
7858 
7859   LHSType = LHS.get()->getType();
7860   RHSType = RHS.get()->getType();
7861 
7862   // The result of comparisons is 'bool' in C++, 'int' in C.
7863   QualType ResultTy = Context.getLogicalOperationType();
7864 
7865   if (IsRelational) {
7866     if (LHSType->isRealType() && RHSType->isRealType())
7867       return ResultTy;
7868   } else {
7869     // Check for comparisons of floating point operands using != and ==.
7870     if (LHSType->hasFloatingRepresentation())
7871       CheckFloatComparison(Loc, LHS.get(), RHS.get());
7872 
7873     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7874       return ResultTy;
7875   }
7876 
7877   const Expr::NullPointerConstantKind LHSNullKind =
7878       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
7879   const Expr::NullPointerConstantKind RHSNullKind =
7880       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
7881   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
7882   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
7883 
7884   if (!IsRelational && LHSIsNull != RHSIsNull) {
7885     bool IsEquality = Opc == BO_EQ;
7886     if (RHSIsNull)
7887       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
7888                                    RHS.get()->getSourceRange());
7889     else
7890       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
7891                                    LHS.get()->getSourceRange());
7892   }
7893 
7894   // All of the following pointer-related warnings are GCC extensions, except
7895   // when handling null pointer constants.
7896   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7897     QualType LCanPointeeTy =
7898       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7899     QualType RCanPointeeTy =
7900       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7901 
7902     if (getLangOpts().CPlusPlus) {
7903       if (LCanPointeeTy == RCanPointeeTy)
7904         return ResultTy;
7905       if (!IsRelational &&
7906           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7907         // Valid unless comparison between non-null pointer and function pointer
7908         // This is a gcc extension compatibility comparison.
7909         // In a SFINAE context, we treat this as a hard error to maintain
7910         // conformance with the C++ standard.
7911         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7912             && !LHSIsNull && !RHSIsNull) {
7913           diagnoseFunctionPointerToVoidComparison(
7914               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
7915 
7916           if (isSFINAEContext())
7917             return QualType();
7918 
7919           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7920           return ResultTy;
7921         }
7922       }
7923 
7924       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7925         return QualType();
7926       else
7927         return ResultTy;
7928     }
7929     // C99 6.5.9p2 and C99 6.5.8p2
7930     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7931                                    RCanPointeeTy.getUnqualifiedType())) {
7932       // Valid unless a relational comparison of function pointers
7933       if (IsRelational && LCanPointeeTy->isFunctionType()) {
7934         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7935           << LHSType << RHSType << LHS.get()->getSourceRange()
7936           << RHS.get()->getSourceRange();
7937       }
7938     } else if (!IsRelational &&
7939                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7940       // Valid unless comparison between non-null pointer and function pointer
7941       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7942           && !LHSIsNull && !RHSIsNull)
7943         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
7944                                                 /*isError*/false);
7945     } else {
7946       // Invalid
7947       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
7948     }
7949     if (LCanPointeeTy != RCanPointeeTy) {
7950       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
7951       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
7952       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
7953                                                : CK_BitCast;
7954       if (LHSIsNull && !RHSIsNull)
7955         LHS = ImpCastExprToType(LHS.take(), RHSType, Kind);
7956       else
7957         RHS = ImpCastExprToType(RHS.take(), LHSType, Kind);
7958     }
7959     return ResultTy;
7960   }
7961 
7962   if (getLangOpts().CPlusPlus) {
7963     // Comparison of nullptr_t with itself.
7964     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
7965       return ResultTy;
7966 
7967     // Comparison of pointers with null pointer constants and equality
7968     // comparisons of member pointers to null pointer constants.
7969     if (RHSIsNull &&
7970         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
7971          (!IsRelational &&
7972           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7973       RHS = ImpCastExprToType(RHS.take(), LHSType,
7974                         LHSType->isMemberPointerType()
7975                           ? CK_NullToMemberPointer
7976                           : CK_NullToPointer);
7977       return ResultTy;
7978     }
7979     if (LHSIsNull &&
7980         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
7981          (!IsRelational &&
7982           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7983       LHS = ImpCastExprToType(LHS.take(), RHSType,
7984                         RHSType->isMemberPointerType()
7985                           ? CK_NullToMemberPointer
7986                           : CK_NullToPointer);
7987       return ResultTy;
7988     }
7989 
7990     // Comparison of member pointers.
7991     if (!IsRelational &&
7992         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7993       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7994         return QualType();
7995       else
7996         return ResultTy;
7997     }
7998 
7999     // Handle scoped enumeration types specifically, since they don't promote
8000     // to integers.
8001     if (LHS.get()->getType()->isEnumeralType() &&
8002         Context.hasSameUnqualifiedType(LHS.get()->getType(),
8003                                        RHS.get()->getType()))
8004       return ResultTy;
8005   }
8006 
8007   // Handle block pointer types.
8008   if (!IsRelational && LHSType->isBlockPointerType() &&
8009       RHSType->isBlockPointerType()) {
8010     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
8011     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
8012 
8013     if (!LHSIsNull && !RHSIsNull &&
8014         !Context.typesAreCompatible(lpointee, rpointee)) {
8015       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8016         << LHSType << RHSType << LHS.get()->getSourceRange()
8017         << RHS.get()->getSourceRange();
8018     }
8019     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
8020     return ResultTy;
8021   }
8022 
8023   // Allow block pointers to be compared with null pointer constants.
8024   if (!IsRelational
8025       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
8026           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
8027     if (!LHSIsNull && !RHSIsNull) {
8028       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
8029              ->getPointeeType()->isVoidType())
8030             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
8031                 ->getPointeeType()->isVoidType())))
8032         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8033           << LHSType << RHSType << LHS.get()->getSourceRange()
8034           << RHS.get()->getSourceRange();
8035     }
8036     if (LHSIsNull && !RHSIsNull)
8037       LHS = ImpCastExprToType(LHS.take(), RHSType,
8038                               RHSType->isPointerType() ? CK_BitCast
8039                                 : CK_AnyPointerToBlockPointerCast);
8040     else
8041       RHS = ImpCastExprToType(RHS.take(), LHSType,
8042                               LHSType->isPointerType() ? CK_BitCast
8043                                 : CK_AnyPointerToBlockPointerCast);
8044     return ResultTy;
8045   }
8046 
8047   if (LHSType->isObjCObjectPointerType() ||
8048       RHSType->isObjCObjectPointerType()) {
8049     const PointerType *LPT = LHSType->getAs<PointerType>();
8050     const PointerType *RPT = RHSType->getAs<PointerType>();
8051     if (LPT || RPT) {
8052       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
8053       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
8054 
8055       if (!LPtrToVoid && !RPtrToVoid &&
8056           !Context.typesAreCompatible(LHSType, RHSType)) {
8057         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8058                                           /*isError*/false);
8059       }
8060       if (LHSIsNull && !RHSIsNull) {
8061         Expr *E = LHS.take();
8062         if (getLangOpts().ObjCAutoRefCount)
8063           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
8064         LHS = ImpCastExprToType(E, RHSType,
8065                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8066       }
8067       else {
8068         Expr *E = RHS.take();
8069         if (getLangOpts().ObjCAutoRefCount)
8070           CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion);
8071         RHS = ImpCastExprToType(E, LHSType,
8072                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8073       }
8074       return ResultTy;
8075     }
8076     if (LHSType->isObjCObjectPointerType() &&
8077         RHSType->isObjCObjectPointerType()) {
8078       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
8079         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8080                                           /*isError*/false);
8081       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
8082         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
8083 
8084       if (LHSIsNull && !RHSIsNull)
8085         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
8086       else
8087         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
8088       return ResultTy;
8089     }
8090   }
8091   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
8092       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
8093     unsigned DiagID = 0;
8094     bool isError = false;
8095     if (LangOpts.DebuggerSupport) {
8096       // Under a debugger, allow the comparison of pointers to integers,
8097       // since users tend to want to compare addresses.
8098     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
8099         (RHSIsNull && RHSType->isIntegerType())) {
8100       if (IsRelational && !getLangOpts().CPlusPlus)
8101         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
8102     } else if (IsRelational && !getLangOpts().CPlusPlus)
8103       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
8104     else if (getLangOpts().CPlusPlus) {
8105       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
8106       isError = true;
8107     } else
8108       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
8109 
8110     if (DiagID) {
8111       Diag(Loc, DiagID)
8112         << LHSType << RHSType << LHS.get()->getSourceRange()
8113         << RHS.get()->getSourceRange();
8114       if (isError)
8115         return QualType();
8116     }
8117 
8118     if (LHSType->isIntegerType())
8119       LHS = ImpCastExprToType(LHS.take(), RHSType,
8120                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8121     else
8122       RHS = ImpCastExprToType(RHS.take(), LHSType,
8123                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8124     return ResultTy;
8125   }
8126 
8127   // Handle block pointers.
8128   if (!IsRelational && RHSIsNull
8129       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
8130     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
8131     return ResultTy;
8132   }
8133   if (!IsRelational && LHSIsNull
8134       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
8135     LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
8136     return ResultTy;
8137   }
8138 
8139   return InvalidOperands(Loc, LHS, RHS);
8140 }
8141 
8142 
8143 // Return a signed type that is of identical size and number of elements.
8144 // For floating point vectors, return an integer type of identical size
8145 // and number of elements.
8146 QualType Sema::GetSignedVectorType(QualType V) {
8147   const VectorType *VTy = V->getAs<VectorType>();
8148   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
8149   if (TypeSize == Context.getTypeSize(Context.CharTy))
8150     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
8151   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
8152     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
8153   else if (TypeSize == Context.getTypeSize(Context.IntTy))
8154     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
8155   else if (TypeSize == Context.getTypeSize(Context.LongTy))
8156     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
8157   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
8158          "Unhandled vector element size in vector compare");
8159   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8160 }
8161 
8162 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
8163 /// operates on extended vector types.  Instead of producing an IntTy result,
8164 /// like a scalar comparison, a vector comparison produces a vector of integer
8165 /// types.
8166 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8167                                           SourceLocation Loc,
8168                                           bool IsRelational) {
8169   // Check to make sure we're operating on vectors of the same type and width,
8170   // Allowing one side to be a scalar of element type.
8171   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
8172   if (vType.isNull())
8173     return vType;
8174 
8175   QualType LHSType = LHS.get()->getType();
8176 
8177   // If AltiVec, the comparison results in a numeric type, i.e.
8178   // bool for C++, int for C
8179   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
8180     return Context.getLogicalOperationType();
8181 
8182   // For non-floating point types, check for self-comparisons of the form
8183   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
8184   // often indicate logic errors in the program.
8185   if (!LHSType->hasFloatingRepresentation() &&
8186       ActiveTemplateInstantiations.empty()) {
8187     if (DeclRefExpr* DRL
8188           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
8189       if (DeclRefExpr* DRR
8190             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
8191         if (DRL->getDecl() == DRR->getDecl())
8192           DiagRuntimeBehavior(Loc, 0,
8193                               PDiag(diag::warn_comparison_always)
8194                                 << 0 // self-
8195                                 << 2 // "a constant"
8196                               );
8197   }
8198 
8199   // Check for comparisons of floating point operands using != and ==.
8200   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
8201     assert (RHS.get()->getType()->hasFloatingRepresentation());
8202     CheckFloatComparison(Loc, LHS.get(), RHS.get());
8203   }
8204 
8205   // Return a signed type for the vector.
8206   return GetSignedVectorType(LHSType);
8207 }
8208 
8209 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8210                                           SourceLocation Loc) {
8211   // Ensure that either both operands are of the same vector type, or
8212   // one operand is of a vector type and the other is of its element type.
8213   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
8214   if (vType.isNull())
8215     return InvalidOperands(Loc, LHS, RHS);
8216   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
8217       vType->hasFloatingRepresentation())
8218     return InvalidOperands(Loc, LHS, RHS);
8219 
8220   return GetSignedVectorType(LHS.get()->getType());
8221 }
8222 
8223 inline QualType Sema::CheckBitwiseOperands(
8224   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8225   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8226 
8227   if (LHS.get()->getType()->isVectorType() ||
8228       RHS.get()->getType()->isVectorType()) {
8229     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8230         RHS.get()->getType()->hasIntegerRepresentation())
8231       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
8232 
8233     return InvalidOperands(Loc, LHS, RHS);
8234   }
8235 
8236   ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
8237   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
8238                                                  IsCompAssign);
8239   if (LHSResult.isInvalid() || RHSResult.isInvalid())
8240     return QualType();
8241   LHS = LHSResult.take();
8242   RHS = RHSResult.take();
8243 
8244   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
8245     return compType;
8246   return InvalidOperands(Loc, LHS, RHS);
8247 }
8248 
8249 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
8250   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
8251 
8252   // Check vector operands differently.
8253   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
8254     return CheckVectorLogicalOperands(LHS, RHS, Loc);
8255 
8256   // Diagnose cases where the user write a logical and/or but probably meant a
8257   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
8258   // is a constant.
8259   if (LHS.get()->getType()->isIntegerType() &&
8260       !LHS.get()->getType()->isBooleanType() &&
8261       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
8262       // Don't warn in macros or template instantiations.
8263       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
8264     // If the RHS can be constant folded, and if it constant folds to something
8265     // that isn't 0 or 1 (which indicate a potential logical operation that
8266     // happened to fold to true/false) then warn.
8267     // Parens on the RHS are ignored.
8268     llvm::APSInt Result;
8269     if (RHS.get()->EvaluateAsInt(Result, Context))
8270       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
8271           (Result != 0 && Result != 1)) {
8272         Diag(Loc, diag::warn_logical_instead_of_bitwise)
8273           << RHS.get()->getSourceRange()
8274           << (Opc == BO_LAnd ? "&&" : "||");
8275         // Suggest replacing the logical operator with the bitwise version
8276         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
8277             << (Opc == BO_LAnd ? "&" : "|")
8278             << FixItHint::CreateReplacement(SourceRange(
8279                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
8280                                                 getLangOpts())),
8281                                             Opc == BO_LAnd ? "&" : "|");
8282         if (Opc == BO_LAnd)
8283           // Suggest replacing "Foo() && kNonZero" with "Foo()"
8284           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
8285               << FixItHint::CreateRemoval(
8286                   SourceRange(
8287                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
8288                                                  0, getSourceManager(),
8289                                                  getLangOpts()),
8290                       RHS.get()->getLocEnd()));
8291       }
8292   }
8293 
8294   if (!Context.getLangOpts().CPlusPlus) {
8295     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
8296     // not operate on the built-in scalar and vector float types.
8297     if (Context.getLangOpts().OpenCL &&
8298         Context.getLangOpts().OpenCLVersion < 120) {
8299       if (LHS.get()->getType()->isFloatingType() ||
8300           RHS.get()->getType()->isFloatingType())
8301         return InvalidOperands(Loc, LHS, RHS);
8302     }
8303 
8304     LHS = UsualUnaryConversions(LHS.take());
8305     if (LHS.isInvalid())
8306       return QualType();
8307 
8308     RHS = UsualUnaryConversions(RHS.take());
8309     if (RHS.isInvalid())
8310       return QualType();
8311 
8312     if (!LHS.get()->getType()->isScalarType() ||
8313         !RHS.get()->getType()->isScalarType())
8314       return InvalidOperands(Loc, LHS, RHS);
8315 
8316     return Context.IntTy;
8317   }
8318 
8319   // The following is safe because we only use this method for
8320   // non-overloadable operands.
8321 
8322   // C++ [expr.log.and]p1
8323   // C++ [expr.log.or]p1
8324   // The operands are both contextually converted to type bool.
8325   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
8326   if (LHSRes.isInvalid())
8327     return InvalidOperands(Loc, LHS, RHS);
8328   LHS = LHSRes;
8329 
8330   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
8331   if (RHSRes.isInvalid())
8332     return InvalidOperands(Loc, LHS, RHS);
8333   RHS = RHSRes;
8334 
8335   // C++ [expr.log.and]p2
8336   // C++ [expr.log.or]p2
8337   // The result is a bool.
8338   return Context.BoolTy;
8339 }
8340 
8341 static bool IsReadonlyMessage(Expr *E, Sema &S) {
8342   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
8343   if (!ME) return false;
8344   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
8345   ObjCMessageExpr *Base =
8346     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
8347   if (!Base) return false;
8348   return Base->getMethodDecl() != 0;
8349 }
8350 
8351 /// Is the given expression (which must be 'const') a reference to a
8352 /// variable which was originally non-const, but which has become
8353 /// 'const' due to being captured within a block?
8354 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
8355 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
8356   assert(E->isLValue() && E->getType().isConstQualified());
8357   E = E->IgnoreParens();
8358 
8359   // Must be a reference to a declaration from an enclosing scope.
8360   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
8361   if (!DRE) return NCCK_None;
8362   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
8363 
8364   // The declaration must be a variable which is not declared 'const'.
8365   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8366   if (!var) return NCCK_None;
8367   if (var->getType().isConstQualified()) return NCCK_None;
8368   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
8369 
8370   // Decide whether the first capture was for a block or a lambda.
8371   DeclContext *DC = S.CurContext, *Prev = 0;
8372   while (DC != var->getDeclContext()) {
8373     Prev = DC;
8374     DC = DC->getParent();
8375   }
8376   // Unless we have an init-capture, we've gone one step too far.
8377   if (!var->isInitCapture())
8378     DC = Prev;
8379   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
8380 }
8381 
8382 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
8383 /// emit an error and return true.  If so, return false.
8384 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
8385   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
8386   SourceLocation OrigLoc = Loc;
8387   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
8388                                                               &Loc);
8389   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8390     IsLV = Expr::MLV_InvalidMessageExpression;
8391   if (IsLV == Expr::MLV_Valid)
8392     return false;
8393 
8394   unsigned Diag = 0;
8395   bool NeedType = false;
8396   switch (IsLV) { // C99 6.5.16p2
8397   case Expr::MLV_ConstQualified:
8398     Diag = diag::err_typecheck_assign_const;
8399 
8400     // Use a specialized diagnostic when we're assigning to an object
8401     // from an enclosing function or block.
8402     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
8403       if (NCCK == NCCK_Block)
8404         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8405       else
8406         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
8407       break;
8408     }
8409 
8410     // In ARC, use some specialized diagnostics for occasions where we
8411     // infer 'const'.  These are always pseudo-strong variables.
8412     if (S.getLangOpts().ObjCAutoRefCount) {
8413       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8414       if (declRef && isa<VarDecl>(declRef->getDecl())) {
8415         VarDecl *var = cast<VarDecl>(declRef->getDecl());
8416 
8417         // Use the normal diagnostic if it's pseudo-__strong but the
8418         // user actually wrote 'const'.
8419         if (var->isARCPseudoStrong() &&
8420             (!var->getTypeSourceInfo() ||
8421              !var->getTypeSourceInfo()->getType().isConstQualified())) {
8422           // There are two pseudo-strong cases:
8423           //  - self
8424           ObjCMethodDecl *method = S.getCurMethodDecl();
8425           if (method && var == method->getSelfDecl())
8426             Diag = method->isClassMethod()
8427               ? diag::err_typecheck_arc_assign_self_class_method
8428               : diag::err_typecheck_arc_assign_self;
8429 
8430           //  - fast enumeration variables
8431           else
8432             Diag = diag::err_typecheck_arr_assign_enumeration;
8433 
8434           SourceRange Assign;
8435           if (Loc != OrigLoc)
8436             Assign = SourceRange(OrigLoc, OrigLoc);
8437           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8438           // We need to preserve the AST regardless, so migration tool
8439           // can do its job.
8440           return false;
8441         }
8442       }
8443     }
8444 
8445     break;
8446   case Expr::MLV_ArrayType:
8447   case Expr::MLV_ArrayTemporary:
8448     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8449     NeedType = true;
8450     break;
8451   case Expr::MLV_NotObjectType:
8452     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8453     NeedType = true;
8454     break;
8455   case Expr::MLV_LValueCast:
8456     Diag = diag::err_typecheck_lvalue_casts_not_supported;
8457     break;
8458   case Expr::MLV_Valid:
8459     llvm_unreachable("did not take early return for MLV_Valid");
8460   case Expr::MLV_InvalidExpression:
8461   case Expr::MLV_MemberFunction:
8462   case Expr::MLV_ClassTemporary:
8463     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8464     break;
8465   case Expr::MLV_IncompleteType:
8466   case Expr::MLV_IncompleteVoidType:
8467     return S.RequireCompleteType(Loc, E->getType(),
8468              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
8469   case Expr::MLV_DuplicateVectorComponents:
8470     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8471     break;
8472   case Expr::MLV_NoSetterProperty:
8473     llvm_unreachable("readonly properties should be processed differently");
8474   case Expr::MLV_InvalidMessageExpression:
8475     Diag = diag::error_readonly_message_assignment;
8476     break;
8477   case Expr::MLV_SubObjCPropertySetting:
8478     Diag = diag::error_no_subobject_property_setting;
8479     break;
8480   }
8481 
8482   SourceRange Assign;
8483   if (Loc != OrigLoc)
8484     Assign = SourceRange(OrigLoc, OrigLoc);
8485   if (NeedType)
8486     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
8487   else
8488     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8489   return true;
8490 }
8491 
8492 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
8493                                          SourceLocation Loc,
8494                                          Sema &Sema) {
8495   // C / C++ fields
8496   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
8497   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
8498   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
8499     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
8500       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
8501   }
8502 
8503   // Objective-C instance variables
8504   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
8505   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
8506   if (OL && OR && OL->getDecl() == OR->getDecl()) {
8507     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
8508     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
8509     if (RL && RR && RL->getDecl() == RR->getDecl())
8510       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
8511   }
8512 }
8513 
8514 // C99 6.5.16.1
8515 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
8516                                        SourceLocation Loc,
8517                                        QualType CompoundType) {
8518   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
8519 
8520   // Verify that LHS is a modifiable lvalue, and emit error if not.
8521   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
8522     return QualType();
8523 
8524   QualType LHSType = LHSExpr->getType();
8525   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
8526                                              CompoundType;
8527   AssignConvertType ConvTy;
8528   if (CompoundType.isNull()) {
8529     Expr *RHSCheck = RHS.get();
8530 
8531     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
8532 
8533     QualType LHSTy(LHSType);
8534     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
8535     if (RHS.isInvalid())
8536       return QualType();
8537     // Special case of NSObject attributes on c-style pointer types.
8538     if (ConvTy == IncompatiblePointer &&
8539         ((Context.isObjCNSObjectType(LHSType) &&
8540           RHSType->isObjCObjectPointerType()) ||
8541          (Context.isObjCNSObjectType(RHSType) &&
8542           LHSType->isObjCObjectPointerType())))
8543       ConvTy = Compatible;
8544 
8545     if (ConvTy == Compatible &&
8546         LHSType->isObjCObjectType())
8547         Diag(Loc, diag::err_objc_object_assignment)
8548           << LHSType;
8549 
8550     // If the RHS is a unary plus or minus, check to see if they = and + are
8551     // right next to each other.  If so, the user may have typo'd "x =+ 4"
8552     // instead of "x += 4".
8553     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8554       RHSCheck = ICE->getSubExpr();
8555     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
8556       if ((UO->getOpcode() == UO_Plus ||
8557            UO->getOpcode() == UO_Minus) &&
8558           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
8559           // Only if the two operators are exactly adjacent.
8560           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
8561           // And there is a space or other character before the subexpr of the
8562           // unary +/-.  We don't want to warn on "x=-1".
8563           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8564           UO->getSubExpr()->getLocStart().isFileID()) {
8565         Diag(Loc, diag::warn_not_compound_assign)
8566           << (UO->getOpcode() == UO_Plus ? "+" : "-")
8567           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
8568       }
8569     }
8570 
8571     if (ConvTy == Compatible) {
8572       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
8573         // Warn about retain cycles where a block captures the LHS, but
8574         // not if the LHS is a simple variable into which the block is
8575         // being stored...unless that variable can be captured by reference!
8576         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
8577         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
8578         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
8579           checkRetainCycles(LHSExpr, RHS.get());
8580 
8581         // It is safe to assign a weak reference into a strong variable.
8582         // Although this code can still have problems:
8583         //   id x = self.weakProp;
8584         //   id y = self.weakProp;
8585         // we do not warn to warn spuriously when 'x' and 'y' are on separate
8586         // paths through the function. This should be revisited if
8587         // -Wrepeated-use-of-weak is made flow-sensitive.
8588         DiagnosticsEngine::Level Level =
8589           Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8590                                    RHS.get()->getLocStart());
8591         if (Level != DiagnosticsEngine::Ignored)
8592           getCurFunction()->markSafeWeakUse(RHS.get());
8593 
8594       } else if (getLangOpts().ObjCAutoRefCount) {
8595         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
8596       }
8597     }
8598   } else {
8599     // Compound assignment "x += y"
8600     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
8601   }
8602 
8603   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
8604                                RHS.get(), AA_Assigning))
8605     return QualType();
8606 
8607   CheckForNullPointerDereference(*this, LHSExpr);
8608 
8609   // C99 6.5.16p3: The type of an assignment expression is the type of the
8610   // left operand unless the left operand has qualified type, in which case
8611   // it is the unqualified version of the type of the left operand.
8612   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8613   // is converted to the type of the assignment expression (above).
8614   // C++ 5.17p1: the type of the assignment expression is that of its left
8615   // operand.
8616   return (getLangOpts().CPlusPlus
8617           ? LHSType : LHSType.getUnqualifiedType());
8618 }
8619 
8620 // C99 6.5.17
8621 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
8622                                    SourceLocation Loc) {
8623   LHS = S.CheckPlaceholderExpr(LHS.take());
8624   RHS = S.CheckPlaceholderExpr(RHS.take());
8625   if (LHS.isInvalid() || RHS.isInvalid())
8626     return QualType();
8627 
8628   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8629   // operands, but not unary promotions.
8630   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
8631 
8632   // So we treat the LHS as a ignored value, and in C++ we allow the
8633   // containing site to determine what should be done with the RHS.
8634   LHS = S.IgnoredValueConversions(LHS.take());
8635   if (LHS.isInvalid())
8636     return QualType();
8637 
8638   S.DiagnoseUnusedExprResult(LHS.get());
8639 
8640   if (!S.getLangOpts().CPlusPlus) {
8641     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8642     if (RHS.isInvalid())
8643       return QualType();
8644     if (!RHS.get()->getType()->isVoidType())
8645       S.RequireCompleteType(Loc, RHS.get()->getType(),
8646                             diag::err_incomplete_type);
8647   }
8648 
8649   return RHS.get()->getType();
8650 }
8651 
8652 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8653 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
8654 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8655                                                ExprValueKind &VK,
8656                                                SourceLocation OpLoc,
8657                                                bool IsInc, bool IsPrefix) {
8658   if (Op->isTypeDependent())
8659     return S.Context.DependentTy;
8660 
8661   QualType ResType = Op->getType();
8662   // Atomic types can be used for increment / decrement where the non-atomic
8663   // versions can, so ignore the _Atomic() specifier for the purpose of
8664   // checking.
8665   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8666     ResType = ResAtomicType->getValueType();
8667 
8668   assert(!ResType.isNull() && "no type for increment/decrement expression");
8669 
8670   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
8671     // Decrement of bool is not allowed.
8672     if (!IsInc) {
8673       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8674       return QualType();
8675     }
8676     // Increment of bool sets it to true, but is deprecated.
8677     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8678   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
8679     // Error on enum increments and decrements in C++ mode
8680     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
8681     return QualType();
8682   } else if (ResType->isRealType()) {
8683     // OK!
8684   } else if (ResType->isPointerType()) {
8685     // C99 6.5.2.4p2, 6.5.6p2
8686     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
8687       return QualType();
8688   } else if (ResType->isObjCObjectPointerType()) {
8689     // On modern runtimes, ObjC pointer arithmetic is forbidden.
8690     // Otherwise, we just need a complete type.
8691     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8692         checkArithmeticOnObjCPointer(S, OpLoc, Op))
8693       return QualType();
8694   } else if (ResType->isAnyComplexType()) {
8695     // C99 does not support ++/-- on complex types, we allow as an extension.
8696     S.Diag(OpLoc, diag::ext_integer_increment_complex)
8697       << ResType << Op->getSourceRange();
8698   } else if (ResType->isPlaceholderType()) {
8699     ExprResult PR = S.CheckPlaceholderExpr(Op);
8700     if (PR.isInvalid()) return QualType();
8701     return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8702                                           IsInc, IsPrefix);
8703   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
8704     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8705   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
8706             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
8707     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
8708   } else {
8709     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8710       << ResType << int(IsInc) << Op->getSourceRange();
8711     return QualType();
8712   }
8713   // At this point, we know we have a real, complex or pointer type.
8714   // Now make sure the operand is a modifiable lvalue.
8715   if (CheckForModifiableLvalue(Op, OpLoc, S))
8716     return QualType();
8717   // In C++, a prefix increment is the same type as the operand. Otherwise
8718   // (in C or with postfix), the increment is the unqualified type of the
8719   // operand.
8720   if (IsPrefix && S.getLangOpts().CPlusPlus) {
8721     VK = VK_LValue;
8722     return ResType;
8723   } else {
8724     VK = VK_RValue;
8725     return ResType.getUnqualifiedType();
8726   }
8727 }
8728 
8729 
8730 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8731 /// This routine allows us to typecheck complex/recursive expressions
8732 /// where the declaration is needed for type checking. We only need to
8733 /// handle cases when the expression references a function designator
8734 /// or is an lvalue. Here are some examples:
8735 ///  - &(x) => x
8736 ///  - &*****f => f for f a function designator.
8737 ///  - &s.xx => s
8738 ///  - &s.zz[1].yy -> s, if zz is an array
8739 ///  - *(x + 1) -> x, if x is an array
8740 ///  - &"123"[2] -> 0
8741 ///  - & __real__ x -> x
8742 static ValueDecl *getPrimaryDecl(Expr *E) {
8743   switch (E->getStmtClass()) {
8744   case Stmt::DeclRefExprClass:
8745     return cast<DeclRefExpr>(E)->getDecl();
8746   case Stmt::MemberExprClass:
8747     // If this is an arrow operator, the address is an offset from
8748     // the base's value, so the object the base refers to is
8749     // irrelevant.
8750     if (cast<MemberExpr>(E)->isArrow())
8751       return 0;
8752     // Otherwise, the expression refers to a part of the base
8753     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8754   case Stmt::ArraySubscriptExprClass: {
8755     // FIXME: This code shouldn't be necessary!  We should catch the implicit
8756     // promotion of register arrays earlier.
8757     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8758     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8759       if (ICE->getSubExpr()->getType()->isArrayType())
8760         return getPrimaryDecl(ICE->getSubExpr());
8761     }
8762     return 0;
8763   }
8764   case Stmt::UnaryOperatorClass: {
8765     UnaryOperator *UO = cast<UnaryOperator>(E);
8766 
8767     switch(UO->getOpcode()) {
8768     case UO_Real:
8769     case UO_Imag:
8770     case UO_Extension:
8771       return getPrimaryDecl(UO->getSubExpr());
8772     default:
8773       return 0;
8774     }
8775   }
8776   case Stmt::ParenExprClass:
8777     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8778   case Stmt::ImplicitCastExprClass:
8779     // If the result of an implicit cast is an l-value, we care about
8780     // the sub-expression; otherwise, the result here doesn't matter.
8781     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8782   default:
8783     return 0;
8784   }
8785 }
8786 
8787 namespace {
8788   enum {
8789     AO_Bit_Field = 0,
8790     AO_Vector_Element = 1,
8791     AO_Property_Expansion = 2,
8792     AO_Register_Variable = 3,
8793     AO_No_Error = 4
8794   };
8795 }
8796 /// \brief Diagnose invalid operand for address of operations.
8797 ///
8798 /// \param Type The type of operand which cannot have its address taken.
8799 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8800                                          Expr *E, unsigned Type) {
8801   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8802 }
8803 
8804 /// CheckAddressOfOperand - The operand of & must be either a function
8805 /// designator or an lvalue designating an object. If it is an lvalue, the
8806 /// object cannot be declared with storage class register or be a bit field.
8807 /// Note: The usual conversions are *not* applied to the operand of the &
8808 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8809 /// In C++, the operand might be an overloaded function name, in which case
8810 /// we allow the '&' but retain the overloaded-function type.
8811 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
8812   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8813     if (PTy->getKind() == BuiltinType::Overload) {
8814       Expr *E = OrigOp.get()->IgnoreParens();
8815       if (!isa<OverloadExpr>(E)) {
8816         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
8817         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
8818           << OrigOp.get()->getSourceRange();
8819         return QualType();
8820       }
8821 
8822       OverloadExpr *Ovl = cast<OverloadExpr>(E);
8823       if (isa<UnresolvedMemberExpr>(Ovl))
8824         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
8825           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8826             << OrigOp.get()->getSourceRange();
8827           return QualType();
8828         }
8829 
8830       return Context.OverloadTy;
8831     }
8832 
8833     if (PTy->getKind() == BuiltinType::UnknownAny)
8834       return Context.UnknownAnyTy;
8835 
8836     if (PTy->getKind() == BuiltinType::BoundMember) {
8837       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8838         << OrigOp.get()->getSourceRange();
8839       return QualType();
8840     }
8841 
8842     OrigOp = CheckPlaceholderExpr(OrigOp.take());
8843     if (OrigOp.isInvalid()) return QualType();
8844   }
8845 
8846   if (OrigOp.get()->isTypeDependent())
8847     return Context.DependentTy;
8848 
8849   assert(!OrigOp.get()->getType()->isPlaceholderType());
8850 
8851   // Make sure to ignore parentheses in subsequent checks
8852   Expr *op = OrigOp.get()->IgnoreParens();
8853 
8854   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
8855   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
8856     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
8857     return QualType();
8858   }
8859 
8860   if (getLangOpts().C99) {
8861     // Implement C99-only parts of addressof rules.
8862     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8863       if (uOp->getOpcode() == UO_Deref)
8864         // Per C99 6.5.3.2, the address of a deref always returns a valid result
8865         // (assuming the deref expression is valid).
8866         return uOp->getSubExpr()->getType();
8867     }
8868     // Technically, there should be a check for array subscript
8869     // expressions here, but the result of one is always an lvalue anyway.
8870   }
8871   ValueDecl *dcl = getPrimaryDecl(op);
8872   Expr::LValueClassification lval = op->ClassifyLValue(Context);
8873   unsigned AddressOfError = AO_No_Error;
8874 
8875   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
8876     bool sfinae = (bool)isSFINAEContext();
8877     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
8878                                   : diag::ext_typecheck_addrof_temporary)
8879       << op->getType() << op->getSourceRange();
8880     if (sfinae)
8881       return QualType();
8882     // Materialize the temporary as an lvalue so that we can take its address.
8883     OrigOp = op = new (Context)
8884         MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true, 0);
8885   } else if (isa<ObjCSelectorExpr>(op)) {
8886     return Context.getPointerType(op->getType());
8887   } else if (lval == Expr::LV_MemberFunction) {
8888     // If it's an instance method, make a member pointer.
8889     // The expression must have exactly the form &A::foo.
8890 
8891     // If the underlying expression isn't a decl ref, give up.
8892     if (!isa<DeclRefExpr>(op)) {
8893       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8894         << OrigOp.get()->getSourceRange();
8895       return QualType();
8896     }
8897     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8898     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8899 
8900     // The id-expression was parenthesized.
8901     if (OrigOp.get() != DRE) {
8902       Diag(OpLoc, diag::err_parens_pointer_member_function)
8903         << OrigOp.get()->getSourceRange();
8904 
8905     // The method was named without a qualifier.
8906     } else if (!DRE->getQualifier()) {
8907       if (MD->getParent()->getName().empty())
8908         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8909           << op->getSourceRange();
8910       else {
8911         SmallString<32> Str;
8912         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8913         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8914           << op->getSourceRange()
8915           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8916       }
8917     }
8918 
8919     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
8920     if (isa<CXXDestructorDecl>(MD))
8921       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
8922 
8923     QualType MPTy = Context.getMemberPointerType(
8924         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
8925     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
8926       RequireCompleteType(OpLoc, MPTy, 0);
8927     return MPTy;
8928   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
8929     // C99 6.5.3.2p1
8930     // The operand must be either an l-value or a function designator
8931     if (!op->getType()->isFunctionType()) {
8932       // Use a special diagnostic for loads from property references.
8933       if (isa<PseudoObjectExpr>(op)) {
8934         AddressOfError = AO_Property_Expansion;
8935       } else {
8936         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8937           << op->getType() << op->getSourceRange();
8938         return QualType();
8939       }
8940     }
8941   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
8942     // The operand cannot be a bit-field
8943     AddressOfError = AO_Bit_Field;
8944   } else if (op->getObjectKind() == OK_VectorComponent) {
8945     // The operand cannot be an element of a vector
8946     AddressOfError = AO_Vector_Element;
8947   } else if (dcl) { // C99 6.5.3.2p1
8948     // We have an lvalue with a decl. Make sure the decl is not declared
8949     // with the register storage-class specifier.
8950     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
8951       // in C++ it is not error to take address of a register
8952       // variable (c++03 7.1.1P3)
8953       if (vd->getStorageClass() == SC_Register &&
8954           !getLangOpts().CPlusPlus) {
8955         AddressOfError = AO_Register_Variable;
8956       }
8957     } else if (isa<FunctionTemplateDecl>(dcl)) {
8958       return Context.OverloadTy;
8959     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8960       // Okay: we can take the address of a field.
8961       // Could be a pointer to member, though, if there is an explicit
8962       // scope qualifier for the class.
8963       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8964         DeclContext *Ctx = dcl->getDeclContext();
8965         if (Ctx && Ctx->isRecord()) {
8966           if (dcl->getType()->isReferenceType()) {
8967             Diag(OpLoc,
8968                  diag::err_cannot_form_pointer_to_member_of_reference_type)
8969               << dcl->getDeclName() << dcl->getType();
8970             return QualType();
8971           }
8972 
8973           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8974             Ctx = Ctx->getParent();
8975 
8976           QualType MPTy = Context.getMemberPointerType(
8977               op->getType(),
8978               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8979           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
8980             RequireCompleteType(OpLoc, MPTy, 0);
8981           return MPTy;
8982         }
8983       }
8984     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
8985       llvm_unreachable("Unknown/unexpected decl type");
8986   }
8987 
8988   if (AddressOfError != AO_No_Error) {
8989     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
8990     return QualType();
8991   }
8992 
8993   if (lval == Expr::LV_IncompleteVoidType) {
8994     // Taking the address of a void variable is technically illegal, but we
8995     // allow it in cases which are otherwise valid.
8996     // Example: "extern void x; void* y = &x;".
8997     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
8998   }
8999 
9000   // If the operand has type "type", the result has type "pointer to type".
9001   if (op->getType()->isObjCObjectType())
9002     return Context.getObjCObjectPointerType(op->getType());
9003   return Context.getPointerType(op->getType());
9004 }
9005 
9006 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
9007 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
9008                                         SourceLocation OpLoc) {
9009   if (Op->isTypeDependent())
9010     return S.Context.DependentTy;
9011 
9012   ExprResult ConvResult = S.UsualUnaryConversions(Op);
9013   if (ConvResult.isInvalid())
9014     return QualType();
9015   Op = ConvResult.take();
9016   QualType OpTy = Op->getType();
9017   QualType Result;
9018 
9019   if (isa<CXXReinterpretCastExpr>(Op)) {
9020     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
9021     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
9022                                      Op->getSourceRange());
9023   }
9024 
9025   // Note that per both C89 and C99, indirection is always legal, even if OpTy
9026   // is an incomplete type or void.  It would be possible to warn about
9027   // dereferencing a void pointer, but it's completely well-defined, and such a
9028   // warning is unlikely to catch any mistakes.
9029   if (const PointerType *PT = OpTy->getAs<PointerType>())
9030     Result = PT->getPointeeType();
9031   else if (const ObjCObjectPointerType *OPT =
9032              OpTy->getAs<ObjCObjectPointerType>())
9033     Result = OPT->getPointeeType();
9034   else {
9035     ExprResult PR = S.CheckPlaceholderExpr(Op);
9036     if (PR.isInvalid()) return QualType();
9037     if (PR.take() != Op)
9038       return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
9039   }
9040 
9041   if (Result.isNull()) {
9042     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
9043       << OpTy << Op->getSourceRange();
9044     return QualType();
9045   }
9046 
9047   // Dereferences are usually l-values...
9048   VK = VK_LValue;
9049 
9050   // ...except that certain expressions are never l-values in C.
9051   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
9052     VK = VK_RValue;
9053 
9054   return Result;
9055 }
9056 
9057 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
9058   tok::TokenKind Kind) {
9059   BinaryOperatorKind Opc;
9060   switch (Kind) {
9061   default: llvm_unreachable("Unknown binop!");
9062   case tok::periodstar:           Opc = BO_PtrMemD; break;
9063   case tok::arrowstar:            Opc = BO_PtrMemI; break;
9064   case tok::star:                 Opc = BO_Mul; break;
9065   case tok::slash:                Opc = BO_Div; break;
9066   case tok::percent:              Opc = BO_Rem; break;
9067   case tok::plus:                 Opc = BO_Add; break;
9068   case tok::minus:                Opc = BO_Sub; break;
9069   case tok::lessless:             Opc = BO_Shl; break;
9070   case tok::greatergreater:       Opc = BO_Shr; break;
9071   case tok::lessequal:            Opc = BO_LE; break;
9072   case tok::less:                 Opc = BO_LT; break;
9073   case tok::greaterequal:         Opc = BO_GE; break;
9074   case tok::greater:              Opc = BO_GT; break;
9075   case tok::exclaimequal:         Opc = BO_NE; break;
9076   case tok::equalequal:           Opc = BO_EQ; break;
9077   case tok::amp:                  Opc = BO_And; break;
9078   case tok::caret:                Opc = BO_Xor; break;
9079   case tok::pipe:                 Opc = BO_Or; break;
9080   case tok::ampamp:               Opc = BO_LAnd; break;
9081   case tok::pipepipe:             Opc = BO_LOr; break;
9082   case tok::equal:                Opc = BO_Assign; break;
9083   case tok::starequal:            Opc = BO_MulAssign; break;
9084   case tok::slashequal:           Opc = BO_DivAssign; break;
9085   case tok::percentequal:         Opc = BO_RemAssign; break;
9086   case tok::plusequal:            Opc = BO_AddAssign; break;
9087   case tok::minusequal:           Opc = BO_SubAssign; break;
9088   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
9089   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
9090   case tok::ampequal:             Opc = BO_AndAssign; break;
9091   case tok::caretequal:           Opc = BO_XorAssign; break;
9092   case tok::pipeequal:            Opc = BO_OrAssign; break;
9093   case tok::comma:                Opc = BO_Comma; break;
9094   }
9095   return Opc;
9096 }
9097 
9098 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
9099   tok::TokenKind Kind) {
9100   UnaryOperatorKind Opc;
9101   switch (Kind) {
9102   default: llvm_unreachable("Unknown unary op!");
9103   case tok::plusplus:     Opc = UO_PreInc; break;
9104   case tok::minusminus:   Opc = UO_PreDec; break;
9105   case tok::amp:          Opc = UO_AddrOf; break;
9106   case tok::star:         Opc = UO_Deref; break;
9107   case tok::plus:         Opc = UO_Plus; break;
9108   case tok::minus:        Opc = UO_Minus; break;
9109   case tok::tilde:        Opc = UO_Not; break;
9110   case tok::exclaim:      Opc = UO_LNot; break;
9111   case tok::kw___real:    Opc = UO_Real; break;
9112   case tok::kw___imag:    Opc = UO_Imag; break;
9113   case tok::kw___extension__: Opc = UO_Extension; break;
9114   }
9115   return Opc;
9116 }
9117 
9118 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
9119 /// This warning is only emitted for builtin assignment operations. It is also
9120 /// suppressed in the event of macro expansions.
9121 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
9122                                    SourceLocation OpLoc) {
9123   if (!S.ActiveTemplateInstantiations.empty())
9124     return;
9125   if (OpLoc.isInvalid() || OpLoc.isMacroID())
9126     return;
9127   LHSExpr = LHSExpr->IgnoreParenImpCasts();
9128   RHSExpr = RHSExpr->IgnoreParenImpCasts();
9129   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9130   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9131   if (!LHSDeclRef || !RHSDeclRef ||
9132       LHSDeclRef->getLocation().isMacroID() ||
9133       RHSDeclRef->getLocation().isMacroID())
9134     return;
9135   const ValueDecl *LHSDecl =
9136     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
9137   const ValueDecl *RHSDecl =
9138     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
9139   if (LHSDecl != RHSDecl)
9140     return;
9141   if (LHSDecl->getType().isVolatileQualified())
9142     return;
9143   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
9144     if (RefTy->getPointeeType().isVolatileQualified())
9145       return;
9146 
9147   S.Diag(OpLoc, diag::warn_self_assignment)
9148       << LHSDeclRef->getType()
9149       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9150 }
9151 
9152 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
9153 /// is usually indicative of introspection within the Objective-C pointer.
9154 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
9155                                           SourceLocation OpLoc) {
9156   if (!S.getLangOpts().ObjC1)
9157     return;
9158 
9159   const Expr *ObjCPointerExpr = 0, *OtherExpr = 0;
9160   const Expr *LHS = L.get();
9161   const Expr *RHS = R.get();
9162 
9163   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9164     ObjCPointerExpr = LHS;
9165     OtherExpr = RHS;
9166   }
9167   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9168     ObjCPointerExpr = RHS;
9169     OtherExpr = LHS;
9170   }
9171 
9172   // This warning is deliberately made very specific to reduce false
9173   // positives with logic that uses '&' for hashing.  This logic mainly
9174   // looks for code trying to introspect into tagged pointers, which
9175   // code should generally never do.
9176   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
9177     unsigned Diag = diag::warn_objc_pointer_masking;
9178     // Determine if we are introspecting the result of performSelectorXXX.
9179     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
9180     // Special case messages to -performSelector and friends, which
9181     // can return non-pointer values boxed in a pointer value.
9182     // Some clients may wish to silence warnings in this subcase.
9183     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
9184       Selector S = ME->getSelector();
9185       StringRef SelArg0 = S.getNameForSlot(0);
9186       if (SelArg0.startswith("performSelector"))
9187         Diag = diag::warn_objc_pointer_masking_performSelector;
9188     }
9189 
9190     S.Diag(OpLoc, Diag)
9191       << ObjCPointerExpr->getSourceRange();
9192   }
9193 }
9194 
9195 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
9196 /// operator @p Opc at location @c TokLoc. This routine only supports
9197 /// built-in operations; ActOnBinOp handles overloaded operators.
9198 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
9199                                     BinaryOperatorKind Opc,
9200                                     Expr *LHSExpr, Expr *RHSExpr) {
9201   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
9202     // The syntax only allows initializer lists on the RHS of assignment,
9203     // so we don't need to worry about accepting invalid code for
9204     // non-assignment operators.
9205     // C++11 5.17p9:
9206     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
9207     //   of x = {} is x = T().
9208     InitializationKind Kind =
9209         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
9210     InitializedEntity Entity =
9211         InitializedEntity::InitializeTemporary(LHSExpr->getType());
9212     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
9213     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
9214     if (Init.isInvalid())
9215       return Init;
9216     RHSExpr = Init.take();
9217   }
9218 
9219   ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
9220   QualType ResultTy;     // Result type of the binary operator.
9221   // The following two variables are used for compound assignment operators
9222   QualType CompLHSTy;    // Type of LHS after promotions for computation
9223   QualType CompResultTy; // Type of computation result
9224   ExprValueKind VK = VK_RValue;
9225   ExprObjectKind OK = OK_Ordinary;
9226 
9227   switch (Opc) {
9228   case BO_Assign:
9229     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
9230     if (getLangOpts().CPlusPlus &&
9231         LHS.get()->getObjectKind() != OK_ObjCProperty) {
9232       VK = LHS.get()->getValueKind();
9233       OK = LHS.get()->getObjectKind();
9234     }
9235     if (!ResultTy.isNull())
9236       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9237     break;
9238   case BO_PtrMemD:
9239   case BO_PtrMemI:
9240     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
9241                                             Opc == BO_PtrMemI);
9242     break;
9243   case BO_Mul:
9244   case BO_Div:
9245     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
9246                                            Opc == BO_Div);
9247     break;
9248   case BO_Rem:
9249     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
9250     break;
9251   case BO_Add:
9252     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
9253     break;
9254   case BO_Sub:
9255     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
9256     break;
9257   case BO_Shl:
9258   case BO_Shr:
9259     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
9260     break;
9261   case BO_LE:
9262   case BO_LT:
9263   case BO_GE:
9264   case BO_GT:
9265     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
9266     break;
9267   case BO_EQ:
9268   case BO_NE:
9269     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
9270     break;
9271   case BO_And:
9272     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
9273   case BO_Xor:
9274   case BO_Or:
9275     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
9276     break;
9277   case BO_LAnd:
9278   case BO_LOr:
9279     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
9280     break;
9281   case BO_MulAssign:
9282   case BO_DivAssign:
9283     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
9284                                                Opc == BO_DivAssign);
9285     CompLHSTy = CompResultTy;
9286     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9287       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9288     break;
9289   case BO_RemAssign:
9290     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
9291     CompLHSTy = CompResultTy;
9292     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9293       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9294     break;
9295   case BO_AddAssign:
9296     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
9297     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9298       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9299     break;
9300   case BO_SubAssign:
9301     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
9302     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9303       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9304     break;
9305   case BO_ShlAssign:
9306   case BO_ShrAssign:
9307     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
9308     CompLHSTy = CompResultTy;
9309     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9310       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9311     break;
9312   case BO_AndAssign:
9313   case BO_XorAssign:
9314   case BO_OrAssign:
9315     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
9316     CompLHSTy = CompResultTy;
9317     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9318       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9319     break;
9320   case BO_Comma:
9321     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
9322     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
9323       VK = RHS.get()->getValueKind();
9324       OK = RHS.get()->getObjectKind();
9325     }
9326     break;
9327   }
9328   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
9329     return ExprError();
9330 
9331   // Check for array bounds violations for both sides of the BinaryOperator
9332   CheckArrayAccess(LHS.get());
9333   CheckArrayAccess(RHS.get());
9334 
9335   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
9336     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
9337                                                  &Context.Idents.get("object_setClass"),
9338                                                  SourceLocation(), LookupOrdinaryName);
9339     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
9340       SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
9341       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
9342       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
9343       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
9344       FixItHint::CreateInsertion(RHSLocEnd, ")");
9345     }
9346     else
9347       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
9348   }
9349   else if (const ObjCIvarRefExpr *OIRE =
9350            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
9351     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
9352 
9353   if (CompResultTy.isNull())
9354     return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
9355                                               ResultTy, VK, OK, OpLoc,
9356                                               FPFeatures.fp_contract));
9357   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
9358       OK_ObjCProperty) {
9359     VK = VK_LValue;
9360     OK = LHS.get()->getObjectKind();
9361   }
9362   return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
9363                                                     ResultTy, VK, OK, CompLHSTy,
9364                                                     CompResultTy, OpLoc,
9365                                                     FPFeatures.fp_contract));
9366 }
9367 
9368 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9369 /// operators are mixed in a way that suggests that the programmer forgot that
9370 /// comparison operators have higher precedence. The most typical example of
9371 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
9372 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
9373                                       SourceLocation OpLoc, Expr *LHSExpr,
9374                                       Expr *RHSExpr) {
9375   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
9376   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
9377 
9378   // Check that one of the sides is a comparison operator.
9379   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
9380   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
9381   if (!isLeftComp && !isRightComp)
9382     return;
9383 
9384   // Bitwise operations are sometimes used as eager logical ops.
9385   // Don't diagnose this.
9386   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
9387   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
9388   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
9389     return;
9390 
9391   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
9392                                                    OpLoc)
9393                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
9394   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
9395   SourceRange ParensRange = isLeftComp ?
9396       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
9397     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
9398 
9399   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9400     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
9401   SuggestParentheses(Self, OpLoc,
9402     Self.PDiag(diag::note_precedence_silence) << OpStr,
9403     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
9404   SuggestParentheses(Self, OpLoc,
9405     Self.PDiag(diag::note_precedence_bitwise_first)
9406       << BinaryOperator::getOpcodeStr(Opc),
9407     ParensRange);
9408 }
9409 
9410 /// \brief It accepts a '&' expr that is inside a '|' one.
9411 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
9412 /// in parentheses.
9413 static void
9414 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
9415                                        BinaryOperator *Bop) {
9416   assert(Bop->getOpcode() == BO_And);
9417   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
9418       << Bop->getSourceRange() << OpLoc;
9419   SuggestParentheses(Self, Bop->getOperatorLoc(),
9420     Self.PDiag(diag::note_precedence_silence)
9421       << Bop->getOpcodeStr(),
9422     Bop->getSourceRange());
9423 }
9424 
9425 /// \brief It accepts a '&&' expr that is inside a '||' one.
9426 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9427 /// in parentheses.
9428 static void
9429 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
9430                                        BinaryOperator *Bop) {
9431   assert(Bop->getOpcode() == BO_LAnd);
9432   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9433       << Bop->getSourceRange() << OpLoc;
9434   SuggestParentheses(Self, Bop->getOperatorLoc(),
9435     Self.PDiag(diag::note_precedence_silence)
9436       << Bop->getOpcodeStr(),
9437     Bop->getSourceRange());
9438 }
9439 
9440 /// \brief Returns true if the given expression can be evaluated as a constant
9441 /// 'true'.
9442 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9443   bool Res;
9444   return !E->isValueDependent() &&
9445          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9446 }
9447 
9448 /// \brief Returns true if the given expression can be evaluated as a constant
9449 /// 'false'.
9450 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9451   bool Res;
9452   return !E->isValueDependent() &&
9453          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9454 }
9455 
9456 /// \brief Look for '&&' in the left hand of a '||' expr.
9457 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
9458                                              Expr *LHSExpr, Expr *RHSExpr) {
9459   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
9460     if (Bop->getOpcode() == BO_LAnd) {
9461       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9462       if (EvaluatesAsFalse(S, RHSExpr))
9463         return;
9464       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9465       if (!EvaluatesAsTrue(S, Bop->getLHS()))
9466         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9467     } else if (Bop->getOpcode() == BO_LOr) {
9468       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9469         // If it's "a || b && 1 || c" we didn't warn earlier for
9470         // "a || b && 1", but warn now.
9471         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9472           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9473       }
9474     }
9475   }
9476 }
9477 
9478 /// \brief Look for '&&' in the right hand of a '||' expr.
9479 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
9480                                              Expr *LHSExpr, Expr *RHSExpr) {
9481   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
9482     if (Bop->getOpcode() == BO_LAnd) {
9483       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9484       if (EvaluatesAsFalse(S, LHSExpr))
9485         return;
9486       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9487       if (!EvaluatesAsTrue(S, Bop->getRHS()))
9488         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9489     }
9490   }
9491 }
9492 
9493 /// \brief Look for '&' in the left or right hand of a '|' expr.
9494 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
9495                                              Expr *OrArg) {
9496   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
9497     if (Bop->getOpcode() == BO_And)
9498       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
9499   }
9500 }
9501 
9502 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
9503                                     Expr *SubExpr, StringRef Shift) {
9504   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
9505     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
9506       StringRef Op = Bop->getOpcodeStr();
9507       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
9508           << Bop->getSourceRange() << OpLoc << Shift << Op;
9509       SuggestParentheses(S, Bop->getOperatorLoc(),
9510           S.PDiag(diag::note_precedence_silence) << Op,
9511           Bop->getSourceRange());
9512     }
9513   }
9514 }
9515 
9516 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
9517                                  Expr *LHSExpr, Expr *RHSExpr) {
9518   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
9519   if (!OCE)
9520     return;
9521 
9522   FunctionDecl *FD = OCE->getDirectCallee();
9523   if (!FD || !FD->isOverloadedOperator())
9524     return;
9525 
9526   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
9527   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
9528     return;
9529 
9530   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
9531       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
9532       << (Kind == OO_LessLess);
9533   SuggestParentheses(S, OCE->getOperatorLoc(),
9534                      S.PDiag(diag::note_precedence_silence)
9535                          << (Kind == OO_LessLess ? "<<" : ">>"),
9536                      OCE->getSourceRange());
9537   SuggestParentheses(S, OpLoc,
9538                      S.PDiag(diag::note_evaluate_comparison_first),
9539                      SourceRange(OCE->getArg(1)->getLocStart(),
9540                                  RHSExpr->getLocEnd()));
9541 }
9542 
9543 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
9544 /// precedence.
9545 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
9546                                     SourceLocation OpLoc, Expr *LHSExpr,
9547                                     Expr *RHSExpr){
9548   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
9549   if (BinaryOperator::isBitwiseOp(Opc))
9550     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
9551 
9552   // Diagnose "arg1 & arg2 | arg3"
9553   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9554     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
9555     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
9556   }
9557 
9558   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9559   // We don't warn for 'assert(a || b && "bad")' since this is safe.
9560   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9561     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
9562     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
9563   }
9564 
9565   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
9566       || Opc == BO_Shr) {
9567     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
9568     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
9569     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
9570   }
9571 
9572   // Warn on overloaded shift operators and comparisons, such as:
9573   // cout << 5 == 4;
9574   if (BinaryOperator::isComparisonOp(Opc))
9575     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
9576 }
9577 
9578 // Binary Operators.  'Tok' is the token for the operator.
9579 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
9580                             tok::TokenKind Kind,
9581                             Expr *LHSExpr, Expr *RHSExpr) {
9582   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
9583   assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
9584   assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
9585 
9586   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9587   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
9588 
9589   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
9590 }
9591 
9592 /// Build an overloaded binary operator expression in the given scope.
9593 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
9594                                        BinaryOperatorKind Opc,
9595                                        Expr *LHS, Expr *RHS) {
9596   // Find all of the overloaded operators visible from this
9597   // point. We perform both an operator-name lookup from the local
9598   // scope and an argument-dependent lookup based on the types of
9599   // the arguments.
9600   UnresolvedSet<16> Functions;
9601   OverloadedOperatorKind OverOp
9602     = BinaryOperator::getOverloadedOperator(Opc);
9603   if (Sc && OverOp != OO_None)
9604     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
9605                                    RHS->getType(), Functions);
9606 
9607   // Build the (potentially-overloaded, potentially-dependent)
9608   // binary operation.
9609   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
9610 }
9611 
9612 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
9613                             BinaryOperatorKind Opc,
9614                             Expr *LHSExpr, Expr *RHSExpr) {
9615   // We want to end up calling one of checkPseudoObjectAssignment
9616   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
9617   // both expressions are overloadable or either is type-dependent),
9618   // or CreateBuiltinBinOp (in any other case).  We also want to get
9619   // any placeholder types out of the way.
9620 
9621   // Handle pseudo-objects in the LHS.
9622   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
9623     // Assignments with a pseudo-object l-value need special analysis.
9624     if (pty->getKind() == BuiltinType::PseudoObject &&
9625         BinaryOperator::isAssignmentOp(Opc))
9626       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
9627 
9628     // Don't resolve overloads if the other type is overloadable.
9629     if (pty->getKind() == BuiltinType::Overload) {
9630       // We can't actually test that if we still have a placeholder,
9631       // though.  Fortunately, none of the exceptions we see in that
9632       // code below are valid when the LHS is an overload set.  Note
9633       // that an overload set can be dependently-typed, but it never
9634       // instantiates to having an overloadable type.
9635       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9636       if (resolvedRHS.isInvalid()) return ExprError();
9637       RHSExpr = resolvedRHS.take();
9638 
9639       if (RHSExpr->isTypeDependent() ||
9640           RHSExpr->getType()->isOverloadableType())
9641         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9642     }
9643 
9644     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
9645     if (LHS.isInvalid()) return ExprError();
9646     LHSExpr = LHS.take();
9647   }
9648 
9649   // Handle pseudo-objects in the RHS.
9650   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
9651     // An overload in the RHS can potentially be resolved by the type
9652     // being assigned to.
9653     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
9654       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9655         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9656 
9657       if (LHSExpr->getType()->isOverloadableType())
9658         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9659 
9660       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9661     }
9662 
9663     // Don't resolve overloads if the other type is overloadable.
9664     if (pty->getKind() == BuiltinType::Overload &&
9665         LHSExpr->getType()->isOverloadableType())
9666       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9667 
9668     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9669     if (!resolvedRHS.isUsable()) return ExprError();
9670     RHSExpr = resolvedRHS.take();
9671   }
9672 
9673   if (getLangOpts().CPlusPlus) {
9674     // If either expression is type-dependent, always build an
9675     // overloaded op.
9676     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9677       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9678 
9679     // Otherwise, build an overloaded op if either expression has an
9680     // overloadable type.
9681     if (LHSExpr->getType()->isOverloadableType() ||
9682         RHSExpr->getType()->isOverloadableType())
9683       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9684   }
9685 
9686   // Build a built-in binary operation.
9687   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9688 }
9689 
9690 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
9691                                       UnaryOperatorKind Opc,
9692                                       Expr *InputExpr) {
9693   ExprResult Input = Owned(InputExpr);
9694   ExprValueKind VK = VK_RValue;
9695   ExprObjectKind OK = OK_Ordinary;
9696   QualType resultType;
9697   switch (Opc) {
9698   case UO_PreInc:
9699   case UO_PreDec:
9700   case UO_PostInc:
9701   case UO_PostDec:
9702     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
9703                                                 Opc == UO_PreInc ||
9704                                                 Opc == UO_PostInc,
9705                                                 Opc == UO_PreInc ||
9706                                                 Opc == UO_PreDec);
9707     break;
9708   case UO_AddrOf:
9709     resultType = CheckAddressOfOperand(Input, OpLoc);
9710     break;
9711   case UO_Deref: {
9712     Input = DefaultFunctionArrayLvalueConversion(Input.take());
9713     if (Input.isInvalid()) return ExprError();
9714     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
9715     break;
9716   }
9717   case UO_Plus:
9718   case UO_Minus:
9719     Input = UsualUnaryConversions(Input.take());
9720     if (Input.isInvalid()) return ExprError();
9721     resultType = Input.get()->getType();
9722     if (resultType->isDependentType())
9723       break;
9724     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9725         resultType->isVectorType())
9726       break;
9727     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
9728              Opc == UO_Plus &&
9729              resultType->isPointerType())
9730       break;
9731 
9732     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9733       << resultType << Input.get()->getSourceRange());
9734 
9735   case UO_Not: // bitwise complement
9736     Input = UsualUnaryConversions(Input.take());
9737     if (Input.isInvalid())
9738       return ExprError();
9739     resultType = Input.get()->getType();
9740     if (resultType->isDependentType())
9741       break;
9742     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9743     if (resultType->isComplexType() || resultType->isComplexIntegerType())
9744       // C99 does not support '~' for complex conjugation.
9745       Diag(OpLoc, diag::ext_integer_complement_complex)
9746           << resultType << Input.get()->getSourceRange();
9747     else if (resultType->hasIntegerRepresentation())
9748       break;
9749     else if (resultType->isExtVectorType()) {
9750       if (Context.getLangOpts().OpenCL) {
9751         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
9752         // on vector float types.
9753         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9754         if (!T->isIntegerType())
9755           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9756                            << resultType << Input.get()->getSourceRange());
9757       }
9758       break;
9759     } else {
9760       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9761                        << resultType << Input.get()->getSourceRange());
9762     }
9763     break;
9764 
9765   case UO_LNot: // logical negation
9766     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
9767     Input = DefaultFunctionArrayLvalueConversion(Input.take());
9768     if (Input.isInvalid()) return ExprError();
9769     resultType = Input.get()->getType();
9770 
9771     // Though we still have to promote half FP to float...
9772     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
9773       Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
9774       resultType = Context.FloatTy;
9775     }
9776 
9777     if (resultType->isDependentType())
9778       break;
9779     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
9780       // C99 6.5.3.3p1: ok, fallthrough;
9781       if (Context.getLangOpts().CPlusPlus) {
9782         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9783         // operand contextually converted to bool.
9784         Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9785                                   ScalarTypeToBooleanCastKind(resultType));
9786       } else if (Context.getLangOpts().OpenCL &&
9787                  Context.getLangOpts().OpenCLVersion < 120) {
9788         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9789         // operate on scalar float types.
9790         if (!resultType->isIntegerType())
9791           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9792                            << resultType << Input.get()->getSourceRange());
9793       }
9794     } else if (resultType->isExtVectorType()) {
9795       if (Context.getLangOpts().OpenCL &&
9796           Context.getLangOpts().OpenCLVersion < 120) {
9797         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9798         // operate on vector float types.
9799         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9800         if (!T->isIntegerType())
9801           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9802                            << resultType << Input.get()->getSourceRange());
9803       }
9804       // Vector logical not returns the signed variant of the operand type.
9805       resultType = GetSignedVectorType(resultType);
9806       break;
9807     } else {
9808       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9809         << resultType << Input.get()->getSourceRange());
9810     }
9811 
9812     // LNot always has type int. C99 6.5.3.3p5.
9813     // In C++, it's bool. C++ 5.3.1p8
9814     resultType = Context.getLogicalOperationType();
9815     break;
9816   case UO_Real:
9817   case UO_Imag:
9818     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
9819     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
9820     // complex l-values to ordinary l-values and all other values to r-values.
9821     if (Input.isInvalid()) return ExprError();
9822     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
9823       if (Input.get()->getValueKind() != VK_RValue &&
9824           Input.get()->getObjectKind() == OK_Ordinary)
9825         VK = Input.get()->getValueKind();
9826     } else if (!getLangOpts().CPlusPlus) {
9827       // In C, a volatile scalar is read by __imag. In C++, it is not.
9828       Input = DefaultLvalueConversion(Input.take());
9829     }
9830     break;
9831   case UO_Extension:
9832     resultType = Input.get()->getType();
9833     VK = Input.get()->getValueKind();
9834     OK = Input.get()->getObjectKind();
9835     break;
9836   }
9837   if (resultType.isNull() || Input.isInvalid())
9838     return ExprError();
9839 
9840   // Check for array bounds violations in the operand of the UnaryOperator,
9841   // except for the '*' and '&' operators that have to be handled specially
9842   // by CheckArrayAccess (as there are special cases like &array[arraysize]
9843   // that are explicitly defined as valid by the standard).
9844   if (Opc != UO_AddrOf && Opc != UO_Deref)
9845     CheckArrayAccess(Input.get());
9846 
9847   return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
9848                                            VK, OK, OpLoc));
9849 }
9850 
9851 /// \brief Determine whether the given expression is a qualified member
9852 /// access expression, of a form that could be turned into a pointer to member
9853 /// with the address-of operator.
9854 static bool isQualifiedMemberAccess(Expr *E) {
9855   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9856     if (!DRE->getQualifier())
9857       return false;
9858 
9859     ValueDecl *VD = DRE->getDecl();
9860     if (!VD->isCXXClassMember())
9861       return false;
9862 
9863     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9864       return true;
9865     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9866       return Method->isInstance();
9867 
9868     return false;
9869   }
9870 
9871   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9872     if (!ULE->getQualifier())
9873       return false;
9874 
9875     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9876                                            DEnd = ULE->decls_end();
9877          D != DEnd; ++D) {
9878       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9879         if (Method->isInstance())
9880           return true;
9881       } else {
9882         // Overload set does not contain methods.
9883         break;
9884       }
9885     }
9886 
9887     return false;
9888   }
9889 
9890   return false;
9891 }
9892 
9893 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
9894                               UnaryOperatorKind Opc, Expr *Input) {
9895   // First things first: handle placeholders so that the
9896   // overloaded-operator check considers the right type.
9897   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
9898     // Increment and decrement of pseudo-object references.
9899     if (pty->getKind() == BuiltinType::PseudoObject &&
9900         UnaryOperator::isIncrementDecrementOp(Opc))
9901       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
9902 
9903     // extension is always a builtin operator.
9904     if (Opc == UO_Extension)
9905       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9906 
9907     // & gets special logic for several kinds of placeholder.
9908     // The builtin code knows what to do.
9909     if (Opc == UO_AddrOf &&
9910         (pty->getKind() == BuiltinType::Overload ||
9911          pty->getKind() == BuiltinType::UnknownAny ||
9912          pty->getKind() == BuiltinType::BoundMember))
9913       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9914 
9915     // Anything else needs to be handled now.
9916     ExprResult Result = CheckPlaceholderExpr(Input);
9917     if (Result.isInvalid()) return ExprError();
9918     Input = Result.take();
9919   }
9920 
9921   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
9922       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
9923       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
9924     // Find all of the overloaded operators visible from this
9925     // point. We perform both an operator-name lookup from the local
9926     // scope and an argument-dependent lookup based on the types of
9927     // the arguments.
9928     UnresolvedSet<16> Functions;
9929     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
9930     if (S && OverOp != OO_None)
9931       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9932                                    Functions);
9933 
9934     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
9935   }
9936 
9937   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9938 }
9939 
9940 // Unary Operators.  'Tok' is the token for the operator.
9941 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
9942                               tok::TokenKind Op, Expr *Input) {
9943   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
9944 }
9945 
9946 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
9947 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
9948                                 LabelDecl *TheDecl) {
9949   TheDecl->markUsed(Context);
9950   // Create the AST node.  The address of a label always has type 'void*'.
9951   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
9952                                        Context.getPointerType(Context.VoidTy)));
9953 }
9954 
9955 /// Given the last statement in a statement-expression, check whether
9956 /// the result is a producing expression (like a call to an
9957 /// ns_returns_retained function) and, if so, rebuild it to hoist the
9958 /// release out of the full-expression.  Otherwise, return null.
9959 /// Cannot fail.
9960 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
9961   // Should always be wrapped with one of these.
9962   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
9963   if (!cleanups) return 0;
9964 
9965   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
9966   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
9967     return 0;
9968 
9969   // Splice out the cast.  This shouldn't modify any interesting
9970   // features of the statement.
9971   Expr *producer = cast->getSubExpr();
9972   assert(producer->getType() == cast->getType());
9973   assert(producer->getValueKind() == cast->getValueKind());
9974   cleanups->setSubExpr(producer);
9975   return cleanups;
9976 }
9977 
9978 void Sema::ActOnStartStmtExpr() {
9979   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9980 }
9981 
9982 void Sema::ActOnStmtExprError() {
9983   // Note that function is also called by TreeTransform when leaving a
9984   // StmtExpr scope without rebuilding anything.
9985 
9986   DiscardCleanupsInEvaluationContext();
9987   PopExpressionEvaluationContext();
9988 }
9989 
9990 ExprResult
9991 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
9992                     SourceLocation RPLoc) { // "({..})"
9993   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9994   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9995 
9996   if (hasAnyUnrecoverableErrorsInThisFunction())
9997     DiscardCleanupsInEvaluationContext();
9998   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9999   PopExpressionEvaluationContext();
10000 
10001   bool isFileScope
10002     = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
10003   if (isFileScope)
10004     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
10005 
10006   // FIXME: there are a variety of strange constraints to enforce here, for
10007   // example, it is not possible to goto into a stmt expression apparently.
10008   // More semantic analysis is needed.
10009 
10010   // If there are sub-stmts in the compound stmt, take the type of the last one
10011   // as the type of the stmtexpr.
10012   QualType Ty = Context.VoidTy;
10013   bool StmtExprMayBindToTemp = false;
10014   if (!Compound->body_empty()) {
10015     Stmt *LastStmt = Compound->body_back();
10016     LabelStmt *LastLabelStmt = 0;
10017     // If LastStmt is a label, skip down through into the body.
10018     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
10019       LastLabelStmt = Label;
10020       LastStmt = Label->getSubStmt();
10021     }
10022 
10023     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
10024       // Do function/array conversion on the last expression, but not
10025       // lvalue-to-rvalue.  However, initialize an unqualified type.
10026       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
10027       if (LastExpr.isInvalid())
10028         return ExprError();
10029       Ty = LastExpr.get()->getType().getUnqualifiedType();
10030 
10031       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
10032         // In ARC, if the final expression ends in a consume, splice
10033         // the consume out and bind it later.  In the alternate case
10034         // (when dealing with a retainable type), the result
10035         // initialization will create a produce.  In both cases the
10036         // result will be +1, and we'll need to balance that out with
10037         // a bind.
10038         if (Expr *rebuiltLastStmt
10039               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
10040           LastExpr = rebuiltLastStmt;
10041         } else {
10042           LastExpr = PerformCopyInitialization(
10043                             InitializedEntity::InitializeResult(LPLoc,
10044                                                                 Ty,
10045                                                                 false),
10046                                                    SourceLocation(),
10047                                                LastExpr);
10048         }
10049 
10050         if (LastExpr.isInvalid())
10051           return ExprError();
10052         if (LastExpr.get() != 0) {
10053           if (!LastLabelStmt)
10054             Compound->setLastStmt(LastExpr.take());
10055           else
10056             LastLabelStmt->setSubStmt(LastExpr.take());
10057           StmtExprMayBindToTemp = true;
10058         }
10059       }
10060     }
10061   }
10062 
10063   // FIXME: Check that expression type is complete/non-abstract; statement
10064   // expressions are not lvalues.
10065   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
10066   if (StmtExprMayBindToTemp)
10067     return MaybeBindToTemporary(ResStmtExpr);
10068   return Owned(ResStmtExpr);
10069 }
10070 
10071 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
10072                                       TypeSourceInfo *TInfo,
10073                                       OffsetOfComponent *CompPtr,
10074                                       unsigned NumComponents,
10075                                       SourceLocation RParenLoc) {
10076   QualType ArgTy = TInfo->getType();
10077   bool Dependent = ArgTy->isDependentType();
10078   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
10079 
10080   // We must have at least one component that refers to the type, and the first
10081   // one is known to be a field designator.  Verify that the ArgTy represents
10082   // a struct/union/class.
10083   if (!Dependent && !ArgTy->isRecordType())
10084     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
10085                        << ArgTy << TypeRange);
10086 
10087   // Type must be complete per C99 7.17p3 because a declaring a variable
10088   // with an incomplete type would be ill-formed.
10089   if (!Dependent
10090       && RequireCompleteType(BuiltinLoc, ArgTy,
10091                              diag::err_offsetof_incomplete_type, TypeRange))
10092     return ExprError();
10093 
10094   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
10095   // GCC extension, diagnose them.
10096   // FIXME: This diagnostic isn't actually visible because the location is in
10097   // a system header!
10098   if (NumComponents != 1)
10099     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
10100       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
10101 
10102   bool DidWarnAboutNonPOD = false;
10103   QualType CurrentType = ArgTy;
10104   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
10105   SmallVector<OffsetOfNode, 4> Comps;
10106   SmallVector<Expr*, 4> Exprs;
10107   for (unsigned i = 0; i != NumComponents; ++i) {
10108     const OffsetOfComponent &OC = CompPtr[i];
10109     if (OC.isBrackets) {
10110       // Offset of an array sub-field.  TODO: Should we allow vector elements?
10111       if (!CurrentType->isDependentType()) {
10112         const ArrayType *AT = Context.getAsArrayType(CurrentType);
10113         if(!AT)
10114           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
10115                            << CurrentType);
10116         CurrentType = AT->getElementType();
10117       } else
10118         CurrentType = Context.DependentTy;
10119 
10120       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
10121       if (IdxRval.isInvalid())
10122         return ExprError();
10123       Expr *Idx = IdxRval.take();
10124 
10125       // The expression must be an integral expression.
10126       // FIXME: An integral constant expression?
10127       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
10128           !Idx->getType()->isIntegerType())
10129         return ExprError(Diag(Idx->getLocStart(),
10130                               diag::err_typecheck_subscript_not_integer)
10131                          << Idx->getSourceRange());
10132 
10133       // Record this array index.
10134       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
10135       Exprs.push_back(Idx);
10136       continue;
10137     }
10138 
10139     // Offset of a field.
10140     if (CurrentType->isDependentType()) {
10141       // We have the offset of a field, but we can't look into the dependent
10142       // type. Just record the identifier of the field.
10143       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
10144       CurrentType = Context.DependentTy;
10145       continue;
10146     }
10147 
10148     // We need to have a complete type to look into.
10149     if (RequireCompleteType(OC.LocStart, CurrentType,
10150                             diag::err_offsetof_incomplete_type))
10151       return ExprError();
10152 
10153     // Look for the designated field.
10154     const RecordType *RC = CurrentType->getAs<RecordType>();
10155     if (!RC)
10156       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
10157                        << CurrentType);
10158     RecordDecl *RD = RC->getDecl();
10159 
10160     // C++ [lib.support.types]p5:
10161     //   The macro offsetof accepts a restricted set of type arguments in this
10162     //   International Standard. type shall be a POD structure or a POD union
10163     //   (clause 9).
10164     // C++11 [support.types]p4:
10165     //   If type is not a standard-layout class (Clause 9), the results are
10166     //   undefined.
10167     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10168       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
10169       unsigned DiagID =
10170         LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type
10171                             : diag::warn_offsetof_non_pod_type;
10172 
10173       if (!IsSafe && !DidWarnAboutNonPOD &&
10174           DiagRuntimeBehavior(BuiltinLoc, 0,
10175                               PDiag(DiagID)
10176                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
10177                               << CurrentType))
10178         DidWarnAboutNonPOD = true;
10179     }
10180 
10181     // Look for the field.
10182     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
10183     LookupQualifiedName(R, RD);
10184     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
10185     IndirectFieldDecl *IndirectMemberDecl = 0;
10186     if (!MemberDecl) {
10187       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
10188         MemberDecl = IndirectMemberDecl->getAnonField();
10189     }
10190 
10191     if (!MemberDecl)
10192       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
10193                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
10194                                                               OC.LocEnd));
10195 
10196     // C99 7.17p3:
10197     //   (If the specified member is a bit-field, the behavior is undefined.)
10198     //
10199     // We diagnose this as an error.
10200     if (MemberDecl->isBitField()) {
10201       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
10202         << MemberDecl->getDeclName()
10203         << SourceRange(BuiltinLoc, RParenLoc);
10204       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
10205       return ExprError();
10206     }
10207 
10208     RecordDecl *Parent = MemberDecl->getParent();
10209     if (IndirectMemberDecl)
10210       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
10211 
10212     // If the member was found in a base class, introduce OffsetOfNodes for
10213     // the base class indirections.
10214     CXXBasePaths Paths;
10215     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
10216       if (Paths.getDetectedVirtual()) {
10217         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
10218           << MemberDecl->getDeclName()
10219           << SourceRange(BuiltinLoc, RParenLoc);
10220         return ExprError();
10221       }
10222 
10223       CXXBasePath &Path = Paths.front();
10224       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
10225            B != BEnd; ++B)
10226         Comps.push_back(OffsetOfNode(B->Base));
10227     }
10228 
10229     if (IndirectMemberDecl) {
10230       for (auto *FI : IndirectMemberDecl->chain()) {
10231         assert(isa<FieldDecl>(FI));
10232         Comps.push_back(OffsetOfNode(OC.LocStart,
10233                                      cast<FieldDecl>(FI), OC.LocEnd));
10234       }
10235     } else
10236       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
10237 
10238     CurrentType = MemberDecl->getType().getNonReferenceType();
10239   }
10240 
10241   return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
10242                                     TInfo, Comps, Exprs, RParenLoc));
10243 }
10244 
10245 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
10246                                       SourceLocation BuiltinLoc,
10247                                       SourceLocation TypeLoc,
10248                                       ParsedType ParsedArgTy,
10249                                       OffsetOfComponent *CompPtr,
10250                                       unsigned NumComponents,
10251                                       SourceLocation RParenLoc) {
10252 
10253   TypeSourceInfo *ArgTInfo;
10254   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
10255   if (ArgTy.isNull())
10256     return ExprError();
10257 
10258   if (!ArgTInfo)
10259     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
10260 
10261   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
10262                               RParenLoc);
10263 }
10264 
10265 
10266 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
10267                                  Expr *CondExpr,
10268                                  Expr *LHSExpr, Expr *RHSExpr,
10269                                  SourceLocation RPLoc) {
10270   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
10271 
10272   ExprValueKind VK = VK_RValue;
10273   ExprObjectKind OK = OK_Ordinary;
10274   QualType resType;
10275   bool ValueDependent = false;
10276   bool CondIsTrue = false;
10277   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
10278     resType = Context.DependentTy;
10279     ValueDependent = true;
10280   } else {
10281     // The conditional expression is required to be a constant expression.
10282     llvm::APSInt condEval(32);
10283     ExprResult CondICE
10284       = VerifyIntegerConstantExpression(CondExpr, &condEval,
10285           diag::err_typecheck_choose_expr_requires_constant, false);
10286     if (CondICE.isInvalid())
10287       return ExprError();
10288     CondExpr = CondICE.take();
10289     CondIsTrue = condEval.getZExtValue();
10290 
10291     // If the condition is > zero, then the AST type is the same as the LSHExpr.
10292     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
10293 
10294     resType = ActiveExpr->getType();
10295     ValueDependent = ActiveExpr->isValueDependent();
10296     VK = ActiveExpr->getValueKind();
10297     OK = ActiveExpr->getObjectKind();
10298   }
10299 
10300   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
10301                                         resType, VK, OK, RPLoc, CondIsTrue,
10302                                         resType->isDependentType(),
10303                                         ValueDependent));
10304 }
10305 
10306 //===----------------------------------------------------------------------===//
10307 // Clang Extensions.
10308 //===----------------------------------------------------------------------===//
10309 
10310 /// ActOnBlockStart - This callback is invoked when a block literal is started.
10311 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
10312   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
10313 
10314   if (LangOpts.CPlusPlus) {
10315     Decl *ManglingContextDecl;
10316     if (MangleNumberingContext *MCtx =
10317             getCurrentMangleNumberContext(Block->getDeclContext(),
10318                                           ManglingContextDecl)) {
10319       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
10320       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
10321     }
10322   }
10323 
10324   PushBlockScope(CurScope, Block);
10325   CurContext->addDecl(Block);
10326   if (CurScope)
10327     PushDeclContext(CurScope, Block);
10328   else
10329     CurContext = Block;
10330 
10331   getCurBlock()->HasImplicitReturnType = true;
10332 
10333   // Enter a new evaluation context to insulate the block from any
10334   // cleanups from the enclosing full-expression.
10335   PushExpressionEvaluationContext(PotentiallyEvaluated);
10336 }
10337 
10338 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
10339                                Scope *CurScope) {
10340   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
10341   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
10342   BlockScopeInfo *CurBlock = getCurBlock();
10343 
10344   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
10345   QualType T = Sig->getType();
10346 
10347   // FIXME: We should allow unexpanded parameter packs here, but that would,
10348   // in turn, make the block expression contain unexpanded parameter packs.
10349   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
10350     // Drop the parameters.
10351     FunctionProtoType::ExtProtoInfo EPI;
10352     EPI.HasTrailingReturn = false;
10353     EPI.TypeQuals |= DeclSpec::TQ_const;
10354     T = Context.getFunctionType(Context.DependentTy, None, EPI);
10355     Sig = Context.getTrivialTypeSourceInfo(T);
10356   }
10357 
10358   // GetTypeForDeclarator always produces a function type for a block
10359   // literal signature.  Furthermore, it is always a FunctionProtoType
10360   // unless the function was written with a typedef.
10361   assert(T->isFunctionType() &&
10362          "GetTypeForDeclarator made a non-function block signature");
10363 
10364   // Look for an explicit signature in that function type.
10365   FunctionProtoTypeLoc ExplicitSignature;
10366 
10367   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
10368   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
10369 
10370     // Check whether that explicit signature was synthesized by
10371     // GetTypeForDeclarator.  If so, don't save that as part of the
10372     // written signature.
10373     if (ExplicitSignature.getLocalRangeBegin() ==
10374         ExplicitSignature.getLocalRangeEnd()) {
10375       // This would be much cheaper if we stored TypeLocs instead of
10376       // TypeSourceInfos.
10377       TypeLoc Result = ExplicitSignature.getReturnLoc();
10378       unsigned Size = Result.getFullDataSize();
10379       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
10380       Sig->getTypeLoc().initializeFullCopy(Result, Size);
10381 
10382       ExplicitSignature = FunctionProtoTypeLoc();
10383     }
10384   }
10385 
10386   CurBlock->TheDecl->setSignatureAsWritten(Sig);
10387   CurBlock->FunctionType = T;
10388 
10389   const FunctionType *Fn = T->getAs<FunctionType>();
10390   QualType RetTy = Fn->getReturnType();
10391   bool isVariadic =
10392     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
10393 
10394   CurBlock->TheDecl->setIsVariadic(isVariadic);
10395 
10396   // Context.DependentTy is used as a placeholder for a missing block
10397   // return type.  TODO:  what should we do with declarators like:
10398   //   ^ * { ... }
10399   // If the answer is "apply template argument deduction"....
10400   if (RetTy != Context.DependentTy) {
10401     CurBlock->ReturnType = RetTy;
10402     CurBlock->TheDecl->setBlockMissingReturnType(false);
10403     CurBlock->HasImplicitReturnType = false;
10404   }
10405 
10406   // Push block parameters from the declarator if we had them.
10407   SmallVector<ParmVarDecl*, 8> Params;
10408   if (ExplicitSignature) {
10409     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
10410       ParmVarDecl *Param = ExplicitSignature.getParam(I);
10411       if (Param->getIdentifier() == 0 &&
10412           !Param->isImplicit() &&
10413           !Param->isInvalidDecl() &&
10414           !getLangOpts().CPlusPlus)
10415         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10416       Params.push_back(Param);
10417     }
10418 
10419   // Fake up parameter variables if we have a typedef, like
10420   //   ^ fntype { ... }
10421   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
10422     for (const auto &I : Fn->param_types()) {
10423       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
10424           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
10425       Params.push_back(Param);
10426     }
10427   }
10428 
10429   // Set the parameters on the block decl.
10430   if (!Params.empty()) {
10431     CurBlock->TheDecl->setParams(Params);
10432     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
10433                              CurBlock->TheDecl->param_end(),
10434                              /*CheckParameterNames=*/false);
10435   }
10436 
10437   // Finally we can process decl attributes.
10438   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
10439 
10440   // Put the parameter variables in scope.
10441   for (auto AI : CurBlock->TheDecl->params()) {
10442     AI->setOwningFunction(CurBlock->TheDecl);
10443 
10444     // If this has an identifier, add it to the scope stack.
10445     if (AI->getIdentifier()) {
10446       CheckShadow(CurBlock->TheScope, AI);
10447 
10448       PushOnScopeChains(AI, CurBlock->TheScope);
10449     }
10450   }
10451 }
10452 
10453 /// ActOnBlockError - If there is an error parsing a block, this callback
10454 /// is invoked to pop the information about the block from the action impl.
10455 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
10456   // Leave the expression-evaluation context.
10457   DiscardCleanupsInEvaluationContext();
10458   PopExpressionEvaluationContext();
10459 
10460   // Pop off CurBlock, handle nested blocks.
10461   PopDeclContext();
10462   PopFunctionScopeInfo();
10463 }
10464 
10465 /// ActOnBlockStmtExpr - This is called when the body of a block statement
10466 /// literal was successfully completed.  ^(int x){...}
10467 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
10468                                     Stmt *Body, Scope *CurScope) {
10469   // If blocks are disabled, emit an error.
10470   if (!LangOpts.Blocks)
10471     Diag(CaretLoc, diag::err_blocks_disable);
10472 
10473   // Leave the expression-evaluation context.
10474   if (hasAnyUnrecoverableErrorsInThisFunction())
10475     DiscardCleanupsInEvaluationContext();
10476   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
10477   PopExpressionEvaluationContext();
10478 
10479   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
10480 
10481   if (BSI->HasImplicitReturnType)
10482     deduceClosureReturnType(*BSI);
10483 
10484   PopDeclContext();
10485 
10486   QualType RetTy = Context.VoidTy;
10487   if (!BSI->ReturnType.isNull())
10488     RetTy = BSI->ReturnType;
10489 
10490   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
10491   QualType BlockTy;
10492 
10493   // Set the captured variables on the block.
10494   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
10495   SmallVector<BlockDecl::Capture, 4> Captures;
10496   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
10497     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
10498     if (Cap.isThisCapture())
10499       continue;
10500     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
10501                               Cap.isNested(), Cap.getInitExpr());
10502     Captures.push_back(NewCap);
10503   }
10504   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
10505                             BSI->CXXThisCaptureIndex != 0);
10506 
10507   // If the user wrote a function type in some form, try to use that.
10508   if (!BSI->FunctionType.isNull()) {
10509     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
10510 
10511     FunctionType::ExtInfo Ext = FTy->getExtInfo();
10512     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
10513 
10514     // Turn protoless block types into nullary block types.
10515     if (isa<FunctionNoProtoType>(FTy)) {
10516       FunctionProtoType::ExtProtoInfo EPI;
10517       EPI.ExtInfo = Ext;
10518       BlockTy = Context.getFunctionType(RetTy, None, EPI);
10519 
10520     // Otherwise, if we don't need to change anything about the function type,
10521     // preserve its sugar structure.
10522     } else if (FTy->getReturnType() == RetTy &&
10523                (!NoReturn || FTy->getNoReturnAttr())) {
10524       BlockTy = BSI->FunctionType;
10525 
10526     // Otherwise, make the minimal modifications to the function type.
10527     } else {
10528       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
10529       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10530       EPI.TypeQuals = 0; // FIXME: silently?
10531       EPI.ExtInfo = Ext;
10532       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
10533     }
10534 
10535   // If we don't have a function type, just build one from nothing.
10536   } else {
10537     FunctionProtoType::ExtProtoInfo EPI;
10538     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
10539     BlockTy = Context.getFunctionType(RetTy, None, EPI);
10540   }
10541 
10542   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
10543                            BSI->TheDecl->param_end());
10544   BlockTy = Context.getBlockPointerType(BlockTy);
10545 
10546   // If needed, diagnose invalid gotos and switches in the block.
10547   if (getCurFunction()->NeedsScopeChecking() &&
10548       !hasAnyUnrecoverableErrorsInThisFunction() &&
10549       !PP.isCodeCompletionEnabled())
10550     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
10551 
10552   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
10553 
10554   // Try to apply the named return value optimization. We have to check again
10555   // if we can do this, though, because blocks keep return statements around
10556   // to deduce an implicit return type.
10557   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
10558       !BSI->TheDecl->isDependentContext())
10559     computeNRVO(Body, getCurBlock());
10560 
10561   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
10562   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10563   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
10564 
10565   // If the block isn't obviously global, i.e. it captures anything at
10566   // all, then we need to do a few things in the surrounding context:
10567   if (Result->getBlockDecl()->hasCaptures()) {
10568     // First, this expression has a new cleanup object.
10569     ExprCleanupObjects.push_back(Result->getBlockDecl());
10570     ExprNeedsCleanups = true;
10571 
10572     // It also gets a branch-protected scope if any of the captured
10573     // variables needs destruction.
10574     for (const auto &CI : Result->getBlockDecl()->captures()) {
10575       const VarDecl *var = CI.getVariable();
10576       if (var->getType().isDestructedType() != QualType::DK_none) {
10577         getCurFunction()->setHasBranchProtectedScope();
10578         break;
10579       }
10580     }
10581   }
10582 
10583   return Owned(Result);
10584 }
10585 
10586 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
10587                                         Expr *E, ParsedType Ty,
10588                                         SourceLocation RPLoc) {
10589   TypeSourceInfo *TInfo;
10590   GetTypeFromParser(Ty, &TInfo);
10591   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
10592 }
10593 
10594 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
10595                                 Expr *E, TypeSourceInfo *TInfo,
10596                                 SourceLocation RPLoc) {
10597   Expr *OrigExpr = E;
10598 
10599   // Get the va_list type
10600   QualType VaListType = Context.getBuiltinVaListType();
10601   if (VaListType->isArrayType()) {
10602     // Deal with implicit array decay; for example, on x86-64,
10603     // va_list is an array, but it's supposed to decay to
10604     // a pointer for va_arg.
10605     VaListType = Context.getArrayDecayedType(VaListType);
10606     // Make sure the input expression also decays appropriately.
10607     ExprResult Result = UsualUnaryConversions(E);
10608     if (Result.isInvalid())
10609       return ExprError();
10610     E = Result.take();
10611   } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
10612     // If va_list is a record type and we are compiling in C++ mode,
10613     // check the argument using reference binding.
10614     InitializedEntity Entity
10615       = InitializedEntity::InitializeParameter(Context,
10616           Context.getLValueReferenceType(VaListType), false);
10617     ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
10618     if (Init.isInvalid())
10619       return ExprError();
10620     E = Init.takeAs<Expr>();
10621   } else {
10622     // Otherwise, the va_list argument must be an l-value because
10623     // it is modified by va_arg.
10624     if (!E->isTypeDependent() &&
10625         CheckForModifiableLvalue(E, BuiltinLoc, *this))
10626       return ExprError();
10627   }
10628 
10629   if (!E->isTypeDependent() &&
10630       !Context.hasSameType(VaListType, E->getType())) {
10631     return ExprError(Diag(E->getLocStart(),
10632                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
10633       << OrigExpr->getType() << E->getSourceRange());
10634   }
10635 
10636   if (!TInfo->getType()->isDependentType()) {
10637     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10638                             diag::err_second_parameter_to_va_arg_incomplete,
10639                             TInfo->getTypeLoc()))
10640       return ExprError();
10641 
10642     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10643                                TInfo->getType(),
10644                                diag::err_second_parameter_to_va_arg_abstract,
10645                                TInfo->getTypeLoc()))
10646       return ExprError();
10647 
10648     if (!TInfo->getType().isPODType(Context)) {
10649       Diag(TInfo->getTypeLoc().getBeginLoc(),
10650            TInfo->getType()->isObjCLifetimeType()
10651              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
10652              : diag::warn_second_parameter_to_va_arg_not_pod)
10653         << TInfo->getType()
10654         << TInfo->getTypeLoc().getSourceRange();
10655     }
10656 
10657     // Check for va_arg where arguments of the given type will be promoted
10658     // (i.e. this va_arg is guaranteed to have undefined behavior).
10659     QualType PromoteType;
10660     if (TInfo->getType()->isPromotableIntegerType()) {
10661       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
10662       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
10663         PromoteType = QualType();
10664     }
10665     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
10666       PromoteType = Context.DoubleTy;
10667     if (!PromoteType.isNull())
10668       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
10669                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
10670                           << TInfo->getType()
10671                           << PromoteType
10672                           << TInfo->getTypeLoc().getSourceRange());
10673   }
10674 
10675   QualType T = TInfo->getType().getNonLValueExprType(Context);
10676   return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
10677 }
10678 
10679 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
10680   // The type of __null will be int or long, depending on the size of
10681   // pointers on the target.
10682   QualType Ty;
10683   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
10684   if (pw == Context.getTargetInfo().getIntWidth())
10685     Ty = Context.IntTy;
10686   else if (pw == Context.getTargetInfo().getLongWidth())
10687     Ty = Context.LongTy;
10688   else if (pw == Context.getTargetInfo().getLongLongWidth())
10689     Ty = Context.LongLongTy;
10690   else {
10691     llvm_unreachable("I don't know size of pointer!");
10692   }
10693 
10694   return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
10695 }
10696 
10697 bool
10698 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
10699   if (!getLangOpts().ObjC1)
10700     return false;
10701 
10702   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10703   if (!PT)
10704     return false;
10705 
10706   if (!PT->isObjCIdType()) {
10707     // Check if the destination is the 'NSString' interface.
10708     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10709     if (!ID || !ID->getIdentifier()->isStr("NSString"))
10710       return false;
10711   }
10712 
10713   // Ignore any parens, implicit casts (should only be
10714   // array-to-pointer decays), and not-so-opaque values.  The last is
10715   // important for making this trigger for property assignments.
10716   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
10717   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10718     if (OV->getSourceExpr())
10719       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10720 
10721   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
10722   if (!SL || !SL->isAscii())
10723     return false;
10724   Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
10725     << FixItHint::CreateInsertion(SL->getLocStart(), "@");
10726   Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).take();
10727   return true;
10728 }
10729 
10730 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10731                                     SourceLocation Loc,
10732                                     QualType DstType, QualType SrcType,
10733                                     Expr *SrcExpr, AssignmentAction Action,
10734                                     bool *Complained) {
10735   if (Complained)
10736     *Complained = false;
10737 
10738   // Decode the result (notice that AST's are still created for extensions).
10739   bool CheckInferredResultType = false;
10740   bool isInvalid = false;
10741   unsigned DiagKind = 0;
10742   FixItHint Hint;
10743   ConversionFixItGenerator ConvHints;
10744   bool MayHaveConvFixit = false;
10745   bool MayHaveFunctionDiff = false;
10746 
10747   switch (ConvTy) {
10748   case Compatible:
10749       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10750       return false;
10751 
10752   case PointerToInt:
10753     DiagKind = diag::ext_typecheck_convert_pointer_int;
10754     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10755     MayHaveConvFixit = true;
10756     break;
10757   case IntToPointer:
10758     DiagKind = diag::ext_typecheck_convert_int_pointer;
10759     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10760     MayHaveConvFixit = true;
10761     break;
10762   case IncompatiblePointer:
10763       DiagKind =
10764         (Action == AA_Passing_CFAudited ?
10765           diag::err_arc_typecheck_convert_incompatible_pointer :
10766           diag::ext_typecheck_convert_incompatible_pointer);
10767     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10768       SrcType->isObjCObjectPointerType();
10769     if (Hint.isNull() && !CheckInferredResultType) {
10770       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10771     }
10772     else if (CheckInferredResultType) {
10773       SrcType = SrcType.getUnqualifiedType();
10774       DstType = DstType.getUnqualifiedType();
10775     }
10776     MayHaveConvFixit = true;
10777     break;
10778   case IncompatiblePointerSign:
10779     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10780     break;
10781   case FunctionVoidPointer:
10782     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10783     break;
10784   case IncompatiblePointerDiscardsQualifiers: {
10785     // Perform array-to-pointer decay if necessary.
10786     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10787 
10788     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10789     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10790     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10791       DiagKind = diag::err_typecheck_incompatible_address_space;
10792       break;
10793 
10794 
10795     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10796       DiagKind = diag::err_typecheck_incompatible_ownership;
10797       break;
10798     }
10799 
10800     llvm_unreachable("unknown error case for discarding qualifiers!");
10801     // fallthrough
10802   }
10803   case CompatiblePointerDiscardsQualifiers:
10804     // If the qualifiers lost were because we were applying the
10805     // (deprecated) C++ conversion from a string literal to a char*
10806     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
10807     // Ideally, this check would be performed in
10808     // checkPointerTypesForAssignment. However, that would require a
10809     // bit of refactoring (so that the second argument is an
10810     // expression, rather than a type), which should be done as part
10811     // of a larger effort to fix checkPointerTypesForAssignment for
10812     // C++ semantics.
10813     if (getLangOpts().CPlusPlus &&
10814         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10815       return false;
10816     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10817     break;
10818   case IncompatibleNestedPointerQualifiers:
10819     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
10820     break;
10821   case IntToBlockPointer:
10822     DiagKind = diag::err_int_to_block_pointer;
10823     break;
10824   case IncompatibleBlockPointer:
10825     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
10826     break;
10827   case IncompatibleObjCQualifiedId:
10828     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
10829     // it can give a more specific diagnostic.
10830     DiagKind = diag::warn_incompatible_qualified_id;
10831     break;
10832   case IncompatibleVectors:
10833     DiagKind = diag::warn_incompatible_vectors;
10834     break;
10835   case IncompatibleObjCWeakRef:
10836     DiagKind = diag::err_arc_weak_unavailable_assign;
10837     break;
10838   case Incompatible:
10839     DiagKind = diag::err_typecheck_convert_incompatible;
10840     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10841     MayHaveConvFixit = true;
10842     isInvalid = true;
10843     MayHaveFunctionDiff = true;
10844     break;
10845   }
10846 
10847   QualType FirstType, SecondType;
10848   switch (Action) {
10849   case AA_Assigning:
10850   case AA_Initializing:
10851     // The destination type comes first.
10852     FirstType = DstType;
10853     SecondType = SrcType;
10854     break;
10855 
10856   case AA_Returning:
10857   case AA_Passing:
10858   case AA_Passing_CFAudited:
10859   case AA_Converting:
10860   case AA_Sending:
10861   case AA_Casting:
10862     // The source type comes first.
10863     FirstType = SrcType;
10864     SecondType = DstType;
10865     break;
10866   }
10867 
10868   PartialDiagnostic FDiag = PDiag(DiagKind);
10869   if (Action == AA_Passing_CFAudited)
10870     FDiag << FirstType << SecondType << SrcExpr->getSourceRange();
10871   else
10872     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
10873 
10874   // If we can fix the conversion, suggest the FixIts.
10875   assert(ConvHints.isNull() || Hint.isNull());
10876   if (!ConvHints.isNull()) {
10877     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
10878          HE = ConvHints.Hints.end(); HI != HE; ++HI)
10879       FDiag << *HI;
10880   } else {
10881     FDiag << Hint;
10882   }
10883   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
10884 
10885   if (MayHaveFunctionDiff)
10886     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
10887 
10888   Diag(Loc, FDiag);
10889 
10890   if (SecondType == Context.OverloadTy)
10891     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
10892                               FirstType);
10893 
10894   if (CheckInferredResultType)
10895     EmitRelatedResultTypeNote(SrcExpr);
10896 
10897   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
10898     EmitRelatedResultTypeNoteForReturn(DstType);
10899 
10900   if (Complained)
10901     *Complained = true;
10902   return isInvalid;
10903 }
10904 
10905 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10906                                                  llvm::APSInt *Result) {
10907   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
10908   public:
10909     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
10910       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
10911     }
10912   } Diagnoser;
10913 
10914   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
10915 }
10916 
10917 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10918                                                  llvm::APSInt *Result,
10919                                                  unsigned DiagID,
10920                                                  bool AllowFold) {
10921   class IDDiagnoser : public VerifyICEDiagnoser {
10922     unsigned DiagID;
10923 
10924   public:
10925     IDDiagnoser(unsigned DiagID)
10926       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
10927 
10928     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
10929       S.Diag(Loc, DiagID) << SR;
10930     }
10931   } Diagnoser(DiagID);
10932 
10933   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
10934 }
10935 
10936 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
10937                                             SourceRange SR) {
10938   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
10939 }
10940 
10941 ExprResult
10942 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10943                                       VerifyICEDiagnoser &Diagnoser,
10944                                       bool AllowFold) {
10945   SourceLocation DiagLoc = E->getLocStart();
10946 
10947   if (getLangOpts().CPlusPlus11) {
10948     // C++11 [expr.const]p5:
10949     //   If an expression of literal class type is used in a context where an
10950     //   integral constant expression is required, then that class type shall
10951     //   have a single non-explicit conversion function to an integral or
10952     //   unscoped enumeration type
10953     ExprResult Converted;
10954     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
10955     public:
10956       CXX11ConvertDiagnoser(bool Silent)
10957           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
10958                                 Silent, true) {}
10959 
10960       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10961                                            QualType T) override {
10962         return S.Diag(Loc, diag::err_ice_not_integral) << T;
10963       }
10964 
10965       SemaDiagnosticBuilder diagnoseIncomplete(
10966           Sema &S, SourceLocation Loc, QualType T) override {
10967         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
10968       }
10969 
10970       SemaDiagnosticBuilder diagnoseExplicitConv(
10971           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
10972         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10973       }
10974 
10975       SemaDiagnosticBuilder noteExplicitConv(
10976           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
10977         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10978                  << ConvTy->isEnumeralType() << ConvTy;
10979       }
10980 
10981       SemaDiagnosticBuilder diagnoseAmbiguous(
10982           Sema &S, SourceLocation Loc, QualType T) override {
10983         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10984       }
10985 
10986       SemaDiagnosticBuilder noteAmbiguous(
10987           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
10988         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10989                  << ConvTy->isEnumeralType() << ConvTy;
10990       }
10991 
10992       SemaDiagnosticBuilder diagnoseConversion(
10993           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
10994         llvm_unreachable("conversion functions are permitted");
10995       }
10996     } ConvertDiagnoser(Diagnoser.Suppress);
10997 
10998     Converted = PerformContextualImplicitConversion(DiagLoc, E,
10999                                                     ConvertDiagnoser);
11000     if (Converted.isInvalid())
11001       return Converted;
11002     E = Converted.take();
11003     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
11004       return ExprError();
11005   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
11006     // An ICE must be of integral or unscoped enumeration type.
11007     if (!Diagnoser.Suppress)
11008       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11009     return ExprError();
11010   }
11011 
11012   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
11013   // in the non-ICE case.
11014   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
11015     if (Result)
11016       *Result = E->EvaluateKnownConstInt(Context);
11017     return Owned(E);
11018   }
11019 
11020   Expr::EvalResult EvalResult;
11021   SmallVector<PartialDiagnosticAt, 8> Notes;
11022   EvalResult.Diag = &Notes;
11023 
11024   // Try to evaluate the expression, and produce diagnostics explaining why it's
11025   // not a constant expression as a side-effect.
11026   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
11027                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
11028 
11029   // In C++11, we can rely on diagnostics being produced for any expression
11030   // which is not a constant expression. If no diagnostics were produced, then
11031   // this is a constant expression.
11032   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
11033     if (Result)
11034       *Result = EvalResult.Val.getInt();
11035     return Owned(E);
11036   }
11037 
11038   // If our only note is the usual "invalid subexpression" note, just point
11039   // the caret at its location rather than producing an essentially
11040   // redundant note.
11041   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11042         diag::note_invalid_subexpr_in_const_expr) {
11043     DiagLoc = Notes[0].first;
11044     Notes.clear();
11045   }
11046 
11047   if (!Folded || !AllowFold) {
11048     if (!Diagnoser.Suppress) {
11049       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11050       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11051         Diag(Notes[I].first, Notes[I].second);
11052     }
11053 
11054     return ExprError();
11055   }
11056 
11057   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
11058   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11059     Diag(Notes[I].first, Notes[I].second);
11060 
11061   if (Result)
11062     *Result = EvalResult.Val.getInt();
11063   return Owned(E);
11064 }
11065 
11066 namespace {
11067   // Handle the case where we conclude a expression which we speculatively
11068   // considered to be unevaluated is actually evaluated.
11069   class TransformToPE : public TreeTransform<TransformToPE> {
11070     typedef TreeTransform<TransformToPE> BaseTransform;
11071 
11072   public:
11073     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
11074 
11075     // Make sure we redo semantic analysis
11076     bool AlwaysRebuild() { return true; }
11077 
11078     // Make sure we handle LabelStmts correctly.
11079     // FIXME: This does the right thing, but maybe we need a more general
11080     // fix to TreeTransform?
11081     StmtResult TransformLabelStmt(LabelStmt *S) {
11082       S->getDecl()->setStmt(0);
11083       return BaseTransform::TransformLabelStmt(S);
11084     }
11085 
11086     // We need to special-case DeclRefExprs referring to FieldDecls which
11087     // are not part of a member pointer formation; normal TreeTransforming
11088     // doesn't catch this case because of the way we represent them in the AST.
11089     // FIXME: This is a bit ugly; is it really the best way to handle this
11090     // case?
11091     //
11092     // Error on DeclRefExprs referring to FieldDecls.
11093     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
11094       if (isa<FieldDecl>(E->getDecl()) &&
11095           !SemaRef.isUnevaluatedContext())
11096         return SemaRef.Diag(E->getLocation(),
11097                             diag::err_invalid_non_static_member_use)
11098             << E->getDecl() << E->getSourceRange();
11099 
11100       return BaseTransform::TransformDeclRefExpr(E);
11101     }
11102 
11103     // Exception: filter out member pointer formation
11104     ExprResult TransformUnaryOperator(UnaryOperator *E) {
11105       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
11106         return E;
11107 
11108       return BaseTransform::TransformUnaryOperator(E);
11109     }
11110 
11111     ExprResult TransformLambdaExpr(LambdaExpr *E) {
11112       // Lambdas never need to be transformed.
11113       return E;
11114     }
11115   };
11116 }
11117 
11118 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
11119   assert(isUnevaluatedContext() &&
11120          "Should only transform unevaluated expressions");
11121   ExprEvalContexts.back().Context =
11122       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
11123   if (isUnevaluatedContext())
11124     return E;
11125   return TransformToPE(*this).TransformExpr(E);
11126 }
11127 
11128 void
11129 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11130                                       Decl *LambdaContextDecl,
11131                                       bool IsDecltype) {
11132   ExprEvalContexts.push_back(
11133              ExpressionEvaluationContextRecord(NewContext,
11134                                                ExprCleanupObjects.size(),
11135                                                ExprNeedsCleanups,
11136                                                LambdaContextDecl,
11137                                                IsDecltype));
11138   ExprNeedsCleanups = false;
11139   if (!MaybeODRUseExprs.empty())
11140     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
11141 }
11142 
11143 void
11144 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11145                                       ReuseLambdaContextDecl_t,
11146                                       bool IsDecltype) {
11147   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
11148   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
11149 }
11150 
11151 void Sema::PopExpressionEvaluationContext() {
11152   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
11153 
11154   if (!Rec.Lambdas.empty()) {
11155     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11156       unsigned D;
11157       if (Rec.isUnevaluated()) {
11158         // C++11 [expr.prim.lambda]p2:
11159         //   A lambda-expression shall not appear in an unevaluated operand
11160         //   (Clause 5).
11161         D = diag::err_lambda_unevaluated_operand;
11162       } else {
11163         // C++1y [expr.const]p2:
11164         //   A conditional-expression e is a core constant expression unless the
11165         //   evaluation of e, following the rules of the abstract machine, would
11166         //   evaluate [...] a lambda-expression.
11167         D = diag::err_lambda_in_constant_expression;
11168       }
11169       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
11170         Diag(Rec.Lambdas[I]->getLocStart(), D);
11171     } else {
11172       // Mark the capture expressions odr-used. This was deferred
11173       // during lambda expression creation.
11174       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
11175         LambdaExpr *Lambda = Rec.Lambdas[I];
11176         for (LambdaExpr::capture_init_iterator
11177                   C = Lambda->capture_init_begin(),
11178                CEnd = Lambda->capture_init_end();
11179              C != CEnd; ++C) {
11180           MarkDeclarationsReferencedInExpr(*C);
11181         }
11182       }
11183     }
11184   }
11185 
11186   // When are coming out of an unevaluated context, clear out any
11187   // temporaries that we may have created as part of the evaluation of
11188   // the expression in that context: they aren't relevant because they
11189   // will never be constructed.
11190   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11191     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
11192                              ExprCleanupObjects.end());
11193     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
11194     CleanupVarDeclMarking();
11195     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
11196   // Otherwise, merge the contexts together.
11197   } else {
11198     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
11199     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
11200                             Rec.SavedMaybeODRUseExprs.end());
11201   }
11202 
11203   // Pop the current expression evaluation context off the stack.
11204   ExprEvalContexts.pop_back();
11205 }
11206 
11207 void Sema::DiscardCleanupsInEvaluationContext() {
11208   ExprCleanupObjects.erase(
11209          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
11210          ExprCleanupObjects.end());
11211   ExprNeedsCleanups = false;
11212   MaybeODRUseExprs.clear();
11213 }
11214 
11215 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
11216   if (!E->getType()->isVariablyModifiedType())
11217     return E;
11218   return TransformToPotentiallyEvaluated(E);
11219 }
11220 
11221 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
11222   // Do not mark anything as "used" within a dependent context; wait for
11223   // an instantiation.
11224   if (SemaRef.CurContext->isDependentContext())
11225     return false;
11226 
11227   switch (SemaRef.ExprEvalContexts.back().Context) {
11228     case Sema::Unevaluated:
11229     case Sema::UnevaluatedAbstract:
11230       // We are in an expression that is not potentially evaluated; do nothing.
11231       // (Depending on how you read the standard, we actually do need to do
11232       // something here for null pointer constants, but the standard's
11233       // definition of a null pointer constant is completely crazy.)
11234       return false;
11235 
11236     case Sema::ConstantEvaluated:
11237     case Sema::PotentiallyEvaluated:
11238       // We are in a potentially evaluated expression (or a constant-expression
11239       // in C++03); we need to do implicit template instantiation, implicitly
11240       // define class members, and mark most declarations as used.
11241       return true;
11242 
11243     case Sema::PotentiallyEvaluatedIfUsed:
11244       // Referenced declarations will only be used if the construct in the
11245       // containing expression is used.
11246       return false;
11247   }
11248   llvm_unreachable("Invalid context");
11249 }
11250 
11251 /// \brief Mark a function referenced, and check whether it is odr-used
11252 /// (C++ [basic.def.odr]p2, C99 6.9p3)
11253 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
11254   assert(Func && "No function?");
11255 
11256   Func->setReferenced();
11257 
11258   // C++11 [basic.def.odr]p3:
11259   //   A function whose name appears as a potentially-evaluated expression is
11260   //   odr-used if it is the unique lookup result or the selected member of a
11261   //   set of overloaded functions [...].
11262   //
11263   // We (incorrectly) mark overload resolution as an unevaluated context, so we
11264   // can just check that here. Skip the rest of this function if we've already
11265   // marked the function as used.
11266   if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
11267     // C++11 [temp.inst]p3:
11268     //   Unless a function template specialization has been explicitly
11269     //   instantiated or explicitly specialized, the function template
11270     //   specialization is implicitly instantiated when the specialization is
11271     //   referenced in a context that requires a function definition to exist.
11272     //
11273     // We consider constexpr function templates to be referenced in a context
11274     // that requires a definition to exist whenever they are referenced.
11275     //
11276     // FIXME: This instantiates constexpr functions too frequently. If this is
11277     // really an unevaluated context (and we're not just in the definition of a
11278     // function template or overload resolution or other cases which we
11279     // incorrectly consider to be unevaluated contexts), and we're not in a
11280     // subexpression which we actually need to evaluate (for instance, a
11281     // template argument, array bound or an expression in a braced-init-list),
11282     // we are not permitted to instantiate this constexpr function definition.
11283     //
11284     // FIXME: This also implicitly defines special members too frequently. They
11285     // are only supposed to be implicitly defined if they are odr-used, but they
11286     // are not odr-used from constant expressions in unevaluated contexts.
11287     // However, they cannot be referenced if they are deleted, and they are
11288     // deleted whenever the implicit definition of the special member would
11289     // fail.
11290     if (!Func->isConstexpr() || Func->getBody())
11291       return;
11292     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
11293     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
11294       return;
11295   }
11296 
11297   // Note that this declaration has been used.
11298   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
11299     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
11300     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
11301       if (Constructor->isDefaultConstructor()) {
11302         if (Constructor->isTrivial())
11303           return;
11304         DefineImplicitDefaultConstructor(Loc, Constructor);
11305       } else if (Constructor->isCopyConstructor()) {
11306         DefineImplicitCopyConstructor(Loc, Constructor);
11307       } else if (Constructor->isMoveConstructor()) {
11308         DefineImplicitMoveConstructor(Loc, Constructor);
11309       }
11310     } else if (Constructor->getInheritedConstructor()) {
11311       DefineInheritingConstructor(Loc, Constructor);
11312     }
11313 
11314     MarkVTableUsed(Loc, Constructor->getParent());
11315   } else if (CXXDestructorDecl *Destructor =
11316                  dyn_cast<CXXDestructorDecl>(Func)) {
11317     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
11318     if (Destructor->isDefaulted() && !Destructor->isDeleted())
11319       DefineImplicitDestructor(Loc, Destructor);
11320     if (Destructor->isVirtual())
11321       MarkVTableUsed(Loc, Destructor->getParent());
11322   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
11323     if (MethodDecl->isOverloadedOperator() &&
11324         MethodDecl->getOverloadedOperator() == OO_Equal) {
11325       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
11326       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
11327         if (MethodDecl->isCopyAssignmentOperator())
11328           DefineImplicitCopyAssignment(Loc, MethodDecl);
11329         else
11330           DefineImplicitMoveAssignment(Loc, MethodDecl);
11331       }
11332     } else if (isa<CXXConversionDecl>(MethodDecl) &&
11333                MethodDecl->getParent()->isLambda()) {
11334       CXXConversionDecl *Conversion =
11335           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
11336       if (Conversion->isLambdaToBlockPointerConversion())
11337         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
11338       else
11339         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
11340     } else if (MethodDecl->isVirtual())
11341       MarkVTableUsed(Loc, MethodDecl->getParent());
11342   }
11343 
11344   // Recursive functions should be marked when used from another function.
11345   // FIXME: Is this really right?
11346   if (CurContext == Func) return;
11347 
11348   // Resolve the exception specification for any function which is
11349   // used: CodeGen will need it.
11350   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
11351   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
11352     ResolveExceptionSpec(Loc, FPT);
11353 
11354   // Implicit instantiation of function templates and member functions of
11355   // class templates.
11356   if (Func->isImplicitlyInstantiable()) {
11357     bool AlreadyInstantiated = false;
11358     SourceLocation PointOfInstantiation = Loc;
11359     if (FunctionTemplateSpecializationInfo *SpecInfo
11360                               = Func->getTemplateSpecializationInfo()) {
11361       if (SpecInfo->getPointOfInstantiation().isInvalid())
11362         SpecInfo->setPointOfInstantiation(Loc);
11363       else if (SpecInfo->getTemplateSpecializationKind()
11364                  == TSK_ImplicitInstantiation) {
11365         AlreadyInstantiated = true;
11366         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
11367       }
11368     } else if (MemberSpecializationInfo *MSInfo
11369                                 = Func->getMemberSpecializationInfo()) {
11370       if (MSInfo->getPointOfInstantiation().isInvalid())
11371         MSInfo->setPointOfInstantiation(Loc);
11372       else if (MSInfo->getTemplateSpecializationKind()
11373                  == TSK_ImplicitInstantiation) {
11374         AlreadyInstantiated = true;
11375         PointOfInstantiation = MSInfo->getPointOfInstantiation();
11376       }
11377     }
11378 
11379     if (!AlreadyInstantiated || Func->isConstexpr()) {
11380       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
11381           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
11382           ActiveTemplateInstantiations.size())
11383         PendingLocalImplicitInstantiations.push_back(
11384             std::make_pair(Func, PointOfInstantiation));
11385       else if (Func->isConstexpr())
11386         // Do not defer instantiations of constexpr functions, to avoid the
11387         // expression evaluator needing to call back into Sema if it sees a
11388         // call to such a function.
11389         InstantiateFunctionDefinition(PointOfInstantiation, Func);
11390       else {
11391         PendingInstantiations.push_back(std::make_pair(Func,
11392                                                        PointOfInstantiation));
11393         // Notify the consumer that a function was implicitly instantiated.
11394         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
11395       }
11396     }
11397   } else {
11398     // Walk redefinitions, as some of them may be instantiable.
11399     for (auto i : Func->redecls()) {
11400       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
11401         MarkFunctionReferenced(Loc, i);
11402     }
11403   }
11404 
11405   // Keep track of used but undefined functions.
11406   if (!Func->isDefined()) {
11407     if (mightHaveNonExternalLinkage(Func))
11408       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11409     else if (Func->getMostRecentDecl()->isInlined() &&
11410              (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
11411              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
11412       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11413   }
11414 
11415   // Normally the most current decl is marked used while processing the use and
11416   // any subsequent decls are marked used by decl merging. This fails with
11417   // template instantiation since marking can happen at the end of the file
11418   // and, because of the two phase lookup, this function is called with at
11419   // decl in the middle of a decl chain. We loop to maintain the invariant
11420   // that once a decl is used, all decls after it are also used.
11421   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
11422     F->markUsed(Context);
11423     if (F == Func)
11424       break;
11425   }
11426 }
11427 
11428 static void
11429 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
11430                                    VarDecl *var, DeclContext *DC) {
11431   DeclContext *VarDC = var->getDeclContext();
11432 
11433   //  If the parameter still belongs to the translation unit, then
11434   //  we're actually just using one parameter in the declaration of
11435   //  the next.
11436   if (isa<ParmVarDecl>(var) &&
11437       isa<TranslationUnitDecl>(VarDC))
11438     return;
11439 
11440   // For C code, don't diagnose about capture if we're not actually in code
11441   // right now; it's impossible to write a non-constant expression outside of
11442   // function context, so we'll get other (more useful) diagnostics later.
11443   //
11444   // For C++, things get a bit more nasty... it would be nice to suppress this
11445   // diagnostic for certain cases like using a local variable in an array bound
11446   // for a member of a local class, but the correct predicate is not obvious.
11447   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
11448     return;
11449 
11450   if (isa<CXXMethodDecl>(VarDC) &&
11451       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
11452     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
11453       << var->getIdentifier();
11454   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
11455     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
11456       << var->getIdentifier() << fn->getDeclName();
11457   } else if (isa<BlockDecl>(VarDC)) {
11458     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
11459       << var->getIdentifier();
11460   } else {
11461     // FIXME: Is there any other context where a local variable can be
11462     // declared?
11463     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
11464       << var->getIdentifier();
11465   }
11466 
11467   S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
11468     << var->getIdentifier();
11469 
11470   // FIXME: Add additional diagnostic info about class etc. which prevents
11471   // capture.
11472 }
11473 
11474 
11475 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
11476                                       bool &SubCapturesAreNested,
11477                                       QualType &CaptureType,
11478                                       QualType &DeclRefType) {
11479    // Check whether we've already captured it.
11480   if (CSI->CaptureMap.count(Var)) {
11481     // If we found a capture, any subcaptures are nested.
11482     SubCapturesAreNested = true;
11483 
11484     // Retrieve the capture type for this variable.
11485     CaptureType = CSI->getCapture(Var).getCaptureType();
11486 
11487     // Compute the type of an expression that refers to this variable.
11488     DeclRefType = CaptureType.getNonReferenceType();
11489 
11490     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
11491     if (Cap.isCopyCapture() &&
11492         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
11493       DeclRefType.addConst();
11494     return true;
11495   }
11496   return false;
11497 }
11498 
11499 // Only block literals, captured statements, and lambda expressions can
11500 // capture; other scopes don't work.
11501 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
11502                                  SourceLocation Loc,
11503                                  const bool Diagnose, Sema &S) {
11504   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
11505     return getLambdaAwareParentOfDeclContext(DC);
11506   else {
11507     if (Diagnose)
11508        diagnoseUncapturableValueReference(S, Loc, Var, DC);
11509   }
11510   return 0;
11511 }
11512 
11513 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
11514 // certain types of variables (unnamed, variably modified types etc.)
11515 // so check for eligibility.
11516 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
11517                                  SourceLocation Loc,
11518                                  const bool Diagnose, Sema &S) {
11519 
11520   bool IsBlock = isa<BlockScopeInfo>(CSI);
11521   bool IsLambda = isa<LambdaScopeInfo>(CSI);
11522 
11523   // Lambdas are not allowed to capture unnamed variables
11524   // (e.g. anonymous unions).
11525   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
11526   // assuming that's the intent.
11527   if (IsLambda && !Var->getDeclName()) {
11528     if (Diagnose) {
11529       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
11530       S.Diag(Var->getLocation(), diag::note_declared_at);
11531     }
11532     return false;
11533   }
11534 
11535   // Prohibit variably-modified types; they're difficult to deal with.
11536   if (Var->getType()->isVariablyModifiedType()) {
11537     if (Diagnose) {
11538       if (IsBlock)
11539         S.Diag(Loc, diag::err_ref_vm_type);
11540       else
11541         S.Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
11542       S.Diag(Var->getLocation(), diag::note_previous_decl)
11543         << Var->getDeclName();
11544     }
11545     return false;
11546   }
11547   // Prohibit structs with flexible array members too.
11548   // We cannot capture what is in the tail end of the struct.
11549   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
11550     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
11551       if (Diagnose) {
11552         if (IsBlock)
11553           S.Diag(Loc, diag::err_ref_flexarray_type);
11554         else
11555           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
11556             << Var->getDeclName();
11557         S.Diag(Var->getLocation(), diag::note_previous_decl)
11558           << Var->getDeclName();
11559       }
11560       return false;
11561     }
11562   }
11563   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11564   // Lambdas and captured statements are not allowed to capture __block
11565   // variables; they don't support the expected semantics.
11566   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
11567     if (Diagnose) {
11568       S.Diag(Loc, diag::err_capture_block_variable)
11569         << Var->getDeclName() << !IsLambda;
11570       S.Diag(Var->getLocation(), diag::note_previous_decl)
11571         << Var->getDeclName();
11572     }
11573     return false;
11574   }
11575 
11576   return true;
11577 }
11578 
11579 // Returns true if the capture by block was successful.
11580 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
11581                                  SourceLocation Loc,
11582                                  const bool BuildAndDiagnose,
11583                                  QualType &CaptureType,
11584                                  QualType &DeclRefType,
11585                                  const bool Nested,
11586                                  Sema &S) {
11587   Expr *CopyExpr = 0;
11588   bool ByRef = false;
11589 
11590   // Blocks are not allowed to capture arrays.
11591   if (CaptureType->isArrayType()) {
11592     if (BuildAndDiagnose) {
11593       S.Diag(Loc, diag::err_ref_array_type);
11594       S.Diag(Var->getLocation(), diag::note_previous_decl)
11595       << Var->getDeclName();
11596     }
11597     return false;
11598   }
11599 
11600   // Forbid the block-capture of autoreleasing variables.
11601   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11602     if (BuildAndDiagnose) {
11603       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
11604         << /*block*/ 0;
11605       S.Diag(Var->getLocation(), diag::note_previous_decl)
11606         << Var->getDeclName();
11607     }
11608     return false;
11609   }
11610   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11611   if (HasBlocksAttr || CaptureType->isReferenceType()) {
11612     // Block capture by reference does not change the capture or
11613     // declaration reference types.
11614     ByRef = true;
11615   } else {
11616     // Block capture by copy introduces 'const'.
11617     CaptureType = CaptureType.getNonReferenceType().withConst();
11618     DeclRefType = CaptureType;
11619 
11620     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
11621       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11622         // The capture logic needs the destructor, so make sure we mark it.
11623         // Usually this is unnecessary because most local variables have
11624         // their destructors marked at declaration time, but parameters are
11625         // an exception because it's technically only the call site that
11626         // actually requires the destructor.
11627         if (isa<ParmVarDecl>(Var))
11628           S.FinalizeVarWithDestructor(Var, Record);
11629 
11630         // Enter a new evaluation context to insulate the copy
11631         // full-expression.
11632         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
11633 
11634         // According to the blocks spec, the capture of a variable from
11635         // the stack requires a const copy constructor.  This is not true
11636         // of the copy/move done to move a __block variable to the heap.
11637         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
11638                                                   DeclRefType.withConst(),
11639                                                   VK_LValue, Loc);
11640 
11641         ExprResult Result
11642           = S.PerformCopyInitialization(
11643               InitializedEntity::InitializeBlock(Var->getLocation(),
11644                                                   CaptureType, false),
11645               Loc, S.Owned(DeclRef));
11646 
11647         // Build a full-expression copy expression if initialization
11648         // succeeded and used a non-trivial constructor.  Recover from
11649         // errors by pretending that the copy isn't necessary.
11650         if (!Result.isInvalid() &&
11651             !cast<CXXConstructExpr>(Result.get())->getConstructor()
11652                 ->isTrivial()) {
11653           Result = S.MaybeCreateExprWithCleanups(Result);
11654           CopyExpr = Result.take();
11655         }
11656       }
11657     }
11658   }
11659 
11660   // Actually capture the variable.
11661   if (BuildAndDiagnose)
11662     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11663                     SourceLocation(), CaptureType, CopyExpr);
11664 
11665   return true;
11666 
11667 }
11668 
11669 
11670 /// \brief Capture the given variable in the captured region.
11671 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
11672                                     VarDecl *Var,
11673                                     SourceLocation Loc,
11674                                     const bool BuildAndDiagnose,
11675                                     QualType &CaptureType,
11676                                     QualType &DeclRefType,
11677                                     const bool RefersToEnclosingLocal,
11678                                     Sema &S) {
11679 
11680   // By default, capture variables by reference.
11681   bool ByRef = true;
11682   // Using an LValue reference type is consistent with Lambdas (see below).
11683   CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11684   Expr *CopyExpr = 0;
11685   if (BuildAndDiagnose) {
11686     // The current implementation assumes that all variables are captured
11687     // by references. Since there is no capture by copy, no expression evaluation
11688     // will be needed.
11689     //
11690     RecordDecl *RD = RSI->TheRecordDecl;
11691 
11692     FieldDecl *Field
11693       = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, CaptureType,
11694                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
11695                           0, false, ICIS_NoInit);
11696     Field->setImplicit(true);
11697     Field->setAccess(AS_private);
11698     RD->addDecl(Field);
11699 
11700     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11701                                             DeclRefType, VK_LValue, Loc);
11702     Var->setReferenced(true);
11703     Var->markUsed(S.Context);
11704   }
11705 
11706   // Actually capture the variable.
11707   if (BuildAndDiagnose)
11708     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc,
11709                     SourceLocation(), CaptureType, CopyExpr);
11710 
11711 
11712   return true;
11713 }
11714 
11715 /// \brief Create a field within the lambda class for the variable
11716 ///  being captured.  Handle Array captures.
11717 static ExprResult addAsFieldToClosureType(Sema &S,
11718                                  LambdaScopeInfo *LSI,
11719                                   VarDecl *Var, QualType FieldType,
11720                                   QualType DeclRefType,
11721                                   SourceLocation Loc,
11722                                   bool RefersToEnclosingLocal) {
11723   CXXRecordDecl *Lambda = LSI->Lambda;
11724 
11725   // Build the non-static data member.
11726   FieldDecl *Field
11727     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
11728                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
11729                         0, false, ICIS_NoInit);
11730   Field->setImplicit(true);
11731   Field->setAccess(AS_private);
11732   Lambda->addDecl(Field);
11733 
11734   // C++11 [expr.prim.lambda]p21:
11735   //   When the lambda-expression is evaluated, the entities that
11736   //   are captured by copy are used to direct-initialize each
11737   //   corresponding non-static data member of the resulting closure
11738   //   object. (For array members, the array elements are
11739   //   direct-initialized in increasing subscript order.) These
11740   //   initializations are performed in the (unspecified) order in
11741   //   which the non-static data members are declared.
11742 
11743   // Introduce a new evaluation context for the initialization, so
11744   // that temporaries introduced as part of the capture are retained
11745   // to be re-"exported" from the lambda expression itself.
11746   EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
11747 
11748   // C++ [expr.prim.labda]p12:
11749   //   An entity captured by a lambda-expression is odr-used (3.2) in
11750   //   the scope containing the lambda-expression.
11751   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11752                                           DeclRefType, VK_LValue, Loc);
11753   Var->setReferenced(true);
11754   Var->markUsed(S.Context);
11755 
11756   // When the field has array type, create index variables for each
11757   // dimension of the array. We use these index variables to subscript
11758   // the source array, and other clients (e.g., CodeGen) will perform
11759   // the necessary iteration with these index variables.
11760   SmallVector<VarDecl *, 4> IndexVariables;
11761   QualType BaseType = FieldType;
11762   QualType SizeType = S.Context.getSizeType();
11763   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
11764   while (const ConstantArrayType *Array
11765                         = S.Context.getAsConstantArrayType(BaseType)) {
11766     // Create the iteration variable for this array index.
11767     IdentifierInfo *IterationVarName = 0;
11768     {
11769       SmallString<8> Str;
11770       llvm::raw_svector_ostream OS(Str);
11771       OS << "__i" << IndexVariables.size();
11772       IterationVarName = &S.Context.Idents.get(OS.str());
11773     }
11774     VarDecl *IterationVar
11775       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11776                         IterationVarName, SizeType,
11777                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11778                         SC_None);
11779     IndexVariables.push_back(IterationVar);
11780     LSI->ArrayIndexVars.push_back(IterationVar);
11781 
11782     // Create a reference to the iteration variable.
11783     ExprResult IterationVarRef
11784       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
11785     assert(!IterationVarRef.isInvalid() &&
11786            "Reference to invented variable cannot fail!");
11787     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
11788     assert(!IterationVarRef.isInvalid() &&
11789            "Conversion of invented variable cannot fail!");
11790 
11791     // Subscript the array with this iteration variable.
11792     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
11793                              Ref, Loc, IterationVarRef.take(), Loc);
11794     if (Subscript.isInvalid()) {
11795       S.CleanupVarDeclMarking();
11796       S.DiscardCleanupsInEvaluationContext();
11797       return ExprError();
11798     }
11799 
11800     Ref = Subscript.take();
11801     BaseType = Array->getElementType();
11802   }
11803 
11804   // Construct the entity that we will be initializing. For an array, this
11805   // will be first element in the array, which may require several levels
11806   // of array-subscript entities.
11807   SmallVector<InitializedEntity, 4> Entities;
11808   Entities.reserve(1 + IndexVariables.size());
11809   Entities.push_back(
11810     InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(),
11811         Field->getType(), Loc));
11812   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
11813     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
11814                                                             0,
11815                                                             Entities.back()));
11816 
11817   InitializationKind InitKind
11818     = InitializationKind::CreateDirect(Loc, Loc, Loc);
11819   InitializationSequence Init(S, Entities.back(), InitKind, Ref);
11820   ExprResult Result(true);
11821   if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
11822     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
11823 
11824   // If this initialization requires any cleanups (e.g., due to a
11825   // default argument to a copy constructor), note that for the
11826   // lambda.
11827   if (S.ExprNeedsCleanups)
11828     LSI->ExprNeedsCleanups = true;
11829 
11830   // Exit the expression evaluation context used for the capture.
11831   S.CleanupVarDeclMarking();
11832   S.DiscardCleanupsInEvaluationContext();
11833   return Result;
11834 }
11835 
11836 
11837 
11838 /// \brief Capture the given variable in the lambda.
11839 static bool captureInLambda(LambdaScopeInfo *LSI,
11840                             VarDecl *Var,
11841                             SourceLocation Loc,
11842                             const bool BuildAndDiagnose,
11843                             QualType &CaptureType,
11844                             QualType &DeclRefType,
11845                             const bool RefersToEnclosingLocal,
11846                             const Sema::TryCaptureKind Kind,
11847                             SourceLocation EllipsisLoc,
11848                             const bool IsTopScope,
11849                             Sema &S) {
11850 
11851   // Determine whether we are capturing by reference or by value.
11852   bool ByRef = false;
11853   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
11854     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
11855   } else {
11856     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
11857   }
11858 
11859   // Compute the type of the field that will capture this variable.
11860   if (ByRef) {
11861     // C++11 [expr.prim.lambda]p15:
11862     //   An entity is captured by reference if it is implicitly or
11863     //   explicitly captured but not captured by copy. It is
11864     //   unspecified whether additional unnamed non-static data
11865     //   members are declared in the closure type for entities
11866     //   captured by reference.
11867     //
11868     // FIXME: It is not clear whether we want to build an lvalue reference
11869     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
11870     // to do the former, while EDG does the latter. Core issue 1249 will
11871     // clarify, but for now we follow GCC because it's a more permissive and
11872     // easily defensible position.
11873     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11874   } else {
11875     // C++11 [expr.prim.lambda]p14:
11876     //   For each entity captured by copy, an unnamed non-static
11877     //   data member is declared in the closure type. The
11878     //   declaration order of these members is unspecified. The type
11879     //   of such a data member is the type of the corresponding
11880     //   captured entity if the entity is not a reference to an
11881     //   object, or the referenced type otherwise. [Note: If the
11882     //   captured entity is a reference to a function, the
11883     //   corresponding data member is also a reference to a
11884     //   function. - end note ]
11885     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
11886       if (!RefType->getPointeeType()->isFunctionType())
11887         CaptureType = RefType->getPointeeType();
11888     }
11889 
11890     // Forbid the lambda copy-capture of autoreleasing variables.
11891     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11892       if (BuildAndDiagnose) {
11893         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
11894         S.Diag(Var->getLocation(), diag::note_previous_decl)
11895           << Var->getDeclName();
11896       }
11897       return false;
11898     }
11899 
11900     // Make sure that by-copy captures are of a complete and non-abstract type.
11901     if (BuildAndDiagnose) {
11902       if (!CaptureType->isDependentType() &&
11903           S.RequireCompleteType(Loc, CaptureType,
11904                                 diag::err_capture_of_incomplete_type,
11905                                 Var->getDeclName()))
11906         return false;
11907 
11908       if (S.RequireNonAbstractType(Loc, CaptureType,
11909                                    diag::err_capture_of_abstract_type))
11910         return false;
11911     }
11912   }
11913 
11914   // Capture this variable in the lambda.
11915   Expr *CopyExpr = 0;
11916   if (BuildAndDiagnose) {
11917     ExprResult Result = addAsFieldToClosureType(S, LSI, Var,
11918                                         CaptureType, DeclRefType, Loc,
11919                                         RefersToEnclosingLocal);
11920     if (!Result.isInvalid())
11921       CopyExpr = Result.take();
11922   }
11923 
11924   // Compute the type of a reference to this captured variable.
11925   if (ByRef)
11926     DeclRefType = CaptureType.getNonReferenceType();
11927   else {
11928     // C++ [expr.prim.lambda]p5:
11929     //   The closure type for a lambda-expression has a public inline
11930     //   function call operator [...]. This function call operator is
11931     //   declared const (9.3.1) if and only if the lambda-expression’s
11932     //   parameter-declaration-clause is not followed by mutable.
11933     DeclRefType = CaptureType.getNonReferenceType();
11934     if (!LSI->Mutable && !CaptureType->isReferenceType())
11935       DeclRefType.addConst();
11936   }
11937 
11938   // Add the capture.
11939   if (BuildAndDiagnose)
11940     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal,
11941                     Loc, EllipsisLoc, CaptureType, CopyExpr);
11942 
11943   return true;
11944 }
11945 
11946 
11947 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc,
11948                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
11949                               bool BuildAndDiagnose,
11950                               QualType &CaptureType,
11951                               QualType &DeclRefType,
11952 						                const unsigned *const FunctionScopeIndexToStopAt) {
11953   bool Nested = false;
11954 
11955   DeclContext *DC = CurContext;
11956   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
11957       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
11958   // We need to sync up the Declaration Context with the
11959   // FunctionScopeIndexToStopAt
11960   if (FunctionScopeIndexToStopAt) {
11961     unsigned FSIndex = FunctionScopes.size() - 1;
11962     while (FSIndex != MaxFunctionScopesIndex) {
11963       DC = getLambdaAwareParentOfDeclContext(DC);
11964       --FSIndex;
11965     }
11966   }
11967 
11968 
11969   // If the variable is declared in the current context (and is not an
11970   // init-capture), there is no need to capture it.
11971   if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true;
11972   if (!Var->hasLocalStorage()) return true;
11973 
11974   // Walk up the stack to determine whether we can capture the variable,
11975   // performing the "simple" checks that don't depend on type. We stop when
11976   // we've either hit the declared scope of the variable or find an existing
11977   // capture of that variable.  We start from the innermost capturing-entity
11978   // (the DC) and ensure that all intervening capturing-entities
11979   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
11980   // declcontext can either capture the variable or have already captured
11981   // the variable.
11982   CaptureType = Var->getType();
11983   DeclRefType = CaptureType.getNonReferenceType();
11984   bool Explicit = (Kind != TryCapture_Implicit);
11985   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
11986   do {
11987     // Only block literals, captured statements, and lambda expressions can
11988     // capture; other scopes don't work.
11989     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
11990                                                               ExprLoc,
11991                                                               BuildAndDiagnose,
11992                                                               *this);
11993     if (!ParentDC) return true;
11994 
11995     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
11996     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
11997 
11998 
11999     // Check whether we've already captured it.
12000     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
12001                                              DeclRefType))
12002       break;
12003     // If we are instantiating a generic lambda call operator body,
12004     // we do not want to capture new variables.  What was captured
12005     // during either a lambdas transformation or initial parsing
12006     // should be used.
12007     if (isGenericLambdaCallOperatorSpecialization(DC)) {
12008       if (BuildAndDiagnose) {
12009         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12010         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
12011           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12012           Diag(Var->getLocation(), diag::note_previous_decl)
12013              << Var->getDeclName();
12014           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
12015         } else
12016           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
12017       }
12018       return true;
12019     }
12020     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
12021     // certain types of variables (unnamed, variably modified types etc.)
12022     // so check for eligibility.
12023     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
12024        return true;
12025 
12026     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
12027       // No capture-default, and this is not an explicit capture
12028       // so cannot capture this variable.
12029       if (BuildAndDiagnose) {
12030         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12031         Diag(Var->getLocation(), diag::note_previous_decl)
12032           << Var->getDeclName();
12033         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
12034              diag::note_lambda_decl);
12035         // FIXME: If we error out because an outer lambda can not implicitly
12036         // capture a variable that an inner lambda explicitly captures, we
12037         // should have the inner lambda do the explicit capture - because
12038         // it makes for cleaner diagnostics later.  This would purely be done
12039         // so that the diagnostic does not misleadingly claim that a variable
12040         // can not be captured by a lambda implicitly even though it is captured
12041         // explicitly.  Suggestion:
12042         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
12043         //    at the function head
12044         //  - cache the StartingDeclContext - this must be a lambda
12045         //  - captureInLambda in the innermost lambda the variable.
12046       }
12047       return true;
12048     }
12049 
12050     FunctionScopesIndex--;
12051     DC = ParentDC;
12052     Explicit = false;
12053   } while (!Var->getDeclContext()->Equals(DC));
12054 
12055   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
12056   // computing the type of the capture at each step, checking type-specific
12057   // requirements, and adding captures if requested.
12058   // If the variable had already been captured previously, we start capturing
12059   // at the lambda nested within that one.
12060   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
12061        ++I) {
12062     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
12063 
12064     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
12065       if (!captureInBlock(BSI, Var, ExprLoc,
12066                           BuildAndDiagnose, CaptureType,
12067                           DeclRefType, Nested, *this))
12068         return true;
12069       Nested = true;
12070     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
12071       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
12072                                    BuildAndDiagnose, CaptureType,
12073                                    DeclRefType, Nested, *this))
12074         return true;
12075       Nested = true;
12076     } else {
12077       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12078       if (!captureInLambda(LSI, Var, ExprLoc,
12079                            BuildAndDiagnose, CaptureType,
12080                            DeclRefType, Nested, Kind, EllipsisLoc,
12081                             /*IsTopScope*/I == N - 1, *this))
12082         return true;
12083       Nested = true;
12084     }
12085   }
12086   return false;
12087 }
12088 
12089 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
12090                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
12091   QualType CaptureType;
12092   QualType DeclRefType;
12093   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
12094                             /*BuildAndDiagnose=*/true, CaptureType,
12095                             DeclRefType, 0);
12096 }
12097 
12098 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
12099   QualType CaptureType;
12100   QualType DeclRefType;
12101 
12102   // Determine whether we can capture this variable.
12103   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
12104                          /*BuildAndDiagnose=*/false, CaptureType,
12105                          DeclRefType, 0))
12106     return QualType();
12107 
12108   return DeclRefType;
12109 }
12110 
12111 
12112 
12113 // If either the type of the variable or the initializer is dependent,
12114 // return false. Otherwise, determine whether the variable is a constant
12115 // expression. Use this if you need to know if a variable that might or
12116 // might not be dependent is truly a constant expression.
12117 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
12118     ASTContext &Context) {
12119 
12120   if (Var->getType()->isDependentType())
12121     return false;
12122   const VarDecl *DefVD = 0;
12123   Var->getAnyInitializer(DefVD);
12124   if (!DefVD)
12125     return false;
12126   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
12127   Expr *Init = cast<Expr>(Eval->Value);
12128   if (Init->isValueDependent())
12129     return false;
12130   return IsVariableAConstantExpression(Var, Context);
12131 }
12132 
12133 
12134 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
12135   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
12136   // an object that satisfies the requirements for appearing in a
12137   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
12138   // is immediately applied."  This function handles the lvalue-to-rvalue
12139   // conversion part.
12140   MaybeODRUseExprs.erase(E->IgnoreParens());
12141 
12142   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
12143   // to a variable that is a constant expression, and if so, identify it as
12144   // a reference to a variable that does not involve an odr-use of that
12145   // variable.
12146   if (LambdaScopeInfo *LSI = getCurLambda()) {
12147     Expr *SansParensExpr = E->IgnoreParens();
12148     VarDecl *Var = 0;
12149     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
12150       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
12151     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
12152       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
12153 
12154     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
12155       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
12156   }
12157 }
12158 
12159 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
12160   if (!Res.isUsable())
12161     return Res;
12162 
12163   // If a constant-expression is a reference to a variable where we delay
12164   // deciding whether it is an odr-use, just assume we will apply the
12165   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
12166   // (a non-type template argument), we have special handling anyway.
12167   UpdateMarkingForLValueToRValue(Res.get());
12168   return Res;
12169 }
12170 
12171 void Sema::CleanupVarDeclMarking() {
12172   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
12173                                         e = MaybeODRUseExprs.end();
12174        i != e; ++i) {
12175     VarDecl *Var;
12176     SourceLocation Loc;
12177     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
12178       Var = cast<VarDecl>(DRE->getDecl());
12179       Loc = DRE->getLocation();
12180     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
12181       Var = cast<VarDecl>(ME->getMemberDecl());
12182       Loc = ME->getMemberLoc();
12183     } else {
12184       llvm_unreachable("Unexpcted expression");
12185     }
12186 
12187     MarkVarDeclODRUsed(Var, Loc, *this, /*MaxFunctionScopeIndex Pointer*/ 0);
12188   }
12189 
12190   MaybeODRUseExprs.clear();
12191 }
12192 
12193 
12194 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
12195                                     VarDecl *Var, Expr *E) {
12196   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
12197          "Invalid Expr argument to DoMarkVarDeclReferenced");
12198   Var->setReferenced();
12199 
12200   // If the context is not potentially evaluated, this is not an odr-use and
12201   // does not trigger instantiation.
12202   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
12203     if (SemaRef.isUnevaluatedContext())
12204       return;
12205 
12206     // If we don't yet know whether this context is going to end up being an
12207     // evaluated context, and we're referencing a variable from an enclosing
12208     // scope, add a potential capture.
12209     //
12210     // FIXME: Is this necessary? These contexts are only used for default
12211     // arguments, where local variables can't be used.
12212     const bool RefersToEnclosingScope =
12213         (SemaRef.CurContext != Var->getDeclContext() &&
12214          Var->getDeclContext()->isFunctionOrMethod() &&
12215          Var->hasLocalStorage());
12216     if (!RefersToEnclosingScope)
12217       return;
12218 
12219     if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
12220       // If a variable could potentially be odr-used, defer marking it so
12221       // until we finish analyzing the full expression for any lvalue-to-rvalue
12222       // or discarded value conversions that would obviate odr-use.
12223       // Add it to the list of potential captures that will be analyzed
12224       // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
12225       // unless the variable is a reference that was initialized by a constant
12226       // expression (this will never need to be captured or odr-used).
12227       assert(E && "Capture variable should be used in an expression.");
12228       if (!Var->getType()->isReferenceType() ||
12229           !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
12230         LSI->addPotentialCapture(E->IgnoreParens());
12231     }
12232     return;
12233   }
12234 
12235   VarTemplateSpecializationDecl *VarSpec =
12236       dyn_cast<VarTemplateSpecializationDecl>(Var);
12237   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
12238          "Can't instantiate a partial template specialization.");
12239 
12240   // Perform implicit instantiation of static data members, static data member
12241   // templates of class templates, and variable template specializations. Delay
12242   // instantiations of variable templates, except for those that could be used
12243   // in a constant expression.
12244   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
12245   if (isTemplateInstantiation(TSK)) {
12246     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
12247 
12248     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
12249       if (Var->getPointOfInstantiation().isInvalid()) {
12250         // This is a modification of an existing AST node. Notify listeners.
12251         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
12252           L->StaticDataMemberInstantiated(Var);
12253       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
12254         // Don't bother trying to instantiate it again, unless we might need
12255         // its initializer before we get to the end of the TU.
12256         TryInstantiating = false;
12257     }
12258 
12259     if (Var->getPointOfInstantiation().isInvalid())
12260       Var->setTemplateSpecializationKind(TSK, Loc);
12261 
12262     if (TryInstantiating) {
12263       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
12264       bool InstantiationDependent = false;
12265       bool IsNonDependent =
12266           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
12267                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
12268                   : true;
12269 
12270       // Do not instantiate specializations that are still type-dependent.
12271       if (IsNonDependent) {
12272         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
12273           // Do not defer instantiations of variables which could be used in a
12274           // constant expression.
12275           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
12276         } else {
12277           SemaRef.PendingInstantiations
12278               .push_back(std::make_pair(Var, PointOfInstantiation));
12279         }
12280       }
12281     }
12282   }
12283 
12284   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
12285   // the requirements for appearing in a constant expression (5.19) and, if
12286   // it is an object, the lvalue-to-rvalue conversion (4.1)
12287   // is immediately applied."  We check the first part here, and
12288   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
12289   // Note that we use the C++11 definition everywhere because nothing in
12290   // C++03 depends on whether we get the C++03 version correct. The second
12291   // part does not apply to references, since they are not objects.
12292   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
12293     // A reference initialized by a constant expression can never be
12294     // odr-used, so simply ignore it.
12295     if (!Var->getType()->isReferenceType())
12296       SemaRef.MaybeODRUseExprs.insert(E);
12297   } else
12298     MarkVarDeclODRUsed(Var, Loc, SemaRef, /*MaxFunctionScopeIndex ptr*/0);
12299 }
12300 
12301 /// \brief Mark a variable referenced, and check whether it is odr-used
12302 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
12303 /// used directly for normal expressions referring to VarDecl.
12304 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
12305   DoMarkVarDeclReferenced(*this, Loc, Var, 0);
12306 }
12307 
12308 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
12309                                Decl *D, Expr *E, bool OdrUse) {
12310   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
12311     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
12312     return;
12313   }
12314 
12315   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
12316 
12317   // If this is a call to a method via a cast, also mark the method in the
12318   // derived class used in case codegen can devirtualize the call.
12319   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12320   if (!ME)
12321     return;
12322   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
12323   if (!MD)
12324     return;
12325   const Expr *Base = ME->getBase();
12326   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
12327   if (!MostDerivedClassDecl)
12328     return;
12329   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
12330   if (!DM || DM->isPure())
12331     return;
12332   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
12333 }
12334 
12335 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
12336 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
12337   // TODO: update this with DR# once a defect report is filed.
12338   // C++11 defect. The address of a pure member should not be an ODR use, even
12339   // if it's a qualified reference.
12340   bool OdrUse = true;
12341   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
12342     if (Method->isVirtual())
12343       OdrUse = false;
12344   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
12345 }
12346 
12347 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
12348 void Sema::MarkMemberReferenced(MemberExpr *E) {
12349   // C++11 [basic.def.odr]p2:
12350   //   A non-overloaded function whose name appears as a potentially-evaluated
12351   //   expression or a member of a set of candidate functions, if selected by
12352   //   overload resolution when referred to from a potentially-evaluated
12353   //   expression, is odr-used, unless it is a pure virtual function and its
12354   //   name is not explicitly qualified.
12355   bool OdrUse = true;
12356   if (!E->hasQualifier()) {
12357     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
12358       if (Method->isPure())
12359         OdrUse = false;
12360   }
12361   SourceLocation Loc = E->getMemberLoc().isValid() ?
12362                             E->getMemberLoc() : E->getLocStart();
12363   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
12364 }
12365 
12366 /// \brief Perform marking for a reference to an arbitrary declaration.  It
12367 /// marks the declaration referenced, and performs odr-use checking for functions
12368 /// and variables. This method should not be used when building an normal
12369 /// expression which refers to a variable.
12370 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
12371   if (OdrUse) {
12372     if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12373       MarkVariableReferenced(Loc, VD);
12374       return;
12375     }
12376     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
12377       MarkFunctionReferenced(Loc, FD);
12378       return;
12379     }
12380   }
12381   D->setReferenced();
12382 }
12383 
12384 namespace {
12385   // Mark all of the declarations referenced
12386   // FIXME: Not fully implemented yet! We need to have a better understanding
12387   // of when we're entering
12388   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
12389     Sema &S;
12390     SourceLocation Loc;
12391 
12392   public:
12393     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
12394 
12395     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
12396 
12397     bool TraverseTemplateArgument(const TemplateArgument &Arg);
12398     bool TraverseRecordType(RecordType *T);
12399   };
12400 }
12401 
12402 bool MarkReferencedDecls::TraverseTemplateArgument(
12403   const TemplateArgument &Arg) {
12404   if (Arg.getKind() == TemplateArgument::Declaration) {
12405     if (Decl *D = Arg.getAsDecl())
12406       S.MarkAnyDeclReferenced(Loc, D, true);
12407   }
12408 
12409   return Inherited::TraverseTemplateArgument(Arg);
12410 }
12411 
12412 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
12413   if (ClassTemplateSpecializationDecl *Spec
12414                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
12415     const TemplateArgumentList &Args = Spec->getTemplateArgs();
12416     return TraverseTemplateArguments(Args.data(), Args.size());
12417   }
12418 
12419   return true;
12420 }
12421 
12422 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
12423   MarkReferencedDecls Marker(*this, Loc);
12424   Marker.TraverseType(Context.getCanonicalType(T));
12425 }
12426 
12427 namespace {
12428   /// \brief Helper class that marks all of the declarations referenced by
12429   /// potentially-evaluated subexpressions as "referenced".
12430   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
12431     Sema &S;
12432     bool SkipLocalVariables;
12433 
12434   public:
12435     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
12436 
12437     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
12438       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
12439 
12440     void VisitDeclRefExpr(DeclRefExpr *E) {
12441       // If we were asked not to visit local variables, don't.
12442       if (SkipLocalVariables) {
12443         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
12444           if (VD->hasLocalStorage())
12445             return;
12446       }
12447 
12448       S.MarkDeclRefReferenced(E);
12449     }
12450 
12451     void VisitMemberExpr(MemberExpr *E) {
12452       S.MarkMemberReferenced(E);
12453       Inherited::VisitMemberExpr(E);
12454     }
12455 
12456     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12457       S.MarkFunctionReferenced(E->getLocStart(),
12458             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
12459       Visit(E->getSubExpr());
12460     }
12461 
12462     void VisitCXXNewExpr(CXXNewExpr *E) {
12463       if (E->getOperatorNew())
12464         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
12465       if (E->getOperatorDelete())
12466         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12467       Inherited::VisitCXXNewExpr(E);
12468     }
12469 
12470     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
12471       if (E->getOperatorDelete())
12472         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12473       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
12474       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12475         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12476         S.MarkFunctionReferenced(E->getLocStart(),
12477                                     S.LookupDestructor(Record));
12478       }
12479 
12480       Inherited::VisitCXXDeleteExpr(E);
12481     }
12482 
12483     void VisitCXXConstructExpr(CXXConstructExpr *E) {
12484       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
12485       Inherited::VisitCXXConstructExpr(E);
12486     }
12487 
12488     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12489       Visit(E->getExpr());
12490     }
12491 
12492     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12493       Inherited::VisitImplicitCastExpr(E);
12494 
12495       if (E->getCastKind() == CK_LValueToRValue)
12496         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
12497     }
12498   };
12499 }
12500 
12501 /// \brief Mark any declarations that appear within this expression or any
12502 /// potentially-evaluated subexpressions as "referenced".
12503 ///
12504 /// \param SkipLocalVariables If true, don't mark local variables as
12505 /// 'referenced'.
12506 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
12507                                             bool SkipLocalVariables) {
12508   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
12509 }
12510 
12511 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
12512 /// of the program being compiled.
12513 ///
12514 /// This routine emits the given diagnostic when the code currently being
12515 /// type-checked is "potentially evaluated", meaning that there is a
12516 /// possibility that the code will actually be executable. Code in sizeof()
12517 /// expressions, code used only during overload resolution, etc., are not
12518 /// potentially evaluated. This routine will suppress such diagnostics or,
12519 /// in the absolutely nutty case of potentially potentially evaluated
12520 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
12521 /// later.
12522 ///
12523 /// This routine should be used for all diagnostics that describe the run-time
12524 /// behavior of a program, such as passing a non-POD value through an ellipsis.
12525 /// Failure to do so will likely result in spurious diagnostics or failures
12526 /// during overload resolution or within sizeof/alignof/typeof/typeid.
12527 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
12528                                const PartialDiagnostic &PD) {
12529   switch (ExprEvalContexts.back().Context) {
12530   case Unevaluated:
12531   case UnevaluatedAbstract:
12532     // The argument will never be evaluated, so don't complain.
12533     break;
12534 
12535   case ConstantEvaluated:
12536     // Relevant diagnostics should be produced by constant evaluation.
12537     break;
12538 
12539   case PotentiallyEvaluated:
12540   case PotentiallyEvaluatedIfUsed:
12541     if (Statement && getCurFunctionOrMethodDecl()) {
12542       FunctionScopes.back()->PossiblyUnreachableDiags.
12543         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
12544     }
12545     else
12546       Diag(Loc, PD);
12547 
12548     return true;
12549   }
12550 
12551   return false;
12552 }
12553 
12554 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
12555                                CallExpr *CE, FunctionDecl *FD) {
12556   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
12557     return false;
12558 
12559   // If we're inside a decltype's expression, don't check for a valid return
12560   // type or construct temporaries until we know whether this is the last call.
12561   if (ExprEvalContexts.back().IsDecltype) {
12562     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
12563     return false;
12564   }
12565 
12566   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
12567     FunctionDecl *FD;
12568     CallExpr *CE;
12569 
12570   public:
12571     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
12572       : FD(FD), CE(CE) { }
12573 
12574     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
12575       if (!FD) {
12576         S.Diag(Loc, diag::err_call_incomplete_return)
12577           << T << CE->getSourceRange();
12578         return;
12579       }
12580 
12581       S.Diag(Loc, diag::err_call_function_incomplete_return)
12582         << CE->getSourceRange() << FD->getDeclName() << T;
12583       S.Diag(FD->getLocation(),
12584              diag::note_function_with_incomplete_return_type_declared_here)
12585         << FD->getDeclName();
12586     }
12587   } Diagnoser(FD, CE);
12588 
12589   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
12590     return true;
12591 
12592   return false;
12593 }
12594 
12595 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
12596 // will prevent this condition from triggering, which is what we want.
12597 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
12598   SourceLocation Loc;
12599 
12600   unsigned diagnostic = diag::warn_condition_is_assignment;
12601   bool IsOrAssign = false;
12602 
12603   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
12604     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
12605       return;
12606 
12607     IsOrAssign = Op->getOpcode() == BO_OrAssign;
12608 
12609     // Greylist some idioms by putting them into a warning subcategory.
12610     if (ObjCMessageExpr *ME
12611           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
12612       Selector Sel = ME->getSelector();
12613 
12614       // self = [<foo> init...]
12615       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
12616         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12617 
12618       // <foo> = [<bar> nextObject]
12619       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
12620         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12621     }
12622 
12623     Loc = Op->getOperatorLoc();
12624   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
12625     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
12626       return;
12627 
12628     IsOrAssign = Op->getOperator() == OO_PipeEqual;
12629     Loc = Op->getOperatorLoc();
12630   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
12631     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
12632   else {
12633     // Not an assignment.
12634     return;
12635   }
12636 
12637   Diag(Loc, diagnostic) << E->getSourceRange();
12638 
12639   SourceLocation Open = E->getLocStart();
12640   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
12641   Diag(Loc, diag::note_condition_assign_silence)
12642         << FixItHint::CreateInsertion(Open, "(")
12643         << FixItHint::CreateInsertion(Close, ")");
12644 
12645   if (IsOrAssign)
12646     Diag(Loc, diag::note_condition_or_assign_to_comparison)
12647       << FixItHint::CreateReplacement(Loc, "!=");
12648   else
12649     Diag(Loc, diag::note_condition_assign_to_comparison)
12650       << FixItHint::CreateReplacement(Loc, "==");
12651 }
12652 
12653 /// \brief Redundant parentheses over an equality comparison can indicate
12654 /// that the user intended an assignment used as condition.
12655 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
12656   // Don't warn if the parens came from a macro.
12657   SourceLocation parenLoc = ParenE->getLocStart();
12658   if (parenLoc.isInvalid() || parenLoc.isMacroID())
12659     return;
12660   // Don't warn for dependent expressions.
12661   if (ParenE->isTypeDependent())
12662     return;
12663 
12664   Expr *E = ParenE->IgnoreParens();
12665 
12666   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
12667     if (opE->getOpcode() == BO_EQ &&
12668         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
12669                                                            == Expr::MLV_Valid) {
12670       SourceLocation Loc = opE->getOperatorLoc();
12671 
12672       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
12673       SourceRange ParenERange = ParenE->getSourceRange();
12674       Diag(Loc, diag::note_equality_comparison_silence)
12675         << FixItHint::CreateRemoval(ParenERange.getBegin())
12676         << FixItHint::CreateRemoval(ParenERange.getEnd());
12677       Diag(Loc, diag::note_equality_comparison_to_assign)
12678         << FixItHint::CreateReplacement(Loc, "=");
12679     }
12680 }
12681 
12682 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
12683   DiagnoseAssignmentAsCondition(E);
12684   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
12685     DiagnoseEqualityWithExtraParens(parenE);
12686 
12687   ExprResult result = CheckPlaceholderExpr(E);
12688   if (result.isInvalid()) return ExprError();
12689   E = result.take();
12690 
12691   if (!E->isTypeDependent()) {
12692     if (getLangOpts().CPlusPlus)
12693       return CheckCXXBooleanCondition(E); // C++ 6.4p4
12694 
12695     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
12696     if (ERes.isInvalid())
12697       return ExprError();
12698     E = ERes.take();
12699 
12700     QualType T = E->getType();
12701     if (!T->isScalarType()) { // C99 6.8.4.1p1
12702       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
12703         << T << E->getSourceRange();
12704       return ExprError();
12705     }
12706   }
12707 
12708   return Owned(E);
12709 }
12710 
12711 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
12712                                        Expr *SubExpr) {
12713   if (!SubExpr)
12714     return ExprError();
12715 
12716   return CheckBooleanCondition(SubExpr, Loc);
12717 }
12718 
12719 namespace {
12720   /// A visitor for rebuilding a call to an __unknown_any expression
12721   /// to have an appropriate type.
12722   struct RebuildUnknownAnyFunction
12723     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
12724 
12725     Sema &S;
12726 
12727     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
12728 
12729     ExprResult VisitStmt(Stmt *S) {
12730       llvm_unreachable("unexpected statement!");
12731     }
12732 
12733     ExprResult VisitExpr(Expr *E) {
12734       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
12735         << E->getSourceRange();
12736       return ExprError();
12737     }
12738 
12739     /// Rebuild an expression which simply semantically wraps another
12740     /// expression which it shares the type and value kind of.
12741     template <class T> ExprResult rebuildSugarExpr(T *E) {
12742       ExprResult SubResult = Visit(E->getSubExpr());
12743       if (SubResult.isInvalid()) return ExprError();
12744 
12745       Expr *SubExpr = SubResult.take();
12746       E->setSubExpr(SubExpr);
12747       E->setType(SubExpr->getType());
12748       E->setValueKind(SubExpr->getValueKind());
12749       assert(E->getObjectKind() == OK_Ordinary);
12750       return E;
12751     }
12752 
12753     ExprResult VisitParenExpr(ParenExpr *E) {
12754       return rebuildSugarExpr(E);
12755     }
12756 
12757     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12758       return rebuildSugarExpr(E);
12759     }
12760 
12761     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12762       ExprResult SubResult = Visit(E->getSubExpr());
12763       if (SubResult.isInvalid()) return ExprError();
12764 
12765       Expr *SubExpr = SubResult.take();
12766       E->setSubExpr(SubExpr);
12767       E->setType(S.Context.getPointerType(SubExpr->getType()));
12768       assert(E->getValueKind() == VK_RValue);
12769       assert(E->getObjectKind() == OK_Ordinary);
12770       return E;
12771     }
12772 
12773     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
12774       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
12775 
12776       E->setType(VD->getType());
12777 
12778       assert(E->getValueKind() == VK_RValue);
12779       if (S.getLangOpts().CPlusPlus &&
12780           !(isa<CXXMethodDecl>(VD) &&
12781             cast<CXXMethodDecl>(VD)->isInstance()))
12782         E->setValueKind(VK_LValue);
12783 
12784       return E;
12785     }
12786 
12787     ExprResult VisitMemberExpr(MemberExpr *E) {
12788       return resolveDecl(E, E->getMemberDecl());
12789     }
12790 
12791     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12792       return resolveDecl(E, E->getDecl());
12793     }
12794   };
12795 }
12796 
12797 /// Given a function expression of unknown-any type, try to rebuild it
12798 /// to have a function type.
12799 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
12800   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
12801   if (Result.isInvalid()) return ExprError();
12802   return S.DefaultFunctionArrayConversion(Result.take());
12803 }
12804 
12805 namespace {
12806   /// A visitor for rebuilding an expression of type __unknown_anytype
12807   /// into one which resolves the type directly on the referring
12808   /// expression.  Strict preservation of the original source
12809   /// structure is not a goal.
12810   struct RebuildUnknownAnyExpr
12811     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
12812 
12813     Sema &S;
12814 
12815     /// The current destination type.
12816     QualType DestType;
12817 
12818     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
12819       : S(S), DestType(CastType) {}
12820 
12821     ExprResult VisitStmt(Stmt *S) {
12822       llvm_unreachable("unexpected statement!");
12823     }
12824 
12825     ExprResult VisitExpr(Expr *E) {
12826       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12827         << E->getSourceRange();
12828       return ExprError();
12829     }
12830 
12831     ExprResult VisitCallExpr(CallExpr *E);
12832     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
12833 
12834     /// Rebuild an expression which simply semantically wraps another
12835     /// expression which it shares the type and value kind of.
12836     template <class T> ExprResult rebuildSugarExpr(T *E) {
12837       ExprResult SubResult = Visit(E->getSubExpr());
12838       if (SubResult.isInvalid()) return ExprError();
12839       Expr *SubExpr = SubResult.take();
12840       E->setSubExpr(SubExpr);
12841       E->setType(SubExpr->getType());
12842       E->setValueKind(SubExpr->getValueKind());
12843       assert(E->getObjectKind() == OK_Ordinary);
12844       return E;
12845     }
12846 
12847     ExprResult VisitParenExpr(ParenExpr *E) {
12848       return rebuildSugarExpr(E);
12849     }
12850 
12851     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12852       return rebuildSugarExpr(E);
12853     }
12854 
12855     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12856       const PointerType *Ptr = DestType->getAs<PointerType>();
12857       if (!Ptr) {
12858         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
12859           << E->getSourceRange();
12860         return ExprError();
12861       }
12862       assert(E->getValueKind() == VK_RValue);
12863       assert(E->getObjectKind() == OK_Ordinary);
12864       E->setType(DestType);
12865 
12866       // Build the sub-expression as if it were an object of the pointee type.
12867       DestType = Ptr->getPointeeType();
12868       ExprResult SubResult = Visit(E->getSubExpr());
12869       if (SubResult.isInvalid()) return ExprError();
12870       E->setSubExpr(SubResult.take());
12871       return E;
12872     }
12873 
12874     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
12875 
12876     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
12877 
12878     ExprResult VisitMemberExpr(MemberExpr *E) {
12879       return resolveDecl(E, E->getMemberDecl());
12880     }
12881 
12882     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12883       return resolveDecl(E, E->getDecl());
12884     }
12885   };
12886 }
12887 
12888 /// Rebuilds a call expression which yielded __unknown_anytype.
12889 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
12890   Expr *CalleeExpr = E->getCallee();
12891 
12892   enum FnKind {
12893     FK_MemberFunction,
12894     FK_FunctionPointer,
12895     FK_BlockPointer
12896   };
12897 
12898   FnKind Kind;
12899   QualType CalleeType = CalleeExpr->getType();
12900   if (CalleeType == S.Context.BoundMemberTy) {
12901     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
12902     Kind = FK_MemberFunction;
12903     CalleeType = Expr::findBoundMemberType(CalleeExpr);
12904   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
12905     CalleeType = Ptr->getPointeeType();
12906     Kind = FK_FunctionPointer;
12907   } else {
12908     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
12909     Kind = FK_BlockPointer;
12910   }
12911   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
12912 
12913   // Verify that this is a legal result type of a function.
12914   if (DestType->isArrayType() || DestType->isFunctionType()) {
12915     unsigned diagID = diag::err_func_returning_array_function;
12916     if (Kind == FK_BlockPointer)
12917       diagID = diag::err_block_returning_array_function;
12918 
12919     S.Diag(E->getExprLoc(), diagID)
12920       << DestType->isFunctionType() << DestType;
12921     return ExprError();
12922   }
12923 
12924   // Otherwise, go ahead and set DestType as the call's result.
12925   E->setType(DestType.getNonLValueExprType(S.Context));
12926   E->setValueKind(Expr::getValueKindForType(DestType));
12927   assert(E->getObjectKind() == OK_Ordinary);
12928 
12929   // Rebuild the function type, replacing the result type with DestType.
12930   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
12931   if (Proto) {
12932     // __unknown_anytype(...) is a special case used by the debugger when
12933     // it has no idea what a function's signature is.
12934     //
12935     // We want to build this call essentially under the K&R
12936     // unprototyped rules, but making a FunctionNoProtoType in C++
12937     // would foul up all sorts of assumptions.  However, we cannot
12938     // simply pass all arguments as variadic arguments, nor can we
12939     // portably just call the function under a non-variadic type; see
12940     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
12941     // However, it turns out that in practice it is generally safe to
12942     // call a function declared as "A foo(B,C,D);" under the prototype
12943     // "A foo(B,C,D,...);".  The only known exception is with the
12944     // Windows ABI, where any variadic function is implicitly cdecl
12945     // regardless of its normal CC.  Therefore we change the parameter
12946     // types to match the types of the arguments.
12947     //
12948     // This is a hack, but it is far superior to moving the
12949     // corresponding target-specific code from IR-gen to Sema/AST.
12950 
12951     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
12952     SmallVector<QualType, 8> ArgTypes;
12953     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
12954       ArgTypes.reserve(E->getNumArgs());
12955       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
12956         Expr *Arg = E->getArg(i);
12957         QualType ArgType = Arg->getType();
12958         if (E->isLValue()) {
12959           ArgType = S.Context.getLValueReferenceType(ArgType);
12960         } else if (E->isXValue()) {
12961           ArgType = S.Context.getRValueReferenceType(ArgType);
12962         }
12963         ArgTypes.push_back(ArgType);
12964       }
12965       ParamTypes = ArgTypes;
12966     }
12967     DestType = S.Context.getFunctionType(DestType, ParamTypes,
12968                                          Proto->getExtProtoInfo());
12969   } else {
12970     DestType = S.Context.getFunctionNoProtoType(DestType,
12971                                                 FnType->getExtInfo());
12972   }
12973 
12974   // Rebuild the appropriate pointer-to-function type.
12975   switch (Kind) {
12976   case FK_MemberFunction:
12977     // Nothing to do.
12978     break;
12979 
12980   case FK_FunctionPointer:
12981     DestType = S.Context.getPointerType(DestType);
12982     break;
12983 
12984   case FK_BlockPointer:
12985     DestType = S.Context.getBlockPointerType(DestType);
12986     break;
12987   }
12988 
12989   // Finally, we can recurse.
12990   ExprResult CalleeResult = Visit(CalleeExpr);
12991   if (!CalleeResult.isUsable()) return ExprError();
12992   E->setCallee(CalleeResult.take());
12993 
12994   // Bind a temporary if necessary.
12995   return S.MaybeBindToTemporary(E);
12996 }
12997 
12998 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
12999   // Verify that this is a legal result type of a call.
13000   if (DestType->isArrayType() || DestType->isFunctionType()) {
13001     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
13002       << DestType->isFunctionType() << DestType;
13003     return ExprError();
13004   }
13005 
13006   // Rewrite the method result type if available.
13007   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
13008     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
13009     Method->setReturnType(DestType);
13010   }
13011 
13012   // Change the type of the message.
13013   E->setType(DestType.getNonReferenceType());
13014   E->setValueKind(Expr::getValueKindForType(DestType));
13015 
13016   return S.MaybeBindToTemporary(E);
13017 }
13018 
13019 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
13020   // The only case we should ever see here is a function-to-pointer decay.
13021   if (E->getCastKind() == CK_FunctionToPointerDecay) {
13022     assert(E->getValueKind() == VK_RValue);
13023     assert(E->getObjectKind() == OK_Ordinary);
13024 
13025     E->setType(DestType);
13026 
13027     // Rebuild the sub-expression as the pointee (function) type.
13028     DestType = DestType->castAs<PointerType>()->getPointeeType();
13029 
13030     ExprResult Result = Visit(E->getSubExpr());
13031     if (!Result.isUsable()) return ExprError();
13032 
13033     E->setSubExpr(Result.take());
13034     return S.Owned(E);
13035   } else if (E->getCastKind() == CK_LValueToRValue) {
13036     assert(E->getValueKind() == VK_RValue);
13037     assert(E->getObjectKind() == OK_Ordinary);
13038 
13039     assert(isa<BlockPointerType>(E->getType()));
13040 
13041     E->setType(DestType);
13042 
13043     // The sub-expression has to be a lvalue reference, so rebuild it as such.
13044     DestType = S.Context.getLValueReferenceType(DestType);
13045 
13046     ExprResult Result = Visit(E->getSubExpr());
13047     if (!Result.isUsable()) return ExprError();
13048 
13049     E->setSubExpr(Result.take());
13050     return S.Owned(E);
13051   } else {
13052     llvm_unreachable("Unhandled cast type!");
13053   }
13054 }
13055 
13056 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
13057   ExprValueKind ValueKind = VK_LValue;
13058   QualType Type = DestType;
13059 
13060   // We know how to make this work for certain kinds of decls:
13061 
13062   //  - functions
13063   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
13064     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
13065       DestType = Ptr->getPointeeType();
13066       ExprResult Result = resolveDecl(E, VD);
13067       if (Result.isInvalid()) return ExprError();
13068       return S.ImpCastExprToType(Result.take(), Type,
13069                                  CK_FunctionToPointerDecay, VK_RValue);
13070     }
13071 
13072     if (!Type->isFunctionType()) {
13073       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
13074         << VD << E->getSourceRange();
13075       return ExprError();
13076     }
13077 
13078     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
13079       if (MD->isInstance()) {
13080         ValueKind = VK_RValue;
13081         Type = S.Context.BoundMemberTy;
13082       }
13083 
13084     // Function references aren't l-values in C.
13085     if (!S.getLangOpts().CPlusPlus)
13086       ValueKind = VK_RValue;
13087 
13088   //  - variables
13089   } else if (isa<VarDecl>(VD)) {
13090     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
13091       Type = RefTy->getPointeeType();
13092     } else if (Type->isFunctionType()) {
13093       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
13094         << VD << E->getSourceRange();
13095       return ExprError();
13096     }
13097 
13098   //  - nothing else
13099   } else {
13100     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
13101       << VD << E->getSourceRange();
13102     return ExprError();
13103   }
13104 
13105   // Modifying the declaration like this is friendly to IR-gen but
13106   // also really dangerous.
13107   VD->setType(DestType);
13108   E->setType(Type);
13109   E->setValueKind(ValueKind);
13110   return S.Owned(E);
13111 }
13112 
13113 /// Check a cast of an unknown-any type.  We intentionally only
13114 /// trigger this for C-style casts.
13115 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
13116                                      Expr *CastExpr, CastKind &CastKind,
13117                                      ExprValueKind &VK, CXXCastPath &Path) {
13118   // Rewrite the casted expression from scratch.
13119   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
13120   if (!result.isUsable()) return ExprError();
13121 
13122   CastExpr = result.take();
13123   VK = CastExpr->getValueKind();
13124   CastKind = CK_NoOp;
13125 
13126   return CastExpr;
13127 }
13128 
13129 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
13130   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
13131 }
13132 
13133 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
13134                                     Expr *arg, QualType &paramType) {
13135   // If the syntactic form of the argument is not an explicit cast of
13136   // any sort, just do default argument promotion.
13137   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
13138   if (!castArg) {
13139     ExprResult result = DefaultArgumentPromotion(arg);
13140     if (result.isInvalid()) return ExprError();
13141     paramType = result.get()->getType();
13142     return result;
13143   }
13144 
13145   // Otherwise, use the type that was written in the explicit cast.
13146   assert(!arg->hasPlaceholderType());
13147   paramType = castArg->getTypeAsWritten();
13148 
13149   // Copy-initialize a parameter of that type.
13150   InitializedEntity entity =
13151     InitializedEntity::InitializeParameter(Context, paramType,
13152                                            /*consumed*/ false);
13153   return PerformCopyInitialization(entity, callLoc, Owned(arg));
13154 }
13155 
13156 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
13157   Expr *orig = E;
13158   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
13159   while (true) {
13160     E = E->IgnoreParenImpCasts();
13161     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
13162       E = call->getCallee();
13163       diagID = diag::err_uncasted_call_of_unknown_any;
13164     } else {
13165       break;
13166     }
13167   }
13168 
13169   SourceLocation loc;
13170   NamedDecl *d;
13171   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
13172     loc = ref->getLocation();
13173     d = ref->getDecl();
13174   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
13175     loc = mem->getMemberLoc();
13176     d = mem->getMemberDecl();
13177   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
13178     diagID = diag::err_uncasted_call_of_unknown_any;
13179     loc = msg->getSelectorStartLoc();
13180     d = msg->getMethodDecl();
13181     if (!d) {
13182       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
13183         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
13184         << orig->getSourceRange();
13185       return ExprError();
13186     }
13187   } else {
13188     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13189       << E->getSourceRange();
13190     return ExprError();
13191   }
13192 
13193   S.Diag(loc, diagID) << d << orig->getSourceRange();
13194 
13195   // Never recoverable.
13196   return ExprError();
13197 }
13198 
13199 /// Check for operands with placeholder types and complain if found.
13200 /// Returns true if there was an error and no recovery was possible.
13201 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
13202   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
13203   if (!placeholderType) return Owned(E);
13204 
13205   switch (placeholderType->getKind()) {
13206 
13207   // Overloaded expressions.
13208   case BuiltinType::Overload: {
13209     // Try to resolve a single function template specialization.
13210     // This is obligatory.
13211     ExprResult result = Owned(E);
13212     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
13213       return result;
13214 
13215     // If that failed, try to recover with a call.
13216     } else {
13217       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
13218                            /*complain*/ true);
13219       return result;
13220     }
13221   }
13222 
13223   // Bound member functions.
13224   case BuiltinType::BoundMember: {
13225     ExprResult result = Owned(E);
13226     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
13227                          /*complain*/ true);
13228     return result;
13229   }
13230 
13231   // ARC unbridged casts.
13232   case BuiltinType::ARCUnbridgedCast: {
13233     Expr *realCast = stripARCUnbridgedCast(E);
13234     diagnoseARCUnbridgedCast(realCast);
13235     return Owned(realCast);
13236   }
13237 
13238   // Expressions of unknown type.
13239   case BuiltinType::UnknownAny:
13240     return diagnoseUnknownAnyExpr(*this, E);
13241 
13242   // Pseudo-objects.
13243   case BuiltinType::PseudoObject:
13244     return checkPseudoObjectRValue(E);
13245 
13246   case BuiltinType::BuiltinFn:
13247     Diag(E->getLocStart(), diag::err_builtin_fn_use);
13248     return ExprError();
13249 
13250   // Everything else should be impossible.
13251 #define BUILTIN_TYPE(Id, SingletonId) \
13252   case BuiltinType::Id:
13253 #define PLACEHOLDER_TYPE(Id, SingletonId)
13254 #include "clang/AST/BuiltinTypes.def"
13255     break;
13256   }
13257 
13258   llvm_unreachable("invalid placeholder type!");
13259 }
13260 
13261 bool Sema::CheckCaseExpression(Expr *E) {
13262   if (E->isTypeDependent())
13263     return true;
13264   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
13265     return E->getType()->isIntegralOrEnumerationType();
13266   return false;
13267 }
13268 
13269 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
13270 ExprResult
13271 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
13272   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
13273          "Unknown Objective-C Boolean value!");
13274   QualType BoolT = Context.ObjCBuiltinBoolTy;
13275   if (!Context.getBOOLDecl()) {
13276     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
13277                         Sema::LookupOrdinaryName);
13278     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
13279       NamedDecl *ND = Result.getFoundDecl();
13280       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
13281         Context.setBOOLDecl(TD);
13282     }
13283   }
13284   if (Context.getBOOLDecl())
13285     BoolT = Context.getBOOLType();
13286   return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
13287                                         BoolT, OpLoc));
13288 }
13289