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/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/RecursiveASTVisitor.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/LiteralSupport.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Sema/AnalysisBasedWarnings.h"
34 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/DelayedDiagnostic.h"
36 #include "clang/Sema/Designator.h"
37 #include "clang/Sema/Initialization.h"
38 #include "clang/Sema/Lookup.h"
39 #include "clang/Sema/ParsedTemplate.h"
40 #include "clang/Sema/Scope.h"
41 #include "clang/Sema/ScopeInfo.h"
42 #include "clang/Sema/SemaFixItUtils.h"
43 #include "clang/Sema/Template.h"
44 using namespace clang;
45 using namespace sema;
46 
47 /// \brief Determine whether the use of this declaration is valid, without
48 /// emitting diagnostics.
49 bool Sema::CanUseDecl(NamedDecl *D) {
50   // See if this is an auto-typed variable whose initializer we are parsing.
51   if (ParsingInitForAutoVars.count(D))
52     return false;
53 
54   // See if this is a deleted function.
55   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
56     if (FD->isDeleted())
57       return false;
58 
59     // If the function has a deduced return type, and we can't deduce it,
60     // then we can't use it either.
61     if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() &&
62         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/false))
63       return false;
64   }
65 
66   // See if this function is unavailable.
67   if (D->getAvailability() == AR_Unavailable &&
68       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
69     return false;
70 
71   return true;
72 }
73 
74 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
75   // Warn if this is used but marked unused.
76   if (D->hasAttr<UnusedAttr>()) {
77     const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
78     if (!DC->hasAttr<UnusedAttr>())
79       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
80   }
81 }
82 
83 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
84                               NamedDecl *D, SourceLocation Loc,
85                               const ObjCInterfaceDecl *UnknownObjCClass) {
86   // See if this declaration is unavailable or deprecated.
87   std::string Message;
88   AvailabilityResult Result = D->getAvailability(&Message);
89   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
90     if (Result == AR_Available) {
91       const DeclContext *DC = ECD->getDeclContext();
92       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
93         Result = TheEnumDecl->getAvailability(&Message);
94     }
95 
96   const ObjCPropertyDecl *ObjCPDecl = 0;
97   if (Result == AR_Deprecated || Result == AR_Unavailable) {
98     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
99       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
100         AvailabilityResult PDeclResult = PD->getAvailability(0);
101         if (PDeclResult == Result)
102           ObjCPDecl = PD;
103       }
104     }
105   }
106 
107   switch (Result) {
108     case AR_Available:
109     case AR_NotYetIntroduced:
110       break;
111 
112     case AR_Deprecated:
113       S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
114       break;
115 
116     case AR_Unavailable:
117       if (S.getCurContextAvailability() != AR_Unavailable) {
118         if (Message.empty()) {
119           if (!UnknownObjCClass) {
120             S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
121             if (ObjCPDecl)
122               S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
123                 << ObjCPDecl->getDeclName() << 1;
124           }
125           else
126             S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
127               << D->getDeclName();
128         }
129         else
130           S.Diag(Loc, diag::err_unavailable_message)
131             << D->getDeclName() << Message;
132         S.Diag(D->getLocation(), diag::note_unavailable_here)
133                   << isa<FunctionDecl>(D) << false;
134         if (ObjCPDecl)
135           S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
136           << ObjCPDecl->getDeclName() << 1;
137       }
138       break;
139     }
140     return Result;
141 }
142 
143 /// \brief Emit a note explaining that this function is deleted.
144 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
145   assert(Decl->isDeleted());
146 
147   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
148 
149   if (Method && Method->isDeleted() && Method->isDefaulted()) {
150     // If the method was explicitly defaulted, point at that declaration.
151     if (!Method->isImplicit())
152       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
153 
154     // Try to diagnose why this special member function was implicitly
155     // deleted. This might fail, if that reason no longer applies.
156     CXXSpecialMember CSM = getSpecialMember(Method);
157     if (CSM != CXXInvalid)
158       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
159 
160     return;
161   }
162 
163   if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
164     if (CXXConstructorDecl *BaseCD =
165             const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
166       Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
167       if (BaseCD->isDeleted()) {
168         NoteDeletedFunction(BaseCD);
169       } else {
170         // FIXME: An explanation of why exactly it can't be inherited
171         // would be nice.
172         Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
173       }
174       return;
175     }
176   }
177 
178   Diag(Decl->getLocation(), diag::note_unavailable_here)
179     << 1 << true;
180 }
181 
182 /// \brief Determine whether a FunctionDecl was ever declared with an
183 /// explicit storage class.
184 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
185   for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
186                                      E = D->redecls_end();
187        I != E; ++I) {
188     if (I->getStorageClass() != SC_None)
189       return true;
190   }
191   return false;
192 }
193 
194 /// \brief Check whether we're in an extern inline function and referring to a
195 /// variable or function with internal linkage (C11 6.7.4p3).
196 ///
197 /// This is only a warning because we used to silently accept this code, but
198 /// in many cases it will not behave correctly. This is not enabled in C++ mode
199 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
200 /// and so while there may still be user mistakes, most of the time we can't
201 /// prove that there are errors.
202 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
203                                                       const NamedDecl *D,
204                                                       SourceLocation Loc) {
205   // This is disabled under C++; there are too many ways for this to fire in
206   // contexts where the warning is a false positive, or where it is technically
207   // correct but benign.
208   if (S.getLangOpts().CPlusPlus)
209     return;
210 
211   // Check if this is an inlined function or method.
212   FunctionDecl *Current = S.getCurFunctionDecl();
213   if (!Current)
214     return;
215   if (!Current->isInlined())
216     return;
217   if (!Current->isExternallyVisible())
218     return;
219 
220   // Check if the decl has internal linkage.
221   if (D->getFormalLinkage() != InternalLinkage)
222     return;
223 
224   // Downgrade from ExtWarn to Extension if
225   //  (1) the supposedly external inline function is in the main file,
226   //      and probably won't be included anywhere else.
227   //  (2) the thing we're referencing is a pure function.
228   //  (3) the thing we're referencing is another inline function.
229   // This last can give us false negatives, but it's better than warning on
230   // wrappers for simple C library functions.
231   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
232   bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
233   if (!DowngradeWarning && UsedFn)
234     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
235 
236   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
237                                : diag::warn_internal_in_extern_inline)
238     << /*IsVar=*/!UsedFn << D;
239 
240   S.MaybeSuggestAddingStaticToDecl(Current);
241 
242   S.Diag(D->getCanonicalDecl()->getLocation(),
243          diag::note_internal_decl_declared_here)
244     << D;
245 }
246 
247 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
248   const FunctionDecl *First = Cur->getFirstDeclaration();
249 
250   // Suggest "static" on the function, if possible.
251   if (!hasAnyExplicitStorageClass(First)) {
252     SourceLocation DeclBegin = First->getSourceRange().getBegin();
253     Diag(DeclBegin, diag::note_convert_inline_to_static)
254       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
255   }
256 }
257 
258 /// \brief Determine whether the use of this declaration is valid, and
259 /// emit any corresponding diagnostics.
260 ///
261 /// This routine diagnoses various problems with referencing
262 /// declarations that can occur when using a declaration. For example,
263 /// it might warn if a deprecated or unavailable declaration is being
264 /// used, or produce an error (and return true) if a C++0x deleted
265 /// function is being used.
266 ///
267 /// \returns true if there was an error (this declaration cannot be
268 /// referenced), false otherwise.
269 ///
270 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
271                              const ObjCInterfaceDecl *UnknownObjCClass) {
272   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
273     // If there were any diagnostics suppressed by template argument deduction,
274     // emit them now.
275     SuppressedDiagnosticsMap::iterator
276       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
277     if (Pos != SuppressedDiagnostics.end()) {
278       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
279       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
280         Diag(Suppressed[I].first, Suppressed[I].second);
281 
282       // Clear out the list of suppressed diagnostics, so that we don't emit
283       // them again for this specialization. However, we don't obsolete this
284       // entry from the table, because we want to avoid ever emitting these
285       // diagnostics again.
286       Suppressed.clear();
287     }
288   }
289 
290   // See if this is an auto-typed variable whose initializer we are parsing.
291   if (ParsingInitForAutoVars.count(D)) {
292     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
293       << D->getDeclName();
294     return true;
295   }
296 
297   // See if this is a deleted function.
298   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
299     if (FD->isDeleted()) {
300       Diag(Loc, diag::err_deleted_function_use);
301       NoteDeletedFunction(FD);
302       return true;
303     }
304 
305     // If the function has a deduced return type, and we can't deduce it,
306     // then we can't use it either.
307     if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() &&
308         DeduceReturnType(FD, Loc))
309       return true;
310   }
311   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
312 
313   DiagnoseUnusedOfDecl(*this, D, Loc);
314 
315   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
316 
317   return false;
318 }
319 
320 /// \brief Retrieve the message suffix that should be added to a
321 /// diagnostic complaining about the given function being deleted or
322 /// unavailable.
323 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
324   std::string Message;
325   if (FD->getAvailability(&Message))
326     return ": " + Message;
327 
328   return std::string();
329 }
330 
331 /// DiagnoseSentinelCalls - This routine checks whether a call or
332 /// message-send is to a declaration with the sentinel attribute, and
333 /// if so, it checks that the requirements of the sentinel are
334 /// satisfied.
335 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
336                                  ArrayRef<Expr *> Args) {
337   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
338   if (!attr)
339     return;
340 
341   // The number of formal parameters of the declaration.
342   unsigned numFormalParams;
343 
344   // The kind of declaration.  This is also an index into a %select in
345   // the diagnostic.
346   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
347 
348   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
349     numFormalParams = MD->param_size();
350     calleeType = CT_Method;
351   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
352     numFormalParams = FD->param_size();
353     calleeType = CT_Function;
354   } else if (isa<VarDecl>(D)) {
355     QualType type = cast<ValueDecl>(D)->getType();
356     const FunctionType *fn = 0;
357     if (const PointerType *ptr = type->getAs<PointerType>()) {
358       fn = ptr->getPointeeType()->getAs<FunctionType>();
359       if (!fn) return;
360       calleeType = CT_Function;
361     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
362       fn = ptr->getPointeeType()->castAs<FunctionType>();
363       calleeType = CT_Block;
364     } else {
365       return;
366     }
367 
368     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
369       numFormalParams = proto->getNumArgs();
370     } else {
371       numFormalParams = 0;
372     }
373   } else {
374     return;
375   }
376 
377   // "nullPos" is the number of formal parameters at the end which
378   // effectively count as part of the variadic arguments.  This is
379   // useful if you would prefer to not have *any* formal parameters,
380   // but the language forces you to have at least one.
381   unsigned nullPos = attr->getNullPos();
382   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
383   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
384 
385   // The number of arguments which should follow the sentinel.
386   unsigned numArgsAfterSentinel = attr->getSentinel();
387 
388   // If there aren't enough arguments for all the formal parameters,
389   // the sentinel, and the args after the sentinel, complain.
390   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
391     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
392     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
393     return;
394   }
395 
396   // Otherwise, find the sentinel expression.
397   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
398   if (!sentinelExpr) return;
399   if (sentinelExpr->isValueDependent()) return;
400   if (Context.isSentinelNullExpr(sentinelExpr)) return;
401 
402   // Pick a reasonable string to insert.  Optimistically use 'nil' or
403   // 'NULL' if those are actually defined in the context.  Only use
404   // 'nil' for ObjC methods, where it's much more likely that the
405   // variadic arguments form a list of object pointers.
406   SourceLocation MissingNilLoc
407     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
408   std::string NullValue;
409   if (calleeType == CT_Method &&
410       PP.getIdentifierInfo("nil")->hasMacroDefinition())
411     NullValue = "nil";
412   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
413     NullValue = "NULL";
414   else
415     NullValue = "(void*) 0";
416 
417   if (MissingNilLoc.isInvalid())
418     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
419   else
420     Diag(MissingNilLoc, diag::warn_missing_sentinel)
421       << int(calleeType)
422       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
423   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
424 }
425 
426 SourceRange Sema::getExprRange(Expr *E) const {
427   return E ? E->getSourceRange() : SourceRange();
428 }
429 
430 //===----------------------------------------------------------------------===//
431 //  Standard Promotions and Conversions
432 //===----------------------------------------------------------------------===//
433 
434 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
435 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
436   // Handle any placeholder expressions which made it here.
437   if (E->getType()->isPlaceholderType()) {
438     ExprResult result = CheckPlaceholderExpr(E);
439     if (result.isInvalid()) return ExprError();
440     E = result.take();
441   }
442 
443   QualType Ty = E->getType();
444   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
445 
446   if (Ty->isFunctionType())
447     E = ImpCastExprToType(E, Context.getPointerType(Ty),
448                           CK_FunctionToPointerDecay).take();
449   else if (Ty->isArrayType()) {
450     // In C90 mode, arrays only promote to pointers if the array expression is
451     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
452     // type 'array of type' is converted to an expression that has type 'pointer
453     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
454     // that has type 'array of type' ...".  The relevant change is "an lvalue"
455     // (C90) to "an expression" (C99).
456     //
457     // C++ 4.2p1:
458     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
459     // T" can be converted to an rvalue of type "pointer to T".
460     //
461     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
462       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
463                             CK_ArrayToPointerDecay).take();
464   }
465   return Owned(E);
466 }
467 
468 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
469   // Check to see if we are dereferencing a null pointer.  If so,
470   // and if not volatile-qualified, this is undefined behavior that the
471   // optimizer will delete, so warn about it.  People sometimes try to use this
472   // to get a deterministic trap and are surprised by clang's behavior.  This
473   // only handles the pattern "*null", which is a very syntactic check.
474   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
475     if (UO->getOpcode() == UO_Deref &&
476         UO->getSubExpr()->IgnoreParenCasts()->
477           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
478         !UO->getType().isVolatileQualified()) {
479     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
480                           S.PDiag(diag::warn_indirection_through_null)
481                             << UO->getSubExpr()->getSourceRange());
482     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
483                         S.PDiag(diag::note_indirection_through_null));
484   }
485 }
486 
487 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
488                                     SourceLocation AssignLoc,
489                                     const Expr* RHS) {
490   const ObjCIvarDecl *IV = OIRE->getDecl();
491   if (!IV)
492     return;
493 
494   DeclarationName MemberName = IV->getDeclName();
495   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
496   if (!Member || !Member->isStr("isa"))
497     return;
498 
499   const Expr *Base = OIRE->getBase();
500   QualType BaseType = Base->getType();
501   if (OIRE->isArrow())
502     BaseType = BaseType->getPointeeType();
503   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
504     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
505       ObjCInterfaceDecl *ClassDeclared = 0;
506       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
507       if (!ClassDeclared->getSuperClass()
508           && (*ClassDeclared->ivar_begin()) == IV) {
509         if (RHS) {
510           NamedDecl *ObjectSetClass =
511             S.LookupSingleName(S.TUScope,
512                                &S.Context.Idents.get("object_setClass"),
513                                SourceLocation(), S.LookupOrdinaryName);
514           if (ObjectSetClass) {
515             SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
516             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
517             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
518             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
519                                                      AssignLoc), ",") <<
520             FixItHint::CreateInsertion(RHSLocEnd, ")");
521           }
522           else
523             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
524         } else {
525           NamedDecl *ObjectGetClass =
526             S.LookupSingleName(S.TUScope,
527                                &S.Context.Idents.get("object_getClass"),
528                                SourceLocation(), S.LookupOrdinaryName);
529           if (ObjectGetClass)
530             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
531             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
532             FixItHint::CreateReplacement(
533                                          SourceRange(OIRE->getOpLoc(),
534                                                      OIRE->getLocEnd()), ")");
535           else
536             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
537         }
538         S.Diag(IV->getLocation(), diag::note_ivar_decl);
539       }
540     }
541 }
542 
543 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
544   // Handle any placeholder expressions which made it here.
545   if (E->getType()->isPlaceholderType()) {
546     ExprResult result = CheckPlaceholderExpr(E);
547     if (result.isInvalid()) return ExprError();
548     E = result.take();
549   }
550 
551   // C++ [conv.lval]p1:
552   //   A glvalue of a non-function, non-array type T can be
553   //   converted to a prvalue.
554   if (!E->isGLValue()) return Owned(E);
555 
556   QualType T = E->getType();
557   assert(!T.isNull() && "r-value conversion on typeless expression?");
558 
559   // We don't want to throw lvalue-to-rvalue casts on top of
560   // expressions of certain types in C++.
561   if (getLangOpts().CPlusPlus &&
562       (E->getType() == Context.OverloadTy ||
563        T->isDependentType() ||
564        T->isRecordType()))
565     return Owned(E);
566 
567   // The C standard is actually really unclear on this point, and
568   // DR106 tells us what the result should be but not why.  It's
569   // generally best to say that void types just doesn't undergo
570   // lvalue-to-rvalue at all.  Note that expressions of unqualified
571   // 'void' type are never l-values, but qualified void can be.
572   if (T->isVoidType())
573     return Owned(E);
574 
575   // OpenCL usually rejects direct accesses to values of 'half' type.
576   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
577       T->isHalfType()) {
578     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
579       << 0 << T;
580     return ExprError();
581   }
582 
583   CheckForNullPointerDereference(*this, E);
584   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
585     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
586                                      &Context.Idents.get("object_getClass"),
587                                      SourceLocation(), LookupOrdinaryName);
588     if (ObjectGetClass)
589       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
590         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
591         FixItHint::CreateReplacement(
592                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
593     else
594       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
595   }
596   else if (const ObjCIvarRefExpr *OIRE =
597             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
598     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0);
599 
600   // C++ [conv.lval]p1:
601   //   [...] If T is a non-class type, the type of the prvalue is the
602   //   cv-unqualified version of T. Otherwise, the type of the
603   //   rvalue is T.
604   //
605   // C99 6.3.2.1p2:
606   //   If the lvalue has qualified type, the value has the unqualified
607   //   version of the type of the lvalue; otherwise, the value has the
608   //   type of the lvalue.
609   if (T.hasQualifiers())
610     T = T.getUnqualifiedType();
611 
612   UpdateMarkingForLValueToRValue(E);
613 
614   // Loading a __weak object implicitly retains the value, so we need a cleanup to
615   // balance that.
616   if (getLangOpts().ObjCAutoRefCount &&
617       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
618     ExprNeedsCleanups = true;
619 
620   ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
621                                                   E, 0, VK_RValue));
622 
623   // C11 6.3.2.1p2:
624   //   ... if the lvalue has atomic type, the value has the non-atomic version
625   //   of the type of the lvalue ...
626   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
627     T = Atomic->getValueType().getUnqualifiedType();
628     Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
629                                          Res.get(), 0, VK_RValue));
630   }
631 
632   return Res;
633 }
634 
635 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
636   ExprResult Res = DefaultFunctionArrayConversion(E);
637   if (Res.isInvalid())
638     return ExprError();
639   Res = DefaultLvalueConversion(Res.take());
640   if (Res.isInvalid())
641     return ExprError();
642   return Res;
643 }
644 
645 
646 /// UsualUnaryConversions - Performs various conversions that are common to most
647 /// operators (C99 6.3). The conversions of array and function types are
648 /// sometimes suppressed. For example, the array->pointer conversion doesn't
649 /// apply if the array is an argument to the sizeof or address (&) operators.
650 /// In these instances, this routine should *not* be called.
651 ExprResult Sema::UsualUnaryConversions(Expr *E) {
652   // First, convert to an r-value.
653   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
654   if (Res.isInvalid())
655     return ExprError();
656   E = Res.take();
657 
658   QualType Ty = E->getType();
659   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
660 
661   // Half FP have to be promoted to float unless it is natively supported
662   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
663     return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
664 
665   // Try to perform integral promotions if the object has a theoretically
666   // promotable type.
667   if (Ty->isIntegralOrUnscopedEnumerationType()) {
668     // C99 6.3.1.1p2:
669     //
670     //   The following may be used in an expression wherever an int or
671     //   unsigned int may be used:
672     //     - an object or expression with an integer type whose integer
673     //       conversion rank is less than or equal to the rank of int
674     //       and unsigned int.
675     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
676     //
677     //   If an int can represent all values of the original type, the
678     //   value is converted to an int; otherwise, it is converted to an
679     //   unsigned int. These are called the integer promotions. All
680     //   other types are unchanged by the integer promotions.
681 
682     QualType PTy = Context.isPromotableBitField(E);
683     if (!PTy.isNull()) {
684       E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
685       return Owned(E);
686     }
687     if (Ty->isPromotableIntegerType()) {
688       QualType PT = Context.getPromotedIntegerType(Ty);
689       E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
690       return Owned(E);
691     }
692   }
693   return Owned(E);
694 }
695 
696 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
697 /// do not have a prototype. Arguments that have type float or __fp16
698 /// are promoted to double. All other argument types are converted by
699 /// UsualUnaryConversions().
700 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
701   QualType Ty = E->getType();
702   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
703 
704   ExprResult Res = UsualUnaryConversions(E);
705   if (Res.isInvalid())
706     return ExprError();
707   E = Res.take();
708 
709   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
710   // double.
711   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
712   if (BTy && (BTy->getKind() == BuiltinType::Half ||
713               BTy->getKind() == BuiltinType::Float))
714     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
715 
716   // C++ performs lvalue-to-rvalue conversion as a default argument
717   // promotion, even on class types, but note:
718   //   C++11 [conv.lval]p2:
719   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
720   //     operand or a subexpression thereof the value contained in the
721   //     referenced object is not accessed. Otherwise, if the glvalue
722   //     has a class type, the conversion copy-initializes a temporary
723   //     of type T from the glvalue and the result of the conversion
724   //     is a prvalue for the temporary.
725   // FIXME: add some way to gate this entire thing for correctness in
726   // potentially potentially evaluated contexts.
727   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
728     ExprResult Temp = PerformCopyInitialization(
729                        InitializedEntity::InitializeTemporary(E->getType()),
730                                                 E->getExprLoc(),
731                                                 Owned(E));
732     if (Temp.isInvalid())
733       return ExprError();
734     E = Temp.get();
735   }
736 
737   return Owned(E);
738 }
739 
740 /// Determine the degree of POD-ness for an expression.
741 /// Incomplete types are considered POD, since this check can be performed
742 /// when we're in an unevaluated context.
743 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
744   if (Ty->isIncompleteType()) {
745     // C++11 [expr.call]p7:
746     //   After these conversions, if the argument does not have arithmetic,
747     //   enumeration, pointer, pointer to member, or class type, the program
748     //   is ill-formed.
749     //
750     // Since we've already performed array-to-pointer and function-to-pointer
751     // decay, the only such type in C++ is cv void. This also handles
752     // initializer lists as variadic arguments.
753     if (Ty->isVoidType())
754       return VAK_Invalid;
755 
756     if (Ty->isObjCObjectType())
757       return VAK_Invalid;
758     return VAK_Valid;
759   }
760 
761   if (Ty.isCXX98PODType(Context))
762     return VAK_Valid;
763 
764   // C++11 [expr.call]p7:
765   //   Passing a potentially-evaluated argument of class type (Clause 9)
766   //   having a non-trivial copy constructor, a non-trivial move constructor,
767   //   or a non-trivial destructor, with no corresponding parameter,
768   //   is conditionally-supported with implementation-defined semantics.
769   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
770     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
771       if (!Record->hasNonTrivialCopyConstructor() &&
772           !Record->hasNonTrivialMoveConstructor() &&
773           !Record->hasNonTrivialDestructor())
774         return VAK_ValidInCXX11;
775 
776   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
777     return VAK_Valid;
778 
779   if (Ty->isObjCObjectType())
780     return VAK_Invalid;
781 
782   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
783   // permitted to reject them. We should consider doing so.
784   return VAK_Undefined;
785 }
786 
787 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
788   // Don't allow one to pass an Objective-C interface to a vararg.
789   const QualType &Ty = E->getType();
790   VarArgKind VAK = isValidVarArgType(Ty);
791 
792   // Complain about passing non-POD types through varargs.
793   switch (VAK) {
794   case VAK_Valid:
795     break;
796 
797   case VAK_ValidInCXX11:
798     DiagRuntimeBehavior(
799         E->getLocStart(), 0,
800         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
801           << E->getType() << CT);
802     break;
803 
804   case VAK_Undefined:
805     DiagRuntimeBehavior(
806         E->getLocStart(), 0,
807         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
808           << getLangOpts().CPlusPlus11 << Ty << CT);
809     break;
810 
811   case VAK_Invalid:
812     if (Ty->isObjCObjectType())
813       DiagRuntimeBehavior(
814           E->getLocStart(), 0,
815           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
816             << Ty << CT);
817     else
818       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
819         << isa<InitListExpr>(E) << Ty << CT;
820     break;
821   }
822 }
823 
824 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
825 /// will create a trap if the resulting type is not a POD type.
826 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
827                                                   FunctionDecl *FDecl) {
828   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
829     // Strip the unbridged-cast placeholder expression off, if applicable.
830     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
831         (CT == VariadicMethod ||
832          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
833       E = stripARCUnbridgedCast(E);
834 
835     // Otherwise, do normal placeholder checking.
836     } else {
837       ExprResult ExprRes = CheckPlaceholderExpr(E);
838       if (ExprRes.isInvalid())
839         return ExprError();
840       E = ExprRes.take();
841     }
842   }
843 
844   ExprResult ExprRes = DefaultArgumentPromotion(E);
845   if (ExprRes.isInvalid())
846     return ExprError();
847   E = ExprRes.take();
848 
849   // Diagnostics regarding non-POD argument types are
850   // emitted along with format string checking in Sema::CheckFunctionCall().
851   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
852     // Turn this into a trap.
853     CXXScopeSpec SS;
854     SourceLocation TemplateKWLoc;
855     UnqualifiedId Name;
856     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
857                        E->getLocStart());
858     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
859                                           Name, true, false);
860     if (TrapFn.isInvalid())
861       return ExprError();
862 
863     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
864                                     E->getLocStart(), None,
865                                     E->getLocEnd());
866     if (Call.isInvalid())
867       return ExprError();
868 
869     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
870                                   Call.get(), E);
871     if (Comma.isInvalid())
872       return ExprError();
873     return Comma.get();
874   }
875 
876   if (!getLangOpts().CPlusPlus &&
877       RequireCompleteType(E->getExprLoc(), E->getType(),
878                           diag::err_call_incomplete_argument))
879     return ExprError();
880 
881   return Owned(E);
882 }
883 
884 /// \brief Converts an integer to complex float type.  Helper function of
885 /// UsualArithmeticConversions()
886 ///
887 /// \return false if the integer expression is an integer type and is
888 /// successfully converted to the complex type.
889 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
890                                                   ExprResult &ComplexExpr,
891                                                   QualType IntTy,
892                                                   QualType ComplexTy,
893                                                   bool SkipCast) {
894   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
895   if (SkipCast) return false;
896   if (IntTy->isIntegerType()) {
897     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
898     IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
899     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
900                                   CK_FloatingRealToComplex);
901   } else {
902     assert(IntTy->isComplexIntegerType());
903     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
904                                   CK_IntegralComplexToFloatingComplex);
905   }
906   return false;
907 }
908 
909 /// \brief Takes two complex float types and converts them to the same type.
910 /// Helper function of UsualArithmeticConversions()
911 static QualType
912 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
913                                             ExprResult &RHS, QualType LHSType,
914                                             QualType RHSType,
915                                             bool IsCompAssign) {
916   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
917 
918   if (order < 0) {
919     // _Complex float -> _Complex double
920     if (!IsCompAssign)
921       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
922     return RHSType;
923   }
924   if (order > 0)
925     // _Complex float -> _Complex double
926     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
927   return LHSType;
928 }
929 
930 /// \brief Converts otherExpr to complex float and promotes complexExpr if
931 /// necessary.  Helper function of UsualArithmeticConversions()
932 static QualType handleOtherComplexFloatConversion(Sema &S,
933                                                   ExprResult &ComplexExpr,
934                                                   ExprResult &OtherExpr,
935                                                   QualType ComplexTy,
936                                                   QualType OtherTy,
937                                                   bool ConvertComplexExpr,
938                                                   bool ConvertOtherExpr) {
939   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
940 
941   // If just the complexExpr is complex, the otherExpr needs to be converted,
942   // and the complexExpr might need to be promoted.
943   if (order > 0) { // complexExpr is wider
944     // float -> _Complex double
945     if (ConvertOtherExpr) {
946       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
947       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
948       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
949                                       CK_FloatingRealToComplex);
950     }
951     return ComplexTy;
952   }
953 
954   // otherTy is at least as wide.  Find its corresponding complex type.
955   QualType result = (order == 0 ? ComplexTy :
956                                   S.Context.getComplexType(OtherTy));
957 
958   // double -> _Complex double
959   if (ConvertOtherExpr)
960     OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
961                                     CK_FloatingRealToComplex);
962 
963   // _Complex float -> _Complex double
964   if (ConvertComplexExpr && order < 0)
965     ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
966                                       CK_FloatingComplexCast);
967 
968   return result;
969 }
970 
971 /// \brief Handle arithmetic conversion with complex types.  Helper function of
972 /// UsualArithmeticConversions()
973 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
974                                              ExprResult &RHS, QualType LHSType,
975                                              QualType RHSType,
976                                              bool IsCompAssign) {
977   // if we have an integer operand, the result is the complex type.
978   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
979                                              /*skipCast*/false))
980     return LHSType;
981   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
982                                              /*skipCast*/IsCompAssign))
983     return RHSType;
984 
985   // This handles complex/complex, complex/float, or float/complex.
986   // When both operands are complex, the shorter operand is converted to the
987   // type of the longer, and that is the type of the result. This corresponds
988   // to what is done when combining two real floating-point operands.
989   // The fun begins when size promotion occur across type domains.
990   // From H&S 6.3.4: When one operand is complex and the other is a real
991   // floating-point type, the less precise type is converted, within it's
992   // real or complex domain, to the precision of the other type. For example,
993   // when combining a "long double" with a "double _Complex", the
994   // "double _Complex" is promoted to "long double _Complex".
995 
996   bool LHSComplexFloat = LHSType->isComplexType();
997   bool RHSComplexFloat = RHSType->isComplexType();
998 
999   // If both are complex, just cast to the more precise type.
1000   if (LHSComplexFloat && RHSComplexFloat)
1001     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
1002                                                        LHSType, RHSType,
1003                                                        IsCompAssign);
1004 
1005   // If only one operand is complex, promote it if necessary and convert the
1006   // other operand to complex.
1007   if (LHSComplexFloat)
1008     return handleOtherComplexFloatConversion(
1009         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
1010         /*convertOtherExpr*/ true);
1011 
1012   assert(RHSComplexFloat);
1013   return handleOtherComplexFloatConversion(
1014       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
1015       /*convertOtherExpr*/ !IsCompAssign);
1016 }
1017 
1018 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1019 /// of UsualArithmeticConversions()
1020 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1021                                            ExprResult &IntExpr,
1022                                            QualType FloatTy, QualType IntTy,
1023                                            bool ConvertFloat, bool ConvertInt) {
1024   if (IntTy->isIntegerType()) {
1025     if (ConvertInt)
1026       // Convert intExpr to the lhs floating point type.
1027       IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
1028                                     CK_IntegralToFloating);
1029     return FloatTy;
1030   }
1031 
1032   // Convert both sides to the appropriate complex float.
1033   assert(IntTy->isComplexIntegerType());
1034   QualType result = S.Context.getComplexType(FloatTy);
1035 
1036   // _Complex int -> _Complex float
1037   if (ConvertInt)
1038     IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
1039                                   CK_IntegralComplexToFloatingComplex);
1040 
1041   // float -> _Complex float
1042   if (ConvertFloat)
1043     FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
1044                                     CK_FloatingRealToComplex);
1045 
1046   return result;
1047 }
1048 
1049 /// \brief Handle arithmethic conversion with floating point types.  Helper
1050 /// function of UsualArithmeticConversions()
1051 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1052                                       ExprResult &RHS, QualType LHSType,
1053                                       QualType RHSType, bool IsCompAssign) {
1054   bool LHSFloat = LHSType->isRealFloatingType();
1055   bool RHSFloat = RHSType->isRealFloatingType();
1056 
1057   // If we have two real floating types, convert the smaller operand
1058   // to the bigger result.
1059   if (LHSFloat && RHSFloat) {
1060     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1061     if (order > 0) {
1062       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
1063       return LHSType;
1064     }
1065 
1066     assert(order < 0 && "illegal float comparison");
1067     if (!IsCompAssign)
1068       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
1069     return RHSType;
1070   }
1071 
1072   if (LHSFloat)
1073     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1074                                       /*convertFloat=*/!IsCompAssign,
1075                                       /*convertInt=*/ true);
1076   assert(RHSFloat);
1077   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1078                                     /*convertInt=*/ true,
1079                                     /*convertFloat=*/!IsCompAssign);
1080 }
1081 
1082 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1083 
1084 namespace {
1085 /// These helper callbacks are placed in an anonymous namespace to
1086 /// permit their use as function template parameters.
1087 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1088   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1089 }
1090 
1091 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1092   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1093                              CK_IntegralComplexCast);
1094 }
1095 }
1096 
1097 /// \brief Handle integer arithmetic conversions.  Helper function of
1098 /// UsualArithmeticConversions()
1099 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1100 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1101                                         ExprResult &RHS, QualType LHSType,
1102                                         QualType RHSType, bool IsCompAssign) {
1103   // The rules for this case are in C99 6.3.1.8
1104   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1105   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1106   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1107   if (LHSSigned == RHSSigned) {
1108     // Same signedness; use the higher-ranked type
1109     if (order >= 0) {
1110       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1111       return LHSType;
1112     } else if (!IsCompAssign)
1113       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1114     return RHSType;
1115   } else if (order != (LHSSigned ? 1 : -1)) {
1116     // The unsigned type has greater than or equal rank to the
1117     // signed type, so use the unsigned type
1118     if (RHSSigned) {
1119       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1120       return LHSType;
1121     } else if (!IsCompAssign)
1122       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1123     return RHSType;
1124   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1125     // The two types are different widths; if we are here, that
1126     // means the signed type is larger than the unsigned type, so
1127     // use the signed type.
1128     if (LHSSigned) {
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 {
1135     // The signed type is higher-ranked than the unsigned type,
1136     // but isn't actually any bigger (like unsigned int and long
1137     // on most 32-bit systems).  Use the unsigned type corresponding
1138     // to the signed type.
1139     QualType result =
1140       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1141     RHS = (*doRHSCast)(S, RHS.take(), result);
1142     if (!IsCompAssign)
1143       LHS = (*doLHSCast)(S, LHS.take(), result);
1144     return result;
1145   }
1146 }
1147 
1148 /// \brief Handle conversions with GCC complex int extension.  Helper function
1149 /// of UsualArithmeticConversions()
1150 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1151                                            ExprResult &RHS, QualType LHSType,
1152                                            QualType RHSType,
1153                                            bool IsCompAssign) {
1154   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1155   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1156 
1157   if (LHSComplexInt && RHSComplexInt) {
1158     QualType LHSEltType = LHSComplexInt->getElementType();
1159     QualType RHSEltType = RHSComplexInt->getElementType();
1160     QualType ScalarType =
1161       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1162         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1163 
1164     return S.Context.getComplexType(ScalarType);
1165   }
1166 
1167   if (LHSComplexInt) {
1168     QualType LHSEltType = LHSComplexInt->getElementType();
1169     QualType ScalarType =
1170       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1171         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1172     QualType ComplexType = S.Context.getComplexType(ScalarType);
1173     RHS = S.ImpCastExprToType(RHS.take(), ComplexType,
1174                               CK_IntegralRealToComplex);
1175 
1176     return ComplexType;
1177   }
1178 
1179   assert(RHSComplexInt);
1180 
1181   QualType RHSEltType = RHSComplexInt->getElementType();
1182   QualType ScalarType =
1183     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1184       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1185   QualType ComplexType = S.Context.getComplexType(ScalarType);
1186 
1187   if (!IsCompAssign)
1188     LHS = S.ImpCastExprToType(LHS.take(), ComplexType,
1189                               CK_IntegralRealToComplex);
1190   return ComplexType;
1191 }
1192 
1193 /// UsualArithmeticConversions - Performs various conversions that are common to
1194 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1195 /// routine returns the first non-arithmetic type found. The client is
1196 /// responsible for emitting appropriate error diagnostics.
1197 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1198                                           bool IsCompAssign) {
1199   if (!IsCompAssign) {
1200     LHS = UsualUnaryConversions(LHS.take());
1201     if (LHS.isInvalid())
1202       return QualType();
1203   }
1204 
1205   RHS = UsualUnaryConversions(RHS.take());
1206   if (RHS.isInvalid())
1207     return QualType();
1208 
1209   // For conversion purposes, we ignore any qualifiers.
1210   // For example, "const float" and "float" are equivalent.
1211   QualType LHSType =
1212     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1213   QualType RHSType =
1214     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1215 
1216   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1217   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1218     LHSType = AtomicLHS->getValueType();
1219 
1220   // If both types are identical, no conversion is needed.
1221   if (LHSType == RHSType)
1222     return LHSType;
1223 
1224   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1225   // The caller can deal with this (e.g. pointer + int).
1226   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1227     return QualType();
1228 
1229   // Apply unary and bitfield promotions to the LHS's type.
1230   QualType LHSUnpromotedType = LHSType;
1231   if (LHSType->isPromotableIntegerType())
1232     LHSType = Context.getPromotedIntegerType(LHSType);
1233   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1234   if (!LHSBitfieldPromoteTy.isNull())
1235     LHSType = LHSBitfieldPromoteTy;
1236   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1237     LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
1238 
1239   // If both types are identical, no conversion is needed.
1240   if (LHSType == RHSType)
1241     return LHSType;
1242 
1243   // At this point, we have two different arithmetic types.
1244 
1245   // Handle complex types first (C99 6.3.1.8p1).
1246   if (LHSType->isComplexType() || RHSType->isComplexType())
1247     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1248                                         IsCompAssign);
1249 
1250   // Now handle "real" floating types (i.e. float, double, long double).
1251   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1252     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1253                                  IsCompAssign);
1254 
1255   // Handle GCC complex int extension.
1256   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1257     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1258                                       IsCompAssign);
1259 
1260   // Finally, we have two differing integer types.
1261   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1262            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1263 }
1264 
1265 
1266 //===----------------------------------------------------------------------===//
1267 //  Semantic Analysis for various Expression Types
1268 //===----------------------------------------------------------------------===//
1269 
1270 
1271 ExprResult
1272 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1273                                 SourceLocation DefaultLoc,
1274                                 SourceLocation RParenLoc,
1275                                 Expr *ControllingExpr,
1276                                 ArrayRef<ParsedType> ArgTypes,
1277                                 ArrayRef<Expr *> ArgExprs) {
1278   unsigned NumAssocs = ArgTypes.size();
1279   assert(NumAssocs == ArgExprs.size());
1280 
1281   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1282   for (unsigned i = 0; i < NumAssocs; ++i) {
1283     if (ArgTypes[i])
1284       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1285     else
1286       Types[i] = 0;
1287   }
1288 
1289   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1290                                              ControllingExpr,
1291                                              llvm::makeArrayRef(Types, NumAssocs),
1292                                              ArgExprs);
1293   delete [] Types;
1294   return ER;
1295 }
1296 
1297 ExprResult
1298 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1299                                  SourceLocation DefaultLoc,
1300                                  SourceLocation RParenLoc,
1301                                  Expr *ControllingExpr,
1302                                  ArrayRef<TypeSourceInfo *> Types,
1303                                  ArrayRef<Expr *> Exprs) {
1304   unsigned NumAssocs = Types.size();
1305   assert(NumAssocs == Exprs.size());
1306   if (ControllingExpr->getType()->isPlaceholderType()) {
1307     ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1308     if (result.isInvalid()) return ExprError();
1309     ControllingExpr = result.take();
1310   }
1311 
1312   bool TypeErrorFound = false,
1313        IsResultDependent = ControllingExpr->isTypeDependent(),
1314        ContainsUnexpandedParameterPack
1315          = ControllingExpr->containsUnexpandedParameterPack();
1316 
1317   for (unsigned i = 0; i < NumAssocs; ++i) {
1318     if (Exprs[i]->containsUnexpandedParameterPack())
1319       ContainsUnexpandedParameterPack = true;
1320 
1321     if (Types[i]) {
1322       if (Types[i]->getType()->containsUnexpandedParameterPack())
1323         ContainsUnexpandedParameterPack = true;
1324 
1325       if (Types[i]->getType()->isDependentType()) {
1326         IsResultDependent = true;
1327       } else {
1328         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1329         // complete object type other than a variably modified type."
1330         unsigned D = 0;
1331         if (Types[i]->getType()->isIncompleteType())
1332           D = diag::err_assoc_type_incomplete;
1333         else if (!Types[i]->getType()->isObjectType())
1334           D = diag::err_assoc_type_nonobject;
1335         else if (Types[i]->getType()->isVariablyModifiedType())
1336           D = diag::err_assoc_type_variably_modified;
1337 
1338         if (D != 0) {
1339           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1340             << Types[i]->getTypeLoc().getSourceRange()
1341             << Types[i]->getType();
1342           TypeErrorFound = true;
1343         }
1344 
1345         // C11 6.5.1.1p2 "No two generic associations in the same generic
1346         // selection shall specify compatible types."
1347         for (unsigned j = i+1; j < NumAssocs; ++j)
1348           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1349               Context.typesAreCompatible(Types[i]->getType(),
1350                                          Types[j]->getType())) {
1351             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1352                  diag::err_assoc_compatible_types)
1353               << Types[j]->getTypeLoc().getSourceRange()
1354               << Types[j]->getType()
1355               << Types[i]->getType();
1356             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1357                  diag::note_compat_assoc)
1358               << Types[i]->getTypeLoc().getSourceRange()
1359               << Types[i]->getType();
1360             TypeErrorFound = true;
1361           }
1362       }
1363     }
1364   }
1365   if (TypeErrorFound)
1366     return ExprError();
1367 
1368   // If we determined that the generic selection is result-dependent, don't
1369   // try to compute the result expression.
1370   if (IsResultDependent)
1371     return Owned(new (Context) GenericSelectionExpr(
1372                    Context, KeyLoc, ControllingExpr,
1373                    Types, Exprs,
1374                    DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
1375 
1376   SmallVector<unsigned, 1> CompatIndices;
1377   unsigned DefaultIndex = -1U;
1378   for (unsigned i = 0; i < NumAssocs; ++i) {
1379     if (!Types[i])
1380       DefaultIndex = i;
1381     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1382                                         Types[i]->getType()))
1383       CompatIndices.push_back(i);
1384   }
1385 
1386   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1387   // type compatible with at most one of the types named in its generic
1388   // association list."
1389   if (CompatIndices.size() > 1) {
1390     // We strip parens here because the controlling expression is typically
1391     // parenthesized in macro definitions.
1392     ControllingExpr = ControllingExpr->IgnoreParens();
1393     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1394       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1395       << (unsigned) CompatIndices.size();
1396     for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
1397          E = CompatIndices.end(); I != E; ++I) {
1398       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1399            diag::note_compat_assoc)
1400         << Types[*I]->getTypeLoc().getSourceRange()
1401         << Types[*I]->getType();
1402     }
1403     return ExprError();
1404   }
1405 
1406   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1407   // its controlling expression shall have type compatible with exactly one of
1408   // the types named in its generic association list."
1409   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1410     // We strip parens here because the controlling expression is typically
1411     // parenthesized in macro definitions.
1412     ControllingExpr = ControllingExpr->IgnoreParens();
1413     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1414       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1415     return ExprError();
1416   }
1417 
1418   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1419   // type name that is compatible with the type of the controlling expression,
1420   // then the result expression of the generic selection is the expression
1421   // in that generic association. Otherwise, the result expression of the
1422   // generic selection is the expression in the default generic association."
1423   unsigned ResultIndex =
1424     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1425 
1426   return Owned(new (Context) GenericSelectionExpr(
1427                  Context, KeyLoc, ControllingExpr,
1428                  Types, Exprs,
1429                  DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
1430                  ResultIndex));
1431 }
1432 
1433 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1434 /// location of the token and the offset of the ud-suffix within it.
1435 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1436                                      unsigned Offset) {
1437   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1438                                         S.getLangOpts());
1439 }
1440 
1441 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1442 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1443 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1444                                                  IdentifierInfo *UDSuffix,
1445                                                  SourceLocation UDSuffixLoc,
1446                                                  ArrayRef<Expr*> Args,
1447                                                  SourceLocation LitEndLoc) {
1448   assert(Args.size() <= 2 && "too many arguments for literal operator");
1449 
1450   QualType ArgTy[2];
1451   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1452     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1453     if (ArgTy[ArgIdx]->isArrayType())
1454       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1455   }
1456 
1457   DeclarationName OpName =
1458     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1459   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1460   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1461 
1462   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1463   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1464                               /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1465     return ExprError();
1466 
1467   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1468 }
1469 
1470 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1471 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1472 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1473 /// multiple tokens.  However, the common case is that StringToks points to one
1474 /// string.
1475 ///
1476 ExprResult
1477 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1478                          Scope *UDLScope) {
1479   assert(NumStringToks && "Must have at least one string!");
1480 
1481   StringLiteralParser Literal(StringToks, NumStringToks, PP);
1482   if (Literal.hadError)
1483     return ExprError();
1484 
1485   SmallVector<SourceLocation, 4> StringTokLocs;
1486   for (unsigned i = 0; i != NumStringToks; ++i)
1487     StringTokLocs.push_back(StringToks[i].getLocation());
1488 
1489   QualType StrTy = Context.CharTy;
1490   if (Literal.isWide())
1491     StrTy = Context.getWideCharType();
1492   else if (Literal.isUTF16())
1493     StrTy = Context.Char16Ty;
1494   else if (Literal.isUTF32())
1495     StrTy = Context.Char32Ty;
1496   else if (Literal.isPascal())
1497     StrTy = Context.UnsignedCharTy;
1498 
1499   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1500   if (Literal.isWide())
1501     Kind = StringLiteral::Wide;
1502   else if (Literal.isUTF8())
1503     Kind = StringLiteral::UTF8;
1504   else if (Literal.isUTF16())
1505     Kind = StringLiteral::UTF16;
1506   else if (Literal.isUTF32())
1507     Kind = StringLiteral::UTF32;
1508 
1509   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1510   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1511     StrTy.addConst();
1512 
1513   // Get an array type for the string, according to C99 6.4.5.  This includes
1514   // the nul terminator character as well as the string length for pascal
1515   // strings.
1516   StrTy = Context.getConstantArrayType(StrTy,
1517                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1518                                        ArrayType::Normal, 0);
1519 
1520   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1521   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1522                                              Kind, Literal.Pascal, StrTy,
1523                                              &StringTokLocs[0],
1524                                              StringTokLocs.size());
1525   if (Literal.getUDSuffix().empty())
1526     return Owned(Lit);
1527 
1528   // We're building a user-defined literal.
1529   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1530   SourceLocation UDSuffixLoc =
1531     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1532                    Literal.getUDSuffixOffset());
1533 
1534   // Make sure we're allowed user-defined literals here.
1535   if (!UDLScope)
1536     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1537 
1538   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1539   //   operator "" X (str, len)
1540   QualType SizeType = Context.getSizeType();
1541   llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1542   IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1543                                                   StringTokLocs[0]);
1544   Expr *Args[] = { Lit, LenArg };
1545   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1546                                         Args, StringTokLocs.back());
1547 }
1548 
1549 ExprResult
1550 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1551                        SourceLocation Loc,
1552                        const CXXScopeSpec *SS) {
1553   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1554   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1555 }
1556 
1557 /// BuildDeclRefExpr - Build an expression that references a
1558 /// declaration that does not require a closure capture.
1559 ExprResult
1560 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1561                        const DeclarationNameInfo &NameInfo,
1562                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1563                        const TemplateArgumentListInfo *TemplateArgs) {
1564   if (getLangOpts().CUDA)
1565     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1566       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1567         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1568                            CalleeTarget = IdentifyCUDATarget(Callee);
1569         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1570           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1571             << CalleeTarget << D->getIdentifier() << CallerTarget;
1572           Diag(D->getLocation(), diag::note_previous_decl)
1573             << D->getIdentifier();
1574           return ExprError();
1575         }
1576       }
1577 
1578   bool refersToEnclosingScope =
1579     (CurContext != D->getDeclContext() &&
1580      D->getDeclContext()->isFunctionOrMethod());
1581 
1582   DeclRefExpr *E;
1583   if (isa<VarTemplateSpecializationDecl>(D)) {
1584     VarTemplateSpecializationDecl *VarSpec =
1585         cast<VarTemplateSpecializationDecl>(D);
1586 
1587     E = DeclRefExpr::Create(
1588         Context,
1589         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1590         VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope,
1591         NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs);
1592   } else {
1593     assert(!TemplateArgs && "No template arguments for non-variable"
1594                             " template specialization referrences");
1595     E = DeclRefExpr::Create(
1596         Context,
1597         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1598         SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD);
1599   }
1600 
1601   MarkDeclRefReferenced(E);
1602 
1603   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1604       Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1605     DiagnosticsEngine::Level Level =
1606       Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1607                                E->getLocStart());
1608     if (Level != DiagnosticsEngine::Ignored)
1609       recordUseOfEvaluatedWeak(E);
1610   }
1611 
1612   // Just in case we're building an illegal pointer-to-member.
1613   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1614   if (FD && FD->isBitField())
1615     E->setObjectKind(OK_BitField);
1616 
1617   return Owned(E);
1618 }
1619 
1620 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1621 /// possibly a list of template arguments.
1622 ///
1623 /// If this produces template arguments, it is permitted to call
1624 /// DecomposeTemplateName.
1625 ///
1626 /// This actually loses a lot of source location information for
1627 /// non-standard name kinds; we should consider preserving that in
1628 /// some way.
1629 void
1630 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1631                              TemplateArgumentListInfo &Buffer,
1632                              DeclarationNameInfo &NameInfo,
1633                              const TemplateArgumentListInfo *&TemplateArgs) {
1634   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1635     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1636     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1637 
1638     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1639                                        Id.TemplateId->NumArgs);
1640     translateTemplateArguments(TemplateArgsPtr, Buffer);
1641 
1642     TemplateName TName = Id.TemplateId->Template.get();
1643     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1644     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1645     TemplateArgs = &Buffer;
1646   } else {
1647     NameInfo = GetNameFromUnqualifiedId(Id);
1648     TemplateArgs = 0;
1649   }
1650 }
1651 
1652 /// Diagnose an empty lookup.
1653 ///
1654 /// \return false if new lookup candidates were found
1655 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1656                                CorrectionCandidateCallback &CCC,
1657                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1658                                ArrayRef<Expr *> Args) {
1659   DeclarationName Name = R.getLookupName();
1660 
1661   unsigned diagnostic = diag::err_undeclared_var_use;
1662   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1663   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1664       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1665       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1666     diagnostic = diag::err_undeclared_use;
1667     diagnostic_suggest = diag::err_undeclared_use_suggest;
1668   }
1669 
1670   // If the original lookup was an unqualified lookup, fake an
1671   // unqualified lookup.  This is useful when (for example) the
1672   // original lookup would not have found something because it was a
1673   // dependent name.
1674   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1675     ? CurContext : 0;
1676   while (DC) {
1677     if (isa<CXXRecordDecl>(DC)) {
1678       LookupQualifiedName(R, DC);
1679 
1680       if (!R.empty()) {
1681         // Don't give errors about ambiguities in this lookup.
1682         R.suppressDiagnostics();
1683 
1684         // During a default argument instantiation the CurContext points
1685         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1686         // function parameter list, hence add an explicit check.
1687         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1688                               ActiveTemplateInstantiations.back().Kind ==
1689             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1690         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1691         bool isInstance = CurMethod &&
1692                           CurMethod->isInstance() &&
1693                           DC == CurMethod->getParent() && !isDefaultArgument;
1694 
1695 
1696         // Give a code modification hint to insert 'this->'.
1697         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1698         // Actually quite difficult!
1699         if (getLangOpts().MicrosoftMode)
1700           diagnostic = diag::warn_found_via_dependent_bases_lookup;
1701         if (isInstance) {
1702           Diag(R.getNameLoc(), diagnostic) << Name
1703             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1704           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1705               CallsUndergoingInstantiation.back()->getCallee());
1706 
1707           CXXMethodDecl *DepMethod;
1708           if (CurMethod->isDependentContext())
1709             DepMethod = CurMethod;
1710           else if (CurMethod->getTemplatedKind() ==
1711               FunctionDecl::TK_FunctionTemplateSpecialization)
1712             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1713                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1714           else
1715             DepMethod = cast<CXXMethodDecl>(
1716                 CurMethod->getInstantiatedFromMemberFunction());
1717           assert(DepMethod && "No template pattern found");
1718 
1719           QualType DepThisType = DepMethod->getThisType(Context);
1720           CheckCXXThisCapture(R.getNameLoc());
1721           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1722                                      R.getNameLoc(), DepThisType, false);
1723           TemplateArgumentListInfo TList;
1724           if (ULE->hasExplicitTemplateArgs())
1725             ULE->copyTemplateArgumentsInto(TList);
1726 
1727           CXXScopeSpec SS;
1728           SS.Adopt(ULE->getQualifierLoc());
1729           CXXDependentScopeMemberExpr *DepExpr =
1730               CXXDependentScopeMemberExpr::Create(
1731                   Context, DepThis, DepThisType, true, SourceLocation(),
1732                   SS.getWithLocInContext(Context),
1733                   ULE->getTemplateKeywordLoc(), 0,
1734                   R.getLookupNameInfo(),
1735                   ULE->hasExplicitTemplateArgs() ? &TList : 0);
1736           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1737         } else {
1738           Diag(R.getNameLoc(), diagnostic) << Name;
1739         }
1740 
1741         // Do we really want to note all of these?
1742         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1743           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1744 
1745         // Return true if we are inside a default argument instantiation
1746         // and the found name refers to an instance member function, otherwise
1747         // the function calling DiagnoseEmptyLookup will try to create an
1748         // implicit member call and this is wrong for default argument.
1749         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1750           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1751           return true;
1752         }
1753 
1754         // Tell the callee to try to recover.
1755         return false;
1756       }
1757 
1758       R.clear();
1759     }
1760 
1761     // In Microsoft mode, if we are performing lookup from within a friend
1762     // function definition declared at class scope then we must set
1763     // DC to the lexical parent to be able to search into the parent
1764     // class.
1765     if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
1766         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1767         DC->getLexicalParent()->isRecord())
1768       DC = DC->getLexicalParent();
1769     else
1770       DC = DC->getParent();
1771   }
1772 
1773   // We didn't find anything, so try to correct for a typo.
1774   TypoCorrection Corrected;
1775   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1776                                     S, &SS, CCC))) {
1777     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1778     std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
1779     bool droppedSpecifier =
1780         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1781     R.setLookupName(Corrected.getCorrection());
1782 
1783     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
1784       if (Corrected.isOverloaded()) {
1785         OverloadCandidateSet OCS(R.getNameLoc());
1786         OverloadCandidateSet::iterator Best;
1787         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1788                                         CDEnd = Corrected.end();
1789              CD != CDEnd; ++CD) {
1790           if (FunctionTemplateDecl *FTD =
1791                    dyn_cast<FunctionTemplateDecl>(*CD))
1792             AddTemplateOverloadCandidate(
1793                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1794                 Args, OCS);
1795           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1796             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1797               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1798                                    Args, OCS);
1799         }
1800         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1801           case OR_Success:
1802             ND = Best->Function;
1803             break;
1804           default:
1805             break;
1806         }
1807       }
1808       R.addDecl(ND);
1809       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
1810         if (SS.isEmpty())
1811           Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1812             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1813         else
1814           Diag(R.getNameLoc(), diag::err_no_member_suggest)
1815             << Name << computeDeclContext(SS, false) << droppedSpecifier
1816             << CorrectedQuotedStr << SS.getRange()
1817             << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
1818                                             CorrectedStr);
1819 
1820         unsigned diag = isa<ImplicitParamDecl>(ND)
1821           ? diag::note_implicit_param_decl
1822           : diag::note_previous_decl;
1823 
1824         Diag(ND->getLocation(), diag)
1825           << CorrectedQuotedStr;
1826 
1827         // Tell the callee to try to recover.
1828         return false;
1829       }
1830 
1831       if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
1832         // FIXME: If we ended up with a typo for a type name or
1833         // Objective-C class name, we're in trouble because the parser
1834         // is in the wrong place to recover. Suggest the typo
1835         // correction, but don't make it a fix-it since we're not going
1836         // to recover well anyway.
1837         if (SS.isEmpty())
1838           Diag(R.getNameLoc(), diagnostic_suggest)
1839             << Name << CorrectedQuotedStr;
1840         else
1841           Diag(R.getNameLoc(), diag::err_no_member_suggest)
1842             << Name << computeDeclContext(SS, false) << droppedSpecifier
1843             << CorrectedQuotedStr << SS.getRange();
1844 
1845         // Don't try to recover; it won't work.
1846         return true;
1847       }
1848     } else {
1849       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1850       // because we aren't able to recover.
1851       if (SS.isEmpty())
1852         Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
1853       else
1854         Diag(R.getNameLoc(), diag::err_no_member_suggest)
1855           << Name << computeDeclContext(SS, false) << droppedSpecifier
1856           << CorrectedQuotedStr << SS.getRange();
1857       return true;
1858     }
1859   }
1860   R.clear();
1861 
1862   // Emit a special diagnostic for failed member lookups.
1863   // FIXME: computing the declaration context might fail here (?)
1864   if (!SS.isEmpty()) {
1865     Diag(R.getNameLoc(), diag::err_no_member)
1866       << Name << computeDeclContext(SS, false)
1867       << SS.getRange();
1868     return true;
1869   }
1870 
1871   // Give up, we can't recover.
1872   Diag(R.getNameLoc(), diagnostic) << Name;
1873   return true;
1874 }
1875 
1876 ExprResult Sema::ActOnIdExpression(Scope *S,
1877                                    CXXScopeSpec &SS,
1878                                    SourceLocation TemplateKWLoc,
1879                                    UnqualifiedId &Id,
1880                                    bool HasTrailingLParen,
1881                                    bool IsAddressOfOperand,
1882                                    CorrectionCandidateCallback *CCC,
1883                                    bool IsInlineAsmIdentifier) {
1884   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1885          "cannot be direct & operand and have a trailing lparen");
1886   if (SS.isInvalid())
1887     return ExprError();
1888 
1889   TemplateArgumentListInfo TemplateArgsBuffer;
1890 
1891   // Decompose the UnqualifiedId into the following data.
1892   DeclarationNameInfo NameInfo;
1893   const TemplateArgumentListInfo *TemplateArgs;
1894   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1895 
1896   DeclarationName Name = NameInfo.getName();
1897   IdentifierInfo *II = Name.getAsIdentifierInfo();
1898   SourceLocation NameLoc = NameInfo.getLoc();
1899 
1900   // C++ [temp.dep.expr]p3:
1901   //   An id-expression is type-dependent if it contains:
1902   //     -- an identifier that was declared with a dependent type,
1903   //        (note: handled after lookup)
1904   //     -- a template-id that is dependent,
1905   //        (note: handled in BuildTemplateIdExpr)
1906   //     -- a conversion-function-id that specifies a dependent type,
1907   //     -- a nested-name-specifier that contains a class-name that
1908   //        names a dependent type.
1909   // Determine whether this is a member of an unknown specialization;
1910   // we need to handle these differently.
1911   bool DependentID = false;
1912   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1913       Name.getCXXNameType()->isDependentType()) {
1914     DependentID = true;
1915   } else if (SS.isSet()) {
1916     if (DeclContext *DC = computeDeclContext(SS, false)) {
1917       if (RequireCompleteDeclContext(SS, DC))
1918         return ExprError();
1919     } else {
1920       DependentID = true;
1921     }
1922   }
1923 
1924   if (DependentID)
1925     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1926                                       IsAddressOfOperand, TemplateArgs);
1927 
1928   // Perform the required lookup.
1929   LookupResult R(*this, NameInfo,
1930                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1931                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1932   if (TemplateArgs) {
1933     // Lookup the template name again to correctly establish the context in
1934     // which it was found. This is really unfortunate as we already did the
1935     // lookup to determine that it was a template name in the first place. If
1936     // this becomes a performance hit, we can work harder to preserve those
1937     // results until we get here but it's likely not worth it.
1938     bool MemberOfUnknownSpecialization;
1939     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1940                        MemberOfUnknownSpecialization);
1941 
1942     if (MemberOfUnknownSpecialization ||
1943         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1944       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1945                                         IsAddressOfOperand, TemplateArgs);
1946   } else {
1947     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
1948     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1949 
1950     // If the result might be in a dependent base class, this is a dependent
1951     // id-expression.
1952     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1953       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1954                                         IsAddressOfOperand, TemplateArgs);
1955 
1956     // If this reference is in an Objective-C method, then we need to do
1957     // some special Objective-C lookup, too.
1958     if (IvarLookupFollowUp) {
1959       ExprResult E(LookupInObjCMethod(R, S, II, true));
1960       if (E.isInvalid())
1961         return ExprError();
1962 
1963       if (Expr *Ex = E.takeAs<Expr>())
1964         return Owned(Ex);
1965     }
1966   }
1967 
1968   if (R.isAmbiguous())
1969     return ExprError();
1970 
1971   // Determine whether this name might be a candidate for
1972   // argument-dependent lookup.
1973   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1974 
1975   if (R.empty() && !ADL) {
1976 
1977     // Otherwise, this could be an implicitly declared function reference (legal
1978     // in C90, extension in C99, forbidden in C++).
1979     if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
1980       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1981       if (D) R.addDecl(D);
1982     }
1983 
1984     // If this name wasn't predeclared and if this is not a function
1985     // call, diagnose the problem.
1986     if (R.empty()) {
1987       // In Microsoft mode, if we are inside a template class member function
1988       // whose parent class has dependent base classes, and we can't resolve
1989       // an identifier, then assume the identifier is type dependent.  The
1990       // goal is to postpone name lookup to instantiation time to be able to
1991       // search into the type dependent base classes.
1992       if (getLangOpts().MicrosoftMode) {
1993         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
1994         if (MD && MD->getParent()->hasAnyDependentBases())
1995           return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1996                                             IsAddressOfOperand, TemplateArgs);
1997       }
1998 
1999       // Don't diagnose an empty lookup for inline assmebly.
2000       if (IsInlineAsmIdentifier)
2001         return ExprError();
2002 
2003       CorrectionCandidateCallback DefaultValidator;
2004       if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
2005         return ExprError();
2006 
2007       assert(!R.empty() &&
2008              "DiagnoseEmptyLookup returned false but added no results");
2009 
2010       // If we found an Objective-C instance variable, let
2011       // LookupInObjCMethod build the appropriate expression to
2012       // reference the ivar.
2013       if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2014         R.clear();
2015         ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2016         // In a hopelessly buggy code, Objective-C instance variable
2017         // lookup fails and no expression will be built to reference it.
2018         if (!E.isInvalid() && !E.get())
2019           return ExprError();
2020         return E;
2021       }
2022     }
2023   }
2024 
2025   // This is guaranteed from this point on.
2026   assert(!R.empty() || ADL);
2027 
2028   // Check whether this might be a C++ implicit instance member access.
2029   // C++ [class.mfct.non-static]p3:
2030   //   When an id-expression that is not part of a class member access
2031   //   syntax and not used to form a pointer to member is used in the
2032   //   body of a non-static member function of class X, if name lookup
2033   //   resolves the name in the id-expression to a non-static non-type
2034   //   member of some class C, the id-expression is transformed into a
2035   //   class member access expression using (*this) as the
2036   //   postfix-expression to the left of the . operator.
2037   //
2038   // But we don't actually need to do this for '&' operands if R
2039   // resolved to a function or overloaded function set, because the
2040   // expression is ill-formed if it actually works out to be a
2041   // non-static member function:
2042   //
2043   // C++ [expr.ref]p4:
2044   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2045   //   [t]he expression can be used only as the left-hand operand of a
2046   //   member function call.
2047   //
2048   // There are other safeguards against such uses, but it's important
2049   // to get this right here so that we don't end up making a
2050   // spuriously dependent expression if we're inside a dependent
2051   // instance method.
2052   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2053     bool MightBeImplicitMember;
2054     if (!IsAddressOfOperand)
2055       MightBeImplicitMember = true;
2056     else if (!SS.isEmpty())
2057       MightBeImplicitMember = false;
2058     else if (R.isOverloadedResult())
2059       MightBeImplicitMember = false;
2060     else if (R.isUnresolvableResult())
2061       MightBeImplicitMember = true;
2062     else
2063       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2064                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2065                               isa<MSPropertyDecl>(R.getFoundDecl());
2066 
2067     if (MightBeImplicitMember)
2068       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2069                                              R, TemplateArgs);
2070   }
2071 
2072   if (TemplateArgs || TemplateKWLoc.isValid()) {
2073 
2074     // In C++1y, if this is a variable template id, then check it
2075     // in BuildTemplateIdExpr().
2076     // The single lookup result must be a variable template declaration.
2077     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2078         Id.TemplateId->Kind == TNK_Var_template) {
2079       assert(R.getAsSingle<VarTemplateDecl>() &&
2080              "There should only be one declaration found.");
2081     }
2082 
2083     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2084   }
2085 
2086   return BuildDeclarationNameExpr(SS, R, ADL);
2087 }
2088 
2089 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2090 /// declaration name, generally during template instantiation.
2091 /// There's a large number of things which don't need to be done along
2092 /// this path.
2093 ExprResult
2094 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2095                                         const DeclarationNameInfo &NameInfo,
2096                                         bool IsAddressOfOperand) {
2097   DeclContext *DC = computeDeclContext(SS, false);
2098   if (!DC)
2099     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2100                                      NameInfo, /*TemplateArgs=*/0);
2101 
2102   if (RequireCompleteDeclContext(SS, DC))
2103     return ExprError();
2104 
2105   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2106   LookupQualifiedName(R, DC);
2107 
2108   if (R.isAmbiguous())
2109     return ExprError();
2110 
2111   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2112     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2113                                      NameInfo, /*TemplateArgs=*/0);
2114 
2115   if (R.empty()) {
2116     Diag(NameInfo.getLoc(), diag::err_no_member)
2117       << NameInfo.getName() << DC << SS.getRange();
2118     return ExprError();
2119   }
2120 
2121   // Defend against this resolving to an implicit member access. We usually
2122   // won't get here if this might be a legitimate a class member (we end up in
2123   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2124   // a pointer-to-member or in an unevaluated context in C++11.
2125   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2126     return BuildPossibleImplicitMemberExpr(SS,
2127                                            /*TemplateKWLoc=*/SourceLocation(),
2128                                            R, /*TemplateArgs=*/0);
2129 
2130   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2131 }
2132 
2133 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2134 /// detected that we're currently inside an ObjC method.  Perform some
2135 /// additional lookup.
2136 ///
2137 /// Ideally, most of this would be done by lookup, but there's
2138 /// actually quite a lot of extra work involved.
2139 ///
2140 /// Returns a null sentinel to indicate trivial success.
2141 ExprResult
2142 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2143                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2144   SourceLocation Loc = Lookup.getNameLoc();
2145   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2146 
2147   // Check for error condition which is already reported.
2148   if (!CurMethod)
2149     return ExprError();
2150 
2151   // There are two cases to handle here.  1) scoped lookup could have failed,
2152   // in which case we should look for an ivar.  2) scoped lookup could have
2153   // found a decl, but that decl is outside the current instance method (i.e.
2154   // a global variable).  In these two cases, we do a lookup for an ivar with
2155   // this name, if the lookup sucedes, we replace it our current decl.
2156 
2157   // If we're in a class method, we don't normally want to look for
2158   // ivars.  But if we don't find anything else, and there's an
2159   // ivar, that's an error.
2160   bool IsClassMethod = CurMethod->isClassMethod();
2161 
2162   bool LookForIvars;
2163   if (Lookup.empty())
2164     LookForIvars = true;
2165   else if (IsClassMethod)
2166     LookForIvars = false;
2167   else
2168     LookForIvars = (Lookup.isSingleResult() &&
2169                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2170   ObjCInterfaceDecl *IFace = 0;
2171   if (LookForIvars) {
2172     IFace = CurMethod->getClassInterface();
2173     ObjCInterfaceDecl *ClassDeclared;
2174     ObjCIvarDecl *IV = 0;
2175     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2176       // Diagnose using an ivar in a class method.
2177       if (IsClassMethod)
2178         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2179                          << IV->getDeclName());
2180 
2181       // If we're referencing an invalid decl, just return this as a silent
2182       // error node.  The error diagnostic was already emitted on the decl.
2183       if (IV->isInvalidDecl())
2184         return ExprError();
2185 
2186       // Check if referencing a field with __attribute__((deprecated)).
2187       if (DiagnoseUseOfDecl(IV, Loc))
2188         return ExprError();
2189 
2190       // Diagnose the use of an ivar outside of the declaring class.
2191       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2192           !declaresSameEntity(ClassDeclared, IFace) &&
2193           !getLangOpts().DebuggerSupport)
2194         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2195 
2196       // FIXME: This should use a new expr for a direct reference, don't
2197       // turn this into Self->ivar, just return a BareIVarExpr or something.
2198       IdentifierInfo &II = Context.Idents.get("self");
2199       UnqualifiedId SelfName;
2200       SelfName.setIdentifier(&II, SourceLocation());
2201       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2202       CXXScopeSpec SelfScopeSpec;
2203       SourceLocation TemplateKWLoc;
2204       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2205                                               SelfName, false, false);
2206       if (SelfExpr.isInvalid())
2207         return ExprError();
2208 
2209       SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2210       if (SelfExpr.isInvalid())
2211         return ExprError();
2212 
2213       MarkAnyDeclReferenced(Loc, IV, true);
2214 
2215       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2216       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2217           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2218         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2219 
2220       ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2221                                                               Loc, IV->getLocation(),
2222                                                               SelfExpr.take(),
2223                                                               true, true);
2224 
2225       if (getLangOpts().ObjCAutoRefCount) {
2226         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2227           DiagnosticsEngine::Level Level =
2228             Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2229           if (Level != DiagnosticsEngine::Ignored)
2230             recordUseOfEvaluatedWeak(Result);
2231         }
2232         if (CurContext->isClosure())
2233           Diag(Loc, diag::warn_implicitly_retains_self)
2234             << FixItHint::CreateInsertion(Loc, "self->");
2235       }
2236 
2237       return Owned(Result);
2238     }
2239   } else if (CurMethod->isInstanceMethod()) {
2240     // We should warn if a local variable hides an ivar.
2241     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2242       ObjCInterfaceDecl *ClassDeclared;
2243       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2244         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2245             declaresSameEntity(IFace, ClassDeclared))
2246           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2247       }
2248     }
2249   } else if (Lookup.isSingleResult() &&
2250              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2251     // If accessing a stand-alone ivar in a class method, this is an error.
2252     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2253       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2254                        << IV->getDeclName());
2255   }
2256 
2257   if (Lookup.empty() && II && AllowBuiltinCreation) {
2258     // FIXME. Consolidate this with similar code in LookupName.
2259     if (unsigned BuiltinID = II->getBuiltinID()) {
2260       if (!(getLangOpts().CPlusPlus &&
2261             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2262         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2263                                            S, Lookup.isForRedeclaration(),
2264                                            Lookup.getNameLoc());
2265         if (D) Lookup.addDecl(D);
2266       }
2267     }
2268   }
2269   // Sentinel value saying that we didn't do anything special.
2270   return Owned((Expr*) 0);
2271 }
2272 
2273 /// \brief Cast a base object to a member's actual type.
2274 ///
2275 /// Logically this happens in three phases:
2276 ///
2277 /// * First we cast from the base type to the naming class.
2278 ///   The naming class is the class into which we were looking
2279 ///   when we found the member;  it's the qualifier type if a
2280 ///   qualifier was provided, and otherwise it's the base type.
2281 ///
2282 /// * Next we cast from the naming class to the declaring class.
2283 ///   If the member we found was brought into a class's scope by
2284 ///   a using declaration, this is that class;  otherwise it's
2285 ///   the class declaring the member.
2286 ///
2287 /// * Finally we cast from the declaring class to the "true"
2288 ///   declaring class of the member.  This conversion does not
2289 ///   obey access control.
2290 ExprResult
2291 Sema::PerformObjectMemberConversion(Expr *From,
2292                                     NestedNameSpecifier *Qualifier,
2293                                     NamedDecl *FoundDecl,
2294                                     NamedDecl *Member) {
2295   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2296   if (!RD)
2297     return Owned(From);
2298 
2299   QualType DestRecordType;
2300   QualType DestType;
2301   QualType FromRecordType;
2302   QualType FromType = From->getType();
2303   bool PointerConversions = false;
2304   if (isa<FieldDecl>(Member)) {
2305     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2306 
2307     if (FromType->getAs<PointerType>()) {
2308       DestType = Context.getPointerType(DestRecordType);
2309       FromRecordType = FromType->getPointeeType();
2310       PointerConversions = true;
2311     } else {
2312       DestType = DestRecordType;
2313       FromRecordType = FromType;
2314     }
2315   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2316     if (Method->isStatic())
2317       return Owned(From);
2318 
2319     DestType = Method->getThisType(Context);
2320     DestRecordType = DestType->getPointeeType();
2321 
2322     if (FromType->getAs<PointerType>()) {
2323       FromRecordType = FromType->getPointeeType();
2324       PointerConversions = true;
2325     } else {
2326       FromRecordType = FromType;
2327       DestType = DestRecordType;
2328     }
2329   } else {
2330     // No conversion necessary.
2331     return Owned(From);
2332   }
2333 
2334   if (DestType->isDependentType() || FromType->isDependentType())
2335     return Owned(From);
2336 
2337   // If the unqualified types are the same, no conversion is necessary.
2338   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2339     return Owned(From);
2340 
2341   SourceRange FromRange = From->getSourceRange();
2342   SourceLocation FromLoc = FromRange.getBegin();
2343 
2344   ExprValueKind VK = From->getValueKind();
2345 
2346   // C++ [class.member.lookup]p8:
2347   //   [...] Ambiguities can often be resolved by qualifying a name with its
2348   //   class name.
2349   //
2350   // If the member was a qualified name and the qualified referred to a
2351   // specific base subobject type, we'll cast to that intermediate type
2352   // first and then to the object in which the member is declared. That allows
2353   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2354   //
2355   //   class Base { public: int x; };
2356   //   class Derived1 : public Base { };
2357   //   class Derived2 : public Base { };
2358   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2359   //
2360   //   void VeryDerived::f() {
2361   //     x = 17; // error: ambiguous base subobjects
2362   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2363   //   }
2364   if (Qualifier && Qualifier->getAsType()) {
2365     QualType QType = QualType(Qualifier->getAsType(), 0);
2366     assert(QType->isRecordType() && "lookup done with non-record type");
2367 
2368     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2369 
2370     // In C++98, the qualifier type doesn't actually have to be a base
2371     // type of the object type, in which case we just ignore it.
2372     // Otherwise build the appropriate casts.
2373     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2374       CXXCastPath BasePath;
2375       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2376                                        FromLoc, FromRange, &BasePath))
2377         return ExprError();
2378 
2379       if (PointerConversions)
2380         QType = Context.getPointerType(QType);
2381       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2382                                VK, &BasePath).take();
2383 
2384       FromType = QType;
2385       FromRecordType = QRecordType;
2386 
2387       // If the qualifier type was the same as the destination type,
2388       // we're done.
2389       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2390         return Owned(From);
2391     }
2392   }
2393 
2394   bool IgnoreAccess = false;
2395 
2396   // If we actually found the member through a using declaration, cast
2397   // down to the using declaration's type.
2398   //
2399   // Pointer equality is fine here because only one declaration of a
2400   // class ever has member declarations.
2401   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2402     assert(isa<UsingShadowDecl>(FoundDecl));
2403     QualType URecordType = Context.getTypeDeclType(
2404                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2405 
2406     // We only need to do this if the naming-class to declaring-class
2407     // conversion is non-trivial.
2408     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2409       assert(IsDerivedFrom(FromRecordType, URecordType));
2410       CXXCastPath BasePath;
2411       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2412                                        FromLoc, FromRange, &BasePath))
2413         return ExprError();
2414 
2415       QualType UType = URecordType;
2416       if (PointerConversions)
2417         UType = Context.getPointerType(UType);
2418       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2419                                VK, &BasePath).take();
2420       FromType = UType;
2421       FromRecordType = URecordType;
2422     }
2423 
2424     // We don't do access control for the conversion from the
2425     // declaring class to the true declaring class.
2426     IgnoreAccess = true;
2427   }
2428 
2429   CXXCastPath BasePath;
2430   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2431                                    FromLoc, FromRange, &BasePath,
2432                                    IgnoreAccess))
2433     return ExprError();
2434 
2435   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2436                            VK, &BasePath);
2437 }
2438 
2439 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2440                                       const LookupResult &R,
2441                                       bool HasTrailingLParen) {
2442   // Only when used directly as the postfix-expression of a call.
2443   if (!HasTrailingLParen)
2444     return false;
2445 
2446   // Never if a scope specifier was provided.
2447   if (SS.isSet())
2448     return false;
2449 
2450   // Only in C++ or ObjC++.
2451   if (!getLangOpts().CPlusPlus)
2452     return false;
2453 
2454   // Turn off ADL when we find certain kinds of declarations during
2455   // normal lookup:
2456   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2457     NamedDecl *D = *I;
2458 
2459     // C++0x [basic.lookup.argdep]p3:
2460     //     -- a declaration of a class member
2461     // Since using decls preserve this property, we check this on the
2462     // original decl.
2463     if (D->isCXXClassMember())
2464       return false;
2465 
2466     // C++0x [basic.lookup.argdep]p3:
2467     //     -- a block-scope function declaration that is not a
2468     //        using-declaration
2469     // NOTE: we also trigger this for function templates (in fact, we
2470     // don't check the decl type at all, since all other decl types
2471     // turn off ADL anyway).
2472     if (isa<UsingShadowDecl>(D))
2473       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2474     else if (D->getDeclContext()->isFunctionOrMethod())
2475       return false;
2476 
2477     // C++0x [basic.lookup.argdep]p3:
2478     //     -- a declaration that is neither a function or a function
2479     //        template
2480     // And also for builtin functions.
2481     if (isa<FunctionDecl>(D)) {
2482       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2483 
2484       // But also builtin functions.
2485       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2486         return false;
2487     } else if (!isa<FunctionTemplateDecl>(D))
2488       return false;
2489   }
2490 
2491   return true;
2492 }
2493 
2494 
2495 /// Diagnoses obvious problems with the use of the given declaration
2496 /// as an expression.  This is only actually called for lookups that
2497 /// were not overloaded, and it doesn't promise that the declaration
2498 /// will in fact be used.
2499 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2500   if (isa<TypedefNameDecl>(D)) {
2501     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2502     return true;
2503   }
2504 
2505   if (isa<ObjCInterfaceDecl>(D)) {
2506     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2507     return true;
2508   }
2509 
2510   if (isa<NamespaceDecl>(D)) {
2511     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2512     return true;
2513   }
2514 
2515   return false;
2516 }
2517 
2518 ExprResult
2519 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2520                                LookupResult &R,
2521                                bool NeedsADL) {
2522   // If this is a single, fully-resolved result and we don't need ADL,
2523   // just build an ordinary singleton decl ref.
2524   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2525     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2526                                     R.getRepresentativeDecl());
2527 
2528   // We only need to check the declaration if there's exactly one
2529   // result, because in the overloaded case the results can only be
2530   // functions and function templates.
2531   if (R.isSingleResult() &&
2532       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2533     return ExprError();
2534 
2535   // Otherwise, just build an unresolved lookup expression.  Suppress
2536   // any lookup-related diagnostics; we'll hash these out later, when
2537   // we've picked a target.
2538   R.suppressDiagnostics();
2539 
2540   UnresolvedLookupExpr *ULE
2541     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2542                                    SS.getWithLocInContext(Context),
2543                                    R.getLookupNameInfo(),
2544                                    NeedsADL, R.isOverloadedResult(),
2545                                    R.begin(), R.end());
2546 
2547   return Owned(ULE);
2548 }
2549 
2550 /// \brief Complete semantic analysis for a reference to the given declaration.
2551 ExprResult Sema::BuildDeclarationNameExpr(
2552     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2553     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) {
2554   assert(D && "Cannot refer to a NULL declaration");
2555   assert(!isa<FunctionTemplateDecl>(D) &&
2556          "Cannot refer unambiguously to a function template");
2557 
2558   SourceLocation Loc = NameInfo.getLoc();
2559   if (CheckDeclInExpr(*this, Loc, D))
2560     return ExprError();
2561 
2562   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2563     // Specifically diagnose references to class templates that are missing
2564     // a template argument list.
2565     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2566                                            << Template << SS.getRange();
2567     Diag(Template->getLocation(), diag::note_template_decl_here);
2568     return ExprError();
2569   }
2570 
2571   // Make sure that we're referring to a value.
2572   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2573   if (!VD) {
2574     Diag(Loc, diag::err_ref_non_value)
2575       << D << SS.getRange();
2576     Diag(D->getLocation(), diag::note_declared_at);
2577     return ExprError();
2578   }
2579 
2580   // Check whether this declaration can be used. Note that we suppress
2581   // this check when we're going to perform argument-dependent lookup
2582   // on this function name, because this might not be the function
2583   // that overload resolution actually selects.
2584   if (DiagnoseUseOfDecl(VD, Loc))
2585     return ExprError();
2586 
2587   // Only create DeclRefExpr's for valid Decl's.
2588   if (VD->isInvalidDecl())
2589     return ExprError();
2590 
2591   // Handle members of anonymous structs and unions.  If we got here,
2592   // and the reference is to a class member indirect field, then this
2593   // must be the subject of a pointer-to-member expression.
2594   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2595     if (!indirectField->isCXXClassMember())
2596       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2597                                                       indirectField);
2598 
2599   {
2600     QualType type = VD->getType();
2601     ExprValueKind valueKind = VK_RValue;
2602 
2603     switch (D->getKind()) {
2604     // Ignore all the non-ValueDecl kinds.
2605 #define ABSTRACT_DECL(kind)
2606 #define VALUE(type, base)
2607 #define DECL(type, base) \
2608     case Decl::type:
2609 #include "clang/AST/DeclNodes.inc"
2610       llvm_unreachable("invalid value decl kind");
2611 
2612     // These shouldn't make it here.
2613     case Decl::ObjCAtDefsField:
2614     case Decl::ObjCIvar:
2615       llvm_unreachable("forming non-member reference to ivar?");
2616 
2617     // Enum constants are always r-values and never references.
2618     // Unresolved using declarations are dependent.
2619     case Decl::EnumConstant:
2620     case Decl::UnresolvedUsingValue:
2621       valueKind = VK_RValue;
2622       break;
2623 
2624     // Fields and indirect fields that got here must be for
2625     // pointer-to-member expressions; we just call them l-values for
2626     // internal consistency, because this subexpression doesn't really
2627     // exist in the high-level semantics.
2628     case Decl::Field:
2629     case Decl::IndirectField:
2630       assert(getLangOpts().CPlusPlus &&
2631              "building reference to field in C?");
2632 
2633       // These can't have reference type in well-formed programs, but
2634       // for internal consistency we do this anyway.
2635       type = type.getNonReferenceType();
2636       valueKind = VK_LValue;
2637       break;
2638 
2639     // Non-type template parameters are either l-values or r-values
2640     // depending on the type.
2641     case Decl::NonTypeTemplateParm: {
2642       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2643         type = reftype->getPointeeType();
2644         valueKind = VK_LValue; // even if the parameter is an r-value reference
2645         break;
2646       }
2647 
2648       // For non-references, we need to strip qualifiers just in case
2649       // the template parameter was declared as 'const int' or whatever.
2650       valueKind = VK_RValue;
2651       type = type.getUnqualifiedType();
2652       break;
2653     }
2654 
2655     case Decl::Var:
2656     case Decl::VarTemplateSpecialization:
2657     case Decl::VarTemplatePartialSpecialization:
2658       // In C, "extern void blah;" is valid and is an r-value.
2659       if (!getLangOpts().CPlusPlus &&
2660           !type.hasQualifiers() &&
2661           type->isVoidType()) {
2662         valueKind = VK_RValue;
2663         break;
2664       }
2665       // fallthrough
2666 
2667     case Decl::ImplicitParam:
2668     case Decl::ParmVar: {
2669       // These are always l-values.
2670       valueKind = VK_LValue;
2671       type = type.getNonReferenceType();
2672 
2673       // FIXME: Does the addition of const really only apply in
2674       // potentially-evaluated contexts? Since the variable isn't actually
2675       // captured in an unevaluated context, it seems that the answer is no.
2676       if (!isUnevaluatedContext()) {
2677         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2678         if (!CapturedType.isNull())
2679           type = CapturedType;
2680       }
2681 
2682       break;
2683     }
2684 
2685     case Decl::Function: {
2686       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2687         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2688           type = Context.BuiltinFnTy;
2689           valueKind = VK_RValue;
2690           break;
2691         }
2692       }
2693 
2694       const FunctionType *fty = type->castAs<FunctionType>();
2695 
2696       // If we're referring to a function with an __unknown_anytype
2697       // result type, make the entire expression __unknown_anytype.
2698       if (fty->getResultType() == Context.UnknownAnyTy) {
2699         type = Context.UnknownAnyTy;
2700         valueKind = VK_RValue;
2701         break;
2702       }
2703 
2704       // Functions are l-values in C++.
2705       if (getLangOpts().CPlusPlus) {
2706         valueKind = VK_LValue;
2707         break;
2708       }
2709 
2710       // C99 DR 316 says that, if a function type comes from a
2711       // function definition (without a prototype), that type is only
2712       // used for checking compatibility. Therefore, when referencing
2713       // the function, we pretend that we don't have the full function
2714       // type.
2715       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2716           isa<FunctionProtoType>(fty))
2717         type = Context.getFunctionNoProtoType(fty->getResultType(),
2718                                               fty->getExtInfo());
2719 
2720       // Functions are r-values in C.
2721       valueKind = VK_RValue;
2722       break;
2723     }
2724 
2725     case Decl::MSProperty:
2726       valueKind = VK_LValue;
2727       break;
2728 
2729     case Decl::CXXMethod:
2730       // If we're referring to a method with an __unknown_anytype
2731       // result type, make the entire expression __unknown_anytype.
2732       // This should only be possible with a type written directly.
2733       if (const FunctionProtoType *proto
2734             = dyn_cast<FunctionProtoType>(VD->getType()))
2735         if (proto->getResultType() == Context.UnknownAnyTy) {
2736           type = Context.UnknownAnyTy;
2737           valueKind = VK_RValue;
2738           break;
2739         }
2740 
2741       // C++ methods are l-values if static, r-values if non-static.
2742       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2743         valueKind = VK_LValue;
2744         break;
2745       }
2746       // fallthrough
2747 
2748     case Decl::CXXConversion:
2749     case Decl::CXXDestructor:
2750     case Decl::CXXConstructor:
2751       valueKind = VK_RValue;
2752       break;
2753     }
2754 
2755     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2756                             TemplateArgs);
2757   }
2758 }
2759 
2760 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2761   PredefinedExpr::IdentType IT;
2762 
2763   switch (Kind) {
2764   default: llvm_unreachable("Unknown simple primary expr!");
2765   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2766   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2767   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2768   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2769   }
2770 
2771   // Pre-defined identifiers are of type char[x], where x is the length of the
2772   // string.
2773 
2774   Decl *currentDecl = getCurFunctionOrMethodDecl();
2775   // Blocks and lambdas can occur at global scope. Don't emit a warning.
2776   if (!currentDecl) {
2777     if (const BlockScopeInfo *BSI = getCurBlock())
2778       currentDecl = BSI->TheDecl;
2779     else if (const LambdaScopeInfo *LSI = getCurLambda())
2780       currentDecl = LSI->CallOperator;
2781   }
2782 
2783   if (!currentDecl) {
2784     Diag(Loc, diag::ext_predef_outside_function);
2785     currentDecl = Context.getTranslationUnitDecl();
2786   }
2787 
2788   QualType ResTy;
2789   if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2790     ResTy = Context.DependentTy;
2791   } else {
2792     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2793 
2794     llvm::APInt LengthI(32, Length + 1);
2795     if (IT == PredefinedExpr::LFunction)
2796       ResTy = Context.WideCharTy.withConst();
2797     else
2798       ResTy = Context.CharTy.withConst();
2799     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2800   }
2801   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2802 }
2803 
2804 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2805   SmallString<16> CharBuffer;
2806   bool Invalid = false;
2807   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2808   if (Invalid)
2809     return ExprError();
2810 
2811   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2812                             PP, Tok.getKind());
2813   if (Literal.hadError())
2814     return ExprError();
2815 
2816   QualType Ty;
2817   if (Literal.isWide())
2818     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
2819   else if (Literal.isUTF16())
2820     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2821   else if (Literal.isUTF32())
2822     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2823   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2824     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2825   else
2826     Ty = Context.CharTy;  // 'x' -> char in C++
2827 
2828   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2829   if (Literal.isWide())
2830     Kind = CharacterLiteral::Wide;
2831   else if (Literal.isUTF16())
2832     Kind = CharacterLiteral::UTF16;
2833   else if (Literal.isUTF32())
2834     Kind = CharacterLiteral::UTF32;
2835 
2836   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2837                                              Tok.getLocation());
2838 
2839   if (Literal.getUDSuffix().empty())
2840     return Owned(Lit);
2841 
2842   // We're building a user-defined literal.
2843   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2844   SourceLocation UDSuffixLoc =
2845     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2846 
2847   // Make sure we're allowed user-defined literals here.
2848   if (!UDLScope)
2849     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2850 
2851   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2852   //   operator "" X (ch)
2853   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2854                                         Lit, Tok.getLocation());
2855 }
2856 
2857 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2858   unsigned IntSize = Context.getTargetInfo().getIntWidth();
2859   return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2860                                       Context.IntTy, Loc));
2861 }
2862 
2863 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2864                                   QualType Ty, SourceLocation Loc) {
2865   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2866 
2867   using llvm::APFloat;
2868   APFloat Val(Format);
2869 
2870   APFloat::opStatus result = Literal.GetFloatValue(Val);
2871 
2872   // Overflow is always an error, but underflow is only an error if
2873   // we underflowed to zero (APFloat reports denormals as underflow).
2874   if ((result & APFloat::opOverflow) ||
2875       ((result & APFloat::opUnderflow) && Val.isZero())) {
2876     unsigned diagnostic;
2877     SmallString<20> buffer;
2878     if (result & APFloat::opOverflow) {
2879       diagnostic = diag::warn_float_overflow;
2880       APFloat::getLargest(Format).toString(buffer);
2881     } else {
2882       diagnostic = diag::warn_float_underflow;
2883       APFloat::getSmallest(Format).toString(buffer);
2884     }
2885 
2886     S.Diag(Loc, diagnostic)
2887       << Ty
2888       << StringRef(buffer.data(), buffer.size());
2889   }
2890 
2891   bool isExact = (result == APFloat::opOK);
2892   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2893 }
2894 
2895 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
2896   // Fast path for a single digit (which is quite common).  A single digit
2897   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
2898   if (Tok.getLength() == 1) {
2899     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2900     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
2901   }
2902 
2903   SmallString<128> SpellingBuffer;
2904   // NumericLiteralParser wants to overread by one character.  Add padding to
2905   // the buffer in case the token is copied to the buffer.  If getSpelling()
2906   // returns a StringRef to the memory buffer, it should have a null char at
2907   // the EOF, so it is also safe.
2908   SpellingBuffer.resize(Tok.getLength() + 1);
2909 
2910   // Get the spelling of the token, which eliminates trigraphs, etc.
2911   bool Invalid = false;
2912   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
2913   if (Invalid)
2914     return ExprError();
2915 
2916   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
2917   if (Literal.hadError)
2918     return ExprError();
2919 
2920   if (Literal.hasUDSuffix()) {
2921     // We're building a user-defined literal.
2922     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2923     SourceLocation UDSuffixLoc =
2924       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2925 
2926     // Make sure we're allowed user-defined literals here.
2927     if (!UDLScope)
2928       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
2929 
2930     QualType CookedTy;
2931     if (Literal.isFloatingLiteral()) {
2932       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2933       // long double, the literal is treated as a call of the form
2934       //   operator "" X (f L)
2935       CookedTy = Context.LongDoubleTy;
2936     } else {
2937       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2938       // unsigned long long, the literal is treated as a call of the form
2939       //   operator "" X (n ULL)
2940       CookedTy = Context.UnsignedLongLongTy;
2941     }
2942 
2943     DeclarationName OpName =
2944       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2945     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2946     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2947 
2948     // Perform literal operator lookup to determine if we're building a raw
2949     // literal or a cooked one.
2950     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2951     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
2952                                   /*AllowRawAndTemplate*/true)) {
2953     case LOLR_Error:
2954       return ExprError();
2955 
2956     case LOLR_Cooked: {
2957       Expr *Lit;
2958       if (Literal.isFloatingLiteral()) {
2959         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2960       } else {
2961         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2962         if (Literal.GetIntegerValue(ResultVal))
2963           Diag(Tok.getLocation(), diag::err_integer_too_large);
2964         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2965                                      Tok.getLocation());
2966       }
2967       return BuildLiteralOperatorCall(R, OpNameInfo, Lit,
2968                                       Tok.getLocation());
2969     }
2970 
2971     case LOLR_Raw: {
2972       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2973       // literal is treated as a call of the form
2974       //   operator "" X ("n")
2975       SourceLocation TokLoc = Tok.getLocation();
2976       unsigned Length = Literal.getUDSuffixOffset();
2977       QualType StrTy = Context.getConstantArrayType(
2978           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
2979           ArrayType::Normal, 0);
2980       Expr *Lit = StringLiteral::Create(
2981           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
2982           /*Pascal*/false, StrTy, &TokLoc, 1);
2983       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
2984     }
2985 
2986     case LOLR_Template:
2987       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2988       // template), L is treated as a call fo the form
2989       //   operator "" X <'c1', 'c2', ... 'ck'>()
2990       // where n is the source character sequence c1 c2 ... ck.
2991       TemplateArgumentListInfo ExplicitArgs;
2992       unsigned CharBits = Context.getIntWidth(Context.CharTy);
2993       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2994       llvm::APSInt Value(CharBits, CharIsUnsigned);
2995       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2996         Value = TokSpelling[I];
2997         TemplateArgument Arg(Context, Value, Context.CharTy);
2998         TemplateArgumentLocInfo ArgInfo;
2999         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3000       }
3001       return BuildLiteralOperatorCall(R, OpNameInfo, None, Tok.getLocation(),
3002                                       &ExplicitArgs);
3003     }
3004 
3005     llvm_unreachable("unexpected literal operator lookup result");
3006   }
3007 
3008   Expr *Res;
3009 
3010   if (Literal.isFloatingLiteral()) {
3011     QualType Ty;
3012     if (Literal.isFloat)
3013       Ty = Context.FloatTy;
3014     else if (!Literal.isLong)
3015       Ty = Context.DoubleTy;
3016     else
3017       Ty = Context.LongDoubleTy;
3018 
3019     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3020 
3021     if (Ty == Context.DoubleTy) {
3022       if (getLangOpts().SinglePrecisionConstants) {
3023         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
3024       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
3025         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3026         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
3027       }
3028     }
3029   } else if (!Literal.isIntegerLiteral()) {
3030     return ExprError();
3031   } else {
3032     QualType Ty;
3033 
3034     // 'long long' is a C99 or C++11 feature.
3035     if (!getLangOpts().C99 && Literal.isLongLong) {
3036       if (getLangOpts().CPlusPlus)
3037         Diag(Tok.getLocation(),
3038              getLangOpts().CPlusPlus11 ?
3039              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3040       else
3041         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3042     }
3043 
3044     // Get the value in the widest-possible width.
3045     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3046     // The microsoft literal suffix extensions support 128-bit literals, which
3047     // may be wider than [u]intmax_t.
3048     // FIXME: Actually, they don't. We seem to have accidentally invented the
3049     //        i128 suffix.
3050     if (Literal.isMicrosoftInteger && MaxWidth < 128 &&
3051         PP.getTargetInfo().hasInt128Type())
3052       MaxWidth = 128;
3053     llvm::APInt ResultVal(MaxWidth, 0);
3054 
3055     if (Literal.GetIntegerValue(ResultVal)) {
3056       // If this value didn't fit into uintmax_t, error and force to ull.
3057       Diag(Tok.getLocation(), diag::err_integer_too_large);
3058       Ty = Context.UnsignedLongLongTy;
3059       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3060              "long long is not intmax_t?");
3061     } else {
3062       // If this value fits into a ULL, try to figure out what else it fits into
3063       // according to the rules of C99 6.4.4.1p5.
3064 
3065       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3066       // be an unsigned int.
3067       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3068 
3069       // Check from smallest to largest, picking the smallest type we can.
3070       unsigned Width = 0;
3071       if (!Literal.isLong && !Literal.isLongLong) {
3072         // Are int/unsigned possibilities?
3073         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3074 
3075         // Does it fit in a unsigned int?
3076         if (ResultVal.isIntN(IntSize)) {
3077           // Does it fit in a signed int?
3078           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3079             Ty = Context.IntTy;
3080           else if (AllowUnsigned)
3081             Ty = Context.UnsignedIntTy;
3082           Width = IntSize;
3083         }
3084       }
3085 
3086       // Are long/unsigned long possibilities?
3087       if (Ty.isNull() && !Literal.isLongLong) {
3088         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3089 
3090         // Does it fit in a unsigned long?
3091         if (ResultVal.isIntN(LongSize)) {
3092           // Does it fit in a signed long?
3093           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3094             Ty = Context.LongTy;
3095           else if (AllowUnsigned)
3096             Ty = Context.UnsignedLongTy;
3097           Width = LongSize;
3098         }
3099       }
3100 
3101       // Check long long if needed.
3102       if (Ty.isNull()) {
3103         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3104 
3105         // Does it fit in a unsigned long long?
3106         if (ResultVal.isIntN(LongLongSize)) {
3107           // Does it fit in a signed long long?
3108           // To be compatible with MSVC, hex integer literals ending with the
3109           // LL or i64 suffix are always signed in Microsoft mode.
3110           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3111               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3112             Ty = Context.LongLongTy;
3113           else if (AllowUnsigned)
3114             Ty = Context.UnsignedLongLongTy;
3115           Width = LongLongSize;
3116         }
3117       }
3118 
3119       // If it doesn't fit in unsigned long long, and we're using Microsoft
3120       // extensions, then its a 128-bit integer literal.
3121       if (Ty.isNull() && Literal.isMicrosoftInteger &&
3122           PP.getTargetInfo().hasInt128Type()) {
3123         if (Literal.isUnsigned)
3124           Ty = Context.UnsignedInt128Ty;
3125         else
3126           Ty = Context.Int128Ty;
3127         Width = 128;
3128       }
3129 
3130       // If we still couldn't decide a type, we probably have something that
3131       // does not fit in a signed long long, but has no U suffix.
3132       if (Ty.isNull()) {
3133         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
3134         Ty = Context.UnsignedLongLongTy;
3135         Width = Context.getTargetInfo().getLongLongWidth();
3136       }
3137 
3138       if (ResultVal.getBitWidth() != Width)
3139         ResultVal = ResultVal.trunc(Width);
3140     }
3141     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3142   }
3143 
3144   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3145   if (Literal.isImaginary)
3146     Res = new (Context) ImaginaryLiteral(Res,
3147                                         Context.getComplexType(Res->getType()));
3148 
3149   return Owned(Res);
3150 }
3151 
3152 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3153   assert((E != 0) && "ActOnParenExpr() missing expr");
3154   return Owned(new (Context) ParenExpr(L, R, E));
3155 }
3156 
3157 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3158                                          SourceLocation Loc,
3159                                          SourceRange ArgRange) {
3160   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3161   // scalar or vector data type argument..."
3162   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3163   // type (C99 6.2.5p18) or void.
3164   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3165     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3166       << T << ArgRange;
3167     return true;
3168   }
3169 
3170   assert((T->isVoidType() || !T->isIncompleteType()) &&
3171          "Scalar types should always be complete");
3172   return false;
3173 }
3174 
3175 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3176                                            SourceLocation Loc,
3177                                            SourceRange ArgRange,
3178                                            UnaryExprOrTypeTrait TraitKind) {
3179   // C99 6.5.3.4p1:
3180   if (T->isFunctionType() &&
3181       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3182     // sizeof(function)/alignof(function) is allowed as an extension.
3183     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3184       << TraitKind << ArgRange;
3185     return false;
3186   }
3187 
3188   // Allow sizeof(void)/alignof(void) as an extension.
3189   if (T->isVoidType()) {
3190     S.Diag(Loc, diag::ext_sizeof_alignof_void_type) << TraitKind << ArgRange;
3191     return false;
3192   }
3193 
3194   return true;
3195 }
3196 
3197 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3198                                              SourceLocation Loc,
3199                                              SourceRange ArgRange,
3200                                              UnaryExprOrTypeTrait TraitKind) {
3201   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3202   // runtime doesn't allow it.
3203   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3204     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3205       << T << (TraitKind == UETT_SizeOf)
3206       << ArgRange;
3207     return true;
3208   }
3209 
3210   return false;
3211 }
3212 
3213 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3214 /// pointer type is equal to T) and emit a warning if it is.
3215 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3216                                      Expr *E) {
3217   // Don't warn if the operation changed the type.
3218   if (T != E->getType())
3219     return;
3220 
3221   // Now look for array decays.
3222   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3223   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3224     return;
3225 
3226   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3227                                              << ICE->getType()
3228                                              << ICE->getSubExpr()->getType();
3229 }
3230 
3231 /// \brief Check the constrains on expression operands to unary type expression
3232 /// and type traits.
3233 ///
3234 /// Completes any types necessary and validates the constraints on the operand
3235 /// expression. The logic mostly mirrors the type-based overload, but may modify
3236 /// the expression as it completes the type for that expression through template
3237 /// instantiation, etc.
3238 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3239                                             UnaryExprOrTypeTrait ExprKind) {
3240   QualType ExprTy = E->getType();
3241   assert(!ExprTy->isReferenceType());
3242 
3243   if (ExprKind == UETT_VecStep)
3244     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3245                                         E->getSourceRange());
3246 
3247   // Whitelist some types as extensions
3248   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3249                                       E->getSourceRange(), ExprKind))
3250     return false;
3251 
3252   if (RequireCompleteExprType(E,
3253                               diag::err_sizeof_alignof_incomplete_type,
3254                               ExprKind, E->getSourceRange()))
3255     return true;
3256 
3257   // Completing the expression's type may have changed it.
3258   ExprTy = E->getType();
3259   assert(!ExprTy->isReferenceType());
3260 
3261   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3262                                        E->getSourceRange(), ExprKind))
3263     return true;
3264 
3265   if (ExprKind == UETT_SizeOf) {
3266     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3267       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3268         QualType OType = PVD->getOriginalType();
3269         QualType Type = PVD->getType();
3270         if (Type->isPointerType() && OType->isArrayType()) {
3271           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3272             << Type << OType;
3273           Diag(PVD->getLocation(), diag::note_declared_at);
3274         }
3275       }
3276     }
3277 
3278     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3279     // decays into a pointer and returns an unintended result. This is most
3280     // likely a typo for "sizeof(array) op x".
3281     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3282       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3283                                BO->getLHS());
3284       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3285                                BO->getRHS());
3286     }
3287   }
3288 
3289   return false;
3290 }
3291 
3292 /// \brief Check the constraints on operands to unary expression and type
3293 /// traits.
3294 ///
3295 /// This will complete any types necessary, and validate the various constraints
3296 /// on those operands.
3297 ///
3298 /// The UsualUnaryConversions() function is *not* called by this routine.
3299 /// C99 6.3.2.1p[2-4] all state:
3300 ///   Except when it is the operand of the sizeof operator ...
3301 ///
3302 /// C++ [expr.sizeof]p4
3303 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3304 ///   standard conversions are not applied to the operand of sizeof.
3305 ///
3306 /// This policy is followed for all of the unary trait expressions.
3307 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3308                                             SourceLocation OpLoc,
3309                                             SourceRange ExprRange,
3310                                             UnaryExprOrTypeTrait ExprKind) {
3311   if (ExprType->isDependentType())
3312     return false;
3313 
3314   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3315   //   the result is the size of the referenced type."
3316   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3317   //   result shall be the alignment of the referenced type."
3318   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3319     ExprType = Ref->getPointeeType();
3320 
3321   if (ExprKind == UETT_VecStep)
3322     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3323 
3324   // Whitelist some types as extensions
3325   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3326                                       ExprKind))
3327     return false;
3328 
3329   if (RequireCompleteType(OpLoc, ExprType,
3330                           diag::err_sizeof_alignof_incomplete_type,
3331                           ExprKind, ExprRange))
3332     return true;
3333 
3334   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3335                                        ExprKind))
3336     return true;
3337 
3338   return false;
3339 }
3340 
3341 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3342   E = E->IgnoreParens();
3343 
3344   // Cannot know anything else if the expression is dependent.
3345   if (E->isTypeDependent())
3346     return false;
3347 
3348   if (E->getObjectKind() == OK_BitField) {
3349     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3350        << 1 << E->getSourceRange();
3351     return true;
3352   }
3353 
3354   ValueDecl *D = 0;
3355   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3356     D = DRE->getDecl();
3357   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3358     D = ME->getMemberDecl();
3359   }
3360 
3361   // If it's a field, require the containing struct to have a
3362   // complete definition so that we can compute the layout.
3363   //
3364   // This requires a very particular set of circumstances.  For a
3365   // field to be contained within an incomplete type, we must in the
3366   // process of parsing that type.  To have an expression refer to a
3367   // field, it must be an id-expression or a member-expression, but
3368   // the latter are always ill-formed when the base type is
3369   // incomplete, including only being partially complete.  An
3370   // id-expression can never refer to a field in C because fields
3371   // are not in the ordinary namespace.  In C++, an id-expression
3372   // can implicitly be a member access, but only if there's an
3373   // implicit 'this' value, and all such contexts are subject to
3374   // delayed parsing --- except for trailing return types in C++11.
3375   // And if an id-expression referring to a field occurs in a
3376   // context that lacks a 'this' value, it's ill-formed --- except,
3377   // agian, in C++11, where such references are allowed in an
3378   // unevaluated context.  So C++11 introduces some new complexity.
3379   //
3380   // For the record, since __alignof__ on expressions is a GCC
3381   // extension, GCC seems to permit this but always gives the
3382   // nonsensical answer 0.
3383   //
3384   // We don't really need the layout here --- we could instead just
3385   // directly check for all the appropriate alignment-lowing
3386   // attributes --- but that would require duplicating a lot of
3387   // logic that just isn't worth duplicating for such a marginal
3388   // use-case.
3389   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3390     // Fast path this check, since we at least know the record has a
3391     // definition if we can find a member of it.
3392     if (!FD->getParent()->isCompleteDefinition()) {
3393       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3394         << E->getSourceRange();
3395       return true;
3396     }
3397 
3398     // Otherwise, if it's a field, and the field doesn't have
3399     // reference type, then it must have a complete type (or be a
3400     // flexible array member, which we explicitly want to
3401     // white-list anyway), which makes the following checks trivial.
3402     if (!FD->getType()->isReferenceType())
3403       return false;
3404   }
3405 
3406   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3407 }
3408 
3409 bool Sema::CheckVecStepExpr(Expr *E) {
3410   E = E->IgnoreParens();
3411 
3412   // Cannot know anything else if the expression is dependent.
3413   if (E->isTypeDependent())
3414     return false;
3415 
3416   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3417 }
3418 
3419 /// \brief Build a sizeof or alignof expression given a type operand.
3420 ExprResult
3421 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3422                                      SourceLocation OpLoc,
3423                                      UnaryExprOrTypeTrait ExprKind,
3424                                      SourceRange R) {
3425   if (!TInfo)
3426     return ExprError();
3427 
3428   QualType T = TInfo->getType();
3429 
3430   if (!T->isDependentType() &&
3431       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3432     return ExprError();
3433 
3434   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3435   return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3436                                                       Context.getSizeType(),
3437                                                       OpLoc, R.getEnd()));
3438 }
3439 
3440 /// \brief Build a sizeof or alignof expression given an expression
3441 /// operand.
3442 ExprResult
3443 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3444                                      UnaryExprOrTypeTrait ExprKind) {
3445   ExprResult PE = CheckPlaceholderExpr(E);
3446   if (PE.isInvalid())
3447     return ExprError();
3448 
3449   E = PE.get();
3450 
3451   // Verify that the operand is valid.
3452   bool isInvalid = false;
3453   if (E->isTypeDependent()) {
3454     // Delay type-checking for type-dependent expressions.
3455   } else if (ExprKind == UETT_AlignOf) {
3456     isInvalid = CheckAlignOfExpr(*this, E);
3457   } else if (ExprKind == UETT_VecStep) {
3458     isInvalid = CheckVecStepExpr(E);
3459   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3460     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3461     isInvalid = true;
3462   } else {
3463     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3464   }
3465 
3466   if (isInvalid)
3467     return ExprError();
3468 
3469   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3470     PE = TransformToPotentiallyEvaluated(E);
3471     if (PE.isInvalid()) return ExprError();
3472     E = PE.take();
3473   }
3474 
3475   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3476   return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3477       ExprKind, E, Context.getSizeType(), OpLoc,
3478       E->getSourceRange().getEnd()));
3479 }
3480 
3481 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3482 /// expr and the same for @c alignof and @c __alignof
3483 /// Note that the ArgRange is invalid if isType is false.
3484 ExprResult
3485 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3486                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3487                                     void *TyOrEx, const SourceRange &ArgRange) {
3488   // If error parsing type, ignore.
3489   if (TyOrEx == 0) return ExprError();
3490 
3491   if (IsType) {
3492     TypeSourceInfo *TInfo;
3493     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3494     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3495   }
3496 
3497   Expr *ArgEx = (Expr *)TyOrEx;
3498   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3499   return Result;
3500 }
3501 
3502 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3503                                      bool IsReal) {
3504   if (V.get()->isTypeDependent())
3505     return S.Context.DependentTy;
3506 
3507   // _Real and _Imag are only l-values for normal l-values.
3508   if (V.get()->getObjectKind() != OK_Ordinary) {
3509     V = S.DefaultLvalueConversion(V.take());
3510     if (V.isInvalid())
3511       return QualType();
3512   }
3513 
3514   // These operators return the element type of a complex type.
3515   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3516     return CT->getElementType();
3517 
3518   // Otherwise they pass through real integer and floating point types here.
3519   if (V.get()->getType()->isArithmeticType())
3520     return V.get()->getType();
3521 
3522   // Test for placeholders.
3523   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3524   if (PR.isInvalid()) return QualType();
3525   if (PR.get() != V.get()) {
3526     V = PR;
3527     return CheckRealImagOperand(S, V, Loc, IsReal);
3528   }
3529 
3530   // Reject anything else.
3531   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3532     << (IsReal ? "__real" : "__imag");
3533   return QualType();
3534 }
3535 
3536 
3537 
3538 ExprResult
3539 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3540                           tok::TokenKind Kind, Expr *Input) {
3541   UnaryOperatorKind Opc;
3542   switch (Kind) {
3543   default: llvm_unreachable("Unknown unary op!");
3544   case tok::plusplus:   Opc = UO_PostInc; break;
3545   case tok::minusminus: Opc = UO_PostDec; break;
3546   }
3547 
3548   // Since this might is a postfix expression, get rid of ParenListExprs.
3549   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3550   if (Result.isInvalid()) return ExprError();
3551   Input = Result.take();
3552 
3553   return BuildUnaryOp(S, OpLoc, Opc, Input);
3554 }
3555 
3556 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3557 ///
3558 /// \return true on error
3559 static bool checkArithmeticOnObjCPointer(Sema &S,
3560                                          SourceLocation opLoc,
3561                                          Expr *op) {
3562   assert(op->getType()->isObjCObjectPointerType());
3563   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3564     return false;
3565 
3566   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3567     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3568     << op->getSourceRange();
3569   return true;
3570 }
3571 
3572 ExprResult
3573 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3574                               Expr *idx, SourceLocation rbLoc) {
3575   // Since this might be a postfix expression, get rid of ParenListExprs.
3576   if (isa<ParenListExpr>(base)) {
3577     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3578     if (result.isInvalid()) return ExprError();
3579     base = result.take();
3580   }
3581 
3582   // Handle any non-overload placeholder types in the base and index
3583   // expressions.  We can't handle overloads here because the other
3584   // operand might be an overloadable type, in which case the overload
3585   // resolution for the operator overload should get the first crack
3586   // at the overload.
3587   if (base->getType()->isNonOverloadPlaceholderType()) {
3588     ExprResult result = CheckPlaceholderExpr(base);
3589     if (result.isInvalid()) return ExprError();
3590     base = result.take();
3591   }
3592   if (idx->getType()->isNonOverloadPlaceholderType()) {
3593     ExprResult result = CheckPlaceholderExpr(idx);
3594     if (result.isInvalid()) return ExprError();
3595     idx = result.take();
3596   }
3597 
3598   // Build an unanalyzed expression if either operand is type-dependent.
3599   if (getLangOpts().CPlusPlus &&
3600       (base->isTypeDependent() || idx->isTypeDependent())) {
3601     return Owned(new (Context) ArraySubscriptExpr(base, idx,
3602                                                   Context.DependentTy,
3603                                                   VK_LValue, OK_Ordinary,
3604                                                   rbLoc));
3605   }
3606 
3607   // Use C++ overloaded-operator rules if either operand has record
3608   // type.  The spec says to do this if either type is *overloadable*,
3609   // but enum types can't declare subscript operators or conversion
3610   // operators, so there's nothing interesting for overload resolution
3611   // to do if there aren't any record types involved.
3612   //
3613   // ObjC pointers have their own subscripting logic that is not tied
3614   // to overload resolution and so should not take this path.
3615   if (getLangOpts().CPlusPlus &&
3616       (base->getType()->isRecordType() ||
3617        (!base->getType()->isObjCObjectPointerType() &&
3618         idx->getType()->isRecordType()))) {
3619     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3620   }
3621 
3622   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3623 }
3624 
3625 ExprResult
3626 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3627                                       Expr *Idx, SourceLocation RLoc) {
3628   Expr *LHSExp = Base;
3629   Expr *RHSExp = Idx;
3630 
3631   // Perform default conversions.
3632   if (!LHSExp->getType()->getAs<VectorType>()) {
3633     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3634     if (Result.isInvalid())
3635       return ExprError();
3636     LHSExp = Result.take();
3637   }
3638   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3639   if (Result.isInvalid())
3640     return ExprError();
3641   RHSExp = Result.take();
3642 
3643   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3644   ExprValueKind VK = VK_LValue;
3645   ExprObjectKind OK = OK_Ordinary;
3646 
3647   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3648   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3649   // in the subscript position. As a result, we need to derive the array base
3650   // and index from the expression types.
3651   Expr *BaseExpr, *IndexExpr;
3652   QualType ResultType;
3653   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3654     BaseExpr = LHSExp;
3655     IndexExpr = RHSExp;
3656     ResultType = Context.DependentTy;
3657   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3658     BaseExpr = LHSExp;
3659     IndexExpr = RHSExp;
3660     ResultType = PTy->getPointeeType();
3661   } else if (const ObjCObjectPointerType *PTy =
3662                LHSTy->getAs<ObjCObjectPointerType>()) {
3663     BaseExpr = LHSExp;
3664     IndexExpr = RHSExp;
3665 
3666     // Use custom logic if this should be the pseudo-object subscript
3667     // expression.
3668     if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3669       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3670 
3671     ResultType = PTy->getPointeeType();
3672     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3673       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3674         << ResultType << BaseExpr->getSourceRange();
3675       return ExprError();
3676     }
3677   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3678      // Handle the uncommon case of "123[Ptr]".
3679     BaseExpr = RHSExp;
3680     IndexExpr = LHSExp;
3681     ResultType = PTy->getPointeeType();
3682   } else if (const ObjCObjectPointerType *PTy =
3683                RHSTy->getAs<ObjCObjectPointerType>()) {
3684      // Handle the uncommon case of "123[Ptr]".
3685     BaseExpr = RHSExp;
3686     IndexExpr = LHSExp;
3687     ResultType = PTy->getPointeeType();
3688     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3689       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3690         << ResultType << BaseExpr->getSourceRange();
3691       return ExprError();
3692     }
3693   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3694     BaseExpr = LHSExp;    // vectors: V[123]
3695     IndexExpr = RHSExp;
3696     VK = LHSExp->getValueKind();
3697     if (VK != VK_RValue)
3698       OK = OK_VectorComponent;
3699 
3700     // FIXME: need to deal with const...
3701     ResultType = VTy->getElementType();
3702   } else if (LHSTy->isArrayType()) {
3703     // If we see an array that wasn't promoted by
3704     // DefaultFunctionArrayLvalueConversion, it must be an array that
3705     // wasn't promoted because of the C90 rule that doesn't
3706     // allow promoting non-lvalue arrays.  Warn, then
3707     // force the promotion here.
3708     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3709         LHSExp->getSourceRange();
3710     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3711                                CK_ArrayToPointerDecay).take();
3712     LHSTy = LHSExp->getType();
3713 
3714     BaseExpr = LHSExp;
3715     IndexExpr = RHSExp;
3716     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3717   } else if (RHSTy->isArrayType()) {
3718     // Same as previous, except for 123[f().a] case
3719     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3720         RHSExp->getSourceRange();
3721     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3722                                CK_ArrayToPointerDecay).take();
3723     RHSTy = RHSExp->getType();
3724 
3725     BaseExpr = RHSExp;
3726     IndexExpr = LHSExp;
3727     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3728   } else {
3729     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3730        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3731   }
3732   // C99 6.5.2.1p1
3733   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3734     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3735                      << IndexExpr->getSourceRange());
3736 
3737   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3738        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3739          && !IndexExpr->isTypeDependent())
3740     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3741 
3742   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3743   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3744   // type. Note that Functions are not objects, and that (in C99 parlance)
3745   // incomplete types are not object types.
3746   if (ResultType->isFunctionType()) {
3747     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3748       << ResultType << BaseExpr->getSourceRange();
3749     return ExprError();
3750   }
3751 
3752   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3753     // GNU extension: subscripting on pointer to void
3754     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3755       << BaseExpr->getSourceRange();
3756 
3757     // C forbids expressions of unqualified void type from being l-values.
3758     // See IsCForbiddenLValueType.
3759     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3760   } else if (!ResultType->isDependentType() &&
3761       RequireCompleteType(LLoc, ResultType,
3762                           diag::err_subscript_incomplete_type, BaseExpr))
3763     return ExprError();
3764 
3765   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3766          !ResultType.isCForbiddenLValueType());
3767 
3768   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3769                                                 ResultType, VK, OK, RLoc));
3770 }
3771 
3772 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3773                                         FunctionDecl *FD,
3774                                         ParmVarDecl *Param) {
3775   if (Param->hasUnparsedDefaultArg()) {
3776     Diag(CallLoc,
3777          diag::err_use_of_default_argument_to_function_declared_later) <<
3778       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3779     Diag(UnparsedDefaultArgLocs[Param],
3780          diag::note_default_argument_declared_here);
3781     return ExprError();
3782   }
3783 
3784   if (Param->hasUninstantiatedDefaultArg()) {
3785     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3786 
3787     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3788                                                  Param);
3789 
3790     // Instantiate the expression.
3791     MultiLevelTemplateArgumentList MutiLevelArgList
3792       = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3793 
3794     InstantiatingTemplate Inst(*this, CallLoc, Param,
3795                                MutiLevelArgList.getInnermost());
3796     if (Inst)
3797       return ExprError();
3798 
3799     ExprResult Result;
3800     {
3801       // C++ [dcl.fct.default]p5:
3802       //   The names in the [default argument] expression are bound, and
3803       //   the semantic constraints are checked, at the point where the
3804       //   default argument expression appears.
3805       ContextRAII SavedContext(*this, FD);
3806       LocalInstantiationScope Local(*this);
3807       Result = SubstExpr(UninstExpr, MutiLevelArgList);
3808     }
3809     if (Result.isInvalid())
3810       return ExprError();
3811 
3812     // Check the expression as an initializer for the parameter.
3813     InitializedEntity Entity
3814       = InitializedEntity::InitializeParameter(Context, Param);
3815     InitializationKind Kind
3816       = InitializationKind::CreateCopy(Param->getLocation(),
3817              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3818     Expr *ResultE = Result.takeAs<Expr>();
3819 
3820     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3821     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3822     if (Result.isInvalid())
3823       return ExprError();
3824 
3825     Expr *Arg = Result.takeAs<Expr>();
3826     CheckCompletedExpr(Arg, Param->getOuterLocStart());
3827     // Build the default argument expression.
3828     return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
3829   }
3830 
3831   // If the default expression creates temporaries, we need to
3832   // push them to the current stack of expression temporaries so they'll
3833   // be properly destroyed.
3834   // FIXME: We should really be rebuilding the default argument with new
3835   // bound temporaries; see the comment in PR5810.
3836   // We don't need to do that with block decls, though, because
3837   // blocks in default argument expression can never capture anything.
3838   if (isa<ExprWithCleanups>(Param->getInit())) {
3839     // Set the "needs cleanups" bit regardless of whether there are
3840     // any explicit objects.
3841     ExprNeedsCleanups = true;
3842 
3843     // Append all the objects to the cleanup list.  Right now, this
3844     // should always be a no-op, because blocks in default argument
3845     // expressions should never be able to capture anything.
3846     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3847            "default argument expression has capturing blocks?");
3848   }
3849 
3850   // We already type-checked the argument, so we know it works.
3851   // Just mark all of the declarations in this potentially-evaluated expression
3852   // as being "referenced".
3853   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3854                                    /*SkipLocalVariables=*/true);
3855   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3856 }
3857 
3858 
3859 Sema::VariadicCallType
3860 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3861                           Expr *Fn) {
3862   if (Proto && Proto->isVariadic()) {
3863     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3864       return VariadicConstructor;
3865     else if (Fn && Fn->getType()->isBlockPointerType())
3866       return VariadicBlock;
3867     else if (FDecl) {
3868       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3869         if (Method->isInstance())
3870           return VariadicMethod;
3871     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
3872       return VariadicMethod;
3873     return VariadicFunction;
3874   }
3875   return VariadicDoesNotApply;
3876 }
3877 
3878 namespace {
3879 class FunctionCallCCC : public FunctionCallFilterCCC {
3880 public:
3881   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
3882                   unsigned NumArgs, bool HasExplicitTemplateArgs)
3883       : FunctionCallFilterCCC(SemaRef, NumArgs, HasExplicitTemplateArgs),
3884         FunctionName(FuncName) {}
3885 
3886   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
3887     if (!candidate.getCorrectionSpecifier() ||
3888         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
3889       return false;
3890     }
3891 
3892     return FunctionCallFilterCCC::ValidateCandidate(candidate);
3893   }
3894 
3895 private:
3896   const IdentifierInfo *const FunctionName;
3897 };
3898 }
3899 
3900 static TypoCorrection TryTypoCorrectionForCall(Sema &S,
3901                                                DeclarationNameInfo FuncName,
3902                                                ArrayRef<Expr *> Args) {
3903   FunctionCallCCC CCC(S, FuncName.getName().getAsIdentifierInfo(),
3904                       Args.size(), false);
3905   if (TypoCorrection Corrected =
3906           S.CorrectTypo(FuncName, Sema::LookupOrdinaryName,
3907                         S.getScopeForContext(S.CurContext), NULL, CCC)) {
3908     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
3909       if (Corrected.isOverloaded()) {
3910         OverloadCandidateSet OCS(FuncName.getLoc());
3911         OverloadCandidateSet::iterator Best;
3912         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
3913                                            CDEnd = Corrected.end();
3914              CD != CDEnd; ++CD) {
3915           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
3916             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
3917                                    OCS);
3918         }
3919         switch (OCS.BestViableFunction(S, FuncName.getLoc(), Best)) {
3920         case OR_Success:
3921           ND = Best->Function;
3922           Corrected.setCorrectionDecl(ND);
3923           break;
3924         default:
3925           break;
3926         }
3927       }
3928       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
3929         return Corrected;
3930       }
3931     }
3932   }
3933   return TypoCorrection();
3934 }
3935 
3936 /// ConvertArgumentsForCall - Converts the arguments specified in
3937 /// Args/NumArgs to the parameter types of the function FDecl with
3938 /// function prototype Proto. Call is the call expression itself, and
3939 /// Fn is the function expression. For a C++ member function, this
3940 /// routine does not attempt to convert the object argument. Returns
3941 /// true if the call is ill-formed.
3942 bool
3943 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3944                               FunctionDecl *FDecl,
3945                               const FunctionProtoType *Proto,
3946                               ArrayRef<Expr *> Args,
3947                               SourceLocation RParenLoc,
3948                               bool IsExecConfig) {
3949   // Bail out early if calling a builtin with custom typechecking.
3950   // We don't need to do this in the
3951   if (FDecl)
3952     if (unsigned ID = FDecl->getBuiltinID())
3953       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3954         return false;
3955 
3956   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
3957   // assignment, to the types of the corresponding parameter, ...
3958   unsigned NumArgsInProto = Proto->getNumArgs();
3959   bool Invalid = false;
3960   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
3961   unsigned FnKind = Fn->getType()->isBlockPointerType()
3962                        ? 1 /* block */
3963                        : (IsExecConfig ? 3 /* kernel function (exec config) */
3964                                        : 0 /* function */);
3965 
3966   // If too few arguments are available (and we don't have default
3967   // arguments for the remaining parameters), don't make the call.
3968   if (Args.size() < NumArgsInProto) {
3969     if (Args.size() < MinArgs) {
3970       TypoCorrection TC;
3971       if (FDecl && (TC = TryTypoCorrectionForCall(
3972                         *this, DeclarationNameInfo(FDecl->getDeclName(),
3973                                                    Fn->getLocStart()),
3974                         Args))) {
3975         std::string CorrectedStr(TC.getAsString(getLangOpts()));
3976         std::string CorrectedQuotedStr(TC.getQuoted(getLangOpts()));
3977         unsigned diag_id =
3978             MinArgs == NumArgsInProto && !Proto->isVariadic()
3979                 ? diag::err_typecheck_call_too_few_args_suggest
3980                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
3981         Diag(RParenLoc, diag_id)
3982             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
3983             << Fn->getSourceRange() << CorrectedQuotedStr
3984             << FixItHint::CreateReplacement(TC.getCorrectionRange(),
3985                                             CorrectedStr);
3986         Diag(TC.getCorrectionDecl()->getLocStart(),
3987              diag::note_previous_decl) << CorrectedQuotedStr;
3988       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3989         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3990                           ? diag::err_typecheck_call_too_few_args_one
3991                           : diag::err_typecheck_call_too_few_args_at_least_one)
3992           << FnKind
3993           << FDecl->getParamDecl(0) << Fn->getSourceRange();
3994       else
3995         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3996                           ? diag::err_typecheck_call_too_few_args
3997                           : diag::err_typecheck_call_too_few_args_at_least)
3998           << FnKind
3999           << MinArgs << static_cast<unsigned>(Args.size())
4000           << Fn->getSourceRange();
4001 
4002       // Emit the location of the prototype.
4003       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4004         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4005           << FDecl;
4006 
4007       return true;
4008     }
4009     Call->setNumArgs(Context, NumArgsInProto);
4010   }
4011 
4012   // If too many are passed and not variadic, error on the extras and drop
4013   // them.
4014   if (Args.size() > NumArgsInProto) {
4015     if (!Proto->isVariadic()) {
4016       TypoCorrection TC;
4017       if (FDecl && (TC = TryTypoCorrectionForCall(
4018                         *this, DeclarationNameInfo(FDecl->getDeclName(),
4019                                                    Fn->getLocStart()),
4020                         Args))) {
4021         std::string CorrectedStr(TC.getAsString(getLangOpts()));
4022         std::string CorrectedQuotedStr(TC.getQuoted(getLangOpts()));
4023         unsigned diag_id =
4024             MinArgs == NumArgsInProto && !Proto->isVariadic()
4025                 ? diag::err_typecheck_call_too_many_args_suggest
4026                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4027         Diag(Args[NumArgsInProto]->getLocStart(), diag_id)
4028             << FnKind << NumArgsInProto << static_cast<unsigned>(Args.size())
4029             << Fn->getSourceRange() << CorrectedQuotedStr
4030             << FixItHint::CreateReplacement(TC.getCorrectionRange(),
4031                                             CorrectedStr);
4032         Diag(TC.getCorrectionDecl()->getLocStart(),
4033              diag::note_previous_decl) << CorrectedQuotedStr;
4034       } else if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4035         Diag(Args[NumArgsInProto]->getLocStart(),
4036              MinArgs == NumArgsInProto
4037                ? diag::err_typecheck_call_too_many_args_one
4038                : diag::err_typecheck_call_too_many_args_at_most_one)
4039           << FnKind
4040           << FDecl->getParamDecl(0) << static_cast<unsigned>(Args.size())
4041           << Fn->getSourceRange()
4042           << SourceRange(Args[NumArgsInProto]->getLocStart(),
4043                          Args.back()->getLocEnd());
4044       else
4045         Diag(Args[NumArgsInProto]->getLocStart(),
4046              MinArgs == NumArgsInProto
4047                ? diag::err_typecheck_call_too_many_args
4048                : diag::err_typecheck_call_too_many_args_at_most)
4049           << FnKind
4050           << NumArgsInProto << static_cast<unsigned>(Args.size())
4051           << Fn->getSourceRange()
4052           << SourceRange(Args[NumArgsInProto]->getLocStart(),
4053                          Args.back()->getLocEnd());
4054 
4055       // Emit the location of the prototype.
4056       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4057         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4058           << FDecl;
4059 
4060       // This deletes the extra arguments.
4061       Call->setNumArgs(Context, NumArgsInProto);
4062       return true;
4063     }
4064   }
4065   SmallVector<Expr *, 8> AllArgs;
4066   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4067 
4068   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4069                                    Proto, 0, Args, AllArgs, CallType);
4070   if (Invalid)
4071     return true;
4072   unsigned TotalNumArgs = AllArgs.size();
4073   for (unsigned i = 0; i < TotalNumArgs; ++i)
4074     Call->setArg(i, AllArgs[i]);
4075 
4076   return false;
4077 }
4078 
4079 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4080                                   FunctionDecl *FDecl,
4081                                   const FunctionProtoType *Proto,
4082                                   unsigned FirstProtoArg,
4083                                   ArrayRef<Expr *> Args,
4084                                   SmallVectorImpl<Expr *> &AllArgs,
4085                                   VariadicCallType CallType,
4086                                   bool AllowExplicit,
4087                                   bool IsListInitialization) {
4088   unsigned NumArgsInProto = Proto->getNumArgs();
4089   unsigned NumArgsToCheck = Args.size();
4090   bool Invalid = false;
4091   if (Args.size() != NumArgsInProto)
4092     // Use default arguments for missing arguments
4093     NumArgsToCheck = NumArgsInProto;
4094   unsigned ArgIx = 0;
4095   // Continue to check argument types (even if we have too few/many args).
4096   for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
4097     QualType ProtoArgType = Proto->getArgType(i);
4098 
4099     Expr *Arg;
4100     ParmVarDecl *Param;
4101     if (ArgIx < Args.size()) {
4102       Arg = Args[ArgIx++];
4103 
4104       if (RequireCompleteType(Arg->getLocStart(),
4105                               ProtoArgType,
4106                               diag::err_call_incomplete_argument, Arg))
4107         return true;
4108 
4109       // Pass the argument
4110       Param = 0;
4111       if (FDecl && i < FDecl->getNumParams())
4112         Param = FDecl->getParamDecl(i);
4113 
4114       // Strip the unbridged-cast placeholder expression off, if applicable.
4115       bool CFAudited = false;
4116       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4117           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4118           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4119         Arg = stripARCUnbridgedCast(Arg);
4120       else if (getLangOpts().ObjCAutoRefCount &&
4121                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4122                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4123         CFAudited = true;
4124 
4125       InitializedEntity Entity = Param ?
4126           InitializedEntity::InitializeParameter(Context, Param, ProtoArgType)
4127         : InitializedEntity::InitializeParameter(Context, ProtoArgType,
4128                                                  Proto->isArgConsumed(i));
4129 
4130       // Remember that parameter belongs to a CF audited API.
4131       if (CFAudited)
4132         Entity.setParameterCFAudited();
4133 
4134       ExprResult ArgE = PerformCopyInitialization(Entity,
4135                                                   SourceLocation(),
4136                                                   Owned(Arg),
4137                                                   IsListInitialization,
4138                                                   AllowExplicit);
4139       if (ArgE.isInvalid())
4140         return true;
4141 
4142       Arg = ArgE.takeAs<Expr>();
4143     } else {
4144       assert(FDecl && "can't use default arguments without a known callee");
4145       Param = FDecl->getParamDecl(i);
4146 
4147       ExprResult ArgExpr =
4148         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4149       if (ArgExpr.isInvalid())
4150         return true;
4151 
4152       Arg = ArgExpr.takeAs<Expr>();
4153     }
4154 
4155     // Check for array bounds violations for each argument to the call. This
4156     // check only triggers warnings when the argument isn't a more complex Expr
4157     // with its own checking, such as a BinaryOperator.
4158     CheckArrayAccess(Arg);
4159 
4160     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4161     CheckStaticArrayArgument(CallLoc, Param, Arg);
4162 
4163     AllArgs.push_back(Arg);
4164   }
4165 
4166   // If this is a variadic call, handle args passed through "...".
4167   if (CallType != VariadicDoesNotApply) {
4168     // Assume that extern "C" functions with variadic arguments that
4169     // return __unknown_anytype aren't *really* variadic.
4170     if (Proto->getResultType() == Context.UnknownAnyTy &&
4171         FDecl && FDecl->isExternC()) {
4172       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4173         QualType paramType; // ignored
4174         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
4175         Invalid |= arg.isInvalid();
4176         AllArgs.push_back(arg.take());
4177       }
4178 
4179     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4180     } else {
4181       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4182         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4183                                                           FDecl);
4184         Invalid |= Arg.isInvalid();
4185         AllArgs.push_back(Arg.take());
4186       }
4187     }
4188 
4189     // Check for array bounds violations.
4190     for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4191       CheckArrayAccess(Args[i]);
4192   }
4193   return Invalid;
4194 }
4195 
4196 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4197   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4198   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4199     TL = DTL.getOriginalLoc();
4200   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4201     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4202       << ATL.getLocalSourceRange();
4203 }
4204 
4205 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4206 /// array parameter, check that it is non-null, and that if it is formed by
4207 /// array-to-pointer decay, the underlying array is sufficiently large.
4208 ///
4209 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4210 /// array type derivation, then for each call to the function, the value of the
4211 /// corresponding actual argument shall provide access to the first element of
4212 /// an array with at least as many elements as specified by the size expression.
4213 void
4214 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4215                                ParmVarDecl *Param,
4216                                const Expr *ArgExpr) {
4217   // Static array parameters are not supported in C++.
4218   if (!Param || getLangOpts().CPlusPlus)
4219     return;
4220 
4221   QualType OrigTy = Param->getOriginalType();
4222 
4223   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4224   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4225     return;
4226 
4227   if (ArgExpr->isNullPointerConstant(Context,
4228                                      Expr::NPC_NeverValueDependent)) {
4229     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4230     DiagnoseCalleeStaticArrayParam(*this, Param);
4231     return;
4232   }
4233 
4234   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4235   if (!CAT)
4236     return;
4237 
4238   const ConstantArrayType *ArgCAT =
4239     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4240   if (!ArgCAT)
4241     return;
4242 
4243   if (ArgCAT->getSize().ult(CAT->getSize())) {
4244     Diag(CallLoc, diag::warn_static_array_too_small)
4245       << ArgExpr->getSourceRange()
4246       << (unsigned) ArgCAT->getSize().getZExtValue()
4247       << (unsigned) CAT->getSize().getZExtValue();
4248     DiagnoseCalleeStaticArrayParam(*this, Param);
4249   }
4250 }
4251 
4252 /// Given a function expression of unknown-any type, try to rebuild it
4253 /// to have a function type.
4254 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4255 
4256 /// Is the given type a placeholder that we need to lower out
4257 /// immediately during argument processing?
4258 static bool isPlaceholderToRemoveAsArg(QualType type) {
4259   // Placeholders are never sugared.
4260   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4261   if (!placeholder) return false;
4262 
4263   switch (placeholder->getKind()) {
4264   // Ignore all the non-placeholder types.
4265 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4266 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4267 #include "clang/AST/BuiltinTypes.def"
4268     return false;
4269 
4270   // We cannot lower out overload sets; they might validly be resolved
4271   // by the call machinery.
4272   case BuiltinType::Overload:
4273     return false;
4274 
4275   // Unbridged casts in ARC can be handled in some call positions and
4276   // should be left in place.
4277   case BuiltinType::ARCUnbridgedCast:
4278     return false;
4279 
4280   // Pseudo-objects should be converted as soon as possible.
4281   case BuiltinType::PseudoObject:
4282     return true;
4283 
4284   // The debugger mode could theoretically but currently does not try
4285   // to resolve unknown-typed arguments based on known parameter types.
4286   case BuiltinType::UnknownAny:
4287     return true;
4288 
4289   // These are always invalid as call arguments and should be reported.
4290   case BuiltinType::BoundMember:
4291   case BuiltinType::BuiltinFn:
4292     return true;
4293   }
4294   llvm_unreachable("bad builtin type kind");
4295 }
4296 
4297 /// Check an argument list for placeholders that we won't try to
4298 /// handle later.
4299 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4300   // Apply this processing to all the arguments at once instead of
4301   // dying at the first failure.
4302   bool hasInvalid = false;
4303   for (size_t i = 0, e = args.size(); i != e; i++) {
4304     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4305       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4306       if (result.isInvalid()) hasInvalid = true;
4307       else args[i] = result.take();
4308     }
4309   }
4310   return hasInvalid;
4311 }
4312 
4313 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4314 /// This provides the location of the left/right parens and a list of comma
4315 /// locations.
4316 ExprResult
4317 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4318                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
4319                     Expr *ExecConfig, bool IsExecConfig) {
4320   // Since this might be a postfix expression, get rid of ParenListExprs.
4321   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4322   if (Result.isInvalid()) return ExprError();
4323   Fn = Result.take();
4324 
4325   if (checkArgsForPlaceholders(*this, ArgExprs))
4326     return ExprError();
4327 
4328   if (getLangOpts().CPlusPlus) {
4329     // If this is a pseudo-destructor expression, build the call immediately.
4330     if (isa<CXXPseudoDestructorExpr>(Fn)) {
4331       if (!ArgExprs.empty()) {
4332         // Pseudo-destructor calls should not have any arguments.
4333         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4334           << FixItHint::CreateRemoval(
4335                                     SourceRange(ArgExprs[0]->getLocStart(),
4336                                                 ArgExprs.back()->getLocEnd()));
4337       }
4338 
4339       return Owned(new (Context) CallExpr(Context, Fn, None,
4340                                           Context.VoidTy, VK_RValue,
4341                                           RParenLoc));
4342     }
4343     if (Fn->getType() == Context.PseudoObjectTy) {
4344       ExprResult result = CheckPlaceholderExpr(Fn);
4345       if (result.isInvalid()) return ExprError();
4346       Fn = result.take();
4347     }
4348 
4349     // Determine whether this is a dependent call inside a C++ template,
4350     // in which case we won't do any semantic analysis now.
4351     // FIXME: Will need to cache the results of name lookup (including ADL) in
4352     // Fn.
4353     bool Dependent = false;
4354     if (Fn->isTypeDependent())
4355       Dependent = true;
4356     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4357       Dependent = true;
4358 
4359     if (Dependent) {
4360       if (ExecConfig) {
4361         return Owned(new (Context) CUDAKernelCallExpr(
4362             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4363             Context.DependentTy, VK_RValue, RParenLoc));
4364       } else {
4365         return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
4366                                             Context.DependentTy, VK_RValue,
4367                                             RParenLoc));
4368       }
4369     }
4370 
4371     // Determine whether this is a call to an object (C++ [over.call.object]).
4372     if (Fn->getType()->isRecordType())
4373       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
4374                                                 ArgExprs, RParenLoc));
4375 
4376     if (Fn->getType() == Context.UnknownAnyTy) {
4377       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4378       if (result.isInvalid()) return ExprError();
4379       Fn = result.take();
4380     }
4381 
4382     if (Fn->getType() == Context.BoundMemberTy) {
4383       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4384     }
4385   }
4386 
4387   // Check for overloaded calls.  This can happen even in C due to extensions.
4388   if (Fn->getType() == Context.OverloadTy) {
4389     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4390 
4391     // We aren't supposed to apply this logic for if there's an '&' involved.
4392     if (!find.HasFormOfMemberPointer) {
4393       OverloadExpr *ovl = find.Expression;
4394       if (isa<UnresolvedLookupExpr>(ovl)) {
4395         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4396         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4397                                        RParenLoc, ExecConfig);
4398       } else {
4399         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4400                                          RParenLoc);
4401       }
4402     }
4403   }
4404 
4405   // If we're directly calling a function, get the appropriate declaration.
4406   if (Fn->getType() == Context.UnknownAnyTy) {
4407     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4408     if (result.isInvalid()) return ExprError();
4409     Fn = result.take();
4410   }
4411 
4412   Expr *NakedFn = Fn->IgnoreParens();
4413 
4414   NamedDecl *NDecl = 0;
4415   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4416     if (UnOp->getOpcode() == UO_AddrOf)
4417       NakedFn = UnOp->getSubExpr()->IgnoreParens();
4418 
4419   if (isa<DeclRefExpr>(NakedFn))
4420     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4421   else if (isa<MemberExpr>(NakedFn))
4422     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4423 
4424   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4425                                ExecConfig, IsExecConfig);
4426 }
4427 
4428 ExprResult
4429 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4430                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
4431   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4432   if (!ConfigDecl)
4433     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4434                           << "cudaConfigureCall");
4435   QualType ConfigQTy = ConfigDecl->getType();
4436 
4437   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4438       ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
4439   MarkFunctionReferenced(LLLLoc, ConfigDecl);
4440 
4441   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
4442                        /*IsExecConfig=*/true);
4443 }
4444 
4445 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4446 ///
4447 /// __builtin_astype( value, dst type )
4448 ///
4449 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4450                                  SourceLocation BuiltinLoc,
4451                                  SourceLocation RParenLoc) {
4452   ExprValueKind VK = VK_RValue;
4453   ExprObjectKind OK = OK_Ordinary;
4454   QualType DstTy = GetTypeFromParser(ParsedDestTy);
4455   QualType SrcTy = E->getType();
4456   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4457     return ExprError(Diag(BuiltinLoc,
4458                           diag::err_invalid_astype_of_different_size)
4459                      << DstTy
4460                      << SrcTy
4461                      << E->getSourceRange());
4462   return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
4463                RParenLoc));
4464 }
4465 
4466 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4467 /// i.e. an expression not of \p OverloadTy.  The expression should
4468 /// unary-convert to an expression of function-pointer or
4469 /// block-pointer type.
4470 ///
4471 /// \param NDecl the declaration being called, if available
4472 ExprResult
4473 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4474                             SourceLocation LParenLoc,
4475                             ArrayRef<Expr *> Args,
4476                             SourceLocation RParenLoc,
4477                             Expr *Config, bool IsExecConfig) {
4478   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4479   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4480 
4481   // Promote the function operand.
4482   // We special-case function promotion here because we only allow promoting
4483   // builtin functions to function pointers in the callee of a call.
4484   ExprResult Result;
4485   if (BuiltinID &&
4486       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4487     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4488                                CK_BuiltinFnToFnPtr).take();
4489   } else {
4490     Result = UsualUnaryConversions(Fn);
4491   }
4492   if (Result.isInvalid())
4493     return ExprError();
4494   Fn = Result.take();
4495 
4496   // Make the call expr early, before semantic checks.  This guarantees cleanup
4497   // of arguments and function on error.
4498   CallExpr *TheCall;
4499   if (Config)
4500     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4501                                                cast<CallExpr>(Config), Args,
4502                                                Context.BoolTy, VK_RValue,
4503                                                RParenLoc);
4504   else
4505     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4506                                      VK_RValue, RParenLoc);
4507 
4508   // Bail out early if calling a builtin with custom typechecking.
4509   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4510     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4511 
4512  retry:
4513   const FunctionType *FuncT;
4514   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4515     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4516     // have type pointer to function".
4517     FuncT = PT->getPointeeType()->getAs<FunctionType>();
4518     if (FuncT == 0)
4519       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4520                          << Fn->getType() << Fn->getSourceRange());
4521   } else if (const BlockPointerType *BPT =
4522                Fn->getType()->getAs<BlockPointerType>()) {
4523     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4524   } else {
4525     // Handle calls to expressions of unknown-any type.
4526     if (Fn->getType() == Context.UnknownAnyTy) {
4527       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4528       if (rewrite.isInvalid()) return ExprError();
4529       Fn = rewrite.take();
4530       TheCall->setCallee(Fn);
4531       goto retry;
4532     }
4533 
4534     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4535       << Fn->getType() << Fn->getSourceRange());
4536   }
4537 
4538   if (getLangOpts().CUDA) {
4539     if (Config) {
4540       // CUDA: Kernel calls must be to global functions
4541       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4542         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4543             << FDecl->getName() << Fn->getSourceRange());
4544 
4545       // CUDA: Kernel function must have 'void' return type
4546       if (!FuncT->getResultType()->isVoidType())
4547         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4548             << Fn->getType() << Fn->getSourceRange());
4549     } else {
4550       // CUDA: Calls to global functions must be configured
4551       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4552         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4553             << FDecl->getName() << Fn->getSourceRange());
4554     }
4555   }
4556 
4557   // Check for a valid return type
4558   if (CheckCallReturnType(FuncT->getResultType(),
4559                           Fn->getLocStart(), TheCall,
4560                           FDecl))
4561     return ExprError();
4562 
4563   // We know the result type of the call, set it.
4564   TheCall->setType(FuncT->getCallResultType(Context));
4565   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
4566 
4567   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4568   if (Proto) {
4569     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4570                                 IsExecConfig))
4571       return ExprError();
4572   } else {
4573     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4574 
4575     if (FDecl) {
4576       // Check if we have too few/too many template arguments, based
4577       // on our knowledge of the function definition.
4578       const FunctionDecl *Def = 0;
4579       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
4580         Proto = Def->getType()->getAs<FunctionProtoType>();
4581        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
4582           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4583           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
4584       }
4585 
4586       // If the function we're calling isn't a function prototype, but we have
4587       // a function prototype from a prior declaratiom, use that prototype.
4588       if (!FDecl->hasPrototype())
4589         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4590     }
4591 
4592     // Promote the arguments (C99 6.5.2.2p6).
4593     for (unsigned i = 0, e = Args.size(); i != e; i++) {
4594       Expr *Arg = Args[i];
4595 
4596       if (Proto && i < Proto->getNumArgs()) {
4597         InitializedEntity Entity
4598           = InitializedEntity::InitializeParameter(Context,
4599                                                    Proto->getArgType(i),
4600                                                    Proto->isArgConsumed(i));
4601         ExprResult ArgE = PerformCopyInitialization(Entity,
4602                                                     SourceLocation(),
4603                                                     Owned(Arg));
4604         if (ArgE.isInvalid())
4605           return true;
4606 
4607         Arg = ArgE.takeAs<Expr>();
4608 
4609       } else {
4610         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4611 
4612         if (ArgE.isInvalid())
4613           return true;
4614 
4615         Arg = ArgE.takeAs<Expr>();
4616       }
4617 
4618       if (RequireCompleteType(Arg->getLocStart(),
4619                               Arg->getType(),
4620                               diag::err_call_incomplete_argument, Arg))
4621         return ExprError();
4622 
4623       TheCall->setArg(i, Arg);
4624     }
4625   }
4626 
4627   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4628     if (!Method->isStatic())
4629       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4630         << Fn->getSourceRange());
4631 
4632   // Check for sentinels
4633   if (NDecl)
4634     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
4635 
4636   // Do special checking on direct calls to functions.
4637   if (FDecl) {
4638     if (CheckFunctionCall(FDecl, TheCall, Proto))
4639       return ExprError();
4640 
4641     if (BuiltinID)
4642       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4643   } else if (NDecl) {
4644     if (CheckPointerCall(NDecl, TheCall, Proto))
4645       return ExprError();
4646   } else {
4647     if (CheckOtherCall(TheCall, Proto))
4648       return ExprError();
4649   }
4650 
4651   return MaybeBindToTemporary(TheCall);
4652 }
4653 
4654 ExprResult
4655 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4656                            SourceLocation RParenLoc, Expr *InitExpr) {
4657   assert(Ty && "ActOnCompoundLiteral(): missing type");
4658   // FIXME: put back this assert when initializers are worked out.
4659   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4660 
4661   TypeSourceInfo *TInfo;
4662   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4663   if (!TInfo)
4664     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4665 
4666   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4667 }
4668 
4669 ExprResult
4670 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4671                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4672   QualType literalType = TInfo->getType();
4673 
4674   if (literalType->isArrayType()) {
4675     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4676           diag::err_illegal_decl_array_incomplete_type,
4677           SourceRange(LParenLoc,
4678                       LiteralExpr->getSourceRange().getEnd())))
4679       return ExprError();
4680     if (literalType->isVariableArrayType())
4681       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4682         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4683   } else if (!literalType->isDependentType() &&
4684              RequireCompleteType(LParenLoc, literalType,
4685                diag::err_typecheck_decl_incomplete_type,
4686                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4687     return ExprError();
4688 
4689   InitializedEntity Entity
4690     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
4691   InitializationKind Kind
4692     = InitializationKind::CreateCStyleCast(LParenLoc,
4693                                            SourceRange(LParenLoc, RParenLoc),
4694                                            /*InitList=*/true);
4695   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
4696   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4697                                       &literalType);
4698   if (Result.isInvalid())
4699     return ExprError();
4700   LiteralExpr = Result.get();
4701 
4702   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4703   if (!getLangOpts().CPlusPlus && isFileScope) { // 6.5.2.5p3
4704     if (CheckForConstantInitializer(LiteralExpr, literalType))
4705       return ExprError();
4706   }
4707 
4708   // In C, compound literals are l-values for some reason.
4709   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4710 
4711   return MaybeBindToTemporary(
4712            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4713                                              VK, LiteralExpr, isFileScope));
4714 }
4715 
4716 ExprResult
4717 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4718                     SourceLocation RBraceLoc) {
4719   // Immediately handle non-overload placeholders.  Overloads can be
4720   // resolved contextually, but everything else here can't.
4721   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4722     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4723       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4724 
4725       // Ignore failures; dropping the entire initializer list because
4726       // of one failure would be terrible for indexing/etc.
4727       if (result.isInvalid()) continue;
4728 
4729       InitArgList[I] = result.take();
4730     }
4731   }
4732 
4733   // Semantic analysis for initializers is done by ActOnDeclarator() and
4734   // CheckInitializer() - it requires knowledge of the object being intialized.
4735 
4736   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4737                                                RBraceLoc);
4738   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4739   return Owned(E);
4740 }
4741 
4742 /// Do an explicit extend of the given block pointer if we're in ARC.
4743 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4744   assert(E.get()->getType()->isBlockPointerType());
4745   assert(E.get()->isRValue());
4746 
4747   // Only do this in an r-value context.
4748   if (!S.getLangOpts().ObjCAutoRefCount) return;
4749 
4750   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4751                                CK_ARCExtendBlockObject, E.get(),
4752                                /*base path*/ 0, VK_RValue);
4753   S.ExprNeedsCleanups = true;
4754 }
4755 
4756 /// Prepare a conversion of the given expression to an ObjC object
4757 /// pointer type.
4758 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4759   QualType type = E.get()->getType();
4760   if (type->isObjCObjectPointerType()) {
4761     return CK_BitCast;
4762   } else if (type->isBlockPointerType()) {
4763     maybeExtendBlockObject(*this, E);
4764     return CK_BlockPointerToObjCPointerCast;
4765   } else {
4766     assert(type->isPointerType());
4767     return CK_CPointerToObjCPointerCast;
4768   }
4769 }
4770 
4771 /// Prepares for a scalar cast, performing all the necessary stages
4772 /// except the final cast and returning the kind required.
4773 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4774   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4775   // Also, callers should have filtered out the invalid cases with
4776   // pointers.  Everything else should be possible.
4777 
4778   QualType SrcTy = Src.get()->getType();
4779   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4780     return CK_NoOp;
4781 
4782   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4783   case Type::STK_MemberPointer:
4784     llvm_unreachable("member pointer type in C");
4785 
4786   case Type::STK_CPointer:
4787   case Type::STK_BlockPointer:
4788   case Type::STK_ObjCObjectPointer:
4789     switch (DestTy->getScalarTypeKind()) {
4790     case Type::STK_CPointer:
4791       return CK_BitCast;
4792     case Type::STK_BlockPointer:
4793       return (SrcKind == Type::STK_BlockPointer
4794                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4795     case Type::STK_ObjCObjectPointer:
4796       if (SrcKind == Type::STK_ObjCObjectPointer)
4797         return CK_BitCast;
4798       if (SrcKind == Type::STK_CPointer)
4799         return CK_CPointerToObjCPointerCast;
4800       maybeExtendBlockObject(*this, Src);
4801       return CK_BlockPointerToObjCPointerCast;
4802     case Type::STK_Bool:
4803       return CK_PointerToBoolean;
4804     case Type::STK_Integral:
4805       return CK_PointerToIntegral;
4806     case Type::STK_Floating:
4807     case Type::STK_FloatingComplex:
4808     case Type::STK_IntegralComplex:
4809     case Type::STK_MemberPointer:
4810       llvm_unreachable("illegal cast from pointer");
4811     }
4812     llvm_unreachable("Should have returned before this");
4813 
4814   case Type::STK_Bool: // casting from bool is like casting from an integer
4815   case Type::STK_Integral:
4816     switch (DestTy->getScalarTypeKind()) {
4817     case Type::STK_CPointer:
4818     case Type::STK_ObjCObjectPointer:
4819     case Type::STK_BlockPointer:
4820       if (Src.get()->isNullPointerConstant(Context,
4821                                            Expr::NPC_ValueDependentIsNull))
4822         return CK_NullToPointer;
4823       return CK_IntegralToPointer;
4824     case Type::STK_Bool:
4825       return CK_IntegralToBoolean;
4826     case Type::STK_Integral:
4827       return CK_IntegralCast;
4828     case Type::STK_Floating:
4829       return CK_IntegralToFloating;
4830     case Type::STK_IntegralComplex:
4831       Src = ImpCastExprToType(Src.take(),
4832                               DestTy->castAs<ComplexType>()->getElementType(),
4833                               CK_IntegralCast);
4834       return CK_IntegralRealToComplex;
4835     case Type::STK_FloatingComplex:
4836       Src = ImpCastExprToType(Src.take(),
4837                               DestTy->castAs<ComplexType>()->getElementType(),
4838                               CK_IntegralToFloating);
4839       return CK_FloatingRealToComplex;
4840     case Type::STK_MemberPointer:
4841       llvm_unreachable("member pointer type in C");
4842     }
4843     llvm_unreachable("Should have returned before this");
4844 
4845   case Type::STK_Floating:
4846     switch (DestTy->getScalarTypeKind()) {
4847     case Type::STK_Floating:
4848       return CK_FloatingCast;
4849     case Type::STK_Bool:
4850       return CK_FloatingToBoolean;
4851     case Type::STK_Integral:
4852       return CK_FloatingToIntegral;
4853     case Type::STK_FloatingComplex:
4854       Src = ImpCastExprToType(Src.take(),
4855                               DestTy->castAs<ComplexType>()->getElementType(),
4856                               CK_FloatingCast);
4857       return CK_FloatingRealToComplex;
4858     case Type::STK_IntegralComplex:
4859       Src = ImpCastExprToType(Src.take(),
4860                               DestTy->castAs<ComplexType>()->getElementType(),
4861                               CK_FloatingToIntegral);
4862       return CK_IntegralRealToComplex;
4863     case Type::STK_CPointer:
4864     case Type::STK_ObjCObjectPointer:
4865     case Type::STK_BlockPointer:
4866       llvm_unreachable("valid float->pointer cast?");
4867     case Type::STK_MemberPointer:
4868       llvm_unreachable("member pointer type in C");
4869     }
4870     llvm_unreachable("Should have returned before this");
4871 
4872   case Type::STK_FloatingComplex:
4873     switch (DestTy->getScalarTypeKind()) {
4874     case Type::STK_FloatingComplex:
4875       return CK_FloatingComplexCast;
4876     case Type::STK_IntegralComplex:
4877       return CK_FloatingComplexToIntegralComplex;
4878     case Type::STK_Floating: {
4879       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4880       if (Context.hasSameType(ET, DestTy))
4881         return CK_FloatingComplexToReal;
4882       Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4883       return CK_FloatingCast;
4884     }
4885     case Type::STK_Bool:
4886       return CK_FloatingComplexToBoolean;
4887     case Type::STK_Integral:
4888       Src = ImpCastExprToType(Src.take(),
4889                               SrcTy->castAs<ComplexType>()->getElementType(),
4890                               CK_FloatingComplexToReal);
4891       return CK_FloatingToIntegral;
4892     case Type::STK_CPointer:
4893     case Type::STK_ObjCObjectPointer:
4894     case Type::STK_BlockPointer:
4895       llvm_unreachable("valid complex float->pointer cast?");
4896     case Type::STK_MemberPointer:
4897       llvm_unreachable("member pointer type in C");
4898     }
4899     llvm_unreachable("Should have returned before this");
4900 
4901   case Type::STK_IntegralComplex:
4902     switch (DestTy->getScalarTypeKind()) {
4903     case Type::STK_FloatingComplex:
4904       return CK_IntegralComplexToFloatingComplex;
4905     case Type::STK_IntegralComplex:
4906       return CK_IntegralComplexCast;
4907     case Type::STK_Integral: {
4908       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4909       if (Context.hasSameType(ET, DestTy))
4910         return CK_IntegralComplexToReal;
4911       Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
4912       return CK_IntegralCast;
4913     }
4914     case Type::STK_Bool:
4915       return CK_IntegralComplexToBoolean;
4916     case Type::STK_Floating:
4917       Src = ImpCastExprToType(Src.take(),
4918                               SrcTy->castAs<ComplexType>()->getElementType(),
4919                               CK_IntegralComplexToReal);
4920       return CK_IntegralToFloating;
4921     case Type::STK_CPointer:
4922     case Type::STK_ObjCObjectPointer:
4923     case Type::STK_BlockPointer:
4924       llvm_unreachable("valid complex int->pointer cast?");
4925     case Type::STK_MemberPointer:
4926       llvm_unreachable("member pointer type in C");
4927     }
4928     llvm_unreachable("Should have returned before this");
4929   }
4930 
4931   llvm_unreachable("Unhandled scalar cast");
4932 }
4933 
4934 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
4935                            CastKind &Kind) {
4936   assert(VectorTy->isVectorType() && "Not a vector type!");
4937 
4938   if (Ty->isVectorType() || Ty->isIntegerType()) {
4939     if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
4940       return Diag(R.getBegin(),
4941                   Ty->isVectorType() ?
4942                   diag::err_invalid_conversion_between_vectors :
4943                   diag::err_invalid_conversion_between_vector_and_integer)
4944         << VectorTy << Ty << R;
4945   } else
4946     return Diag(R.getBegin(),
4947                 diag::err_invalid_conversion_between_vector_and_scalar)
4948       << VectorTy << Ty << R;
4949 
4950   Kind = CK_BitCast;
4951   return false;
4952 }
4953 
4954 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4955                                     Expr *CastExpr, CastKind &Kind) {
4956   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
4957 
4958   QualType SrcTy = CastExpr->getType();
4959 
4960   // If SrcTy is a VectorType, the total size must match to explicitly cast to
4961   // an ExtVectorType.
4962   // In OpenCL, casts between vectors of different types are not allowed.
4963   // (See OpenCL 6.2).
4964   if (SrcTy->isVectorType()) {
4965     if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4966         || (getLangOpts().OpenCL &&
4967             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
4968       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4969         << DestTy << SrcTy << R;
4970       return ExprError();
4971     }
4972     Kind = CK_BitCast;
4973     return Owned(CastExpr);
4974   }
4975 
4976   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
4977   // conversion will take place first from scalar to elt type, and then
4978   // splat from elt type to vector.
4979   if (SrcTy->isPointerType())
4980     return Diag(R.getBegin(),
4981                 diag::err_invalid_conversion_between_vector_and_scalar)
4982       << DestTy << SrcTy << R;
4983 
4984   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4985   ExprResult CastExprRes = Owned(CastExpr);
4986   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
4987   if (CastExprRes.isInvalid())
4988     return ExprError();
4989   CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
4990 
4991   Kind = CK_VectorSplat;
4992   return Owned(CastExpr);
4993 }
4994 
4995 ExprResult
4996 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4997                     Declarator &D, ParsedType &Ty,
4998                     SourceLocation RParenLoc, Expr *CastExpr) {
4999   assert(!D.isInvalidType() && (CastExpr != 0) &&
5000          "ActOnCastExpr(): missing type or expr");
5001 
5002   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5003   if (D.isInvalidType())
5004     return ExprError();
5005 
5006   if (getLangOpts().CPlusPlus) {
5007     // Check that there are no default arguments (C++ only).
5008     CheckExtraCXXDefaultArguments(D);
5009   }
5010 
5011   checkUnusedDeclAttributes(D);
5012 
5013   QualType castType = castTInfo->getType();
5014   Ty = CreateParsedType(castType, castTInfo);
5015 
5016   bool isVectorLiteral = false;
5017 
5018   // Check for an altivec or OpenCL literal,
5019   // i.e. all the elements are integer constants.
5020   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5021   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5022   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
5023        && castType->isVectorType() && (PE || PLE)) {
5024     if (PLE && PLE->getNumExprs() == 0) {
5025       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5026       return ExprError();
5027     }
5028     if (PE || PLE->getNumExprs() == 1) {
5029       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5030       if (!E->getType()->isVectorType())
5031         isVectorLiteral = true;
5032     }
5033     else
5034       isVectorLiteral = true;
5035   }
5036 
5037   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5038   // then handle it as such.
5039   if (isVectorLiteral)
5040     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5041 
5042   // If the Expr being casted is a ParenListExpr, handle it specially.
5043   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5044   // sequence of BinOp comma operators.
5045   if (isa<ParenListExpr>(CastExpr)) {
5046     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5047     if (Result.isInvalid()) return ExprError();
5048     CastExpr = Result.take();
5049   }
5050 
5051   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5052 }
5053 
5054 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5055                                     SourceLocation RParenLoc, Expr *E,
5056                                     TypeSourceInfo *TInfo) {
5057   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5058          "Expected paren or paren list expression");
5059 
5060   Expr **exprs;
5061   unsigned numExprs;
5062   Expr *subExpr;
5063   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5064   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5065     LiteralLParenLoc = PE->getLParenLoc();
5066     LiteralRParenLoc = PE->getRParenLoc();
5067     exprs = PE->getExprs();
5068     numExprs = PE->getNumExprs();
5069   } else { // isa<ParenExpr> by assertion at function entrance
5070     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5071     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5072     subExpr = cast<ParenExpr>(E)->getSubExpr();
5073     exprs = &subExpr;
5074     numExprs = 1;
5075   }
5076 
5077   QualType Ty = TInfo->getType();
5078   assert(Ty->isVectorType() && "Expected vector type");
5079 
5080   SmallVector<Expr *, 8> initExprs;
5081   const VectorType *VTy = Ty->getAs<VectorType>();
5082   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5083 
5084   // '(...)' form of vector initialization in AltiVec: the number of
5085   // initializers must be one or must match the size of the vector.
5086   // If a single value is specified in the initializer then it will be
5087   // replicated to all the components of the vector
5088   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5089     // The number of initializers must be one or must match the size of the
5090     // vector. If a single value is specified in the initializer then it will
5091     // be replicated to all the components of the vector
5092     if (numExprs == 1) {
5093       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5094       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5095       if (Literal.isInvalid())
5096         return ExprError();
5097       Literal = ImpCastExprToType(Literal.take(), ElemTy,
5098                                   PrepareScalarCast(Literal, ElemTy));
5099       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
5100     }
5101     else if (numExprs < numElems) {
5102       Diag(E->getExprLoc(),
5103            diag::err_incorrect_number_of_vector_initializers);
5104       return ExprError();
5105     }
5106     else
5107       initExprs.append(exprs, exprs + numExprs);
5108   }
5109   else {
5110     // For OpenCL, when the number of initializers is a single value,
5111     // it will be replicated to all components of the vector.
5112     if (getLangOpts().OpenCL &&
5113         VTy->getVectorKind() == VectorType::GenericVector &&
5114         numExprs == 1) {
5115         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5116         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5117         if (Literal.isInvalid())
5118           return ExprError();
5119         Literal = ImpCastExprToType(Literal.take(), ElemTy,
5120                                     PrepareScalarCast(Literal, ElemTy));
5121         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
5122     }
5123 
5124     initExprs.append(exprs, exprs + numExprs);
5125   }
5126   // FIXME: This means that pretty-printing the final AST will produce curly
5127   // braces instead of the original commas.
5128   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5129                                                    initExprs, LiteralRParenLoc);
5130   initE->setType(Ty);
5131   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5132 }
5133 
5134 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5135 /// the ParenListExpr into a sequence of comma binary operators.
5136 ExprResult
5137 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5138   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5139   if (!E)
5140     return Owned(OrigExpr);
5141 
5142   ExprResult Result(E->getExpr(0));
5143 
5144   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5145     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5146                         E->getExpr(i));
5147 
5148   if (Result.isInvalid()) return ExprError();
5149 
5150   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5151 }
5152 
5153 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5154                                     SourceLocation R,
5155                                     MultiExprArg Val) {
5156   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5157   return Owned(expr);
5158 }
5159 
5160 /// \brief Emit a specialized diagnostic when one expression is a null pointer
5161 /// constant and the other is not a pointer.  Returns true if a diagnostic is
5162 /// emitted.
5163 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5164                                       SourceLocation QuestionLoc) {
5165   Expr *NullExpr = LHSExpr;
5166   Expr *NonPointerExpr = RHSExpr;
5167   Expr::NullPointerConstantKind NullKind =
5168       NullExpr->isNullPointerConstant(Context,
5169                                       Expr::NPC_ValueDependentIsNotNull);
5170 
5171   if (NullKind == Expr::NPCK_NotNull) {
5172     NullExpr = RHSExpr;
5173     NonPointerExpr = LHSExpr;
5174     NullKind =
5175         NullExpr->isNullPointerConstant(Context,
5176                                         Expr::NPC_ValueDependentIsNotNull);
5177   }
5178 
5179   if (NullKind == Expr::NPCK_NotNull)
5180     return false;
5181 
5182   if (NullKind == Expr::NPCK_ZeroExpression)
5183     return false;
5184 
5185   if (NullKind == Expr::NPCK_ZeroLiteral) {
5186     // In this case, check to make sure that we got here from a "NULL"
5187     // string in the source code.
5188     NullExpr = NullExpr->IgnoreParenImpCasts();
5189     SourceLocation loc = NullExpr->getExprLoc();
5190     if (!findMacroSpelling(loc, "NULL"))
5191       return false;
5192   }
5193 
5194   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5195   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5196       << NonPointerExpr->getType() << DiagType
5197       << NonPointerExpr->getSourceRange();
5198   return true;
5199 }
5200 
5201 /// \brief Return false if the condition expression is valid, true otherwise.
5202 static bool checkCondition(Sema &S, Expr *Cond) {
5203   QualType CondTy = Cond->getType();
5204 
5205   // C99 6.5.15p2
5206   if (CondTy->isScalarType()) return false;
5207 
5208   // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
5209   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
5210     return false;
5211 
5212   // Emit the proper error message.
5213   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
5214                               diag::err_typecheck_cond_expect_scalar :
5215                               diag::err_typecheck_cond_expect_scalar_or_vector)
5216     << CondTy;
5217   return true;
5218 }
5219 
5220 /// \brief Return false if the two expressions can be converted to a vector,
5221 /// true otherwise
5222 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
5223                                                     ExprResult &RHS,
5224                                                     QualType CondTy) {
5225   // Both operands should be of scalar type.
5226   if (!LHS.get()->getType()->isScalarType()) {
5227     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5228       << CondTy;
5229     return true;
5230   }
5231   if (!RHS.get()->getType()->isScalarType()) {
5232     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5233       << CondTy;
5234     return true;
5235   }
5236 
5237   // Implicity convert these scalars to the type of the condition.
5238   LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5239   RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
5240   return false;
5241 }
5242 
5243 /// \brief Handle when one or both operands are void type.
5244 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5245                                          ExprResult &RHS) {
5246     Expr *LHSExpr = LHS.get();
5247     Expr *RHSExpr = RHS.get();
5248 
5249     if (!LHSExpr->getType()->isVoidType())
5250       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5251         << RHSExpr->getSourceRange();
5252     if (!RHSExpr->getType()->isVoidType())
5253       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5254         << LHSExpr->getSourceRange();
5255     LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
5256     RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
5257     return S.Context.VoidTy;
5258 }
5259 
5260 /// \brief Return false if the NullExpr can be promoted to PointerTy,
5261 /// true otherwise.
5262 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5263                                         QualType PointerTy) {
5264   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5265       !NullExpr.get()->isNullPointerConstant(S.Context,
5266                                             Expr::NPC_ValueDependentIsNull))
5267     return true;
5268 
5269   NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
5270   return false;
5271 }
5272 
5273 /// \brief Checks compatibility between two pointers and return the resulting
5274 /// type.
5275 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5276                                                      ExprResult &RHS,
5277                                                      SourceLocation Loc) {
5278   QualType LHSTy = LHS.get()->getType();
5279   QualType RHSTy = RHS.get()->getType();
5280 
5281   if (S.Context.hasSameType(LHSTy, RHSTy)) {
5282     // Two identical pointers types are always compatible.
5283     return LHSTy;
5284   }
5285 
5286   QualType lhptee, rhptee;
5287 
5288   // Get the pointee types.
5289   bool IsBlockPointer = false;
5290   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5291     lhptee = LHSBTy->getPointeeType();
5292     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5293     IsBlockPointer = true;
5294   } else {
5295     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5296     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5297   }
5298 
5299   // C99 6.5.15p6: If both operands are pointers to compatible types or to
5300   // differently qualified versions of compatible types, the result type is
5301   // a pointer to an appropriately qualified version of the composite
5302   // type.
5303 
5304   // Only CVR-qualifiers exist in the standard, and the differently-qualified
5305   // clause doesn't make sense for our extensions. E.g. address space 2 should
5306   // be incompatible with address space 3: they may live on different devices or
5307   // anything.
5308   Qualifiers lhQual = lhptee.getQualifiers();
5309   Qualifiers rhQual = rhptee.getQualifiers();
5310 
5311   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5312   lhQual.removeCVRQualifiers();
5313   rhQual.removeCVRQualifiers();
5314 
5315   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5316   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5317 
5318   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5319 
5320   if (CompositeTy.isNull()) {
5321     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
5322       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5323       << RHS.get()->getSourceRange();
5324     // In this situation, we assume void* type. No especially good
5325     // reason, but this is what gcc does, and we do have to pick
5326     // to get a consistent AST.
5327     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5328     LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5329     RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5330     return incompatTy;
5331   }
5332 
5333   // The pointer types are compatible.
5334   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5335   if (IsBlockPointer)
5336     ResultTy = S.Context.getBlockPointerType(ResultTy);
5337   else
5338     ResultTy = S.Context.getPointerType(ResultTy);
5339 
5340   LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
5341   RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
5342   return ResultTy;
5343 }
5344 
5345 /// \brief Return the resulting type when the operands are both block pointers.
5346 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5347                                                           ExprResult &LHS,
5348                                                           ExprResult &RHS,
5349                                                           SourceLocation Loc) {
5350   QualType LHSTy = LHS.get()->getType();
5351   QualType RHSTy = RHS.get()->getType();
5352 
5353   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5354     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5355       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5356       LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5357       RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5358       return destType;
5359     }
5360     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5361       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5362       << RHS.get()->getSourceRange();
5363     return QualType();
5364   }
5365 
5366   // We have 2 block pointer types.
5367   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5368 }
5369 
5370 /// \brief Return the resulting type when the operands are both pointers.
5371 static QualType
5372 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5373                                             ExprResult &RHS,
5374                                             SourceLocation Loc) {
5375   // get the pointer types
5376   QualType LHSTy = LHS.get()->getType();
5377   QualType RHSTy = RHS.get()->getType();
5378 
5379   // get the "pointed to" types
5380   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5381   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5382 
5383   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5384   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5385     // Figure out necessary qualifiers (C99 6.5.15p6)
5386     QualType destPointee
5387       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5388     QualType destType = S.Context.getPointerType(destPointee);
5389     // Add qualifiers if necessary.
5390     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5391     // Promote to void*.
5392     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5393     return destType;
5394   }
5395   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5396     QualType destPointee
5397       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5398     QualType destType = S.Context.getPointerType(destPointee);
5399     // Add qualifiers if necessary.
5400     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5401     // Promote to void*.
5402     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5403     return destType;
5404   }
5405 
5406   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5407 }
5408 
5409 /// \brief Return false if the first expression is not an integer and the second
5410 /// expression is not a pointer, true otherwise.
5411 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5412                                         Expr* PointerExpr, SourceLocation Loc,
5413                                         bool IsIntFirstExpr) {
5414   if (!PointerExpr->getType()->isPointerType() ||
5415       !Int.get()->getType()->isIntegerType())
5416     return false;
5417 
5418   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5419   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5420 
5421   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5422     << Expr1->getType() << Expr2->getType()
5423     << Expr1->getSourceRange() << Expr2->getSourceRange();
5424   Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
5425                             CK_IntegralToPointer);
5426   return true;
5427 }
5428 
5429 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5430 /// In that case, LHS = cond.
5431 /// C99 6.5.15
5432 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5433                                         ExprResult &RHS, ExprValueKind &VK,
5434                                         ExprObjectKind &OK,
5435                                         SourceLocation QuestionLoc) {
5436 
5437   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5438   if (!LHSResult.isUsable()) return QualType();
5439   LHS = LHSResult;
5440 
5441   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5442   if (!RHSResult.isUsable()) return QualType();
5443   RHS = RHSResult;
5444 
5445   // C++ is sufficiently different to merit its own checker.
5446   if (getLangOpts().CPlusPlus)
5447     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5448 
5449   VK = VK_RValue;
5450   OK = OK_Ordinary;
5451 
5452   Cond = UsualUnaryConversions(Cond.take());
5453   if (Cond.isInvalid())
5454     return QualType();
5455   UsualArithmeticConversions(LHS, RHS);
5456   if (LHS.isInvalid() || RHS.isInvalid())
5457     return QualType();
5458 
5459   QualType CondTy = Cond.get()->getType();
5460   QualType LHSTy = LHS.get()->getType();
5461   QualType RHSTy = RHS.get()->getType();
5462 
5463   // first, check the condition.
5464   if (checkCondition(*this, Cond.get()))
5465     return QualType();
5466 
5467   // Now check the two expressions.
5468   if (LHSTy->isVectorType() || RHSTy->isVectorType())
5469     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5470 
5471   // If the condition is a vector, and both operands are scalar,
5472   // attempt to implicity convert them to the vector type to act like the
5473   // built in select. (OpenCL v1.1 s6.3.i)
5474   if (getLangOpts().OpenCL && CondTy->isVectorType())
5475     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5476       return QualType();
5477 
5478   // If both operands have arithmetic type, do the usual arithmetic conversions
5479   // to find a common type: C99 6.5.15p3,5.
5480   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType())
5481     return LHS.get()->getType();
5482 
5483   // If both operands are the same structure or union type, the result is that
5484   // type.
5485   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5486     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5487       if (LHSRT->getDecl() == RHSRT->getDecl())
5488         // "If both the operands have structure or union type, the result has
5489         // that type."  This implies that CV qualifiers are dropped.
5490         return LHSTy.getUnqualifiedType();
5491     // FIXME: Type of conditional expression must be complete in C mode.
5492   }
5493 
5494   // C99 6.5.15p5: "If both operands have void type, the result has void type."
5495   // The following || allows only one side to be void (a GCC-ism).
5496   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5497     return checkConditionalVoidType(*this, LHS, RHS);
5498   }
5499 
5500   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5501   // the type of the other operand."
5502   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5503   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5504 
5505   // All objective-c pointer type analysis is done here.
5506   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5507                                                         QuestionLoc);
5508   if (LHS.isInvalid() || RHS.isInvalid())
5509     return QualType();
5510   if (!compositeType.isNull())
5511     return compositeType;
5512 
5513 
5514   // Handle block pointer types.
5515   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5516     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5517                                                      QuestionLoc);
5518 
5519   // Check constraints for C object pointers types (C99 6.5.15p3,6).
5520   if (LHSTy->isPointerType() && RHSTy->isPointerType())
5521     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5522                                                        QuestionLoc);
5523 
5524   // GCC compatibility: soften pointer/integer mismatch.  Note that
5525   // null pointers have been filtered out by this point.
5526   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5527       /*isIntFirstExpr=*/true))
5528     return RHSTy;
5529   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5530       /*isIntFirstExpr=*/false))
5531     return LHSTy;
5532 
5533   // Emit a better diagnostic if one of the expressions is a null pointer
5534   // constant and the other is not a pointer type. In this case, the user most
5535   // likely forgot to take the address of the other expression.
5536   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5537     return QualType();
5538 
5539   // Otherwise, the operands are not compatible.
5540   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5541     << LHSTy << RHSTy << LHS.get()->getSourceRange()
5542     << RHS.get()->getSourceRange();
5543   return QualType();
5544 }
5545 
5546 /// FindCompositeObjCPointerType - Helper method to find composite type of
5547 /// two objective-c pointer types of the two input expressions.
5548 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5549                                             SourceLocation QuestionLoc) {
5550   QualType LHSTy = LHS.get()->getType();
5551   QualType RHSTy = RHS.get()->getType();
5552 
5553   // Handle things like Class and struct objc_class*.  Here we case the result
5554   // to the pseudo-builtin, because that will be implicitly cast back to the
5555   // redefinition type if an attempt is made to access its fields.
5556   if (LHSTy->isObjCClassType() &&
5557       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5558     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5559     return LHSTy;
5560   }
5561   if (RHSTy->isObjCClassType() &&
5562       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5563     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5564     return RHSTy;
5565   }
5566   // And the same for struct objc_object* / id
5567   if (LHSTy->isObjCIdType() &&
5568       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5569     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5570     return LHSTy;
5571   }
5572   if (RHSTy->isObjCIdType() &&
5573       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5574     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5575     return RHSTy;
5576   }
5577   // And the same for struct objc_selector* / SEL
5578   if (Context.isObjCSelType(LHSTy) &&
5579       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5580     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
5581     return LHSTy;
5582   }
5583   if (Context.isObjCSelType(RHSTy) &&
5584       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5585     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
5586     return RHSTy;
5587   }
5588   // Check constraints for Objective-C object pointers types.
5589   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5590 
5591     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5592       // Two identical object pointer types are always compatible.
5593       return LHSTy;
5594     }
5595     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5596     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5597     QualType compositeType = LHSTy;
5598 
5599     // If both operands are interfaces and either operand can be
5600     // assigned to the other, use that type as the composite
5601     // type. This allows
5602     //   xxx ? (A*) a : (B*) b
5603     // where B is a subclass of A.
5604     //
5605     // Additionally, as for assignment, if either type is 'id'
5606     // allow silent coercion. Finally, if the types are
5607     // incompatible then make sure to use 'id' as the composite
5608     // type so the result is acceptable for sending messages to.
5609 
5610     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5611     // It could return the composite type.
5612     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5613       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5614     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5615       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5616     } else if ((LHSTy->isObjCQualifiedIdType() ||
5617                 RHSTy->isObjCQualifiedIdType()) &&
5618                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5619       // Need to handle "id<xx>" explicitly.
5620       // GCC allows qualified id and any Objective-C type to devolve to
5621       // id. Currently localizing to here until clear this should be
5622       // part of ObjCQualifiedIdTypesAreCompatible.
5623       compositeType = Context.getObjCIdType();
5624     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5625       compositeType = Context.getObjCIdType();
5626     } else if (!(compositeType =
5627                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5628       ;
5629     else {
5630       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5631       << LHSTy << RHSTy
5632       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5633       QualType incompatTy = Context.getObjCIdType();
5634       LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5635       RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5636       return incompatTy;
5637     }
5638     // The object pointer types are compatible.
5639     LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5640     RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
5641     return compositeType;
5642   }
5643   // Check Objective-C object pointer types and 'void *'
5644   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5645     if (getLangOpts().ObjCAutoRefCount) {
5646       // ARC forbids the implicit conversion of object pointers to 'void *',
5647       // so these types are not compatible.
5648       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5649           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5650       LHS = RHS = true;
5651       return QualType();
5652     }
5653     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5654     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5655     QualType destPointee
5656     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5657     QualType destType = Context.getPointerType(destPointee);
5658     // Add qualifiers if necessary.
5659     LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5660     // Promote to void*.
5661     RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5662     return destType;
5663   }
5664   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5665     if (getLangOpts().ObjCAutoRefCount) {
5666       // ARC forbids the implicit conversion of object pointers to 'void *',
5667       // so these types are not compatible.
5668       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5669           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5670       LHS = RHS = true;
5671       return QualType();
5672     }
5673     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5674     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5675     QualType destPointee
5676     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5677     QualType destType = Context.getPointerType(destPointee);
5678     // Add qualifiers if necessary.
5679     RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5680     // Promote to void*.
5681     LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5682     return destType;
5683   }
5684   return QualType();
5685 }
5686 
5687 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5688 /// ParenRange in parentheses.
5689 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5690                                const PartialDiagnostic &Note,
5691                                SourceRange ParenRange) {
5692   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5693   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5694       EndLoc.isValid()) {
5695     Self.Diag(Loc, Note)
5696       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5697       << FixItHint::CreateInsertion(EndLoc, ")");
5698   } else {
5699     // We can't display the parentheses, so just show the bare note.
5700     Self.Diag(Loc, Note) << ParenRange;
5701   }
5702 }
5703 
5704 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5705   return Opc >= BO_Mul && Opc <= BO_Shr;
5706 }
5707 
5708 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5709 /// expression, either using a built-in or overloaded operator,
5710 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5711 /// expression.
5712 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5713                                    Expr **RHSExprs) {
5714   // Don't strip parenthesis: we should not warn if E is in parenthesis.
5715   E = E->IgnoreImpCasts();
5716   E = E->IgnoreConversionOperator();
5717   E = E->IgnoreImpCasts();
5718 
5719   // Built-in binary operator.
5720   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5721     if (IsArithmeticOp(OP->getOpcode())) {
5722       *Opcode = OP->getOpcode();
5723       *RHSExprs = OP->getRHS();
5724       return true;
5725     }
5726   }
5727 
5728   // Overloaded operator.
5729   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5730     if (Call->getNumArgs() != 2)
5731       return false;
5732 
5733     // Make sure this is really a binary operator that is safe to pass into
5734     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5735     OverloadedOperatorKind OO = Call->getOperator();
5736     if (OO < OO_Plus || OO > OO_Arrow ||
5737         OO == OO_PlusPlus || OO == OO_MinusMinus)
5738       return false;
5739 
5740     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5741     if (IsArithmeticOp(OpKind)) {
5742       *Opcode = OpKind;
5743       *RHSExprs = Call->getArg(1);
5744       return true;
5745     }
5746   }
5747 
5748   return false;
5749 }
5750 
5751 static bool IsLogicOp(BinaryOperatorKind Opc) {
5752   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5753 }
5754 
5755 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5756 /// or is a logical expression such as (x==y) which has int type, but is
5757 /// commonly interpreted as boolean.
5758 static bool ExprLooksBoolean(Expr *E) {
5759   E = E->IgnoreParenImpCasts();
5760 
5761   if (E->getType()->isBooleanType())
5762     return true;
5763   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5764     return IsLogicOp(OP->getOpcode());
5765   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5766     return OP->getOpcode() == UO_LNot;
5767 
5768   return false;
5769 }
5770 
5771 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5772 /// and binary operator are mixed in a way that suggests the programmer assumed
5773 /// the conditional operator has higher precedence, for example:
5774 /// "int x = a + someBinaryCondition ? 1 : 2".
5775 static void DiagnoseConditionalPrecedence(Sema &Self,
5776                                           SourceLocation OpLoc,
5777                                           Expr *Condition,
5778                                           Expr *LHSExpr,
5779                                           Expr *RHSExpr) {
5780   BinaryOperatorKind CondOpcode;
5781   Expr *CondRHS;
5782 
5783   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5784     return;
5785   if (!ExprLooksBoolean(CondRHS))
5786     return;
5787 
5788   // The condition is an arithmetic binary expression, with a right-
5789   // hand side that looks boolean, so warn.
5790 
5791   Self.Diag(OpLoc, diag::warn_precedence_conditional)
5792       << Condition->getSourceRange()
5793       << BinaryOperator::getOpcodeStr(CondOpcode);
5794 
5795   SuggestParentheses(Self, OpLoc,
5796     Self.PDiag(diag::note_precedence_silence)
5797       << BinaryOperator::getOpcodeStr(CondOpcode),
5798     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5799 
5800   SuggestParentheses(Self, OpLoc,
5801     Self.PDiag(diag::note_precedence_conditional_first),
5802     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5803 }
5804 
5805 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5806 /// in the case of a the GNU conditional expr extension.
5807 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5808                                     SourceLocation ColonLoc,
5809                                     Expr *CondExpr, Expr *LHSExpr,
5810                                     Expr *RHSExpr) {
5811   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5812   // was the condition.
5813   OpaqueValueExpr *opaqueValue = 0;
5814   Expr *commonExpr = 0;
5815   if (LHSExpr == 0) {
5816     commonExpr = CondExpr;
5817     // Lower out placeholder types first.  This is important so that we don't
5818     // try to capture a placeholder. This happens in few cases in C++; such
5819     // as Objective-C++'s dictionary subscripting syntax.
5820     if (commonExpr->hasPlaceholderType()) {
5821       ExprResult result = CheckPlaceholderExpr(commonExpr);
5822       if (!result.isUsable()) return ExprError();
5823       commonExpr = result.take();
5824     }
5825     // We usually want to apply unary conversions *before* saving, except
5826     // in the special case of a C++ l-value conditional.
5827     if (!(getLangOpts().CPlusPlus
5828           && !commonExpr->isTypeDependent()
5829           && commonExpr->getValueKind() == RHSExpr->getValueKind()
5830           && commonExpr->isGLValue()
5831           && commonExpr->isOrdinaryOrBitFieldObject()
5832           && RHSExpr->isOrdinaryOrBitFieldObject()
5833           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5834       ExprResult commonRes = UsualUnaryConversions(commonExpr);
5835       if (commonRes.isInvalid())
5836         return ExprError();
5837       commonExpr = commonRes.take();
5838     }
5839 
5840     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5841                                                 commonExpr->getType(),
5842                                                 commonExpr->getValueKind(),
5843                                                 commonExpr->getObjectKind(),
5844                                                 commonExpr);
5845     LHSExpr = CondExpr = opaqueValue;
5846   }
5847 
5848   ExprValueKind VK = VK_RValue;
5849   ExprObjectKind OK = OK_Ordinary;
5850   ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5851   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
5852                                              VK, OK, QuestionLoc);
5853   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5854       RHS.isInvalid())
5855     return ExprError();
5856 
5857   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5858                                 RHS.get());
5859 
5860   if (!commonExpr)
5861     return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5862                                                    LHS.take(), ColonLoc,
5863                                                    RHS.take(), result, VK, OK));
5864 
5865   return Owned(new (Context)
5866     BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5867                               RHS.take(), QuestionLoc, ColonLoc, result, VK,
5868                               OK));
5869 }
5870 
5871 // checkPointerTypesForAssignment - This is a very tricky routine (despite
5872 // being closely modeled after the C99 spec:-). The odd characteristic of this
5873 // routine is it effectively iqnores the qualifiers on the top level pointee.
5874 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5875 // FIXME: add a couple examples in this comment.
5876 static Sema::AssignConvertType
5877 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5878   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5879   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5880 
5881   // get the "pointed to" type (ignoring qualifiers at the top level)
5882   const Type *lhptee, *rhptee;
5883   Qualifiers lhq, rhq;
5884   llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5885   llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
5886 
5887   Sema::AssignConvertType ConvTy = Sema::Compatible;
5888 
5889   // C99 6.5.16.1p1: This following citation is common to constraints
5890   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5891   // qualifiers of the type *pointed to* by the right;
5892   Qualifiers lq;
5893 
5894   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5895   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5896       lhq.compatiblyIncludesObjCLifetime(rhq)) {
5897     // Ignore lifetime for further calculation.
5898     lhq.removeObjCLifetime();
5899     rhq.removeObjCLifetime();
5900   }
5901 
5902   if (!lhq.compatiblyIncludes(rhq)) {
5903     // Treat address-space mismatches as fatal.  TODO: address subspaces
5904     if (lhq.getAddressSpace() != rhq.getAddressSpace())
5905       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5906 
5907     // It's okay to add or remove GC or lifetime qualifiers when converting to
5908     // and from void*.
5909     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
5910                         .compatiblyIncludes(
5911                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
5912              && (lhptee->isVoidType() || rhptee->isVoidType()))
5913       ; // keep old
5914 
5915     // Treat lifetime mismatches as fatal.
5916     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5917       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5918 
5919     // For GCC compatibility, other qualifier mismatches are treated
5920     // as still compatible in C.
5921     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5922   }
5923 
5924   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5925   // incomplete type and the other is a pointer to a qualified or unqualified
5926   // version of void...
5927   if (lhptee->isVoidType()) {
5928     if (rhptee->isIncompleteOrObjectType())
5929       return ConvTy;
5930 
5931     // As an extension, we allow cast to/from void* to function pointer.
5932     assert(rhptee->isFunctionType());
5933     return Sema::FunctionVoidPointer;
5934   }
5935 
5936   if (rhptee->isVoidType()) {
5937     if (lhptee->isIncompleteOrObjectType())
5938       return ConvTy;
5939 
5940     // As an extension, we allow cast to/from void* to function pointer.
5941     assert(lhptee->isFunctionType());
5942     return Sema::FunctionVoidPointer;
5943   }
5944 
5945   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
5946   // unqualified versions of compatible types, ...
5947   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5948   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
5949     // Check if the pointee types are compatible ignoring the sign.
5950     // We explicitly check for char so that we catch "char" vs
5951     // "unsigned char" on systems where "char" is unsigned.
5952     if (lhptee->isCharType())
5953       ltrans = S.Context.UnsignedCharTy;
5954     else if (lhptee->hasSignedIntegerRepresentation())
5955       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
5956 
5957     if (rhptee->isCharType())
5958       rtrans = S.Context.UnsignedCharTy;
5959     else if (rhptee->hasSignedIntegerRepresentation())
5960       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
5961 
5962     if (ltrans == rtrans) {
5963       // Types are compatible ignoring the sign. Qualifier incompatibility
5964       // takes priority over sign incompatibility because the sign
5965       // warning can be disabled.
5966       if (ConvTy != Sema::Compatible)
5967         return ConvTy;
5968 
5969       return Sema::IncompatiblePointerSign;
5970     }
5971 
5972     // If we are a multi-level pointer, it's possible that our issue is simply
5973     // one of qualification - e.g. char ** -> const char ** is not allowed. If
5974     // the eventual target type is the same and the pointers have the same
5975     // level of indirection, this must be the issue.
5976     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
5977       do {
5978         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5979         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
5980       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
5981 
5982       if (lhptee == rhptee)
5983         return Sema::IncompatibleNestedPointerQualifiers;
5984     }
5985 
5986     // General pointer incompatibility takes priority over qualifiers.
5987     return Sema::IncompatiblePointer;
5988   }
5989   if (!S.getLangOpts().CPlusPlus &&
5990       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5991     return Sema::IncompatiblePointer;
5992   return ConvTy;
5993 }
5994 
5995 /// checkBlockPointerTypesForAssignment - This routine determines whether two
5996 /// block pointer types are compatible or whether a block and normal pointer
5997 /// are compatible. It is more restrict than comparing two function pointer
5998 // types.
5999 static Sema::AssignConvertType
6000 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6001                                     QualType RHSType) {
6002   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6003   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6004 
6005   QualType lhptee, rhptee;
6006 
6007   // get the "pointed to" type (ignoring qualifiers at the top level)
6008   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6009   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6010 
6011   // In C++, the types have to match exactly.
6012   if (S.getLangOpts().CPlusPlus)
6013     return Sema::IncompatibleBlockPointer;
6014 
6015   Sema::AssignConvertType ConvTy = Sema::Compatible;
6016 
6017   // For blocks we enforce that qualifiers are identical.
6018   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6019     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6020 
6021   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6022     return Sema::IncompatibleBlockPointer;
6023 
6024   return ConvTy;
6025 }
6026 
6027 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6028 /// for assignment compatibility.
6029 static Sema::AssignConvertType
6030 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6031                                    QualType RHSType) {
6032   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6033   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6034 
6035   if (LHSType->isObjCBuiltinType()) {
6036     // Class is not compatible with ObjC object pointers.
6037     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6038         !RHSType->isObjCQualifiedClassType())
6039       return Sema::IncompatiblePointer;
6040     return Sema::Compatible;
6041   }
6042   if (RHSType->isObjCBuiltinType()) {
6043     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6044         !LHSType->isObjCQualifiedClassType())
6045       return Sema::IncompatiblePointer;
6046     return Sema::Compatible;
6047   }
6048   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6049   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6050 
6051   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6052       // make an exception for id<P>
6053       !LHSType->isObjCQualifiedIdType())
6054     return Sema::CompatiblePointerDiscardsQualifiers;
6055 
6056   if (S.Context.typesAreCompatible(LHSType, RHSType))
6057     return Sema::Compatible;
6058   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6059     return Sema::IncompatibleObjCQualifiedId;
6060   return Sema::IncompatiblePointer;
6061 }
6062 
6063 Sema::AssignConvertType
6064 Sema::CheckAssignmentConstraints(SourceLocation Loc,
6065                                  QualType LHSType, QualType RHSType) {
6066   // Fake up an opaque expression.  We don't actually care about what
6067   // cast operations are required, so if CheckAssignmentConstraints
6068   // adds casts to this they'll be wasted, but fortunately that doesn't
6069   // usually happen on valid code.
6070   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6071   ExprResult RHSPtr = &RHSExpr;
6072   CastKind K = CK_Invalid;
6073 
6074   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
6075 }
6076 
6077 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6078 /// has code to accommodate several GCC extensions when type checking
6079 /// pointers. Here are some objectionable examples that GCC considers warnings:
6080 ///
6081 ///  int a, *pint;
6082 ///  short *pshort;
6083 ///  struct foo *pfoo;
6084 ///
6085 ///  pint = pshort; // warning: assignment from incompatible pointer type
6086 ///  a = pint; // warning: assignment makes integer from pointer without a cast
6087 ///  pint = a; // warning: assignment makes pointer from integer without a cast
6088 ///  pint = pfoo; // warning: assignment from incompatible pointer type
6089 ///
6090 /// As a result, the code for dealing with pointers is more complex than the
6091 /// C99 spec dictates.
6092 ///
6093 /// Sets 'Kind' for any result kind except Incompatible.
6094 Sema::AssignConvertType
6095 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6096                                  CastKind &Kind) {
6097   QualType RHSType = RHS.get()->getType();
6098   QualType OrigLHSType = LHSType;
6099 
6100   // Get canonical types.  We're not formatting these types, just comparing
6101   // them.
6102   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6103   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6104 
6105   // Common case: no conversion required.
6106   if (LHSType == RHSType) {
6107     Kind = CK_NoOp;
6108     return Compatible;
6109   }
6110 
6111   // If we have an atomic type, try a non-atomic assignment, then just add an
6112   // atomic qualification step.
6113   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6114     Sema::AssignConvertType result =
6115       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6116     if (result != Compatible)
6117       return result;
6118     if (Kind != CK_NoOp)
6119       RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
6120     Kind = CK_NonAtomicToAtomic;
6121     return Compatible;
6122   }
6123 
6124   // If the left-hand side is a reference type, then we are in a
6125   // (rare!) case where we've allowed the use of references in C,
6126   // e.g., as a parameter type in a built-in function. In this case,
6127   // just make sure that the type referenced is compatible with the
6128   // right-hand side type. The caller is responsible for adjusting
6129   // LHSType so that the resulting expression does not have reference
6130   // type.
6131   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6132     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6133       Kind = CK_LValueBitCast;
6134       return Compatible;
6135     }
6136     return Incompatible;
6137   }
6138 
6139   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6140   // to the same ExtVector type.
6141   if (LHSType->isExtVectorType()) {
6142     if (RHSType->isExtVectorType())
6143       return Incompatible;
6144     if (RHSType->isArithmeticType()) {
6145       // CK_VectorSplat does T -> vector T, so first cast to the
6146       // element type.
6147       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6148       if (elType != RHSType) {
6149         Kind = PrepareScalarCast(RHS, elType);
6150         RHS = ImpCastExprToType(RHS.take(), elType, Kind);
6151       }
6152       Kind = CK_VectorSplat;
6153       return Compatible;
6154     }
6155   }
6156 
6157   // Conversions to or from vector type.
6158   if (LHSType->isVectorType() || RHSType->isVectorType()) {
6159     if (LHSType->isVectorType() && RHSType->isVectorType()) {
6160       // Allow assignments of an AltiVec vector type to an equivalent GCC
6161       // vector type and vice versa
6162       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6163         Kind = CK_BitCast;
6164         return Compatible;
6165       }
6166 
6167       // If we are allowing lax vector conversions, and LHS and RHS are both
6168       // vectors, the total size only needs to be the same. This is a bitcast;
6169       // no bits are changed but the result type is different.
6170       if (getLangOpts().LaxVectorConversions &&
6171           (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
6172         Kind = CK_BitCast;
6173         return IncompatibleVectors;
6174       }
6175     }
6176     return Incompatible;
6177   }
6178 
6179   // Arithmetic conversions.
6180   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
6181       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
6182     Kind = PrepareScalarCast(RHS, LHSType);
6183     return Compatible;
6184   }
6185 
6186   // Conversions to normal pointers.
6187   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
6188     // U* -> T*
6189     if (isa<PointerType>(RHSType)) {
6190       Kind = CK_BitCast;
6191       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
6192     }
6193 
6194     // int -> T*
6195     if (RHSType->isIntegerType()) {
6196       Kind = CK_IntegralToPointer; // FIXME: null?
6197       return IntToPointer;
6198     }
6199 
6200     // C pointers are not compatible with ObjC object pointers,
6201     // with two exceptions:
6202     if (isa<ObjCObjectPointerType>(RHSType)) {
6203       //  - conversions to void*
6204       if (LHSPointer->getPointeeType()->isVoidType()) {
6205         Kind = CK_BitCast;
6206         return Compatible;
6207       }
6208 
6209       //  - conversions from 'Class' to the redefinition type
6210       if (RHSType->isObjCClassType() &&
6211           Context.hasSameType(LHSType,
6212                               Context.getObjCClassRedefinitionType())) {
6213         Kind = CK_BitCast;
6214         return Compatible;
6215       }
6216 
6217       Kind = CK_BitCast;
6218       return IncompatiblePointer;
6219     }
6220 
6221     // U^ -> void*
6222     if (RHSType->getAs<BlockPointerType>()) {
6223       if (LHSPointer->getPointeeType()->isVoidType()) {
6224         Kind = CK_BitCast;
6225         return Compatible;
6226       }
6227     }
6228 
6229     return Incompatible;
6230   }
6231 
6232   // Conversions to block pointers.
6233   if (isa<BlockPointerType>(LHSType)) {
6234     // U^ -> T^
6235     if (RHSType->isBlockPointerType()) {
6236       Kind = CK_BitCast;
6237       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
6238     }
6239 
6240     // int or null -> T^
6241     if (RHSType->isIntegerType()) {
6242       Kind = CK_IntegralToPointer; // FIXME: null
6243       return IntToBlockPointer;
6244     }
6245 
6246     // id -> T^
6247     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
6248       Kind = CK_AnyPointerToBlockPointerCast;
6249       return Compatible;
6250     }
6251 
6252     // void* -> T^
6253     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
6254       if (RHSPT->getPointeeType()->isVoidType()) {
6255         Kind = CK_AnyPointerToBlockPointerCast;
6256         return Compatible;
6257       }
6258 
6259     return Incompatible;
6260   }
6261 
6262   // Conversions to Objective-C pointers.
6263   if (isa<ObjCObjectPointerType>(LHSType)) {
6264     // A* -> B*
6265     if (RHSType->isObjCObjectPointerType()) {
6266       Kind = CK_BitCast;
6267       Sema::AssignConvertType result =
6268         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
6269       if (getLangOpts().ObjCAutoRefCount &&
6270           result == Compatible &&
6271           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
6272         result = IncompatibleObjCWeakRef;
6273       return result;
6274     }
6275 
6276     // int or null -> A*
6277     if (RHSType->isIntegerType()) {
6278       Kind = CK_IntegralToPointer; // FIXME: null
6279       return IntToPointer;
6280     }
6281 
6282     // In general, C pointers are not compatible with ObjC object pointers,
6283     // with two exceptions:
6284     if (isa<PointerType>(RHSType)) {
6285       Kind = CK_CPointerToObjCPointerCast;
6286 
6287       //  - conversions from 'void*'
6288       if (RHSType->isVoidPointerType()) {
6289         return Compatible;
6290       }
6291 
6292       //  - conversions to 'Class' from its redefinition type
6293       if (LHSType->isObjCClassType() &&
6294           Context.hasSameType(RHSType,
6295                               Context.getObjCClassRedefinitionType())) {
6296         return Compatible;
6297       }
6298 
6299       return IncompatiblePointer;
6300     }
6301 
6302     // T^ -> A*
6303     if (RHSType->isBlockPointerType()) {
6304       maybeExtendBlockObject(*this, RHS);
6305       Kind = CK_BlockPointerToObjCPointerCast;
6306       return Compatible;
6307     }
6308 
6309     return Incompatible;
6310   }
6311 
6312   // Conversions from pointers that are not covered by the above.
6313   if (isa<PointerType>(RHSType)) {
6314     // T* -> _Bool
6315     if (LHSType == Context.BoolTy) {
6316       Kind = CK_PointerToBoolean;
6317       return Compatible;
6318     }
6319 
6320     // T* -> int
6321     if (LHSType->isIntegerType()) {
6322       Kind = CK_PointerToIntegral;
6323       return PointerToInt;
6324     }
6325 
6326     return Incompatible;
6327   }
6328 
6329   // Conversions from Objective-C pointers that are not covered by the above.
6330   if (isa<ObjCObjectPointerType>(RHSType)) {
6331     // T* -> _Bool
6332     if (LHSType == Context.BoolTy) {
6333       Kind = CK_PointerToBoolean;
6334       return Compatible;
6335     }
6336 
6337     // T* -> int
6338     if (LHSType->isIntegerType()) {
6339       Kind = CK_PointerToIntegral;
6340       return PointerToInt;
6341     }
6342 
6343     return Incompatible;
6344   }
6345 
6346   // struct A -> struct B
6347   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6348     if (Context.typesAreCompatible(LHSType, RHSType)) {
6349       Kind = CK_NoOp;
6350       return Compatible;
6351     }
6352   }
6353 
6354   return Incompatible;
6355 }
6356 
6357 /// \brief Constructs a transparent union from an expression that is
6358 /// used to initialize the transparent union.
6359 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6360                                       ExprResult &EResult, QualType UnionType,
6361                                       FieldDecl *Field) {
6362   // Build an initializer list that designates the appropriate member
6363   // of the transparent union.
6364   Expr *E = EResult.take();
6365   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6366                                                    E, SourceLocation());
6367   Initializer->setType(UnionType);
6368   Initializer->setInitializedFieldInUnion(Field);
6369 
6370   // Build a compound literal constructing a value of the transparent
6371   // union type from this initializer list.
6372   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6373   EResult = S.Owned(
6374     new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6375                                 VK_RValue, Initializer, false));
6376 }
6377 
6378 Sema::AssignConvertType
6379 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
6380                                                ExprResult &RHS) {
6381   QualType RHSType = RHS.get()->getType();
6382 
6383   // If the ArgType is a Union type, we want to handle a potential
6384   // transparent_union GCC extension.
6385   const RecordType *UT = ArgType->getAsUnionType();
6386   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6387     return Incompatible;
6388 
6389   // The field to initialize within the transparent union.
6390   RecordDecl *UD = UT->getDecl();
6391   FieldDecl *InitField = 0;
6392   // It's compatible if the expression matches any of the fields.
6393   for (RecordDecl::field_iterator it = UD->field_begin(),
6394          itend = UD->field_end();
6395        it != itend; ++it) {
6396     if (it->getType()->isPointerType()) {
6397       // If the transparent union contains a pointer type, we allow:
6398       // 1) void pointer
6399       // 2) null pointer constant
6400       if (RHSType->isPointerType())
6401         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6402           RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
6403           InitField = *it;
6404           break;
6405         }
6406 
6407       if (RHS.get()->isNullPointerConstant(Context,
6408                                            Expr::NPC_ValueDependentIsNull)) {
6409         RHS = ImpCastExprToType(RHS.take(), it->getType(),
6410                                 CK_NullToPointer);
6411         InitField = *it;
6412         break;
6413       }
6414     }
6415 
6416     CastKind Kind = CK_Invalid;
6417     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6418           == Compatible) {
6419       RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
6420       InitField = *it;
6421       break;
6422     }
6423   }
6424 
6425   if (!InitField)
6426     return Incompatible;
6427 
6428   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6429   return Compatible;
6430 }
6431 
6432 Sema::AssignConvertType
6433 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6434                                        bool Diagnose,
6435                                        bool DiagnoseCFAudited) {
6436   if (getLangOpts().CPlusPlus) {
6437     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6438       // C++ 5.17p3: If the left operand is not of class type, the
6439       // expression is implicitly converted (C++ 4) to the
6440       // cv-unqualified type of the left operand.
6441       ExprResult Res;
6442       if (Diagnose) {
6443         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6444                                         AA_Assigning);
6445       } else {
6446         ImplicitConversionSequence ICS =
6447             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6448                                   /*SuppressUserConversions=*/false,
6449                                   /*AllowExplicit=*/false,
6450                                   /*InOverloadResolution=*/false,
6451                                   /*CStyle=*/false,
6452                                   /*AllowObjCWritebackConversion=*/false);
6453         if (ICS.isFailure())
6454           return Incompatible;
6455         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6456                                         ICS, AA_Assigning);
6457       }
6458       if (Res.isInvalid())
6459         return Incompatible;
6460       Sema::AssignConvertType result = Compatible;
6461       if (getLangOpts().ObjCAutoRefCount &&
6462           !CheckObjCARCUnavailableWeakConversion(LHSType,
6463                                                  RHS.get()->getType()))
6464         result = IncompatibleObjCWeakRef;
6465       RHS = Res;
6466       return result;
6467     }
6468 
6469     // FIXME: Currently, we fall through and treat C++ classes like C
6470     // structures.
6471     // FIXME: We also fall through for atomics; not sure what should
6472     // happen there, though.
6473   }
6474 
6475   // C99 6.5.16.1p1: the left operand is a pointer and the right is
6476   // a null pointer constant.
6477   if ((LHSType->isPointerType() ||
6478        LHSType->isObjCObjectPointerType() ||
6479        LHSType->isBlockPointerType())
6480       && RHS.get()->isNullPointerConstant(Context,
6481                                           Expr::NPC_ValueDependentIsNull)) {
6482     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
6483     return Compatible;
6484   }
6485 
6486   // This check seems unnatural, however it is necessary to ensure the proper
6487   // conversion of functions/arrays. If the conversion were done for all
6488   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6489   // expressions that suppress this implicit conversion (&, sizeof).
6490   //
6491   // Suppress this for references: C++ 8.5.3p5.
6492   if (!LHSType->isReferenceType()) {
6493     RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6494     if (RHS.isInvalid())
6495       return Incompatible;
6496   }
6497 
6498   CastKind Kind = CK_Invalid;
6499   Sema::AssignConvertType result =
6500     CheckAssignmentConstraints(LHSType, RHS, Kind);
6501 
6502   // C99 6.5.16.1p2: The value of the right operand is converted to the
6503   // type of the assignment expression.
6504   // CheckAssignmentConstraints allows the left-hand side to be a reference,
6505   // so that we can use references in built-in functions even in C.
6506   // The getNonReferenceType() call makes sure that the resulting expression
6507   // does not have reference type.
6508   if (result != Incompatible && RHS.get()->getType() != LHSType) {
6509     QualType Ty = LHSType.getNonLValueExprType(Context);
6510     Expr *E = RHS.take();
6511     if (getLangOpts().ObjCAutoRefCount)
6512       CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
6513                              DiagnoseCFAudited);
6514     RHS = ImpCastExprToType(E, Ty, Kind);
6515   }
6516   return result;
6517 }
6518 
6519 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6520                                ExprResult &RHS) {
6521   Diag(Loc, diag::err_typecheck_invalid_operands)
6522     << LHS.get()->getType() << RHS.get()->getType()
6523     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6524   return QualType();
6525 }
6526 
6527 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6528                                    SourceLocation Loc, bool IsCompAssign) {
6529   if (!IsCompAssign) {
6530     LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6531     if (LHS.isInvalid())
6532       return QualType();
6533   }
6534   RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6535   if (RHS.isInvalid())
6536     return QualType();
6537 
6538   // For conversion purposes, we ignore any qualifiers.
6539   // For example, "const float" and "float" are equivalent.
6540   QualType LHSType =
6541     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6542   QualType RHSType =
6543     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6544 
6545   // If the vector types are identical, return.
6546   if (LHSType == RHSType)
6547     return LHSType;
6548 
6549   // Handle the case of equivalent AltiVec and GCC vector types
6550   if (LHSType->isVectorType() && RHSType->isVectorType() &&
6551       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6552     if (LHSType->isExtVectorType()) {
6553       RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6554       return LHSType;
6555     }
6556 
6557     if (!IsCompAssign)
6558       LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6559     return RHSType;
6560   }
6561 
6562   if (getLangOpts().LaxVectorConversions &&
6563       Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
6564     // If we are allowing lax vector conversions, and LHS and RHS are both
6565     // vectors, the total size only needs to be the same. This is a
6566     // bitcast; no bits are changed but the result type is different.
6567     // FIXME: Should we really be allowing this?
6568     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6569     return LHSType;
6570   }
6571 
6572   // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6573   // swap back (so that we don't reverse the inputs to a subtract, for instance.
6574   bool swapped = false;
6575   if (RHSType->isExtVectorType() && !IsCompAssign) {
6576     swapped = true;
6577     std::swap(RHS, LHS);
6578     std::swap(RHSType, LHSType);
6579   }
6580 
6581   // Handle the case of an ext vector and scalar.
6582   if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
6583     QualType EltTy = LV->getElementType();
6584     if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6585       int order = Context.getIntegerTypeOrder(EltTy, RHSType);
6586       if (order > 0)
6587         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
6588       if (order >= 0) {
6589         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6590         if (swapped) std::swap(RHS, LHS);
6591         return LHSType;
6592       }
6593     }
6594     if (EltTy->isRealFloatingType() && RHSType->isScalarType()) {
6595       if (RHSType->isRealFloatingType()) {
6596         int order = Context.getFloatingTypeOrder(EltTy, RHSType);
6597         if (order > 0)
6598           RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
6599         if (order >= 0) {
6600           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6601           if (swapped) std::swap(RHS, LHS);
6602           return LHSType;
6603         }
6604       }
6605       if (RHSType->isIntegralType(Context)) {
6606         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralToFloating);
6607         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6608         if (swapped) std::swap(RHS, LHS);
6609         return LHSType;
6610       }
6611     }
6612   }
6613 
6614   // Vectors of different size or scalar and non-ext-vector are errors.
6615   if (swapped) std::swap(RHS, LHS);
6616   Diag(Loc, diag::err_typecheck_vector_not_convertable)
6617     << LHS.get()->getType() << RHS.get()->getType()
6618     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6619   return QualType();
6620 }
6621 
6622 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6623 // expression.  These are mainly cases where the null pointer is used as an
6624 // integer instead of a pointer.
6625 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6626                                 SourceLocation Loc, bool IsCompare) {
6627   // The canonical way to check for a GNU null is with isNullPointerConstant,
6628   // but we use a bit of a hack here for speed; this is a relatively
6629   // hot path, and isNullPointerConstant is slow.
6630   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6631   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6632 
6633   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6634 
6635   // Avoid analyzing cases where the result will either be invalid (and
6636   // diagnosed as such) or entirely valid and not something to warn about.
6637   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6638       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6639     return;
6640 
6641   // Comparison operations would not make sense with a null pointer no matter
6642   // what the other expression is.
6643   if (!IsCompare) {
6644     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6645         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6646         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6647     return;
6648   }
6649 
6650   // The rest of the operations only make sense with a null pointer
6651   // if the other expression is a pointer.
6652   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6653       NonNullType->canDecayToPointerType())
6654     return;
6655 
6656   S.Diag(Loc, diag::warn_null_in_comparison_operation)
6657       << LHSNull /* LHS is NULL */ << NonNullType
6658       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6659 }
6660 
6661 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6662                                            SourceLocation Loc,
6663                                            bool IsCompAssign, bool IsDiv) {
6664   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6665 
6666   if (LHS.get()->getType()->isVectorType() ||
6667       RHS.get()->getType()->isVectorType())
6668     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6669 
6670   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6671   if (LHS.isInvalid() || RHS.isInvalid())
6672     return QualType();
6673 
6674 
6675   if (compType.isNull() || !compType->isArithmeticType())
6676     return InvalidOperands(Loc, LHS, RHS);
6677 
6678   // Check for division by zero.
6679   llvm::APSInt RHSValue;
6680   if (IsDiv && !RHS.get()->isValueDependent() &&
6681       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6682     DiagRuntimeBehavior(Loc, RHS.get(),
6683                         PDiag(diag::warn_division_by_zero)
6684                           << RHS.get()->getSourceRange());
6685 
6686   return compType;
6687 }
6688 
6689 QualType Sema::CheckRemainderOperands(
6690   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6691   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6692 
6693   if (LHS.get()->getType()->isVectorType() ||
6694       RHS.get()->getType()->isVectorType()) {
6695     if (LHS.get()->getType()->hasIntegerRepresentation() &&
6696         RHS.get()->getType()->hasIntegerRepresentation())
6697       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6698     return InvalidOperands(Loc, LHS, RHS);
6699   }
6700 
6701   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6702   if (LHS.isInvalid() || RHS.isInvalid())
6703     return QualType();
6704 
6705   if (compType.isNull() || !compType->isIntegerType())
6706     return InvalidOperands(Loc, LHS, RHS);
6707 
6708   // Check for remainder by zero.
6709   llvm::APSInt RHSValue;
6710   if (!RHS.get()->isValueDependent() &&
6711       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6712     DiagRuntimeBehavior(Loc, RHS.get(),
6713                         PDiag(diag::warn_remainder_by_zero)
6714                           << RHS.get()->getSourceRange());
6715 
6716   return compType;
6717 }
6718 
6719 /// \brief Diagnose invalid arithmetic on two void pointers.
6720 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
6721                                                 Expr *LHSExpr, Expr *RHSExpr) {
6722   S.Diag(Loc, S.getLangOpts().CPlusPlus
6723                 ? diag::err_typecheck_pointer_arith_void_type
6724                 : diag::ext_gnu_void_ptr)
6725     << 1 /* two pointers */ << LHSExpr->getSourceRange()
6726                             << RHSExpr->getSourceRange();
6727 }
6728 
6729 /// \brief Diagnose invalid arithmetic on a void pointer.
6730 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6731                                             Expr *Pointer) {
6732   S.Diag(Loc, S.getLangOpts().CPlusPlus
6733                 ? diag::err_typecheck_pointer_arith_void_type
6734                 : diag::ext_gnu_void_ptr)
6735     << 0 /* one pointer */ << Pointer->getSourceRange();
6736 }
6737 
6738 /// \brief Diagnose invalid arithmetic on two function pointers.
6739 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6740                                                     Expr *LHS, Expr *RHS) {
6741   assert(LHS->getType()->isAnyPointerType());
6742   assert(RHS->getType()->isAnyPointerType());
6743   S.Diag(Loc, S.getLangOpts().CPlusPlus
6744                 ? diag::err_typecheck_pointer_arith_function_type
6745                 : diag::ext_gnu_ptr_func_arith)
6746     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6747     // We only show the second type if it differs from the first.
6748     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6749                                                    RHS->getType())
6750     << RHS->getType()->getPointeeType()
6751     << LHS->getSourceRange() << RHS->getSourceRange();
6752 }
6753 
6754 /// \brief Diagnose invalid arithmetic on a function pointer.
6755 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6756                                                 Expr *Pointer) {
6757   assert(Pointer->getType()->isAnyPointerType());
6758   S.Diag(Loc, S.getLangOpts().CPlusPlus
6759                 ? diag::err_typecheck_pointer_arith_function_type
6760                 : diag::ext_gnu_ptr_func_arith)
6761     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6762     << 0 /* one pointer, so only one type */
6763     << Pointer->getSourceRange();
6764 }
6765 
6766 /// \brief Emit error if Operand is incomplete pointer type
6767 ///
6768 /// \returns True if pointer has incomplete type
6769 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6770                                                  Expr *Operand) {
6771   assert(Operand->getType()->isAnyPointerType() &&
6772          !Operand->getType()->isDependentType());
6773   QualType PointeeTy = Operand->getType()->getPointeeType();
6774   return S.RequireCompleteType(Loc, PointeeTy,
6775                                diag::err_typecheck_arithmetic_incomplete_type,
6776                                PointeeTy, Operand->getSourceRange());
6777 }
6778 
6779 /// \brief Check the validity of an arithmetic pointer operand.
6780 ///
6781 /// If the operand has pointer type, this code will check for pointer types
6782 /// which are invalid in arithmetic operations. These will be diagnosed
6783 /// appropriately, including whether or not the use is supported as an
6784 /// extension.
6785 ///
6786 /// \returns True when the operand is valid to use (even if as an extension).
6787 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6788                                             Expr *Operand) {
6789   if (!Operand->getType()->isAnyPointerType()) return true;
6790 
6791   QualType PointeeTy = Operand->getType()->getPointeeType();
6792   if (PointeeTy->isVoidType()) {
6793     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6794     return !S.getLangOpts().CPlusPlus;
6795   }
6796   if (PointeeTy->isFunctionType()) {
6797     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6798     return !S.getLangOpts().CPlusPlus;
6799   }
6800 
6801   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
6802 
6803   return true;
6804 }
6805 
6806 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6807 /// operands.
6808 ///
6809 /// This routine will diagnose any invalid arithmetic on pointer operands much
6810 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
6811 /// for emitting a single diagnostic even for operations where both LHS and RHS
6812 /// are (potentially problematic) pointers.
6813 ///
6814 /// \returns True when the operand is valid to use (even if as an extension).
6815 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
6816                                                 Expr *LHSExpr, Expr *RHSExpr) {
6817   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6818   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
6819   if (!isLHSPointer && !isRHSPointer) return true;
6820 
6821   QualType LHSPointeeTy, RHSPointeeTy;
6822   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6823   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
6824 
6825   // Check for arithmetic on pointers to incomplete types.
6826   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6827   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6828   if (isLHSVoidPtr || isRHSVoidPtr) {
6829     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6830     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6831     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
6832 
6833     return !S.getLangOpts().CPlusPlus;
6834   }
6835 
6836   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6837   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6838   if (isLHSFuncPtr || isRHSFuncPtr) {
6839     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6840     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6841                                                                 RHSExpr);
6842     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
6843 
6844     return !S.getLangOpts().CPlusPlus;
6845   }
6846 
6847   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6848     return false;
6849   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6850     return false;
6851 
6852   return true;
6853 }
6854 
6855 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6856 /// literal.
6857 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6858                                   Expr *LHSExpr, Expr *RHSExpr) {
6859   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6860   Expr* IndexExpr = RHSExpr;
6861   if (!StrExpr) {
6862     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6863     IndexExpr = LHSExpr;
6864   }
6865 
6866   bool IsStringPlusInt = StrExpr &&
6867       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6868   if (!IsStringPlusInt)
6869     return;
6870 
6871   llvm::APSInt index;
6872   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6873     unsigned StrLenWithNull = StrExpr->getLength() + 1;
6874     if (index.isNonNegative() &&
6875         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6876                               index.isUnsigned()))
6877       return;
6878   }
6879 
6880   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6881   Self.Diag(OpLoc, diag::warn_string_plus_int)
6882       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6883 
6884   // Only print a fixit for "str" + int, not for int + "str".
6885   if (IndexExpr == RHSExpr) {
6886     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6887     Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6888         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6889         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6890         << FixItHint::CreateInsertion(EndLoc, "]");
6891   } else
6892     Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6893 }
6894 
6895 /// \brief Emit error when two pointers are incompatible.
6896 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
6897                                            Expr *LHSExpr, Expr *RHSExpr) {
6898   assert(LHSExpr->getType()->isAnyPointerType());
6899   assert(RHSExpr->getType()->isAnyPointerType());
6900   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6901     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6902     << RHSExpr->getSourceRange();
6903 }
6904 
6905 QualType Sema::CheckAdditionOperands( // C99 6.5.6
6906     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6907     QualType* CompLHSTy) {
6908   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6909 
6910   if (LHS.get()->getType()->isVectorType() ||
6911       RHS.get()->getType()->isVectorType()) {
6912     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6913     if (CompLHSTy) *CompLHSTy = compType;
6914     return compType;
6915   }
6916 
6917   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6918   if (LHS.isInvalid() || RHS.isInvalid())
6919     return QualType();
6920 
6921   // Diagnose "string literal" '+' int.
6922   if (Opc == BO_Add)
6923     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6924 
6925   // handle the common case first (both operands are arithmetic).
6926   if (!compType.isNull() && compType->isArithmeticType()) {
6927     if (CompLHSTy) *CompLHSTy = compType;
6928     return compType;
6929   }
6930 
6931   // Type-checking.  Ultimately the pointer's going to be in PExp;
6932   // note that we bias towards the LHS being the pointer.
6933   Expr *PExp = LHS.get(), *IExp = RHS.get();
6934 
6935   bool isObjCPointer;
6936   if (PExp->getType()->isPointerType()) {
6937     isObjCPointer = false;
6938   } else if (PExp->getType()->isObjCObjectPointerType()) {
6939     isObjCPointer = true;
6940   } else {
6941     std::swap(PExp, IExp);
6942     if (PExp->getType()->isPointerType()) {
6943       isObjCPointer = false;
6944     } else if (PExp->getType()->isObjCObjectPointerType()) {
6945       isObjCPointer = true;
6946     } else {
6947       return InvalidOperands(Loc, LHS, RHS);
6948     }
6949   }
6950   assert(PExp->getType()->isAnyPointerType());
6951 
6952   if (!IExp->getType()->isIntegerType())
6953     return InvalidOperands(Loc, LHS, RHS);
6954 
6955   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6956     return QualType();
6957 
6958   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
6959     return QualType();
6960 
6961   // Check array bounds for pointer arithemtic
6962   CheckArrayAccess(PExp, IExp);
6963 
6964   if (CompLHSTy) {
6965     QualType LHSTy = Context.isPromotableBitField(LHS.get());
6966     if (LHSTy.isNull()) {
6967       LHSTy = LHS.get()->getType();
6968       if (LHSTy->isPromotableIntegerType())
6969         LHSTy = Context.getPromotedIntegerType(LHSTy);
6970     }
6971     *CompLHSTy = LHSTy;
6972   }
6973 
6974   return PExp->getType();
6975 }
6976 
6977 // C99 6.5.6
6978 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
6979                                         SourceLocation Loc,
6980                                         QualType* CompLHSTy) {
6981   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6982 
6983   if (LHS.get()->getType()->isVectorType() ||
6984       RHS.get()->getType()->isVectorType()) {
6985     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6986     if (CompLHSTy) *CompLHSTy = compType;
6987     return compType;
6988   }
6989 
6990   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6991   if (LHS.isInvalid() || RHS.isInvalid())
6992     return QualType();
6993 
6994   // Enforce type constraints: C99 6.5.6p3.
6995 
6996   // Handle the common case first (both operands are arithmetic).
6997   if (!compType.isNull() && compType->isArithmeticType()) {
6998     if (CompLHSTy) *CompLHSTy = compType;
6999     return compType;
7000   }
7001 
7002   // Either ptr - int   or   ptr - ptr.
7003   if (LHS.get()->getType()->isAnyPointerType()) {
7004     QualType lpointee = LHS.get()->getType()->getPointeeType();
7005 
7006     // Diagnose bad cases where we step over interface counts.
7007     if (LHS.get()->getType()->isObjCObjectPointerType() &&
7008         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
7009       return QualType();
7010 
7011     // The result type of a pointer-int computation is the pointer type.
7012     if (RHS.get()->getType()->isIntegerType()) {
7013       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
7014         return QualType();
7015 
7016       // Check array bounds for pointer arithemtic
7017       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
7018                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
7019 
7020       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7021       return LHS.get()->getType();
7022     }
7023 
7024     // Handle pointer-pointer subtractions.
7025     if (const PointerType *RHSPTy
7026           = RHS.get()->getType()->getAs<PointerType>()) {
7027       QualType rpointee = RHSPTy->getPointeeType();
7028 
7029       if (getLangOpts().CPlusPlus) {
7030         // Pointee types must be the same: C++ [expr.add]
7031         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7032           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7033         }
7034       } else {
7035         // Pointee types must be compatible C99 6.5.6p3
7036         if (!Context.typesAreCompatible(
7037                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7038                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7039           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7040           return QualType();
7041         }
7042       }
7043 
7044       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
7045                                                LHS.get(), RHS.get()))
7046         return QualType();
7047 
7048       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7049       return Context.getPointerDiffType();
7050     }
7051   }
7052 
7053   return InvalidOperands(Loc, LHS, RHS);
7054 }
7055 
7056 static bool isScopedEnumerationType(QualType T) {
7057   if (const EnumType *ET = dyn_cast<EnumType>(T))
7058     return ET->getDecl()->isScoped();
7059   return false;
7060 }
7061 
7062 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
7063                                    SourceLocation Loc, unsigned Opc,
7064                                    QualType LHSType) {
7065   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
7066   // so skip remaining warnings as we don't want to modify values within Sema.
7067   if (S.getLangOpts().OpenCL)
7068     return;
7069 
7070   llvm::APSInt Right;
7071   // Check right/shifter operand
7072   if (RHS.get()->isValueDependent() ||
7073       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
7074     return;
7075 
7076   if (Right.isNegative()) {
7077     S.DiagRuntimeBehavior(Loc, RHS.get(),
7078                           S.PDiag(diag::warn_shift_negative)
7079                             << RHS.get()->getSourceRange());
7080     return;
7081   }
7082   llvm::APInt LeftBits(Right.getBitWidth(),
7083                        S.Context.getTypeSize(LHS.get()->getType()));
7084   if (Right.uge(LeftBits)) {
7085     S.DiagRuntimeBehavior(Loc, RHS.get(),
7086                           S.PDiag(diag::warn_shift_gt_typewidth)
7087                             << RHS.get()->getSourceRange());
7088     return;
7089   }
7090   if (Opc != BO_Shl)
7091     return;
7092 
7093   // When left shifting an ICE which is signed, we can check for overflow which
7094   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7095   // integers have defined behavior modulo one more than the maximum value
7096   // representable in the result type, so never warn for those.
7097   llvm::APSInt Left;
7098   if (LHS.get()->isValueDependent() ||
7099       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
7100       LHSType->hasUnsignedIntegerRepresentation())
7101     return;
7102   llvm::APInt ResultBits =
7103       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7104   if (LeftBits.uge(ResultBits))
7105     return;
7106   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7107   Result = Result.shl(Right);
7108 
7109   // Print the bit representation of the signed integer as an unsigned
7110   // hexadecimal number.
7111   SmallString<40> HexResult;
7112   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7113 
7114   // If we are only missing a sign bit, this is less likely to result in actual
7115   // bugs -- if the result is cast back to an unsigned type, it will have the
7116   // expected value. Thus we place this behind a different warning that can be
7117   // turned off separately if needed.
7118   if (LeftBits == ResultBits - 1) {
7119     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7120         << HexResult.str() << LHSType
7121         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7122     return;
7123   }
7124 
7125   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7126     << HexResult.str() << Result.getMinSignedBits() << LHSType
7127     << Left.getBitWidth() << LHS.get()->getSourceRange()
7128     << RHS.get()->getSourceRange();
7129 }
7130 
7131 // C99 6.5.7
7132 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
7133                                   SourceLocation Loc, unsigned Opc,
7134                                   bool IsCompAssign) {
7135   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7136 
7137   // Vector shifts promote their scalar inputs to vector type.
7138   if (LHS.get()->getType()->isVectorType() ||
7139       RHS.get()->getType()->isVectorType())
7140     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7141 
7142   // Shifts don't perform usual arithmetic conversions, they just do integer
7143   // promotions on each operand. C99 6.5.7p3
7144 
7145   // For the LHS, do usual unary conversions, but then reset them away
7146   // if this is a compound assignment.
7147   ExprResult OldLHS = LHS;
7148   LHS = UsualUnaryConversions(LHS.take());
7149   if (LHS.isInvalid())
7150     return QualType();
7151   QualType LHSType = LHS.get()->getType();
7152   if (IsCompAssign) LHS = OldLHS;
7153 
7154   // The RHS is simpler.
7155   RHS = UsualUnaryConversions(RHS.take());
7156   if (RHS.isInvalid())
7157     return QualType();
7158   QualType RHSType = RHS.get()->getType();
7159 
7160   // C99 6.5.7p2: Each of the operands shall have integer type.
7161   if (!LHSType->hasIntegerRepresentation() ||
7162       !RHSType->hasIntegerRepresentation())
7163     return InvalidOperands(Loc, LHS, RHS);
7164 
7165   // C++0x: Don't allow scoped enums. FIXME: Use something better than
7166   // hasIntegerRepresentation() above instead of this.
7167   if (isScopedEnumerationType(LHSType) ||
7168       isScopedEnumerationType(RHSType)) {
7169     return InvalidOperands(Loc, LHS, RHS);
7170   }
7171   // Sanity-check shift operands
7172   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
7173 
7174   // "The type of the result is that of the promoted left operand."
7175   return LHSType;
7176 }
7177 
7178 static bool IsWithinTemplateSpecialization(Decl *D) {
7179   if (DeclContext *DC = D->getDeclContext()) {
7180     if (isa<ClassTemplateSpecializationDecl>(DC))
7181       return true;
7182     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7183       return FD->isFunctionTemplateSpecialization();
7184   }
7185   return false;
7186 }
7187 
7188 /// If two different enums are compared, raise a warning.
7189 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
7190                                 Expr *RHS) {
7191   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
7192   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
7193 
7194   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
7195   if (!LHSEnumType)
7196     return;
7197   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
7198   if (!RHSEnumType)
7199     return;
7200 
7201   // Ignore anonymous enums.
7202   if (!LHSEnumType->getDecl()->getIdentifier())
7203     return;
7204   if (!RHSEnumType->getDecl()->getIdentifier())
7205     return;
7206 
7207   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
7208     return;
7209 
7210   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7211       << LHSStrippedType << RHSStrippedType
7212       << LHS->getSourceRange() << RHS->getSourceRange();
7213 }
7214 
7215 /// \brief Diagnose bad pointer comparisons.
7216 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
7217                                               ExprResult &LHS, ExprResult &RHS,
7218                                               bool IsError) {
7219   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
7220                       : diag::ext_typecheck_comparison_of_distinct_pointers)
7221     << LHS.get()->getType() << RHS.get()->getType()
7222     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7223 }
7224 
7225 /// \brief Returns false if the pointers are converted to a composite type,
7226 /// true otherwise.
7227 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
7228                                            ExprResult &LHS, ExprResult &RHS) {
7229   // C++ [expr.rel]p2:
7230   //   [...] Pointer conversions (4.10) and qualification
7231   //   conversions (4.4) are performed on pointer operands (or on
7232   //   a pointer operand and a null pointer constant) to bring
7233   //   them to their composite pointer type. [...]
7234   //
7235   // C++ [expr.eq]p1 uses the same notion for (in)equality
7236   // comparisons of pointers.
7237 
7238   // C++ [expr.eq]p2:
7239   //   In addition, pointers to members can be compared, or a pointer to
7240   //   member and a null pointer constant. Pointer to member conversions
7241   //   (4.11) and qualification conversions (4.4) are performed to bring
7242   //   them to a common type. If one operand is a null pointer constant,
7243   //   the common type is the type of the other operand. Otherwise, the
7244   //   common type is a pointer to member type similar (4.4) to the type
7245   //   of one of the operands, with a cv-qualification signature (4.4)
7246   //   that is the union of the cv-qualification signatures of the operand
7247   //   types.
7248 
7249   QualType LHSType = LHS.get()->getType();
7250   QualType RHSType = RHS.get()->getType();
7251   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
7252          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
7253 
7254   bool NonStandardCompositeType = false;
7255   bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
7256   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
7257   if (T.isNull()) {
7258     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
7259     return true;
7260   }
7261 
7262   if (NonStandardCompositeType)
7263     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
7264       << LHSType << RHSType << T << LHS.get()->getSourceRange()
7265       << RHS.get()->getSourceRange();
7266 
7267   LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
7268   RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
7269   return false;
7270 }
7271 
7272 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
7273                                                     ExprResult &LHS,
7274                                                     ExprResult &RHS,
7275                                                     bool IsError) {
7276   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
7277                       : diag::ext_typecheck_comparison_of_fptr_to_void)
7278     << LHS.get()->getType() << RHS.get()->getType()
7279     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7280 }
7281 
7282 static bool isObjCObjectLiteral(ExprResult &E) {
7283   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
7284   case Stmt::ObjCArrayLiteralClass:
7285   case Stmt::ObjCDictionaryLiteralClass:
7286   case Stmt::ObjCStringLiteralClass:
7287   case Stmt::ObjCBoxedExprClass:
7288     return true;
7289   default:
7290     // Note that ObjCBoolLiteral is NOT an object literal!
7291     return false;
7292   }
7293 }
7294 
7295 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
7296   const ObjCObjectPointerType *Type =
7297     LHS->getType()->getAs<ObjCObjectPointerType>();
7298 
7299   // If this is not actually an Objective-C object, bail out.
7300   if (!Type)
7301     return false;
7302 
7303   // Get the LHS object's interface type.
7304   QualType InterfaceType = Type->getPointeeType();
7305   if (const ObjCObjectType *iQFaceTy =
7306       InterfaceType->getAsObjCQualifiedInterfaceType())
7307     InterfaceType = iQFaceTy->getBaseType();
7308 
7309   // If the RHS isn't an Objective-C object, bail out.
7310   if (!RHS->getType()->isObjCObjectPointerType())
7311     return false;
7312 
7313   // Try to find the -isEqual: method.
7314   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
7315   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
7316                                                       InterfaceType,
7317                                                       /*instance=*/true);
7318   if (!Method) {
7319     if (Type->isObjCIdType()) {
7320       // For 'id', just check the global pool.
7321       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
7322                                                   /*receiverId=*/true,
7323                                                   /*warn=*/false);
7324     } else {
7325       // Check protocols.
7326       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
7327                                              /*instance=*/true);
7328     }
7329   }
7330 
7331   if (!Method)
7332     return false;
7333 
7334   QualType T = Method->param_begin()[0]->getType();
7335   if (!T->isObjCObjectPointerType())
7336     return false;
7337 
7338   QualType R = Method->getResultType();
7339   if (!R->isScalarType())
7340     return false;
7341 
7342   return true;
7343 }
7344 
7345 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
7346   FromE = FromE->IgnoreParenImpCasts();
7347   switch (FromE->getStmtClass()) {
7348     default:
7349       break;
7350     case Stmt::ObjCStringLiteralClass:
7351       // "string literal"
7352       return LK_String;
7353     case Stmt::ObjCArrayLiteralClass:
7354       // "array literal"
7355       return LK_Array;
7356     case Stmt::ObjCDictionaryLiteralClass:
7357       // "dictionary literal"
7358       return LK_Dictionary;
7359     case Stmt::BlockExprClass:
7360       return LK_Block;
7361     case Stmt::ObjCBoxedExprClass: {
7362       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
7363       switch (Inner->getStmtClass()) {
7364         case Stmt::IntegerLiteralClass:
7365         case Stmt::FloatingLiteralClass:
7366         case Stmt::CharacterLiteralClass:
7367         case Stmt::ObjCBoolLiteralExprClass:
7368         case Stmt::CXXBoolLiteralExprClass:
7369           // "numeric literal"
7370           return LK_Numeric;
7371         case Stmt::ImplicitCastExprClass: {
7372           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
7373           // Boolean literals can be represented by implicit casts.
7374           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
7375             return LK_Numeric;
7376           break;
7377         }
7378         default:
7379           break;
7380       }
7381       return LK_Boxed;
7382     }
7383   }
7384   return LK_None;
7385 }
7386 
7387 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
7388                                           ExprResult &LHS, ExprResult &RHS,
7389                                           BinaryOperator::Opcode Opc){
7390   Expr *Literal;
7391   Expr *Other;
7392   if (isObjCObjectLiteral(LHS)) {
7393     Literal = LHS.get();
7394     Other = RHS.get();
7395   } else {
7396     Literal = RHS.get();
7397     Other = LHS.get();
7398   }
7399 
7400   // Don't warn on comparisons against nil.
7401   Other = Other->IgnoreParenCasts();
7402   if (Other->isNullPointerConstant(S.getASTContext(),
7403                                    Expr::NPC_ValueDependentIsNotNull))
7404     return;
7405 
7406   // This should be kept in sync with warn_objc_literal_comparison.
7407   // LK_String should always be after the other literals, since it has its own
7408   // warning flag.
7409   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
7410   assert(LiteralKind != Sema::LK_Block);
7411   if (LiteralKind == Sema::LK_None) {
7412     llvm_unreachable("Unknown Objective-C object literal kind");
7413   }
7414 
7415   if (LiteralKind == Sema::LK_String)
7416     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7417       << Literal->getSourceRange();
7418   else
7419     S.Diag(Loc, diag::warn_objc_literal_comparison)
7420       << LiteralKind << Literal->getSourceRange();
7421 
7422   if (BinaryOperator::isEqualityOp(Opc) &&
7423       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7424     SourceLocation Start = LHS.get()->getLocStart();
7425     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
7426     CharSourceRange OpRange =
7427       CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
7428 
7429     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7430       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
7431       << FixItHint::CreateReplacement(OpRange, " isEqual:")
7432       << FixItHint::CreateInsertion(End, "]");
7433   }
7434 }
7435 
7436 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
7437                                                 ExprResult &RHS,
7438                                                 SourceLocation Loc,
7439                                                 unsigned OpaqueOpc) {
7440   // This checking requires bools.
7441   if (!S.getLangOpts().Bool) return;
7442 
7443   // Check that left hand side is !something.
7444   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
7445   if (!UO || UO->getOpcode() != UO_LNot) return;
7446 
7447   // Only check if the right hand side is non-bool arithmetic type.
7448   if (RHS.get()->getType()->isBooleanType()) return;
7449 
7450   // Make sure that the something in !something is not bool.
7451   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
7452   if (SubExpr->getType()->isBooleanType()) return;
7453 
7454   // Emit warning.
7455   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
7456       << Loc;
7457 
7458   // First note suggest !(x < y)
7459   SourceLocation FirstOpen = SubExpr->getLocStart();
7460   SourceLocation FirstClose = RHS.get()->getLocEnd();
7461   FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
7462   if (FirstClose.isInvalid())
7463     FirstOpen = SourceLocation();
7464   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
7465       << FixItHint::CreateInsertion(FirstOpen, "(")
7466       << FixItHint::CreateInsertion(FirstClose, ")");
7467 
7468   // Second note suggests (!x) < y
7469   SourceLocation SecondOpen = LHS.get()->getLocStart();
7470   SourceLocation SecondClose = LHS.get()->getLocEnd();
7471   SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
7472   if (SecondClose.isInvalid())
7473     SecondOpen = SourceLocation();
7474   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
7475       << FixItHint::CreateInsertion(SecondOpen, "(")
7476       << FixItHint::CreateInsertion(SecondClose, ")");
7477 }
7478 
7479 // C99 6.5.8, C++ [expr.rel]
7480 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
7481                                     SourceLocation Loc, unsigned OpaqueOpc,
7482                                     bool IsRelational) {
7483   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7484 
7485   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7486 
7487   // Handle vector comparisons separately.
7488   if (LHS.get()->getType()->isVectorType() ||
7489       RHS.get()->getType()->isVectorType())
7490     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
7491 
7492   QualType LHSType = LHS.get()->getType();
7493   QualType RHSType = RHS.get()->getType();
7494 
7495   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7496   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
7497 
7498   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
7499   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
7500 
7501   if (!LHSType->hasFloatingRepresentation() &&
7502       !(LHSType->isBlockPointerType() && IsRelational) &&
7503       !LHS.get()->getLocStart().isMacroID() &&
7504       !RHS.get()->getLocStart().isMacroID()) {
7505     // For non-floating point types, check for self-comparisons of the form
7506     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7507     // often indicate logic errors in the program.
7508     //
7509     // NOTE: Don't warn about comparison expressions resulting from macro
7510     // expansion. Also don't warn about comparisons which are only self
7511     // comparisons within a template specialization. The warnings should catch
7512     // obvious cases in the definition of the template anyways. The idea is to
7513     // warn when the typed comparison operator will always evaluate to the same
7514     // result.
7515     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
7516       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
7517         if (DRL->getDecl() == DRR->getDecl() &&
7518             !IsWithinTemplateSpecialization(DRL->getDecl())) {
7519           DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7520                               << 0 // self-
7521                               << (Opc == BO_EQ
7522                                   || Opc == BO_LE
7523                                   || Opc == BO_GE));
7524         } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
7525                    !DRL->getDecl()->getType()->isReferenceType() &&
7526                    !DRR->getDecl()->getType()->isReferenceType()) {
7527             // what is it always going to eval to?
7528             char always_evals_to;
7529             switch(Opc) {
7530             case BO_EQ: // e.g. array1 == array2
7531               always_evals_to = 0; // false
7532               break;
7533             case BO_NE: // e.g. array1 != array2
7534               always_evals_to = 1; // true
7535               break;
7536             default:
7537               // best we can say is 'a constant'
7538               always_evals_to = 2; // e.g. array1 <= array2
7539               break;
7540             }
7541             DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7542                                 << 1 // array
7543                                 << always_evals_to);
7544         }
7545       }
7546     }
7547 
7548     if (isa<CastExpr>(LHSStripped))
7549       LHSStripped = LHSStripped->IgnoreParenCasts();
7550     if (isa<CastExpr>(RHSStripped))
7551       RHSStripped = RHSStripped->IgnoreParenCasts();
7552 
7553     // Warn about comparisons against a string constant (unless the other
7554     // operand is null), the user probably wants strcmp.
7555     Expr *literalString = 0;
7556     Expr *literalStringStripped = 0;
7557     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7558         !RHSStripped->isNullPointerConstant(Context,
7559                                             Expr::NPC_ValueDependentIsNull)) {
7560       literalString = LHS.get();
7561       literalStringStripped = LHSStripped;
7562     } else if ((isa<StringLiteral>(RHSStripped) ||
7563                 isa<ObjCEncodeExpr>(RHSStripped)) &&
7564                !LHSStripped->isNullPointerConstant(Context,
7565                                             Expr::NPC_ValueDependentIsNull)) {
7566       literalString = RHS.get();
7567       literalStringStripped = RHSStripped;
7568     }
7569 
7570     if (literalString) {
7571       DiagRuntimeBehavior(Loc, 0,
7572         PDiag(diag::warn_stringcompare)
7573           << isa<ObjCEncodeExpr>(literalStringStripped)
7574           << literalString->getSourceRange());
7575     }
7576   }
7577 
7578   // C99 6.5.8p3 / C99 6.5.9p4
7579   UsualArithmeticConversions(LHS, RHS);
7580   if (LHS.isInvalid() || RHS.isInvalid())
7581     return QualType();
7582 
7583   LHSType = LHS.get()->getType();
7584   RHSType = RHS.get()->getType();
7585 
7586   // The result of comparisons is 'bool' in C++, 'int' in C.
7587   QualType ResultTy = Context.getLogicalOperationType();
7588 
7589   if (IsRelational) {
7590     if (LHSType->isRealType() && RHSType->isRealType())
7591       return ResultTy;
7592   } else {
7593     // Check for comparisons of floating point operands using != and ==.
7594     if (LHSType->hasFloatingRepresentation())
7595       CheckFloatComparison(Loc, LHS.get(), RHS.get());
7596 
7597     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7598       return ResultTy;
7599   }
7600 
7601   bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
7602                                               Expr::NPC_ValueDependentIsNull);
7603   bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
7604                                               Expr::NPC_ValueDependentIsNull);
7605 
7606   // All of the following pointer-related warnings are GCC extensions, except
7607   // when handling null pointer constants.
7608   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7609     QualType LCanPointeeTy =
7610       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7611     QualType RCanPointeeTy =
7612       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7613 
7614     if (getLangOpts().CPlusPlus) {
7615       if (LCanPointeeTy == RCanPointeeTy)
7616         return ResultTy;
7617       if (!IsRelational &&
7618           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7619         // Valid unless comparison between non-null pointer and function pointer
7620         // This is a gcc extension compatibility comparison.
7621         // In a SFINAE context, we treat this as a hard error to maintain
7622         // conformance with the C++ standard.
7623         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7624             && !LHSIsNull && !RHSIsNull) {
7625           diagnoseFunctionPointerToVoidComparison(
7626               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
7627 
7628           if (isSFINAEContext())
7629             return QualType();
7630 
7631           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7632           return ResultTy;
7633         }
7634       }
7635 
7636       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7637         return QualType();
7638       else
7639         return ResultTy;
7640     }
7641     // C99 6.5.9p2 and C99 6.5.8p2
7642     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7643                                    RCanPointeeTy.getUnqualifiedType())) {
7644       // Valid unless a relational comparison of function pointers
7645       if (IsRelational && LCanPointeeTy->isFunctionType()) {
7646         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7647           << LHSType << RHSType << LHS.get()->getSourceRange()
7648           << RHS.get()->getSourceRange();
7649       }
7650     } else if (!IsRelational &&
7651                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7652       // Valid unless comparison between non-null pointer and function pointer
7653       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7654           && !LHSIsNull && !RHSIsNull)
7655         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
7656                                                 /*isError*/false);
7657     } else {
7658       // Invalid
7659       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
7660     }
7661     if (LCanPointeeTy != RCanPointeeTy) {
7662       if (LHSIsNull && !RHSIsNull)
7663         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7664       else
7665         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7666     }
7667     return ResultTy;
7668   }
7669 
7670   if (getLangOpts().CPlusPlus) {
7671     // Comparison of nullptr_t with itself.
7672     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
7673       return ResultTy;
7674 
7675     // Comparison of pointers with null pointer constants and equality
7676     // comparisons of member pointers to null pointer constants.
7677     if (RHSIsNull &&
7678         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
7679          (!IsRelational &&
7680           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7681       RHS = ImpCastExprToType(RHS.take(), LHSType,
7682                         LHSType->isMemberPointerType()
7683                           ? CK_NullToMemberPointer
7684                           : CK_NullToPointer);
7685       return ResultTy;
7686     }
7687     if (LHSIsNull &&
7688         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
7689          (!IsRelational &&
7690           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7691       LHS = ImpCastExprToType(LHS.take(), RHSType,
7692                         RHSType->isMemberPointerType()
7693                           ? CK_NullToMemberPointer
7694                           : CK_NullToPointer);
7695       return ResultTy;
7696     }
7697 
7698     // Comparison of member pointers.
7699     if (!IsRelational &&
7700         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7701       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7702         return QualType();
7703       else
7704         return ResultTy;
7705     }
7706 
7707     // Handle scoped enumeration types specifically, since they don't promote
7708     // to integers.
7709     if (LHS.get()->getType()->isEnumeralType() &&
7710         Context.hasSameUnqualifiedType(LHS.get()->getType(),
7711                                        RHS.get()->getType()))
7712       return ResultTy;
7713   }
7714 
7715   // Handle block pointer types.
7716   if (!IsRelational && LHSType->isBlockPointerType() &&
7717       RHSType->isBlockPointerType()) {
7718     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7719     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
7720 
7721     if (!LHSIsNull && !RHSIsNull &&
7722         !Context.typesAreCompatible(lpointee, rpointee)) {
7723       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7724         << LHSType << RHSType << LHS.get()->getSourceRange()
7725         << RHS.get()->getSourceRange();
7726     }
7727     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7728     return ResultTy;
7729   }
7730 
7731   // Allow block pointers to be compared with null pointer constants.
7732   if (!IsRelational
7733       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7734           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
7735     if (!LHSIsNull && !RHSIsNull) {
7736       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
7737              ->getPointeeType()->isVoidType())
7738             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
7739                 ->getPointeeType()->isVoidType())))
7740         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7741           << LHSType << RHSType << LHS.get()->getSourceRange()
7742           << RHS.get()->getSourceRange();
7743     }
7744     if (LHSIsNull && !RHSIsNull)
7745       LHS = ImpCastExprToType(LHS.take(), RHSType,
7746                               RHSType->isPointerType() ? CK_BitCast
7747                                 : CK_AnyPointerToBlockPointerCast);
7748     else
7749       RHS = ImpCastExprToType(RHS.take(), LHSType,
7750                               LHSType->isPointerType() ? CK_BitCast
7751                                 : CK_AnyPointerToBlockPointerCast);
7752     return ResultTy;
7753   }
7754 
7755   if (LHSType->isObjCObjectPointerType() ||
7756       RHSType->isObjCObjectPointerType()) {
7757     const PointerType *LPT = LHSType->getAs<PointerType>();
7758     const PointerType *RPT = RHSType->getAs<PointerType>();
7759     if (LPT || RPT) {
7760       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7761       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
7762 
7763       if (!LPtrToVoid && !RPtrToVoid &&
7764           !Context.typesAreCompatible(LHSType, RHSType)) {
7765         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7766                                           /*isError*/false);
7767       }
7768       if (LHSIsNull && !RHSIsNull) {
7769         Expr *E = LHS.take();
7770         if (getLangOpts().ObjCAutoRefCount)
7771           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
7772         LHS = ImpCastExprToType(E, RHSType,
7773                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7774       }
7775       else {
7776         Expr *E = RHS.take();
7777         if (getLangOpts().ObjCAutoRefCount)
7778           CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion);
7779         RHS = ImpCastExprToType(E, LHSType,
7780                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7781       }
7782       return ResultTy;
7783     }
7784     if (LHSType->isObjCObjectPointerType() &&
7785         RHSType->isObjCObjectPointerType()) {
7786       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7787         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7788                                           /*isError*/false);
7789       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7790         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
7791 
7792       if (LHSIsNull && !RHSIsNull)
7793         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7794       else
7795         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7796       return ResultTy;
7797     }
7798   }
7799   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7800       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
7801     unsigned DiagID = 0;
7802     bool isError = false;
7803     if (LangOpts.DebuggerSupport) {
7804       // Under a debugger, allow the comparison of pointers to integers,
7805       // since users tend to want to compare addresses.
7806     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
7807         (RHSIsNull && RHSType->isIntegerType())) {
7808       if (IsRelational && !getLangOpts().CPlusPlus)
7809         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
7810     } else if (IsRelational && !getLangOpts().CPlusPlus)
7811       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
7812     else if (getLangOpts().CPlusPlus) {
7813       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7814       isError = true;
7815     } else
7816       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
7817 
7818     if (DiagID) {
7819       Diag(Loc, DiagID)
7820         << LHSType << RHSType << LHS.get()->getSourceRange()
7821         << RHS.get()->getSourceRange();
7822       if (isError)
7823         return QualType();
7824     }
7825 
7826     if (LHSType->isIntegerType())
7827       LHS = ImpCastExprToType(LHS.take(), RHSType,
7828                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7829     else
7830       RHS = ImpCastExprToType(RHS.take(), LHSType,
7831                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7832     return ResultTy;
7833   }
7834 
7835   // Handle block pointers.
7836   if (!IsRelational && RHSIsNull
7837       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7838     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
7839     return ResultTy;
7840   }
7841   if (!IsRelational && LHSIsNull
7842       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7843     LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
7844     return ResultTy;
7845   }
7846 
7847   return InvalidOperands(Loc, LHS, RHS);
7848 }
7849 
7850 
7851 // Return a signed type that is of identical size and number of elements.
7852 // For floating point vectors, return an integer type of identical size
7853 // and number of elements.
7854 QualType Sema::GetSignedVectorType(QualType V) {
7855   const VectorType *VTy = V->getAs<VectorType>();
7856   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7857   if (TypeSize == Context.getTypeSize(Context.CharTy))
7858     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7859   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7860     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7861   else if (TypeSize == Context.getTypeSize(Context.IntTy))
7862     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7863   else if (TypeSize == Context.getTypeSize(Context.LongTy))
7864     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7865   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7866          "Unhandled vector element size in vector compare");
7867   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7868 }
7869 
7870 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7871 /// operates on extended vector types.  Instead of producing an IntTy result,
7872 /// like a scalar comparison, a vector comparison produces a vector of integer
7873 /// types.
7874 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7875                                           SourceLocation Loc,
7876                                           bool IsRelational) {
7877   // Check to make sure we're operating on vectors of the same type and width,
7878   // Allowing one side to be a scalar of element type.
7879   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
7880   if (vType.isNull())
7881     return vType;
7882 
7883   QualType LHSType = LHS.get()->getType();
7884 
7885   // If AltiVec, the comparison results in a numeric type, i.e.
7886   // bool for C++, int for C
7887   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
7888     return Context.getLogicalOperationType();
7889 
7890   // For non-floating point types, check for self-comparisons of the form
7891   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7892   // often indicate logic errors in the program.
7893   if (!LHSType->hasFloatingRepresentation()) {
7894     if (DeclRefExpr* DRL
7895           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7896       if (DeclRefExpr* DRR
7897             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
7898         if (DRL->getDecl() == DRR->getDecl())
7899           DiagRuntimeBehavior(Loc, 0,
7900                               PDiag(diag::warn_comparison_always)
7901                                 << 0 // self-
7902                                 << 2 // "a constant"
7903                               );
7904   }
7905 
7906   // Check for comparisons of floating point operands using != and ==.
7907   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
7908     assert (RHS.get()->getType()->hasFloatingRepresentation());
7909     CheckFloatComparison(Loc, LHS.get(), RHS.get());
7910   }
7911 
7912   // Return a signed type for the vector.
7913   return GetSignedVectorType(LHSType);
7914 }
7915 
7916 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7917                                           SourceLocation Loc) {
7918   // Ensure that either both operands are of the same vector type, or
7919   // one operand is of a vector type and the other is of its element type.
7920   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7921   if (vType.isNull())
7922     return InvalidOperands(Loc, LHS, RHS);
7923   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
7924       vType->hasFloatingRepresentation())
7925     return InvalidOperands(Loc, LHS, RHS);
7926 
7927   return GetSignedVectorType(LHS.get()->getType());
7928 }
7929 
7930 inline QualType Sema::CheckBitwiseOperands(
7931   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7932   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7933 
7934   if (LHS.get()->getType()->isVectorType() ||
7935       RHS.get()->getType()->isVectorType()) {
7936     if (LHS.get()->getType()->hasIntegerRepresentation() &&
7937         RHS.get()->getType()->hasIntegerRepresentation())
7938       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7939 
7940     return InvalidOperands(Loc, LHS, RHS);
7941   }
7942 
7943   ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7944   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
7945                                                  IsCompAssign);
7946   if (LHSResult.isInvalid() || RHSResult.isInvalid())
7947     return QualType();
7948   LHS = LHSResult.take();
7949   RHS = RHSResult.take();
7950 
7951   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
7952     return compType;
7953   return InvalidOperands(Loc, LHS, RHS);
7954 }
7955 
7956 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
7957   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
7958 
7959   // Check vector operands differently.
7960   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7961     return CheckVectorLogicalOperands(LHS, RHS, Loc);
7962 
7963   // Diagnose cases where the user write a logical and/or but probably meant a
7964   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
7965   // is a constant.
7966   if (LHS.get()->getType()->isIntegerType() &&
7967       !LHS.get()->getType()->isBooleanType() &&
7968       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
7969       // Don't warn in macros or template instantiations.
7970       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
7971     // If the RHS can be constant folded, and if it constant folds to something
7972     // that isn't 0 or 1 (which indicate a potential logical operation that
7973     // happened to fold to true/false) then warn.
7974     // Parens on the RHS are ignored.
7975     llvm::APSInt Result;
7976     if (RHS.get()->EvaluateAsInt(Result, Context))
7977       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
7978           (Result != 0 && Result != 1)) {
7979         Diag(Loc, diag::warn_logical_instead_of_bitwise)
7980           << RHS.get()->getSourceRange()
7981           << (Opc == BO_LAnd ? "&&" : "||");
7982         // Suggest replacing the logical operator with the bitwise version
7983         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7984             << (Opc == BO_LAnd ? "&" : "|")
7985             << FixItHint::CreateReplacement(SourceRange(
7986                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
7987                                                 getLangOpts())),
7988                                             Opc == BO_LAnd ? "&" : "|");
7989         if (Opc == BO_LAnd)
7990           // Suggest replacing "Foo() && kNonZero" with "Foo()"
7991           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7992               << FixItHint::CreateRemoval(
7993                   SourceRange(
7994                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
7995                                                  0, getSourceManager(),
7996                                                  getLangOpts()),
7997                       RHS.get()->getLocEnd()));
7998       }
7999   }
8000 
8001   if (!Context.getLangOpts().CPlusPlus) {
8002     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
8003     // not operate on the built-in scalar and vector float types.
8004     if (Context.getLangOpts().OpenCL &&
8005         Context.getLangOpts().OpenCLVersion < 120) {
8006       if (LHS.get()->getType()->isFloatingType() ||
8007           RHS.get()->getType()->isFloatingType())
8008         return InvalidOperands(Loc, LHS, RHS);
8009     }
8010 
8011     LHS = UsualUnaryConversions(LHS.take());
8012     if (LHS.isInvalid())
8013       return QualType();
8014 
8015     RHS = UsualUnaryConversions(RHS.take());
8016     if (RHS.isInvalid())
8017       return QualType();
8018 
8019     if (!LHS.get()->getType()->isScalarType() ||
8020         !RHS.get()->getType()->isScalarType())
8021       return InvalidOperands(Loc, LHS, RHS);
8022 
8023     return Context.IntTy;
8024   }
8025 
8026   // The following is safe because we only use this method for
8027   // non-overloadable operands.
8028 
8029   // C++ [expr.log.and]p1
8030   // C++ [expr.log.or]p1
8031   // The operands are both contextually converted to type bool.
8032   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
8033   if (LHSRes.isInvalid())
8034     return InvalidOperands(Loc, LHS, RHS);
8035   LHS = LHSRes;
8036 
8037   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
8038   if (RHSRes.isInvalid())
8039     return InvalidOperands(Loc, LHS, RHS);
8040   RHS = RHSRes;
8041 
8042   // C++ [expr.log.and]p2
8043   // C++ [expr.log.or]p2
8044   // The result is a bool.
8045   return Context.BoolTy;
8046 }
8047 
8048 static bool IsReadonlyMessage(Expr *E, Sema &S) {
8049   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
8050   if (!ME) return false;
8051   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
8052   ObjCMessageExpr *Base =
8053     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
8054   if (!Base) return false;
8055   return Base->getMethodDecl() != 0;
8056 }
8057 
8058 /// Is the given expression (which must be 'const') a reference to a
8059 /// variable which was originally non-const, but which has become
8060 /// 'const' due to being captured within a block?
8061 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
8062 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
8063   assert(E->isLValue() && E->getType().isConstQualified());
8064   E = E->IgnoreParens();
8065 
8066   // Must be a reference to a declaration from an enclosing scope.
8067   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
8068   if (!DRE) return NCCK_None;
8069   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
8070 
8071   // The declaration must be a variable which is not declared 'const'.
8072   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8073   if (!var) return NCCK_None;
8074   if (var->getType().isConstQualified()) return NCCK_None;
8075   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
8076 
8077   // Decide whether the first capture was for a block or a lambda.
8078   DeclContext *DC = S.CurContext;
8079   while (DC->getParent() != var->getDeclContext())
8080     DC = DC->getParent();
8081   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
8082 }
8083 
8084 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
8085 /// emit an error and return true.  If so, return false.
8086 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
8087   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
8088   SourceLocation OrigLoc = Loc;
8089   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
8090                                                               &Loc);
8091   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8092     IsLV = Expr::MLV_InvalidMessageExpression;
8093   if (IsLV == Expr::MLV_Valid)
8094     return false;
8095 
8096   unsigned Diag = 0;
8097   bool NeedType = false;
8098   switch (IsLV) { // C99 6.5.16p2
8099   case Expr::MLV_ConstQualified:
8100     Diag = diag::err_typecheck_assign_const;
8101 
8102     // Use a specialized diagnostic when we're assigning to an object
8103     // from an enclosing function or block.
8104     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
8105       if (NCCK == NCCK_Block)
8106         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8107       else
8108         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
8109       break;
8110     }
8111 
8112     // In ARC, use some specialized diagnostics for occasions where we
8113     // infer 'const'.  These are always pseudo-strong variables.
8114     if (S.getLangOpts().ObjCAutoRefCount) {
8115       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8116       if (declRef && isa<VarDecl>(declRef->getDecl())) {
8117         VarDecl *var = cast<VarDecl>(declRef->getDecl());
8118 
8119         // Use the normal diagnostic if it's pseudo-__strong but the
8120         // user actually wrote 'const'.
8121         if (var->isARCPseudoStrong() &&
8122             (!var->getTypeSourceInfo() ||
8123              !var->getTypeSourceInfo()->getType().isConstQualified())) {
8124           // There are two pseudo-strong cases:
8125           //  - self
8126           ObjCMethodDecl *method = S.getCurMethodDecl();
8127           if (method && var == method->getSelfDecl())
8128             Diag = method->isClassMethod()
8129               ? diag::err_typecheck_arc_assign_self_class_method
8130               : diag::err_typecheck_arc_assign_self;
8131 
8132           //  - fast enumeration variables
8133           else
8134             Diag = diag::err_typecheck_arr_assign_enumeration;
8135 
8136           SourceRange Assign;
8137           if (Loc != OrigLoc)
8138             Assign = SourceRange(OrigLoc, OrigLoc);
8139           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8140           // We need to preserve the AST regardless, so migration tool
8141           // can do its job.
8142           return false;
8143         }
8144       }
8145     }
8146 
8147     break;
8148   case Expr::MLV_ArrayType:
8149   case Expr::MLV_ArrayTemporary:
8150     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8151     NeedType = true;
8152     break;
8153   case Expr::MLV_NotObjectType:
8154     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8155     NeedType = true;
8156     break;
8157   case Expr::MLV_LValueCast:
8158     Diag = diag::err_typecheck_lvalue_casts_not_supported;
8159     break;
8160   case Expr::MLV_Valid:
8161     llvm_unreachable("did not take early return for MLV_Valid");
8162   case Expr::MLV_InvalidExpression:
8163   case Expr::MLV_MemberFunction:
8164   case Expr::MLV_ClassTemporary:
8165     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8166     break;
8167   case Expr::MLV_IncompleteType:
8168   case Expr::MLV_IncompleteVoidType:
8169     return S.RequireCompleteType(Loc, E->getType(),
8170              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
8171   case Expr::MLV_DuplicateVectorComponents:
8172     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8173     break;
8174   case Expr::MLV_NoSetterProperty:
8175     llvm_unreachable("readonly properties should be processed differently");
8176   case Expr::MLV_InvalidMessageExpression:
8177     Diag = diag::error_readonly_message_assignment;
8178     break;
8179   case Expr::MLV_SubObjCPropertySetting:
8180     Diag = diag::error_no_subobject_property_setting;
8181     break;
8182   }
8183 
8184   SourceRange Assign;
8185   if (Loc != OrigLoc)
8186     Assign = SourceRange(OrigLoc, OrigLoc);
8187   if (NeedType)
8188     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
8189   else
8190     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8191   return true;
8192 }
8193 
8194 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
8195                                          SourceLocation Loc,
8196                                          Sema &Sema) {
8197   // C / C++ fields
8198   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
8199   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
8200   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
8201     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
8202       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
8203   }
8204 
8205   // Objective-C instance variables
8206   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
8207   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
8208   if (OL && OR && OL->getDecl() == OR->getDecl()) {
8209     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
8210     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
8211     if (RL && RR && RL->getDecl() == RR->getDecl())
8212       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
8213   }
8214 }
8215 
8216 // C99 6.5.16.1
8217 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
8218                                        SourceLocation Loc,
8219                                        QualType CompoundType) {
8220   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
8221 
8222   // Verify that LHS is a modifiable lvalue, and emit error if not.
8223   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
8224     return QualType();
8225 
8226   QualType LHSType = LHSExpr->getType();
8227   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
8228                                              CompoundType;
8229   AssignConvertType ConvTy;
8230   if (CompoundType.isNull()) {
8231     Expr *RHSCheck = RHS.get();
8232 
8233     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
8234 
8235     QualType LHSTy(LHSType);
8236     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
8237     if (RHS.isInvalid())
8238       return QualType();
8239     // Special case of NSObject attributes on c-style pointer types.
8240     if (ConvTy == IncompatiblePointer &&
8241         ((Context.isObjCNSObjectType(LHSType) &&
8242           RHSType->isObjCObjectPointerType()) ||
8243          (Context.isObjCNSObjectType(RHSType) &&
8244           LHSType->isObjCObjectPointerType())))
8245       ConvTy = Compatible;
8246 
8247     if (ConvTy == Compatible &&
8248         LHSType->isObjCObjectType())
8249         Diag(Loc, diag::err_objc_object_assignment)
8250           << LHSType;
8251 
8252     // If the RHS is a unary plus or minus, check to see if they = and + are
8253     // right next to each other.  If so, the user may have typo'd "x =+ 4"
8254     // instead of "x += 4".
8255     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8256       RHSCheck = ICE->getSubExpr();
8257     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
8258       if ((UO->getOpcode() == UO_Plus ||
8259            UO->getOpcode() == UO_Minus) &&
8260           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
8261           // Only if the two operators are exactly adjacent.
8262           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
8263           // And there is a space or other character before the subexpr of the
8264           // unary +/-.  We don't want to warn on "x=-1".
8265           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8266           UO->getSubExpr()->getLocStart().isFileID()) {
8267         Diag(Loc, diag::warn_not_compound_assign)
8268           << (UO->getOpcode() == UO_Plus ? "+" : "-")
8269           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
8270       }
8271     }
8272 
8273     if (ConvTy == Compatible) {
8274       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
8275         // Warn about retain cycles where a block captures the LHS, but
8276         // not if the LHS is a simple variable into which the block is
8277         // being stored...unless that variable can be captured by reference!
8278         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
8279         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
8280         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
8281           checkRetainCycles(LHSExpr, RHS.get());
8282 
8283         // It is safe to assign a weak reference into a strong variable.
8284         // Although this code can still have problems:
8285         //   id x = self.weakProp;
8286         //   id y = self.weakProp;
8287         // we do not warn to warn spuriously when 'x' and 'y' are on separate
8288         // paths through the function. This should be revisited if
8289         // -Wrepeated-use-of-weak is made flow-sensitive.
8290         DiagnosticsEngine::Level Level =
8291           Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8292                                    RHS.get()->getLocStart());
8293         if (Level != DiagnosticsEngine::Ignored)
8294           getCurFunction()->markSafeWeakUse(RHS.get());
8295 
8296       } else if (getLangOpts().ObjCAutoRefCount) {
8297         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
8298       }
8299     }
8300   } else {
8301     // Compound assignment "x += y"
8302     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
8303   }
8304 
8305   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
8306                                RHS.get(), AA_Assigning))
8307     return QualType();
8308 
8309   CheckForNullPointerDereference(*this, LHSExpr);
8310 
8311   // C99 6.5.16p3: The type of an assignment expression is the type of the
8312   // left operand unless the left operand has qualified type, in which case
8313   // it is the unqualified version of the type of the left operand.
8314   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8315   // is converted to the type of the assignment expression (above).
8316   // C++ 5.17p1: the type of the assignment expression is that of its left
8317   // operand.
8318   return (getLangOpts().CPlusPlus
8319           ? LHSType : LHSType.getUnqualifiedType());
8320 }
8321 
8322 // C99 6.5.17
8323 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
8324                                    SourceLocation Loc) {
8325   LHS = S.CheckPlaceholderExpr(LHS.take());
8326   RHS = S.CheckPlaceholderExpr(RHS.take());
8327   if (LHS.isInvalid() || RHS.isInvalid())
8328     return QualType();
8329 
8330   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8331   // operands, but not unary promotions.
8332   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
8333 
8334   // So we treat the LHS as a ignored value, and in C++ we allow the
8335   // containing site to determine what should be done with the RHS.
8336   LHS = S.IgnoredValueConversions(LHS.take());
8337   if (LHS.isInvalid())
8338     return QualType();
8339 
8340   S.DiagnoseUnusedExprResult(LHS.get());
8341 
8342   if (!S.getLangOpts().CPlusPlus) {
8343     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8344     if (RHS.isInvalid())
8345       return QualType();
8346     if (!RHS.get()->getType()->isVoidType())
8347       S.RequireCompleteType(Loc, RHS.get()->getType(),
8348                             diag::err_incomplete_type);
8349   }
8350 
8351   return RHS.get()->getType();
8352 }
8353 
8354 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8355 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
8356 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8357                                                ExprValueKind &VK,
8358                                                SourceLocation OpLoc,
8359                                                bool IsInc, bool IsPrefix) {
8360   if (Op->isTypeDependent())
8361     return S.Context.DependentTy;
8362 
8363   QualType ResType = Op->getType();
8364   // Atomic types can be used for increment / decrement where the non-atomic
8365   // versions can, so ignore the _Atomic() specifier for the purpose of
8366   // checking.
8367   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8368     ResType = ResAtomicType->getValueType();
8369 
8370   assert(!ResType.isNull() && "no type for increment/decrement expression");
8371 
8372   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
8373     // Decrement of bool is not allowed.
8374     if (!IsInc) {
8375       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8376       return QualType();
8377     }
8378     // Increment of bool sets it to true, but is deprecated.
8379     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8380   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
8381     // Error on enum increments and decrements in C++ mode
8382     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
8383     return QualType();
8384   } else if (ResType->isRealType()) {
8385     // OK!
8386   } else if (ResType->isPointerType()) {
8387     // C99 6.5.2.4p2, 6.5.6p2
8388     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
8389       return QualType();
8390   } else if (ResType->isObjCObjectPointerType()) {
8391     // On modern runtimes, ObjC pointer arithmetic is forbidden.
8392     // Otherwise, we just need a complete type.
8393     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8394         checkArithmeticOnObjCPointer(S, OpLoc, Op))
8395       return QualType();
8396   } else if (ResType->isAnyComplexType()) {
8397     // C99 does not support ++/-- on complex types, we allow as an extension.
8398     S.Diag(OpLoc, diag::ext_integer_increment_complex)
8399       << ResType << Op->getSourceRange();
8400   } else if (ResType->isPlaceholderType()) {
8401     ExprResult PR = S.CheckPlaceholderExpr(Op);
8402     if (PR.isInvalid()) return QualType();
8403     return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8404                                           IsInc, IsPrefix);
8405   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
8406     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8407   } else {
8408     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8409       << ResType << int(IsInc) << Op->getSourceRange();
8410     return QualType();
8411   }
8412   // At this point, we know we have a real, complex or pointer type.
8413   // Now make sure the operand is a modifiable lvalue.
8414   if (CheckForModifiableLvalue(Op, OpLoc, S))
8415     return QualType();
8416   // In C++, a prefix increment is the same type as the operand. Otherwise
8417   // (in C or with postfix), the increment is the unqualified type of the
8418   // operand.
8419   if (IsPrefix && S.getLangOpts().CPlusPlus) {
8420     VK = VK_LValue;
8421     return ResType;
8422   } else {
8423     VK = VK_RValue;
8424     return ResType.getUnqualifiedType();
8425   }
8426 }
8427 
8428 
8429 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8430 /// This routine allows us to typecheck complex/recursive expressions
8431 /// where the declaration is needed for type checking. We only need to
8432 /// handle cases when the expression references a function designator
8433 /// or is an lvalue. Here are some examples:
8434 ///  - &(x) => x
8435 ///  - &*****f => f for f a function designator.
8436 ///  - &s.xx => s
8437 ///  - &s.zz[1].yy -> s, if zz is an array
8438 ///  - *(x + 1) -> x, if x is an array
8439 ///  - &"123"[2] -> 0
8440 ///  - & __real__ x -> x
8441 static ValueDecl *getPrimaryDecl(Expr *E) {
8442   switch (E->getStmtClass()) {
8443   case Stmt::DeclRefExprClass:
8444     return cast<DeclRefExpr>(E)->getDecl();
8445   case Stmt::MemberExprClass:
8446     // If this is an arrow operator, the address is an offset from
8447     // the base's value, so the object the base refers to is
8448     // irrelevant.
8449     if (cast<MemberExpr>(E)->isArrow())
8450       return 0;
8451     // Otherwise, the expression refers to a part of the base
8452     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8453   case Stmt::ArraySubscriptExprClass: {
8454     // FIXME: This code shouldn't be necessary!  We should catch the implicit
8455     // promotion of register arrays earlier.
8456     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8457     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8458       if (ICE->getSubExpr()->getType()->isArrayType())
8459         return getPrimaryDecl(ICE->getSubExpr());
8460     }
8461     return 0;
8462   }
8463   case Stmt::UnaryOperatorClass: {
8464     UnaryOperator *UO = cast<UnaryOperator>(E);
8465 
8466     switch(UO->getOpcode()) {
8467     case UO_Real:
8468     case UO_Imag:
8469     case UO_Extension:
8470       return getPrimaryDecl(UO->getSubExpr());
8471     default:
8472       return 0;
8473     }
8474   }
8475   case Stmt::ParenExprClass:
8476     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8477   case Stmt::ImplicitCastExprClass:
8478     // If the result of an implicit cast is an l-value, we care about
8479     // the sub-expression; otherwise, the result here doesn't matter.
8480     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8481   default:
8482     return 0;
8483   }
8484 }
8485 
8486 namespace {
8487   enum {
8488     AO_Bit_Field = 0,
8489     AO_Vector_Element = 1,
8490     AO_Property_Expansion = 2,
8491     AO_Register_Variable = 3,
8492     AO_No_Error = 4
8493   };
8494 }
8495 /// \brief Diagnose invalid operand for address of operations.
8496 ///
8497 /// \param Type The type of operand which cannot have its address taken.
8498 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8499                                          Expr *E, unsigned Type) {
8500   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8501 }
8502 
8503 /// CheckAddressOfOperand - The operand of & must be either a function
8504 /// designator or an lvalue designating an object. If it is an lvalue, the
8505 /// object cannot be declared with storage class register or be a bit field.
8506 /// Note: The usual conversions are *not* applied to the operand of the &
8507 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8508 /// In C++, the operand might be an overloaded function name, in which case
8509 /// we allow the '&' but retain the overloaded-function type.
8510 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
8511   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8512     if (PTy->getKind() == BuiltinType::Overload) {
8513       Expr *E = OrigOp.get()->IgnoreParens();
8514       if (!isa<OverloadExpr>(E)) {
8515         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
8516         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
8517           << OrigOp.get()->getSourceRange();
8518         return QualType();
8519       }
8520 
8521       OverloadExpr *Ovl = cast<OverloadExpr>(E);
8522       if (isa<UnresolvedMemberExpr>(Ovl))
8523         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
8524           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8525             << OrigOp.get()->getSourceRange();
8526           return QualType();
8527         }
8528 
8529       return Context.OverloadTy;
8530     }
8531 
8532     if (PTy->getKind() == BuiltinType::UnknownAny)
8533       return Context.UnknownAnyTy;
8534 
8535     if (PTy->getKind() == BuiltinType::BoundMember) {
8536       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8537         << OrigOp.get()->getSourceRange();
8538       return QualType();
8539     }
8540 
8541     OrigOp = CheckPlaceholderExpr(OrigOp.take());
8542     if (OrigOp.isInvalid()) return QualType();
8543   }
8544 
8545   if (OrigOp.get()->isTypeDependent())
8546     return Context.DependentTy;
8547 
8548   assert(!OrigOp.get()->getType()->isPlaceholderType());
8549 
8550   // Make sure to ignore parentheses in subsequent checks
8551   Expr *op = OrigOp.get()->IgnoreParens();
8552 
8553   if (getLangOpts().C99) {
8554     // Implement C99-only parts of addressof rules.
8555     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8556       if (uOp->getOpcode() == UO_Deref)
8557         // Per C99 6.5.3.2, the address of a deref always returns a valid result
8558         // (assuming the deref expression is valid).
8559         return uOp->getSubExpr()->getType();
8560     }
8561     // Technically, there should be a check for array subscript
8562     // expressions here, but the result of one is always an lvalue anyway.
8563   }
8564   ValueDecl *dcl = getPrimaryDecl(op);
8565   Expr::LValueClassification lval = op->ClassifyLValue(Context);
8566   unsigned AddressOfError = AO_No_Error;
8567 
8568   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
8569     bool sfinae = (bool)isSFINAEContext();
8570     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
8571                                   : diag::ext_typecheck_addrof_temporary)
8572       << op->getType() << op->getSourceRange();
8573     if (sfinae)
8574       return QualType();
8575     // Materialize the temporary as an lvalue so that we can take its address.
8576     OrigOp = op = new (Context)
8577         MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true, 0);
8578   } else if (isa<ObjCSelectorExpr>(op)) {
8579     return Context.getPointerType(op->getType());
8580   } else if (lval == Expr::LV_MemberFunction) {
8581     // If it's an instance method, make a member pointer.
8582     // The expression must have exactly the form &A::foo.
8583 
8584     // If the underlying expression isn't a decl ref, give up.
8585     if (!isa<DeclRefExpr>(op)) {
8586       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8587         << OrigOp.get()->getSourceRange();
8588       return QualType();
8589     }
8590     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8591     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8592 
8593     // The id-expression was parenthesized.
8594     if (OrigOp.get() != DRE) {
8595       Diag(OpLoc, diag::err_parens_pointer_member_function)
8596         << OrigOp.get()->getSourceRange();
8597 
8598     // The method was named without a qualifier.
8599     } else if (!DRE->getQualifier()) {
8600       if (MD->getParent()->getName().empty())
8601         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8602           << op->getSourceRange();
8603       else {
8604         SmallString<32> Str;
8605         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8606         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8607           << op->getSourceRange()
8608           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8609       }
8610     }
8611 
8612     return Context.getMemberPointerType(op->getType(),
8613               Context.getTypeDeclType(MD->getParent()).getTypePtr());
8614   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
8615     // C99 6.5.3.2p1
8616     // The operand must be either an l-value or a function designator
8617     if (!op->getType()->isFunctionType()) {
8618       // Use a special diagnostic for loads from property references.
8619       if (isa<PseudoObjectExpr>(op)) {
8620         AddressOfError = AO_Property_Expansion;
8621       } else {
8622         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8623           << op->getType() << op->getSourceRange();
8624         return QualType();
8625       }
8626     }
8627   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
8628     // The operand cannot be a bit-field
8629     AddressOfError = AO_Bit_Field;
8630   } else if (op->getObjectKind() == OK_VectorComponent) {
8631     // The operand cannot be an element of a vector
8632     AddressOfError = AO_Vector_Element;
8633   } else if (dcl) { // C99 6.5.3.2p1
8634     // We have an lvalue with a decl. Make sure the decl is not declared
8635     // with the register storage-class specifier.
8636     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
8637       // in C++ it is not error to take address of a register
8638       // variable (c++03 7.1.1P3)
8639       if (vd->getStorageClass() == SC_Register &&
8640           !getLangOpts().CPlusPlus) {
8641         AddressOfError = AO_Register_Variable;
8642       }
8643     } else if (isa<FunctionTemplateDecl>(dcl)) {
8644       return Context.OverloadTy;
8645     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8646       // Okay: we can take the address of a field.
8647       // Could be a pointer to member, though, if there is an explicit
8648       // scope qualifier for the class.
8649       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8650         DeclContext *Ctx = dcl->getDeclContext();
8651         if (Ctx && Ctx->isRecord()) {
8652           if (dcl->getType()->isReferenceType()) {
8653             Diag(OpLoc,
8654                  diag::err_cannot_form_pointer_to_member_of_reference_type)
8655               << dcl->getDeclName() << dcl->getType();
8656             return QualType();
8657           }
8658 
8659           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8660             Ctx = Ctx->getParent();
8661           return Context.getMemberPointerType(op->getType(),
8662                 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8663         }
8664       }
8665     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
8666       llvm_unreachable("Unknown/unexpected decl type");
8667   }
8668 
8669   if (AddressOfError != AO_No_Error) {
8670     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
8671     return QualType();
8672   }
8673 
8674   if (lval == Expr::LV_IncompleteVoidType) {
8675     // Taking the address of a void variable is technically illegal, but we
8676     // allow it in cases which are otherwise valid.
8677     // Example: "extern void x; void* y = &x;".
8678     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
8679   }
8680 
8681   // If the operand has type "type", the result has type "pointer to type".
8682   if (op->getType()->isObjCObjectType())
8683     return Context.getObjCObjectPointerType(op->getType());
8684   return Context.getPointerType(op->getType());
8685 }
8686 
8687 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
8688 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8689                                         SourceLocation OpLoc) {
8690   if (Op->isTypeDependent())
8691     return S.Context.DependentTy;
8692 
8693   ExprResult ConvResult = S.UsualUnaryConversions(Op);
8694   if (ConvResult.isInvalid())
8695     return QualType();
8696   Op = ConvResult.take();
8697   QualType OpTy = Op->getType();
8698   QualType Result;
8699 
8700   if (isa<CXXReinterpretCastExpr>(Op)) {
8701     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8702     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8703                                      Op->getSourceRange());
8704   }
8705 
8706   // Note that per both C89 and C99, indirection is always legal, even if OpTy
8707   // is an incomplete type or void.  It would be possible to warn about
8708   // dereferencing a void pointer, but it's completely well-defined, and such a
8709   // warning is unlikely to catch any mistakes.
8710   if (const PointerType *PT = OpTy->getAs<PointerType>())
8711     Result = PT->getPointeeType();
8712   else if (const ObjCObjectPointerType *OPT =
8713              OpTy->getAs<ObjCObjectPointerType>())
8714     Result = OPT->getPointeeType();
8715   else {
8716     ExprResult PR = S.CheckPlaceholderExpr(Op);
8717     if (PR.isInvalid()) return QualType();
8718     if (PR.take() != Op)
8719       return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
8720   }
8721 
8722   if (Result.isNull()) {
8723     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
8724       << OpTy << Op->getSourceRange();
8725     return QualType();
8726   }
8727 
8728   // Dereferences are usually l-values...
8729   VK = VK_LValue;
8730 
8731   // ...except that certain expressions are never l-values in C.
8732   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
8733     VK = VK_RValue;
8734 
8735   return Result;
8736 }
8737 
8738 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
8739   tok::TokenKind Kind) {
8740   BinaryOperatorKind Opc;
8741   switch (Kind) {
8742   default: llvm_unreachable("Unknown binop!");
8743   case tok::periodstar:           Opc = BO_PtrMemD; break;
8744   case tok::arrowstar:            Opc = BO_PtrMemI; break;
8745   case tok::star:                 Opc = BO_Mul; break;
8746   case tok::slash:                Opc = BO_Div; break;
8747   case tok::percent:              Opc = BO_Rem; break;
8748   case tok::plus:                 Opc = BO_Add; break;
8749   case tok::minus:                Opc = BO_Sub; break;
8750   case tok::lessless:             Opc = BO_Shl; break;
8751   case tok::greatergreater:       Opc = BO_Shr; break;
8752   case tok::lessequal:            Opc = BO_LE; break;
8753   case tok::less:                 Opc = BO_LT; break;
8754   case tok::greaterequal:         Opc = BO_GE; break;
8755   case tok::greater:              Opc = BO_GT; break;
8756   case tok::exclaimequal:         Opc = BO_NE; break;
8757   case tok::equalequal:           Opc = BO_EQ; break;
8758   case tok::amp:                  Opc = BO_And; break;
8759   case tok::caret:                Opc = BO_Xor; break;
8760   case tok::pipe:                 Opc = BO_Or; break;
8761   case tok::ampamp:               Opc = BO_LAnd; break;
8762   case tok::pipepipe:             Opc = BO_LOr; break;
8763   case tok::equal:                Opc = BO_Assign; break;
8764   case tok::starequal:            Opc = BO_MulAssign; break;
8765   case tok::slashequal:           Opc = BO_DivAssign; break;
8766   case tok::percentequal:         Opc = BO_RemAssign; break;
8767   case tok::plusequal:            Opc = BO_AddAssign; break;
8768   case tok::minusequal:           Opc = BO_SubAssign; break;
8769   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
8770   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
8771   case tok::ampequal:             Opc = BO_AndAssign; break;
8772   case tok::caretequal:           Opc = BO_XorAssign; break;
8773   case tok::pipeequal:            Opc = BO_OrAssign; break;
8774   case tok::comma:                Opc = BO_Comma; break;
8775   }
8776   return Opc;
8777 }
8778 
8779 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
8780   tok::TokenKind Kind) {
8781   UnaryOperatorKind Opc;
8782   switch (Kind) {
8783   default: llvm_unreachable("Unknown unary op!");
8784   case tok::plusplus:     Opc = UO_PreInc; break;
8785   case tok::minusminus:   Opc = UO_PreDec; break;
8786   case tok::amp:          Opc = UO_AddrOf; break;
8787   case tok::star:         Opc = UO_Deref; break;
8788   case tok::plus:         Opc = UO_Plus; break;
8789   case tok::minus:        Opc = UO_Minus; break;
8790   case tok::tilde:        Opc = UO_Not; break;
8791   case tok::exclaim:      Opc = UO_LNot; break;
8792   case tok::kw___real:    Opc = UO_Real; break;
8793   case tok::kw___imag:    Opc = UO_Imag; break;
8794   case tok::kw___extension__: Opc = UO_Extension; break;
8795   }
8796   return Opc;
8797 }
8798 
8799 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8800 /// This warning is only emitted for builtin assignment operations. It is also
8801 /// suppressed in the event of macro expansions.
8802 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
8803                                    SourceLocation OpLoc) {
8804   if (!S.ActiveTemplateInstantiations.empty())
8805     return;
8806   if (OpLoc.isInvalid() || OpLoc.isMacroID())
8807     return;
8808   LHSExpr = LHSExpr->IgnoreParenImpCasts();
8809   RHSExpr = RHSExpr->IgnoreParenImpCasts();
8810   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8811   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8812   if (!LHSDeclRef || !RHSDeclRef ||
8813       LHSDeclRef->getLocation().isMacroID() ||
8814       RHSDeclRef->getLocation().isMacroID())
8815     return;
8816   const ValueDecl *LHSDecl =
8817     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8818   const ValueDecl *RHSDecl =
8819     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8820   if (LHSDecl != RHSDecl)
8821     return;
8822   if (LHSDecl->getType().isVolatileQualified())
8823     return;
8824   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
8825     if (RefTy->getPointeeType().isVolatileQualified())
8826       return;
8827 
8828   S.Diag(OpLoc, diag::warn_self_assignment)
8829       << LHSDeclRef->getType()
8830       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8831 }
8832 
8833 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
8834 /// is usually indicative of introspection within the Objective-C pointer.
8835 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
8836                                           SourceLocation OpLoc) {
8837   if (!S.getLangOpts().ObjC1)
8838     return;
8839 
8840   const Expr *ObjCPointerExpr = 0, *OtherExpr = 0;
8841   const Expr *LHS = L.get();
8842   const Expr *RHS = R.get();
8843 
8844   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
8845     ObjCPointerExpr = LHS;
8846     OtherExpr = RHS;
8847   }
8848   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
8849     ObjCPointerExpr = RHS;
8850     OtherExpr = LHS;
8851   }
8852 
8853   // This warning is deliberately made very specific to reduce false
8854   // positives with logic that uses '&' for hashing.  This logic mainly
8855   // looks for code trying to introspect into tagged pointers, which
8856   // code should generally never do.
8857   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
8858     unsigned Diag = diag::warn_objc_pointer_masking;
8859     // Determine if we are introspecting the result of performSelectorXXX.
8860     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
8861     // Special case messages to -performSelector and friends, which
8862     // can return non-pointer values boxed in a pointer value.
8863     // Some clients may wish to silence warnings in this subcase.
8864     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
8865       Selector S = ME->getSelector();
8866       StringRef SelArg0 = S.getNameForSlot(0);
8867       if (SelArg0.startswith("performSelector"))
8868         Diag = diag::warn_objc_pointer_masking_performSelector;
8869     }
8870 
8871     S.Diag(OpLoc, Diag)
8872       << ObjCPointerExpr->getSourceRange();
8873   }
8874 }
8875 
8876 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
8877 /// operator @p Opc at location @c TokLoc. This routine only supports
8878 /// built-in operations; ActOnBinOp handles overloaded operators.
8879 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
8880                                     BinaryOperatorKind Opc,
8881                                     Expr *LHSExpr, Expr *RHSExpr) {
8882   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
8883     // The syntax only allows initializer lists on the RHS of assignment,
8884     // so we don't need to worry about accepting invalid code for
8885     // non-assignment operators.
8886     // C++11 5.17p9:
8887     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8888     //   of x = {} is x = T().
8889     InitializationKind Kind =
8890         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8891     InitializedEntity Entity =
8892         InitializedEntity::InitializeTemporary(LHSExpr->getType());
8893     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
8894     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
8895     if (Init.isInvalid())
8896       return Init;
8897     RHSExpr = Init.take();
8898   }
8899 
8900   ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
8901   QualType ResultTy;     // Result type of the binary operator.
8902   // The following two variables are used for compound assignment operators
8903   QualType CompLHSTy;    // Type of LHS after promotions for computation
8904   QualType CompResultTy; // Type of computation result
8905   ExprValueKind VK = VK_RValue;
8906   ExprObjectKind OK = OK_Ordinary;
8907 
8908   switch (Opc) {
8909   case BO_Assign:
8910     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
8911     if (getLangOpts().CPlusPlus &&
8912         LHS.get()->getObjectKind() != OK_ObjCProperty) {
8913       VK = LHS.get()->getValueKind();
8914       OK = LHS.get()->getObjectKind();
8915     }
8916     if (!ResultTy.isNull())
8917       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
8918     break;
8919   case BO_PtrMemD:
8920   case BO_PtrMemI:
8921     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
8922                                             Opc == BO_PtrMemI);
8923     break;
8924   case BO_Mul:
8925   case BO_Div:
8926     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
8927                                            Opc == BO_Div);
8928     break;
8929   case BO_Rem:
8930     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
8931     break;
8932   case BO_Add:
8933     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
8934     break;
8935   case BO_Sub:
8936     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
8937     break;
8938   case BO_Shl:
8939   case BO_Shr:
8940     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
8941     break;
8942   case BO_LE:
8943   case BO_LT:
8944   case BO_GE:
8945   case BO_GT:
8946     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
8947     break;
8948   case BO_EQ:
8949   case BO_NE:
8950     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
8951     break;
8952   case BO_And:
8953     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
8954   case BO_Xor:
8955   case BO_Or:
8956     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
8957     break;
8958   case BO_LAnd:
8959   case BO_LOr:
8960     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
8961     break;
8962   case BO_MulAssign:
8963   case BO_DivAssign:
8964     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
8965                                                Opc == BO_DivAssign);
8966     CompLHSTy = CompResultTy;
8967     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8968       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8969     break;
8970   case BO_RemAssign:
8971     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
8972     CompLHSTy = CompResultTy;
8973     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8974       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8975     break;
8976   case BO_AddAssign:
8977     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
8978     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8979       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8980     break;
8981   case BO_SubAssign:
8982     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8983     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8984       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8985     break;
8986   case BO_ShlAssign:
8987   case BO_ShrAssign:
8988     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
8989     CompLHSTy = CompResultTy;
8990     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8991       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8992     break;
8993   case BO_AndAssign:
8994   case BO_XorAssign:
8995   case BO_OrAssign:
8996     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
8997     CompLHSTy = CompResultTy;
8998     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8999       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9000     break;
9001   case BO_Comma:
9002     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
9003     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
9004       VK = RHS.get()->getValueKind();
9005       OK = RHS.get()->getObjectKind();
9006     }
9007     break;
9008   }
9009   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
9010     return ExprError();
9011 
9012   // Check for array bounds violations for both sides of the BinaryOperator
9013   CheckArrayAccess(LHS.get());
9014   CheckArrayAccess(RHS.get());
9015 
9016   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
9017     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
9018                                                  &Context.Idents.get("object_setClass"),
9019                                                  SourceLocation(), LookupOrdinaryName);
9020     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
9021       SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
9022       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
9023       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
9024       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
9025       FixItHint::CreateInsertion(RHSLocEnd, ")");
9026     }
9027     else
9028       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
9029   }
9030   else if (const ObjCIvarRefExpr *OIRE =
9031            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
9032     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
9033 
9034   if (CompResultTy.isNull())
9035     return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
9036                                               ResultTy, VK, OK, OpLoc,
9037                                               FPFeatures.fp_contract));
9038   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
9039       OK_ObjCProperty) {
9040     VK = VK_LValue;
9041     OK = LHS.get()->getObjectKind();
9042   }
9043   return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
9044                                                     ResultTy, VK, OK, CompLHSTy,
9045                                                     CompResultTy, OpLoc,
9046                                                     FPFeatures.fp_contract));
9047 }
9048 
9049 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9050 /// operators are mixed in a way that suggests that the programmer forgot that
9051 /// comparison operators have higher precedence. The most typical example of
9052 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
9053 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
9054                                       SourceLocation OpLoc, Expr *LHSExpr,
9055                                       Expr *RHSExpr) {
9056   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
9057   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
9058 
9059   // Check that one of the sides is a comparison operator.
9060   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
9061   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
9062   if (!isLeftComp && !isRightComp)
9063     return;
9064 
9065   // Bitwise operations are sometimes used as eager logical ops.
9066   // Don't diagnose this.
9067   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
9068   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
9069   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
9070     return;
9071 
9072   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
9073                                                    OpLoc)
9074                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
9075   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
9076   SourceRange ParensRange = isLeftComp ?
9077       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
9078     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
9079 
9080   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9081     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
9082   SuggestParentheses(Self, OpLoc,
9083     Self.PDiag(diag::note_precedence_silence) << OpStr,
9084     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
9085   SuggestParentheses(Self, OpLoc,
9086     Self.PDiag(diag::note_precedence_bitwise_first)
9087       << BinaryOperator::getOpcodeStr(Opc),
9088     ParensRange);
9089 }
9090 
9091 /// \brief It accepts a '&' expr that is inside a '|' one.
9092 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
9093 /// in parentheses.
9094 static void
9095 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
9096                                        BinaryOperator *Bop) {
9097   assert(Bop->getOpcode() == BO_And);
9098   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
9099       << Bop->getSourceRange() << OpLoc;
9100   SuggestParentheses(Self, Bop->getOperatorLoc(),
9101     Self.PDiag(diag::note_precedence_silence)
9102       << Bop->getOpcodeStr(),
9103     Bop->getSourceRange());
9104 }
9105 
9106 /// \brief It accepts a '&&' expr that is inside a '||' one.
9107 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9108 /// in parentheses.
9109 static void
9110 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
9111                                        BinaryOperator *Bop) {
9112   assert(Bop->getOpcode() == BO_LAnd);
9113   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9114       << Bop->getSourceRange() << OpLoc;
9115   SuggestParentheses(Self, Bop->getOperatorLoc(),
9116     Self.PDiag(diag::note_precedence_silence)
9117       << Bop->getOpcodeStr(),
9118     Bop->getSourceRange());
9119 }
9120 
9121 /// \brief Returns true if the given expression can be evaluated as a constant
9122 /// 'true'.
9123 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9124   bool Res;
9125   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9126 }
9127 
9128 /// \brief Returns true if the given expression can be evaluated as a constant
9129 /// 'false'.
9130 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9131   bool Res;
9132   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9133 }
9134 
9135 /// \brief Look for '&&' in the left hand of a '||' expr.
9136 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
9137                                              Expr *LHSExpr, Expr *RHSExpr) {
9138   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
9139     if (Bop->getOpcode() == BO_LAnd) {
9140       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9141       if (EvaluatesAsFalse(S, RHSExpr))
9142         return;
9143       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9144       if (!EvaluatesAsTrue(S, Bop->getLHS()))
9145         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9146     } else if (Bop->getOpcode() == BO_LOr) {
9147       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9148         // If it's "a || b && 1 || c" we didn't warn earlier for
9149         // "a || b && 1", but warn now.
9150         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9151           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9152       }
9153     }
9154   }
9155 }
9156 
9157 /// \brief Look for '&&' in the right hand of a '||' expr.
9158 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
9159                                              Expr *LHSExpr, Expr *RHSExpr) {
9160   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
9161     if (Bop->getOpcode() == BO_LAnd) {
9162       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9163       if (EvaluatesAsFalse(S, LHSExpr))
9164         return;
9165       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9166       if (!EvaluatesAsTrue(S, Bop->getRHS()))
9167         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9168     }
9169   }
9170 }
9171 
9172 /// \brief Look for '&' in the left or right hand of a '|' expr.
9173 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
9174                                              Expr *OrArg) {
9175   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
9176     if (Bop->getOpcode() == BO_And)
9177       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
9178   }
9179 }
9180 
9181 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
9182                                     Expr *SubExpr, StringRef Shift) {
9183   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
9184     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
9185       StringRef Op = Bop->getOpcodeStr();
9186       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
9187           << Bop->getSourceRange() << OpLoc << Shift << Op;
9188       SuggestParentheses(S, Bop->getOperatorLoc(),
9189           S.PDiag(diag::note_precedence_silence) << Op,
9190           Bop->getSourceRange());
9191     }
9192   }
9193 }
9194 
9195 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
9196                                  Expr *LHSExpr, Expr *RHSExpr) {
9197   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
9198   if (!OCE)
9199     return;
9200 
9201   FunctionDecl *FD = OCE->getDirectCallee();
9202   if (!FD || !FD->isOverloadedOperator())
9203     return;
9204 
9205   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
9206   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
9207     return;
9208 
9209   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
9210       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
9211       << (Kind == OO_LessLess);
9212   SuggestParentheses(S, OCE->getOperatorLoc(),
9213                      S.PDiag(diag::note_precedence_silence)
9214                          << (Kind == OO_LessLess ? "<<" : ">>"),
9215                      OCE->getSourceRange());
9216   SuggestParentheses(S, OpLoc,
9217                      S.PDiag(diag::note_evaluate_comparison_first),
9218                      SourceRange(OCE->getArg(1)->getLocStart(),
9219                                  RHSExpr->getLocEnd()));
9220 }
9221 
9222 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
9223 /// precedence.
9224 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
9225                                     SourceLocation OpLoc, Expr *LHSExpr,
9226                                     Expr *RHSExpr){
9227   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
9228   if (BinaryOperator::isBitwiseOp(Opc))
9229     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
9230 
9231   // Diagnose "arg1 & arg2 | arg3"
9232   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9233     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
9234     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
9235   }
9236 
9237   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9238   // We don't warn for 'assert(a || b && "bad")' since this is safe.
9239   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9240     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
9241     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
9242   }
9243 
9244   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
9245       || Opc == BO_Shr) {
9246     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
9247     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
9248     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
9249   }
9250 
9251   // Warn on overloaded shift operators and comparisons, such as:
9252   // cout << 5 == 4;
9253   if (BinaryOperator::isComparisonOp(Opc))
9254     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
9255 }
9256 
9257 // Binary Operators.  'Tok' is the token for the operator.
9258 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
9259                             tok::TokenKind Kind,
9260                             Expr *LHSExpr, Expr *RHSExpr) {
9261   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
9262   assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
9263   assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
9264 
9265   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9266   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
9267 
9268   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
9269 }
9270 
9271 /// Build an overloaded binary operator expression in the given scope.
9272 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
9273                                        BinaryOperatorKind Opc,
9274                                        Expr *LHS, Expr *RHS) {
9275   // Find all of the overloaded operators visible from this
9276   // point. We perform both an operator-name lookup from the local
9277   // scope and an argument-dependent lookup based on the types of
9278   // the arguments.
9279   UnresolvedSet<16> Functions;
9280   OverloadedOperatorKind OverOp
9281     = BinaryOperator::getOverloadedOperator(Opc);
9282   if (Sc && OverOp != OO_None)
9283     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
9284                                    RHS->getType(), Functions);
9285 
9286   // Build the (potentially-overloaded, potentially-dependent)
9287   // binary operation.
9288   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
9289 }
9290 
9291 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
9292                             BinaryOperatorKind Opc,
9293                             Expr *LHSExpr, Expr *RHSExpr) {
9294   // We want to end up calling one of checkPseudoObjectAssignment
9295   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
9296   // both expressions are overloadable or either is type-dependent),
9297   // or CreateBuiltinBinOp (in any other case).  We also want to get
9298   // any placeholder types out of the way.
9299 
9300   // Handle pseudo-objects in the LHS.
9301   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
9302     // Assignments with a pseudo-object l-value need special analysis.
9303     if (pty->getKind() == BuiltinType::PseudoObject &&
9304         BinaryOperator::isAssignmentOp(Opc))
9305       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
9306 
9307     // Don't resolve overloads if the other type is overloadable.
9308     if (pty->getKind() == BuiltinType::Overload) {
9309       // We can't actually test that if we still have a placeholder,
9310       // though.  Fortunately, none of the exceptions we see in that
9311       // code below are valid when the LHS is an overload set.  Note
9312       // that an overload set can be dependently-typed, but it never
9313       // instantiates to having an overloadable type.
9314       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9315       if (resolvedRHS.isInvalid()) return ExprError();
9316       RHSExpr = resolvedRHS.take();
9317 
9318       if (RHSExpr->isTypeDependent() ||
9319           RHSExpr->getType()->isOverloadableType())
9320         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9321     }
9322 
9323     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
9324     if (LHS.isInvalid()) return ExprError();
9325     LHSExpr = LHS.take();
9326   }
9327 
9328   // Handle pseudo-objects in the RHS.
9329   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
9330     // An overload in the RHS can potentially be resolved by the type
9331     // being assigned to.
9332     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
9333       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9334         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9335 
9336       if (LHSExpr->getType()->isOverloadableType())
9337         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9338 
9339       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9340     }
9341 
9342     // Don't resolve overloads if the other type is overloadable.
9343     if (pty->getKind() == BuiltinType::Overload &&
9344         LHSExpr->getType()->isOverloadableType())
9345       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9346 
9347     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9348     if (!resolvedRHS.isUsable()) return ExprError();
9349     RHSExpr = resolvedRHS.take();
9350   }
9351 
9352   if (getLangOpts().CPlusPlus) {
9353     // If either expression is type-dependent, always build an
9354     // overloaded op.
9355     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9356       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9357 
9358     // Otherwise, build an overloaded op if either expression has an
9359     // overloadable type.
9360     if (LHSExpr->getType()->isOverloadableType() ||
9361         RHSExpr->getType()->isOverloadableType())
9362       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9363   }
9364 
9365   // Build a built-in binary operation.
9366   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9367 }
9368 
9369 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
9370                                       UnaryOperatorKind Opc,
9371                                       Expr *InputExpr) {
9372   ExprResult Input = Owned(InputExpr);
9373   ExprValueKind VK = VK_RValue;
9374   ExprObjectKind OK = OK_Ordinary;
9375   QualType resultType;
9376   switch (Opc) {
9377   case UO_PreInc:
9378   case UO_PreDec:
9379   case UO_PostInc:
9380   case UO_PostDec:
9381     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
9382                                                 Opc == UO_PreInc ||
9383                                                 Opc == UO_PostInc,
9384                                                 Opc == UO_PreInc ||
9385                                                 Opc == UO_PreDec);
9386     break;
9387   case UO_AddrOf:
9388     resultType = CheckAddressOfOperand(Input, OpLoc);
9389     break;
9390   case UO_Deref: {
9391     Input = DefaultFunctionArrayLvalueConversion(Input.take());
9392     if (Input.isInvalid()) return ExprError();
9393     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
9394     break;
9395   }
9396   case UO_Plus:
9397   case UO_Minus:
9398     Input = UsualUnaryConversions(Input.take());
9399     if (Input.isInvalid()) return ExprError();
9400     resultType = Input.get()->getType();
9401     if (resultType->isDependentType())
9402       break;
9403     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9404         resultType->isVectorType())
9405       break;
9406     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
9407              resultType->isEnumeralType())
9408       break;
9409     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
9410              Opc == UO_Plus &&
9411              resultType->isPointerType())
9412       break;
9413 
9414     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9415       << resultType << Input.get()->getSourceRange());
9416 
9417   case UO_Not: // bitwise complement
9418     Input = UsualUnaryConversions(Input.take());
9419     if (Input.isInvalid())
9420       return ExprError();
9421     resultType = Input.get()->getType();
9422     if (resultType->isDependentType())
9423       break;
9424     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9425     if (resultType->isComplexType() || resultType->isComplexIntegerType())
9426       // C99 does not support '~' for complex conjugation.
9427       Diag(OpLoc, diag::ext_integer_complement_complex)
9428           << resultType << Input.get()->getSourceRange();
9429     else if (resultType->hasIntegerRepresentation())
9430       break;
9431     else if (resultType->isExtVectorType()) {
9432       if (Context.getLangOpts().OpenCL) {
9433         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
9434         // on vector float types.
9435         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9436         if (!T->isIntegerType())
9437           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9438                            << resultType << Input.get()->getSourceRange());
9439       }
9440       break;
9441     } else {
9442       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9443                        << resultType << Input.get()->getSourceRange());
9444     }
9445     break;
9446 
9447   case UO_LNot: // logical negation
9448     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
9449     Input = DefaultFunctionArrayLvalueConversion(Input.take());
9450     if (Input.isInvalid()) return ExprError();
9451     resultType = Input.get()->getType();
9452 
9453     // Though we still have to promote half FP to float...
9454     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
9455       Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
9456       resultType = Context.FloatTy;
9457     }
9458 
9459     if (resultType->isDependentType())
9460       break;
9461     if (resultType->isScalarType()) {
9462       // C99 6.5.3.3p1: ok, fallthrough;
9463       if (Context.getLangOpts().CPlusPlus) {
9464         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9465         // operand contextually converted to bool.
9466         Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9467                                   ScalarTypeToBooleanCastKind(resultType));
9468       } else if (Context.getLangOpts().OpenCL &&
9469                  Context.getLangOpts().OpenCLVersion < 120) {
9470         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9471         // operate on scalar float types.
9472         if (!resultType->isIntegerType())
9473           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9474                            << resultType << Input.get()->getSourceRange());
9475       }
9476     } else if (resultType->isExtVectorType()) {
9477       if (Context.getLangOpts().OpenCL &&
9478           Context.getLangOpts().OpenCLVersion < 120) {
9479         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9480         // operate on vector float types.
9481         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9482         if (!T->isIntegerType())
9483           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9484                            << resultType << Input.get()->getSourceRange());
9485       }
9486       // Vector logical not returns the signed variant of the operand type.
9487       resultType = GetSignedVectorType(resultType);
9488       break;
9489     } else {
9490       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9491         << resultType << Input.get()->getSourceRange());
9492     }
9493 
9494     // LNot always has type int. C99 6.5.3.3p5.
9495     // In C++, it's bool. C++ 5.3.1p8
9496     resultType = Context.getLogicalOperationType();
9497     break;
9498   case UO_Real:
9499   case UO_Imag:
9500     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
9501     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
9502     // complex l-values to ordinary l-values and all other values to r-values.
9503     if (Input.isInvalid()) return ExprError();
9504     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
9505       if (Input.get()->getValueKind() != VK_RValue &&
9506           Input.get()->getObjectKind() == OK_Ordinary)
9507         VK = Input.get()->getValueKind();
9508     } else if (!getLangOpts().CPlusPlus) {
9509       // In C, a volatile scalar is read by __imag. In C++, it is not.
9510       Input = DefaultLvalueConversion(Input.take());
9511     }
9512     break;
9513   case UO_Extension:
9514     resultType = Input.get()->getType();
9515     VK = Input.get()->getValueKind();
9516     OK = Input.get()->getObjectKind();
9517     break;
9518   }
9519   if (resultType.isNull() || Input.isInvalid())
9520     return ExprError();
9521 
9522   // Check for array bounds violations in the operand of the UnaryOperator,
9523   // except for the '*' and '&' operators that have to be handled specially
9524   // by CheckArrayAccess (as there are special cases like &array[arraysize]
9525   // that are explicitly defined as valid by the standard).
9526   if (Opc != UO_AddrOf && Opc != UO_Deref)
9527     CheckArrayAccess(Input.get());
9528 
9529   return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
9530                                            VK, OK, OpLoc));
9531 }
9532 
9533 /// \brief Determine whether the given expression is a qualified member
9534 /// access expression, of a form that could be turned into a pointer to member
9535 /// with the address-of operator.
9536 static bool isQualifiedMemberAccess(Expr *E) {
9537   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9538     if (!DRE->getQualifier())
9539       return false;
9540 
9541     ValueDecl *VD = DRE->getDecl();
9542     if (!VD->isCXXClassMember())
9543       return false;
9544 
9545     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9546       return true;
9547     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9548       return Method->isInstance();
9549 
9550     return false;
9551   }
9552 
9553   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9554     if (!ULE->getQualifier())
9555       return false;
9556 
9557     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9558                                            DEnd = ULE->decls_end();
9559          D != DEnd; ++D) {
9560       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9561         if (Method->isInstance())
9562           return true;
9563       } else {
9564         // Overload set does not contain methods.
9565         break;
9566       }
9567     }
9568 
9569     return false;
9570   }
9571 
9572   return false;
9573 }
9574 
9575 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
9576                               UnaryOperatorKind Opc, Expr *Input) {
9577   // First things first: handle placeholders so that the
9578   // overloaded-operator check considers the right type.
9579   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
9580     // Increment and decrement of pseudo-object references.
9581     if (pty->getKind() == BuiltinType::PseudoObject &&
9582         UnaryOperator::isIncrementDecrementOp(Opc))
9583       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
9584 
9585     // extension is always a builtin operator.
9586     if (Opc == UO_Extension)
9587       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9588 
9589     // & gets special logic for several kinds of placeholder.
9590     // The builtin code knows what to do.
9591     if (Opc == UO_AddrOf &&
9592         (pty->getKind() == BuiltinType::Overload ||
9593          pty->getKind() == BuiltinType::UnknownAny ||
9594          pty->getKind() == BuiltinType::BoundMember))
9595       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9596 
9597     // Anything else needs to be handled now.
9598     ExprResult Result = CheckPlaceholderExpr(Input);
9599     if (Result.isInvalid()) return ExprError();
9600     Input = Result.take();
9601   }
9602 
9603   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
9604       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
9605       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
9606     // Find all of the overloaded operators visible from this
9607     // point. We perform both an operator-name lookup from the local
9608     // scope and an argument-dependent lookup based on the types of
9609     // the arguments.
9610     UnresolvedSet<16> Functions;
9611     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
9612     if (S && OverOp != OO_None)
9613       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9614                                    Functions);
9615 
9616     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
9617   }
9618 
9619   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9620 }
9621 
9622 // Unary Operators.  'Tok' is the token for the operator.
9623 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
9624                               tok::TokenKind Op, Expr *Input) {
9625   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
9626 }
9627 
9628 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
9629 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
9630                                 LabelDecl *TheDecl) {
9631   TheDecl->setUsed();
9632   // Create the AST node.  The address of a label always has type 'void*'.
9633   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
9634                                        Context.getPointerType(Context.VoidTy)));
9635 }
9636 
9637 /// Given the last statement in a statement-expression, check whether
9638 /// the result is a producing expression (like a call to an
9639 /// ns_returns_retained function) and, if so, rebuild it to hoist the
9640 /// release out of the full-expression.  Otherwise, return null.
9641 /// Cannot fail.
9642 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
9643   // Should always be wrapped with one of these.
9644   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
9645   if (!cleanups) return 0;
9646 
9647   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
9648   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
9649     return 0;
9650 
9651   // Splice out the cast.  This shouldn't modify any interesting
9652   // features of the statement.
9653   Expr *producer = cast->getSubExpr();
9654   assert(producer->getType() == cast->getType());
9655   assert(producer->getValueKind() == cast->getValueKind());
9656   cleanups->setSubExpr(producer);
9657   return cleanups;
9658 }
9659 
9660 void Sema::ActOnStartStmtExpr() {
9661   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9662 }
9663 
9664 void Sema::ActOnStmtExprError() {
9665   // Note that function is also called by TreeTransform when leaving a
9666   // StmtExpr scope without rebuilding anything.
9667 
9668   DiscardCleanupsInEvaluationContext();
9669   PopExpressionEvaluationContext();
9670 }
9671 
9672 ExprResult
9673 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
9674                     SourceLocation RPLoc) { // "({..})"
9675   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9676   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9677 
9678   if (hasAnyUnrecoverableErrorsInThisFunction())
9679     DiscardCleanupsInEvaluationContext();
9680   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9681   PopExpressionEvaluationContext();
9682 
9683   bool isFileScope
9684     = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
9685   if (isFileScope)
9686     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
9687 
9688   // FIXME: there are a variety of strange constraints to enforce here, for
9689   // example, it is not possible to goto into a stmt expression apparently.
9690   // More semantic analysis is needed.
9691 
9692   // If there are sub stmts in the compound stmt, take the type of the last one
9693   // as the type of the stmtexpr.
9694   QualType Ty = Context.VoidTy;
9695   bool StmtExprMayBindToTemp = false;
9696   if (!Compound->body_empty()) {
9697     Stmt *LastStmt = Compound->body_back();
9698     LabelStmt *LastLabelStmt = 0;
9699     // If LastStmt is a label, skip down through into the body.
9700     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9701       LastLabelStmt = Label;
9702       LastStmt = Label->getSubStmt();
9703     }
9704 
9705     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
9706       // Do function/array conversion on the last expression, but not
9707       // lvalue-to-rvalue.  However, initialize an unqualified type.
9708       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9709       if (LastExpr.isInvalid())
9710         return ExprError();
9711       Ty = LastExpr.get()->getType().getUnqualifiedType();
9712 
9713       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9714         // In ARC, if the final expression ends in a consume, splice
9715         // the consume out and bind it later.  In the alternate case
9716         // (when dealing with a retainable type), the result
9717         // initialization will create a produce.  In both cases the
9718         // result will be +1, and we'll need to balance that out with
9719         // a bind.
9720         if (Expr *rebuiltLastStmt
9721               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9722           LastExpr = rebuiltLastStmt;
9723         } else {
9724           LastExpr = PerformCopyInitialization(
9725                             InitializedEntity::InitializeResult(LPLoc,
9726                                                                 Ty,
9727                                                                 false),
9728                                                    SourceLocation(),
9729                                                LastExpr);
9730         }
9731 
9732         if (LastExpr.isInvalid())
9733           return ExprError();
9734         if (LastExpr.get() != 0) {
9735           if (!LastLabelStmt)
9736             Compound->setLastStmt(LastExpr.take());
9737           else
9738             LastLabelStmt->setSubStmt(LastExpr.take());
9739           StmtExprMayBindToTemp = true;
9740         }
9741       }
9742     }
9743   }
9744 
9745   // FIXME: Check that expression type is complete/non-abstract; statement
9746   // expressions are not lvalues.
9747   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9748   if (StmtExprMayBindToTemp)
9749     return MaybeBindToTemporary(ResStmtExpr);
9750   return Owned(ResStmtExpr);
9751 }
9752 
9753 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
9754                                       TypeSourceInfo *TInfo,
9755                                       OffsetOfComponent *CompPtr,
9756                                       unsigned NumComponents,
9757                                       SourceLocation RParenLoc) {
9758   QualType ArgTy = TInfo->getType();
9759   bool Dependent = ArgTy->isDependentType();
9760   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
9761 
9762   // We must have at least one component that refers to the type, and the first
9763   // one is known to be a field designator.  Verify that the ArgTy represents
9764   // a struct/union/class.
9765   if (!Dependent && !ArgTy->isRecordType())
9766     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9767                        << ArgTy << TypeRange);
9768 
9769   // Type must be complete per C99 7.17p3 because a declaring a variable
9770   // with an incomplete type would be ill-formed.
9771   if (!Dependent
9772       && RequireCompleteType(BuiltinLoc, ArgTy,
9773                              diag::err_offsetof_incomplete_type, TypeRange))
9774     return ExprError();
9775 
9776   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9777   // GCC extension, diagnose them.
9778   // FIXME: This diagnostic isn't actually visible because the location is in
9779   // a system header!
9780   if (NumComponents != 1)
9781     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9782       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
9783 
9784   bool DidWarnAboutNonPOD = false;
9785   QualType CurrentType = ArgTy;
9786   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9787   SmallVector<OffsetOfNode, 4> Comps;
9788   SmallVector<Expr*, 4> Exprs;
9789   for (unsigned i = 0; i != NumComponents; ++i) {
9790     const OffsetOfComponent &OC = CompPtr[i];
9791     if (OC.isBrackets) {
9792       // Offset of an array sub-field.  TODO: Should we allow vector elements?
9793       if (!CurrentType->isDependentType()) {
9794         const ArrayType *AT = Context.getAsArrayType(CurrentType);
9795         if(!AT)
9796           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9797                            << CurrentType);
9798         CurrentType = AT->getElementType();
9799       } else
9800         CurrentType = Context.DependentTy;
9801 
9802       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9803       if (IdxRval.isInvalid())
9804         return ExprError();
9805       Expr *Idx = IdxRval.take();
9806 
9807       // The expression must be an integral expression.
9808       // FIXME: An integral constant expression?
9809       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9810           !Idx->getType()->isIntegerType())
9811         return ExprError(Diag(Idx->getLocStart(),
9812                               diag::err_typecheck_subscript_not_integer)
9813                          << Idx->getSourceRange());
9814 
9815       // Record this array index.
9816       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9817       Exprs.push_back(Idx);
9818       continue;
9819     }
9820 
9821     // Offset of a field.
9822     if (CurrentType->isDependentType()) {
9823       // We have the offset of a field, but we can't look into the dependent
9824       // type. Just record the identifier of the field.
9825       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9826       CurrentType = Context.DependentTy;
9827       continue;
9828     }
9829 
9830     // We need to have a complete type to look into.
9831     if (RequireCompleteType(OC.LocStart, CurrentType,
9832                             diag::err_offsetof_incomplete_type))
9833       return ExprError();
9834 
9835     // Look for the designated field.
9836     const RecordType *RC = CurrentType->getAs<RecordType>();
9837     if (!RC)
9838       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9839                        << CurrentType);
9840     RecordDecl *RD = RC->getDecl();
9841 
9842     // C++ [lib.support.types]p5:
9843     //   The macro offsetof accepts a restricted set of type arguments in this
9844     //   International Standard. type shall be a POD structure or a POD union
9845     //   (clause 9).
9846     // C++11 [support.types]p4:
9847     //   If type is not a standard-layout class (Clause 9), the results are
9848     //   undefined.
9849     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9850       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
9851       unsigned DiagID =
9852         LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type
9853                             : diag::warn_offsetof_non_pod_type;
9854 
9855       if (!IsSafe && !DidWarnAboutNonPOD &&
9856           DiagRuntimeBehavior(BuiltinLoc, 0,
9857                               PDiag(DiagID)
9858                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9859                               << CurrentType))
9860         DidWarnAboutNonPOD = true;
9861     }
9862 
9863     // Look for the field.
9864     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9865     LookupQualifiedName(R, RD);
9866     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
9867     IndirectFieldDecl *IndirectMemberDecl = 0;
9868     if (!MemberDecl) {
9869       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
9870         MemberDecl = IndirectMemberDecl->getAnonField();
9871     }
9872 
9873     if (!MemberDecl)
9874       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9875                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9876                                                               OC.LocEnd));
9877 
9878     // C99 7.17p3:
9879     //   (If the specified member is a bit-field, the behavior is undefined.)
9880     //
9881     // We diagnose this as an error.
9882     if (MemberDecl->isBitField()) {
9883       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9884         << MemberDecl->getDeclName()
9885         << SourceRange(BuiltinLoc, RParenLoc);
9886       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9887       return ExprError();
9888     }
9889 
9890     RecordDecl *Parent = MemberDecl->getParent();
9891     if (IndirectMemberDecl)
9892       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
9893 
9894     // If the member was found in a base class, introduce OffsetOfNodes for
9895     // the base class indirections.
9896     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9897                        /*DetectVirtual=*/false);
9898     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
9899       CXXBasePath &Path = Paths.front();
9900       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9901            B != BEnd; ++B)
9902         Comps.push_back(OffsetOfNode(B->Base));
9903     }
9904 
9905     if (IndirectMemberDecl) {
9906       for (IndirectFieldDecl::chain_iterator FI =
9907            IndirectMemberDecl->chain_begin(),
9908            FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9909         assert(isa<FieldDecl>(*FI));
9910         Comps.push_back(OffsetOfNode(OC.LocStart,
9911                                      cast<FieldDecl>(*FI), OC.LocEnd));
9912       }
9913     } else
9914       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
9915 
9916     CurrentType = MemberDecl->getType().getNonReferenceType();
9917   }
9918 
9919   return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9920                                     TInfo, Comps, Exprs, RParenLoc));
9921 }
9922 
9923 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
9924                                       SourceLocation BuiltinLoc,
9925                                       SourceLocation TypeLoc,
9926                                       ParsedType ParsedArgTy,
9927                                       OffsetOfComponent *CompPtr,
9928                                       unsigned NumComponents,
9929                                       SourceLocation RParenLoc) {
9930 
9931   TypeSourceInfo *ArgTInfo;
9932   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
9933   if (ArgTy.isNull())
9934     return ExprError();
9935 
9936   if (!ArgTInfo)
9937     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9938 
9939   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9940                               RParenLoc);
9941 }
9942 
9943 
9944 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
9945                                  Expr *CondExpr,
9946                                  Expr *LHSExpr, Expr *RHSExpr,
9947                                  SourceLocation RPLoc) {
9948   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9949 
9950   ExprValueKind VK = VK_RValue;
9951   ExprObjectKind OK = OK_Ordinary;
9952   QualType resType;
9953   bool ValueDependent = false;
9954   bool CondIsTrue = false;
9955   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
9956     resType = Context.DependentTy;
9957     ValueDependent = true;
9958   } else {
9959     // The conditional expression is required to be a constant expression.
9960     llvm::APSInt condEval(32);
9961     ExprResult CondICE
9962       = VerifyIntegerConstantExpression(CondExpr, &condEval,
9963           diag::err_typecheck_choose_expr_requires_constant, false);
9964     if (CondICE.isInvalid())
9965       return ExprError();
9966     CondExpr = CondICE.take();
9967     CondIsTrue = condEval.getZExtValue();
9968 
9969     // If the condition is > zero, then the AST type is the same as the LSHExpr.
9970     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
9971 
9972     resType = ActiveExpr->getType();
9973     ValueDependent = ActiveExpr->isValueDependent();
9974     VK = ActiveExpr->getValueKind();
9975     OK = ActiveExpr->getObjectKind();
9976   }
9977 
9978   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
9979                                         resType, VK, OK, RPLoc, CondIsTrue,
9980                                         resType->isDependentType(),
9981                                         ValueDependent));
9982 }
9983 
9984 //===----------------------------------------------------------------------===//
9985 // Clang Extensions.
9986 //===----------------------------------------------------------------------===//
9987 
9988 /// ActOnBlockStart - This callback is invoked when a block literal is started.
9989 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
9990   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9991 
9992   {
9993     Decl *ManglingContextDecl;
9994     if (MangleNumberingContext *MCtx =
9995             getCurrentMangleNumberContext(Block->getDeclContext(),
9996                                           ManglingContextDecl)) {
9997       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
9998       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
9999     }
10000   }
10001 
10002   PushBlockScope(CurScope, Block);
10003   CurContext->addDecl(Block);
10004   if (CurScope)
10005     PushDeclContext(CurScope, Block);
10006   else
10007     CurContext = Block;
10008 
10009   getCurBlock()->HasImplicitReturnType = true;
10010 
10011   // Enter a new evaluation context to insulate the block from any
10012   // cleanups from the enclosing full-expression.
10013   PushExpressionEvaluationContext(PotentiallyEvaluated);
10014 }
10015 
10016 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
10017                                Scope *CurScope) {
10018   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
10019   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
10020   BlockScopeInfo *CurBlock = getCurBlock();
10021 
10022   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
10023   QualType T = Sig->getType();
10024 
10025   // FIXME: We should allow unexpanded parameter packs here, but that would,
10026   // in turn, make the block expression contain unexpanded parameter packs.
10027   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
10028     // Drop the parameters.
10029     FunctionProtoType::ExtProtoInfo EPI;
10030     EPI.HasTrailingReturn = false;
10031     EPI.TypeQuals |= DeclSpec::TQ_const;
10032     T = Context.getFunctionType(Context.DependentTy, None, EPI);
10033     Sig = Context.getTrivialTypeSourceInfo(T);
10034   }
10035 
10036   // GetTypeForDeclarator always produces a function type for a block
10037   // literal signature.  Furthermore, it is always a FunctionProtoType
10038   // unless the function was written with a typedef.
10039   assert(T->isFunctionType() &&
10040          "GetTypeForDeclarator made a non-function block signature");
10041 
10042   // Look for an explicit signature in that function type.
10043   FunctionProtoTypeLoc ExplicitSignature;
10044 
10045   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
10046   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
10047 
10048     // Check whether that explicit signature was synthesized by
10049     // GetTypeForDeclarator.  If so, don't save that as part of the
10050     // written signature.
10051     if (ExplicitSignature.getLocalRangeBegin() ==
10052         ExplicitSignature.getLocalRangeEnd()) {
10053       // This would be much cheaper if we stored TypeLocs instead of
10054       // TypeSourceInfos.
10055       TypeLoc Result = ExplicitSignature.getResultLoc();
10056       unsigned Size = Result.getFullDataSize();
10057       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
10058       Sig->getTypeLoc().initializeFullCopy(Result, Size);
10059 
10060       ExplicitSignature = FunctionProtoTypeLoc();
10061     }
10062   }
10063 
10064   CurBlock->TheDecl->setSignatureAsWritten(Sig);
10065   CurBlock->FunctionType = T;
10066 
10067   const FunctionType *Fn = T->getAs<FunctionType>();
10068   QualType RetTy = Fn->getResultType();
10069   bool isVariadic =
10070     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
10071 
10072   CurBlock->TheDecl->setIsVariadic(isVariadic);
10073 
10074   // Context.DependentTy is used as a placeholder for a missing block
10075   // return type.  TODO:  what should we do with declarators like:
10076   //   ^ * { ... }
10077   // If the answer is "apply template argument deduction"....
10078   if (RetTy != Context.DependentTy) {
10079     CurBlock->ReturnType = RetTy;
10080     CurBlock->TheDecl->setBlockMissingReturnType(false);
10081     CurBlock->HasImplicitReturnType = false;
10082   }
10083 
10084   // Push block parameters from the declarator if we had them.
10085   SmallVector<ParmVarDecl*, 8> Params;
10086   if (ExplicitSignature) {
10087     for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
10088       ParmVarDecl *Param = ExplicitSignature.getArg(I);
10089       if (Param->getIdentifier() == 0 &&
10090           !Param->isImplicit() &&
10091           !Param->isInvalidDecl() &&
10092           !getLangOpts().CPlusPlus)
10093         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10094       Params.push_back(Param);
10095     }
10096 
10097   // Fake up parameter variables if we have a typedef, like
10098   //   ^ fntype { ... }
10099   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
10100     for (FunctionProtoType::arg_type_iterator
10101            I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
10102       ParmVarDecl *Param =
10103         BuildParmVarDeclForTypedef(CurBlock->TheDecl,
10104                                    ParamInfo.getLocStart(),
10105                                    *I);
10106       Params.push_back(Param);
10107     }
10108   }
10109 
10110   // Set the parameters on the block decl.
10111   if (!Params.empty()) {
10112     CurBlock->TheDecl->setParams(Params);
10113     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
10114                              CurBlock->TheDecl->param_end(),
10115                              /*CheckParameterNames=*/false);
10116   }
10117 
10118   // Finally we can process decl attributes.
10119   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
10120 
10121   // Put the parameter variables in scope.
10122   for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
10123          E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
10124     (*AI)->setOwningFunction(CurBlock->TheDecl);
10125 
10126     // If this has an identifier, add it to the scope stack.
10127     if ((*AI)->getIdentifier()) {
10128       CheckShadow(CurBlock->TheScope, *AI);
10129 
10130       PushOnScopeChains(*AI, CurBlock->TheScope);
10131     }
10132   }
10133 }
10134 
10135 /// ActOnBlockError - If there is an error parsing a block, this callback
10136 /// is invoked to pop the information about the block from the action impl.
10137 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
10138   // Leave the expression-evaluation context.
10139   DiscardCleanupsInEvaluationContext();
10140   PopExpressionEvaluationContext();
10141 
10142   // Pop off CurBlock, handle nested blocks.
10143   PopDeclContext();
10144   PopFunctionScopeInfo();
10145 }
10146 
10147 /// ActOnBlockStmtExpr - This is called when the body of a block statement
10148 /// literal was successfully completed.  ^(int x){...}
10149 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
10150                                     Stmt *Body, Scope *CurScope) {
10151   // If blocks are disabled, emit an error.
10152   if (!LangOpts.Blocks)
10153     Diag(CaretLoc, diag::err_blocks_disable);
10154 
10155   // Leave the expression-evaluation context.
10156   if (hasAnyUnrecoverableErrorsInThisFunction())
10157     DiscardCleanupsInEvaluationContext();
10158   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
10159   PopExpressionEvaluationContext();
10160 
10161   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
10162 
10163   if (BSI->HasImplicitReturnType)
10164     deduceClosureReturnType(*BSI);
10165 
10166   PopDeclContext();
10167 
10168   QualType RetTy = Context.VoidTy;
10169   if (!BSI->ReturnType.isNull())
10170     RetTy = BSI->ReturnType;
10171 
10172   bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
10173   QualType BlockTy;
10174 
10175   // Set the captured variables on the block.
10176   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
10177   SmallVector<BlockDecl::Capture, 4> Captures;
10178   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
10179     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
10180     if (Cap.isThisCapture())
10181       continue;
10182     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
10183                               Cap.isNested(), Cap.getInitExpr());
10184     Captures.push_back(NewCap);
10185   }
10186   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
10187                             BSI->CXXThisCaptureIndex != 0);
10188 
10189   // If the user wrote a function type in some form, try to use that.
10190   if (!BSI->FunctionType.isNull()) {
10191     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
10192 
10193     FunctionType::ExtInfo Ext = FTy->getExtInfo();
10194     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
10195 
10196     // Turn protoless block types into nullary block types.
10197     if (isa<FunctionNoProtoType>(FTy)) {
10198       FunctionProtoType::ExtProtoInfo EPI;
10199       EPI.ExtInfo = Ext;
10200       BlockTy = Context.getFunctionType(RetTy, None, EPI);
10201 
10202     // Otherwise, if we don't need to change anything about the function type,
10203     // preserve its sugar structure.
10204     } else if (FTy->getResultType() == RetTy &&
10205                (!NoReturn || FTy->getNoReturnAttr())) {
10206       BlockTy = BSI->FunctionType;
10207 
10208     // Otherwise, make the minimal modifications to the function type.
10209     } else {
10210       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
10211       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10212       EPI.TypeQuals = 0; // FIXME: silently?
10213       EPI.ExtInfo = Ext;
10214       BlockTy = Context.getFunctionType(RetTy, FPT->getArgTypes(), EPI);
10215     }
10216 
10217   // If we don't have a function type, just build one from nothing.
10218   } else {
10219     FunctionProtoType::ExtProtoInfo EPI;
10220     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
10221     BlockTy = Context.getFunctionType(RetTy, None, EPI);
10222   }
10223 
10224   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
10225                            BSI->TheDecl->param_end());
10226   BlockTy = Context.getBlockPointerType(BlockTy);
10227 
10228   // If needed, diagnose invalid gotos and switches in the block.
10229   if (getCurFunction()->NeedsScopeChecking() &&
10230       !hasAnyUnrecoverableErrorsInThisFunction() &&
10231       !PP.isCodeCompletionEnabled())
10232     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
10233 
10234   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
10235 
10236   // Try to apply the named return value optimization. We have to check again
10237   // if we can do this, though, because blocks keep return statements around
10238   // to deduce an implicit return type.
10239   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
10240       !BSI->TheDecl->isDependentContext())
10241     computeNRVO(Body, getCurBlock());
10242 
10243   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
10244   const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
10245   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
10246 
10247   // If the block isn't obviously global, i.e. it captures anything at
10248   // all, then we need to do a few things in the surrounding context:
10249   if (Result->getBlockDecl()->hasCaptures()) {
10250     // First, this expression has a new cleanup object.
10251     ExprCleanupObjects.push_back(Result->getBlockDecl());
10252     ExprNeedsCleanups = true;
10253 
10254     // It also gets a branch-protected scope if any of the captured
10255     // variables needs destruction.
10256     for (BlockDecl::capture_const_iterator
10257            ci = Result->getBlockDecl()->capture_begin(),
10258            ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
10259       const VarDecl *var = ci->getVariable();
10260       if (var->getType().isDestructedType() != QualType::DK_none) {
10261         getCurFunction()->setHasBranchProtectedScope();
10262         break;
10263       }
10264     }
10265   }
10266 
10267   return Owned(Result);
10268 }
10269 
10270 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
10271                                         Expr *E, ParsedType Ty,
10272                                         SourceLocation RPLoc) {
10273   TypeSourceInfo *TInfo;
10274   GetTypeFromParser(Ty, &TInfo);
10275   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
10276 }
10277 
10278 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
10279                                 Expr *E, TypeSourceInfo *TInfo,
10280                                 SourceLocation RPLoc) {
10281   Expr *OrigExpr = E;
10282 
10283   // Get the va_list type
10284   QualType VaListType = Context.getBuiltinVaListType();
10285   if (VaListType->isArrayType()) {
10286     // Deal with implicit array decay; for example, on x86-64,
10287     // va_list is an array, but it's supposed to decay to
10288     // a pointer for va_arg.
10289     VaListType = Context.getArrayDecayedType(VaListType);
10290     // Make sure the input expression also decays appropriately.
10291     ExprResult Result = UsualUnaryConversions(E);
10292     if (Result.isInvalid())
10293       return ExprError();
10294     E = Result.take();
10295   } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
10296     // If va_list is a record type and we are compiling in C++ mode,
10297     // check the argument using reference binding.
10298     InitializedEntity Entity
10299       = InitializedEntity::InitializeParameter(Context,
10300           Context.getLValueReferenceType(VaListType), false);
10301     ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
10302     if (Init.isInvalid())
10303       return ExprError();
10304     E = Init.takeAs<Expr>();
10305   } else {
10306     // Otherwise, the va_list argument must be an l-value because
10307     // it is modified by va_arg.
10308     if (!E->isTypeDependent() &&
10309         CheckForModifiableLvalue(E, BuiltinLoc, *this))
10310       return ExprError();
10311   }
10312 
10313   if (!E->isTypeDependent() &&
10314       !Context.hasSameType(VaListType, E->getType())) {
10315     return ExprError(Diag(E->getLocStart(),
10316                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
10317       << OrigExpr->getType() << E->getSourceRange());
10318   }
10319 
10320   if (!TInfo->getType()->isDependentType()) {
10321     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10322                             diag::err_second_parameter_to_va_arg_incomplete,
10323                             TInfo->getTypeLoc()))
10324       return ExprError();
10325 
10326     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10327                                TInfo->getType(),
10328                                diag::err_second_parameter_to_va_arg_abstract,
10329                                TInfo->getTypeLoc()))
10330       return ExprError();
10331 
10332     if (!TInfo->getType().isPODType(Context)) {
10333       Diag(TInfo->getTypeLoc().getBeginLoc(),
10334            TInfo->getType()->isObjCLifetimeType()
10335              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
10336              : diag::warn_second_parameter_to_va_arg_not_pod)
10337         << TInfo->getType()
10338         << TInfo->getTypeLoc().getSourceRange();
10339     }
10340 
10341     // Check for va_arg where arguments of the given type will be promoted
10342     // (i.e. this va_arg is guaranteed to have undefined behavior).
10343     QualType PromoteType;
10344     if (TInfo->getType()->isPromotableIntegerType()) {
10345       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
10346       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
10347         PromoteType = QualType();
10348     }
10349     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
10350       PromoteType = Context.DoubleTy;
10351     if (!PromoteType.isNull())
10352       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
10353                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
10354                           << TInfo->getType()
10355                           << PromoteType
10356                           << TInfo->getTypeLoc().getSourceRange());
10357   }
10358 
10359   QualType T = TInfo->getType().getNonLValueExprType(Context);
10360   return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
10361 }
10362 
10363 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
10364   // The type of __null will be int or long, depending on the size of
10365   // pointers on the target.
10366   QualType Ty;
10367   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
10368   if (pw == Context.getTargetInfo().getIntWidth())
10369     Ty = Context.IntTy;
10370   else if (pw == Context.getTargetInfo().getLongWidth())
10371     Ty = Context.LongTy;
10372   else if (pw == Context.getTargetInfo().getLongLongWidth())
10373     Ty = Context.LongLongTy;
10374   else {
10375     llvm_unreachable("I don't know size of pointer!");
10376   }
10377 
10378   return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
10379 }
10380 
10381 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
10382                                            Expr *SrcExpr, FixItHint &Hint,
10383                                            bool &IsNSString) {
10384   if (!SemaRef.getLangOpts().ObjC1)
10385     return;
10386 
10387   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10388   if (!PT)
10389     return;
10390 
10391   // Check if the destination is of type 'id'.
10392   if (!PT->isObjCIdType()) {
10393     // Check if the destination is the 'NSString' interface.
10394     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10395     if (!ID || !ID->getIdentifier()->isStr("NSString"))
10396       return;
10397     IsNSString = true;
10398   }
10399 
10400   // Ignore any parens, implicit casts (should only be
10401   // array-to-pointer decays), and not-so-opaque values.  The last is
10402   // important for making this trigger for property assignments.
10403   SrcExpr = SrcExpr->IgnoreParenImpCasts();
10404   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10405     if (OV->getSourceExpr())
10406       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10407 
10408   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
10409   if (!SL || !SL->isAscii())
10410     return;
10411 
10412   Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
10413 }
10414 
10415 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10416                                     SourceLocation Loc,
10417                                     QualType DstType, QualType SrcType,
10418                                     Expr *SrcExpr, AssignmentAction Action,
10419                                     bool *Complained) {
10420   if (Complained)
10421     *Complained = false;
10422 
10423   // Decode the result (notice that AST's are still created for extensions).
10424   bool CheckInferredResultType = false;
10425   bool isInvalid = false;
10426   unsigned DiagKind = 0;
10427   FixItHint Hint;
10428   ConversionFixItGenerator ConvHints;
10429   bool MayHaveConvFixit = false;
10430   bool MayHaveFunctionDiff = false;
10431   bool IsNSString = false;
10432 
10433   switch (ConvTy) {
10434   case Compatible:
10435       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10436       return false;
10437 
10438   case PointerToInt:
10439     DiagKind = diag::ext_typecheck_convert_pointer_int;
10440     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10441     MayHaveConvFixit = true;
10442     break;
10443   case IntToPointer:
10444     DiagKind = diag::ext_typecheck_convert_int_pointer;
10445     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10446     MayHaveConvFixit = true;
10447     break;
10448   case IncompatiblePointer:
10449     MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint, IsNSString);
10450       DiagKind =
10451         (Action == AA_Passing_CFAudited ?
10452           diag::err_arc_typecheck_convert_incompatible_pointer :
10453           diag::ext_typecheck_convert_incompatible_pointer);
10454     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10455       SrcType->isObjCObjectPointerType();
10456     if (Hint.isNull() && !CheckInferredResultType) {
10457       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10458     }
10459     else if (CheckInferredResultType) {
10460       SrcType = SrcType.getUnqualifiedType();
10461       DstType = DstType.getUnqualifiedType();
10462     }
10463     else if (IsNSString && !Hint.isNull())
10464       DiagKind = diag::warn_missing_atsign_prefix;
10465     MayHaveConvFixit = true;
10466     break;
10467   case IncompatiblePointerSign:
10468     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10469     break;
10470   case FunctionVoidPointer:
10471     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10472     break;
10473   case IncompatiblePointerDiscardsQualifiers: {
10474     // Perform array-to-pointer decay if necessary.
10475     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10476 
10477     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10478     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10479     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10480       DiagKind = diag::err_typecheck_incompatible_address_space;
10481       break;
10482 
10483 
10484     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10485       DiagKind = diag::err_typecheck_incompatible_ownership;
10486       break;
10487     }
10488 
10489     llvm_unreachable("unknown error case for discarding qualifiers!");
10490     // fallthrough
10491   }
10492   case CompatiblePointerDiscardsQualifiers:
10493     // If the qualifiers lost were because we were applying the
10494     // (deprecated) C++ conversion from a string literal to a char*
10495     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
10496     // Ideally, this check would be performed in
10497     // checkPointerTypesForAssignment. However, that would require a
10498     // bit of refactoring (so that the second argument is an
10499     // expression, rather than a type), which should be done as part
10500     // of a larger effort to fix checkPointerTypesForAssignment for
10501     // C++ semantics.
10502     if (getLangOpts().CPlusPlus &&
10503         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10504       return false;
10505     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10506     break;
10507   case IncompatibleNestedPointerQualifiers:
10508     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
10509     break;
10510   case IntToBlockPointer:
10511     DiagKind = diag::err_int_to_block_pointer;
10512     break;
10513   case IncompatibleBlockPointer:
10514     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
10515     break;
10516   case IncompatibleObjCQualifiedId:
10517     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
10518     // it can give a more specific diagnostic.
10519     DiagKind = diag::warn_incompatible_qualified_id;
10520     break;
10521   case IncompatibleVectors:
10522     DiagKind = diag::warn_incompatible_vectors;
10523     break;
10524   case IncompatibleObjCWeakRef:
10525     DiagKind = diag::err_arc_weak_unavailable_assign;
10526     break;
10527   case Incompatible:
10528     DiagKind = diag::err_typecheck_convert_incompatible;
10529     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10530     MayHaveConvFixit = true;
10531     isInvalid = true;
10532     MayHaveFunctionDiff = true;
10533     break;
10534   }
10535 
10536   QualType FirstType, SecondType;
10537   switch (Action) {
10538   case AA_Assigning:
10539   case AA_Initializing:
10540     // The destination type comes first.
10541     FirstType = DstType;
10542     SecondType = SrcType;
10543     break;
10544 
10545   case AA_Returning:
10546   case AA_Passing:
10547   case AA_Passing_CFAudited:
10548   case AA_Converting:
10549   case AA_Sending:
10550   case AA_Casting:
10551     // The source type comes first.
10552     FirstType = SrcType;
10553     SecondType = DstType;
10554     break;
10555   }
10556 
10557   PartialDiagnostic FDiag = PDiag(DiagKind);
10558   if (Action == AA_Passing_CFAudited)
10559     FDiag << FirstType << SecondType << SrcExpr->getSourceRange();
10560   else
10561     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
10562 
10563   // If we can fix the conversion, suggest the FixIts.
10564   assert(ConvHints.isNull() || Hint.isNull());
10565   if (!ConvHints.isNull()) {
10566     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
10567          HE = ConvHints.Hints.end(); HI != HE; ++HI)
10568       FDiag << *HI;
10569   } else {
10570     FDiag << Hint;
10571   }
10572   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
10573 
10574   if (MayHaveFunctionDiff)
10575     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
10576 
10577   Diag(Loc, FDiag);
10578 
10579   if (SecondType == Context.OverloadTy)
10580     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
10581                               FirstType);
10582 
10583   if (CheckInferredResultType)
10584     EmitRelatedResultTypeNote(SrcExpr);
10585 
10586   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
10587     EmitRelatedResultTypeNoteForReturn(DstType);
10588 
10589   if (Complained)
10590     *Complained = true;
10591   return isInvalid;
10592 }
10593 
10594 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10595                                                  llvm::APSInt *Result) {
10596   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
10597   public:
10598     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10599       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
10600     }
10601   } Diagnoser;
10602 
10603   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
10604 }
10605 
10606 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10607                                                  llvm::APSInt *Result,
10608                                                  unsigned DiagID,
10609                                                  bool AllowFold) {
10610   class IDDiagnoser : public VerifyICEDiagnoser {
10611     unsigned DiagID;
10612 
10613   public:
10614     IDDiagnoser(unsigned DiagID)
10615       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
10616 
10617     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10618       S.Diag(Loc, DiagID) << SR;
10619     }
10620   } Diagnoser(DiagID);
10621 
10622   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
10623 }
10624 
10625 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
10626                                             SourceRange SR) {
10627   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
10628 }
10629 
10630 ExprResult
10631 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10632                                       VerifyICEDiagnoser &Diagnoser,
10633                                       bool AllowFold) {
10634   SourceLocation DiagLoc = E->getLocStart();
10635 
10636   if (getLangOpts().CPlusPlus11) {
10637     // C++11 [expr.const]p5:
10638     //   If an expression of literal class type is used in a context where an
10639     //   integral constant expression is required, then that class type shall
10640     //   have a single non-explicit conversion function to an integral or
10641     //   unscoped enumeration type
10642     ExprResult Converted;
10643     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
10644     public:
10645       CXX11ConvertDiagnoser(bool Silent)
10646           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
10647                                 Silent, true) {}
10648 
10649       virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10650                                                    QualType T) {
10651         return S.Diag(Loc, diag::err_ice_not_integral) << T;
10652       }
10653 
10654       virtual SemaDiagnosticBuilder diagnoseIncomplete(
10655           Sema &S, SourceLocation Loc, QualType T) {
10656         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
10657       }
10658 
10659       virtual SemaDiagnosticBuilder diagnoseExplicitConv(
10660           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
10661         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10662       }
10663 
10664       virtual SemaDiagnosticBuilder noteExplicitConv(
10665           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
10666         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10667                  << ConvTy->isEnumeralType() << ConvTy;
10668       }
10669 
10670       virtual SemaDiagnosticBuilder diagnoseAmbiguous(
10671           Sema &S, SourceLocation Loc, QualType T) {
10672         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10673       }
10674 
10675       virtual SemaDiagnosticBuilder noteAmbiguous(
10676           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
10677         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10678                  << ConvTy->isEnumeralType() << ConvTy;
10679       }
10680 
10681       virtual SemaDiagnosticBuilder diagnoseConversion(
10682           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
10683         llvm_unreachable("conversion functions are permitted");
10684       }
10685     } ConvertDiagnoser(Diagnoser.Suppress);
10686 
10687     Converted = PerformContextualImplicitConversion(DiagLoc, E,
10688                                                     ConvertDiagnoser);
10689     if (Converted.isInvalid())
10690       return Converted;
10691     E = Converted.take();
10692     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10693       return ExprError();
10694   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10695     // An ICE must be of integral or unscoped enumeration type.
10696     if (!Diagnoser.Suppress)
10697       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10698     return ExprError();
10699   }
10700 
10701   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10702   // in the non-ICE case.
10703   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
10704     if (Result)
10705       *Result = E->EvaluateKnownConstInt(Context);
10706     return Owned(E);
10707   }
10708 
10709   Expr::EvalResult EvalResult;
10710   SmallVector<PartialDiagnosticAt, 8> Notes;
10711   EvalResult.Diag = &Notes;
10712 
10713   // Try to evaluate the expression, and produce diagnostics explaining why it's
10714   // not a constant expression as a side-effect.
10715   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10716                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10717 
10718   // In C++11, we can rely on diagnostics being produced for any expression
10719   // which is not a constant expression. If no diagnostics were produced, then
10720   // this is a constant expression.
10721   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
10722     if (Result)
10723       *Result = EvalResult.Val.getInt();
10724     return Owned(E);
10725   }
10726 
10727   // If our only note is the usual "invalid subexpression" note, just point
10728   // the caret at its location rather than producing an essentially
10729   // redundant note.
10730   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10731         diag::note_invalid_subexpr_in_const_expr) {
10732     DiagLoc = Notes[0].first;
10733     Notes.clear();
10734   }
10735 
10736   if (!Folded || !AllowFold) {
10737     if (!Diagnoser.Suppress) {
10738       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10739       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10740         Diag(Notes[I].first, Notes[I].second);
10741     }
10742 
10743     return ExprError();
10744   }
10745 
10746   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
10747   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10748     Diag(Notes[I].first, Notes[I].second);
10749 
10750   if (Result)
10751     *Result = EvalResult.Val.getInt();
10752   return Owned(E);
10753 }
10754 
10755 namespace {
10756   // Handle the case where we conclude a expression which we speculatively
10757   // considered to be unevaluated is actually evaluated.
10758   class TransformToPE : public TreeTransform<TransformToPE> {
10759     typedef TreeTransform<TransformToPE> BaseTransform;
10760 
10761   public:
10762     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10763 
10764     // Make sure we redo semantic analysis
10765     bool AlwaysRebuild() { return true; }
10766 
10767     // Make sure we handle LabelStmts correctly.
10768     // FIXME: This does the right thing, but maybe we need a more general
10769     // fix to TreeTransform?
10770     StmtResult TransformLabelStmt(LabelStmt *S) {
10771       S->getDecl()->setStmt(0);
10772       return BaseTransform::TransformLabelStmt(S);
10773     }
10774 
10775     // We need to special-case DeclRefExprs referring to FieldDecls which
10776     // are not part of a member pointer formation; normal TreeTransforming
10777     // doesn't catch this case because of the way we represent them in the AST.
10778     // FIXME: This is a bit ugly; is it really the best way to handle this
10779     // case?
10780     //
10781     // Error on DeclRefExprs referring to FieldDecls.
10782     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10783       if (isa<FieldDecl>(E->getDecl()) &&
10784           !SemaRef.isUnevaluatedContext())
10785         return SemaRef.Diag(E->getLocation(),
10786                             diag::err_invalid_non_static_member_use)
10787             << E->getDecl() << E->getSourceRange();
10788 
10789       return BaseTransform::TransformDeclRefExpr(E);
10790     }
10791 
10792     // Exception: filter out member pointer formation
10793     ExprResult TransformUnaryOperator(UnaryOperator *E) {
10794       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10795         return E;
10796 
10797       return BaseTransform::TransformUnaryOperator(E);
10798     }
10799 
10800     ExprResult TransformLambdaExpr(LambdaExpr *E) {
10801       // Lambdas never need to be transformed.
10802       return E;
10803     }
10804   };
10805 }
10806 
10807 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
10808   assert(isUnevaluatedContext() &&
10809          "Should only transform unevaluated expressions");
10810   ExprEvalContexts.back().Context =
10811       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10812   if (isUnevaluatedContext())
10813     return E;
10814   return TransformToPE(*this).TransformExpr(E);
10815 }
10816 
10817 void
10818 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10819                                       Decl *LambdaContextDecl,
10820                                       bool IsDecltype) {
10821   ExprEvalContexts.push_back(
10822              ExpressionEvaluationContextRecord(NewContext,
10823                                                ExprCleanupObjects.size(),
10824                                                ExprNeedsCleanups,
10825                                                LambdaContextDecl,
10826                                                IsDecltype));
10827   ExprNeedsCleanups = false;
10828   if (!MaybeODRUseExprs.empty())
10829     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
10830 }
10831 
10832 void
10833 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10834                                       ReuseLambdaContextDecl_t,
10835                                       bool IsDecltype) {
10836   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
10837   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
10838 }
10839 
10840 void Sema::PopExpressionEvaluationContext() {
10841   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
10842 
10843   if (!Rec.Lambdas.empty()) {
10844     if (Rec.isUnevaluated()) {
10845       // C++11 [expr.prim.lambda]p2:
10846       //   A lambda-expression shall not appear in an unevaluated operand
10847       //   (Clause 5).
10848       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10849         Diag(Rec.Lambdas[I]->getLocStart(),
10850              diag::err_lambda_unevaluated_operand);
10851     } else {
10852       // Mark the capture expressions odr-used. This was deferred
10853       // during lambda expression creation.
10854       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10855         LambdaExpr *Lambda = Rec.Lambdas[I];
10856         for (LambdaExpr::capture_init_iterator
10857                   C = Lambda->capture_init_begin(),
10858                CEnd = Lambda->capture_init_end();
10859              C != CEnd; ++C) {
10860           MarkDeclarationsReferencedInExpr(*C);
10861         }
10862       }
10863     }
10864   }
10865 
10866   // When are coming out of an unevaluated context, clear out any
10867   // temporaries that we may have created as part of the evaluation of
10868   // the expression in that context: they aren't relevant because they
10869   // will never be constructed.
10870   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
10871     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10872                              ExprCleanupObjects.end());
10873     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
10874     CleanupVarDeclMarking();
10875     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
10876   // Otherwise, merge the contexts together.
10877   } else {
10878     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
10879     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10880                             Rec.SavedMaybeODRUseExprs.end());
10881   }
10882 
10883   // Pop the current expression evaluation context off the stack.
10884   ExprEvalContexts.pop_back();
10885 }
10886 
10887 void Sema::DiscardCleanupsInEvaluationContext() {
10888   ExprCleanupObjects.erase(
10889          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10890          ExprCleanupObjects.end());
10891   ExprNeedsCleanups = false;
10892   MaybeODRUseExprs.clear();
10893 }
10894 
10895 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10896   if (!E->getType()->isVariablyModifiedType())
10897     return E;
10898   return TransformToPotentiallyEvaluated(E);
10899 }
10900 
10901 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
10902   // Do not mark anything as "used" within a dependent context; wait for
10903   // an instantiation.
10904   if (SemaRef.CurContext->isDependentContext())
10905     return false;
10906 
10907   switch (SemaRef.ExprEvalContexts.back().Context) {
10908     case Sema::Unevaluated:
10909     case Sema::UnevaluatedAbstract:
10910       // We are in an expression that is not potentially evaluated; do nothing.
10911       // (Depending on how you read the standard, we actually do need to do
10912       // something here for null pointer constants, but the standard's
10913       // definition of a null pointer constant is completely crazy.)
10914       return false;
10915 
10916     case Sema::ConstantEvaluated:
10917     case Sema::PotentiallyEvaluated:
10918       // We are in a potentially evaluated expression (or a constant-expression
10919       // in C++03); we need to do implicit template instantiation, implicitly
10920       // define class members, and mark most declarations as used.
10921       return true;
10922 
10923     case Sema::PotentiallyEvaluatedIfUsed:
10924       // Referenced declarations will only be used if the construct in the
10925       // containing expression is used.
10926       return false;
10927   }
10928   llvm_unreachable("Invalid context");
10929 }
10930 
10931 /// \brief Mark a function referenced, and check whether it is odr-used
10932 /// (C++ [basic.def.odr]p2, C99 6.9p3)
10933 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10934   assert(Func && "No function?");
10935 
10936   Func->setReferenced();
10937 
10938   // C++11 [basic.def.odr]p3:
10939   //   A function whose name appears as a potentially-evaluated expression is
10940   //   odr-used if it is the unique lookup result or the selected member of a
10941   //   set of overloaded functions [...].
10942   //
10943   // We (incorrectly) mark overload resolution as an unevaluated context, so we
10944   // can just check that here. Skip the rest of this function if we've already
10945   // marked the function as used.
10946   if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
10947     // C++11 [temp.inst]p3:
10948     //   Unless a function template specialization has been explicitly
10949     //   instantiated or explicitly specialized, the function template
10950     //   specialization is implicitly instantiated when the specialization is
10951     //   referenced in a context that requires a function definition to exist.
10952     //
10953     // We consider constexpr function templates to be referenced in a context
10954     // that requires a definition to exist whenever they are referenced.
10955     //
10956     // FIXME: This instantiates constexpr functions too frequently. If this is
10957     // really an unevaluated context (and we're not just in the definition of a
10958     // function template or overload resolution or other cases which we
10959     // incorrectly consider to be unevaluated contexts), and we're not in a
10960     // subexpression which we actually need to evaluate (for instance, a
10961     // template argument, array bound or an expression in a braced-init-list),
10962     // we are not permitted to instantiate this constexpr function definition.
10963     //
10964     // FIXME: This also implicitly defines special members too frequently. They
10965     // are only supposed to be implicitly defined if they are odr-used, but they
10966     // are not odr-used from constant expressions in unevaluated contexts.
10967     // However, they cannot be referenced if they are deleted, and they are
10968     // deleted whenever the implicit definition of the special member would
10969     // fail.
10970     if (!Func->isConstexpr() || Func->getBody())
10971       return;
10972     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
10973     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
10974       return;
10975   }
10976 
10977   // Note that this declaration has been used.
10978   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
10979     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
10980       if (Constructor->isDefaultConstructor()) {
10981         if (Constructor->isTrivial())
10982           return;
10983         if (!Constructor->isUsed(false))
10984           DefineImplicitDefaultConstructor(Loc, Constructor);
10985       } else if (Constructor->isCopyConstructor()) {
10986         if (!Constructor->isUsed(false))
10987           DefineImplicitCopyConstructor(Loc, Constructor);
10988       } else if (Constructor->isMoveConstructor()) {
10989         if (!Constructor->isUsed(false))
10990           DefineImplicitMoveConstructor(Loc, Constructor);
10991       }
10992     } else if (Constructor->getInheritedConstructor()) {
10993       if (!Constructor->isUsed(false))
10994         DefineInheritingConstructor(Loc, Constructor);
10995     }
10996 
10997     MarkVTableUsed(Loc, Constructor->getParent());
10998   } else if (CXXDestructorDecl *Destructor =
10999                  dyn_cast<CXXDestructorDecl>(Func)) {
11000     if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
11001         !Destructor->isUsed(false))
11002       DefineImplicitDestructor(Loc, Destructor);
11003     if (Destructor->isVirtual())
11004       MarkVTableUsed(Loc, Destructor->getParent());
11005   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
11006     if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
11007         MethodDecl->isOverloadedOperator() &&
11008         MethodDecl->getOverloadedOperator() == OO_Equal) {
11009       if (!MethodDecl->isUsed(false)) {
11010         if (MethodDecl->isCopyAssignmentOperator())
11011           DefineImplicitCopyAssignment(Loc, MethodDecl);
11012         else
11013           DefineImplicitMoveAssignment(Loc, MethodDecl);
11014       }
11015     } else if (isa<CXXConversionDecl>(MethodDecl) &&
11016                MethodDecl->getParent()->isLambda()) {
11017       CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
11018       if (Conversion->isLambdaToBlockPointerConversion())
11019         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
11020       else
11021         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
11022     } else if (MethodDecl->isVirtual())
11023       MarkVTableUsed(Loc, MethodDecl->getParent());
11024   }
11025 
11026   // Recursive functions should be marked when used from another function.
11027   // FIXME: Is this really right?
11028   if (CurContext == Func) return;
11029 
11030   // Resolve the exception specification for any function which is
11031   // used: CodeGen will need it.
11032   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
11033   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
11034     ResolveExceptionSpec(Loc, FPT);
11035 
11036   // Implicit instantiation of function templates and member functions of
11037   // class templates.
11038   if (Func->isImplicitlyInstantiable()) {
11039     bool AlreadyInstantiated = false;
11040     SourceLocation PointOfInstantiation = Loc;
11041     if (FunctionTemplateSpecializationInfo *SpecInfo
11042                               = Func->getTemplateSpecializationInfo()) {
11043       if (SpecInfo->getPointOfInstantiation().isInvalid())
11044         SpecInfo->setPointOfInstantiation(Loc);
11045       else if (SpecInfo->getTemplateSpecializationKind()
11046                  == TSK_ImplicitInstantiation) {
11047         AlreadyInstantiated = true;
11048         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
11049       }
11050     } else if (MemberSpecializationInfo *MSInfo
11051                                 = Func->getMemberSpecializationInfo()) {
11052       if (MSInfo->getPointOfInstantiation().isInvalid())
11053         MSInfo->setPointOfInstantiation(Loc);
11054       else if (MSInfo->getTemplateSpecializationKind()
11055                  == TSK_ImplicitInstantiation) {
11056         AlreadyInstantiated = true;
11057         PointOfInstantiation = MSInfo->getPointOfInstantiation();
11058       }
11059     }
11060 
11061     if (!AlreadyInstantiated || Func->isConstexpr()) {
11062       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
11063           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
11064           ActiveTemplateInstantiations.size())
11065         PendingLocalImplicitInstantiations.push_back(
11066             std::make_pair(Func, PointOfInstantiation));
11067       else if (Func->isConstexpr())
11068         // Do not defer instantiations of constexpr functions, to avoid the
11069         // expression evaluator needing to call back into Sema if it sees a
11070         // call to such a function.
11071         InstantiateFunctionDefinition(PointOfInstantiation, Func);
11072       else {
11073         PendingInstantiations.push_back(std::make_pair(Func,
11074                                                        PointOfInstantiation));
11075         // Notify the consumer that a function was implicitly instantiated.
11076         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
11077       }
11078     }
11079   } else {
11080     // Walk redefinitions, as some of them may be instantiable.
11081     for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
11082          e(Func->redecls_end()); i != e; ++i) {
11083       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
11084         MarkFunctionReferenced(Loc, *i);
11085     }
11086   }
11087 
11088   // Keep track of used but undefined functions.
11089   if (!Func->isDefined()) {
11090     if (mightHaveNonExternalLinkage(Func))
11091       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11092     else if (Func->getMostRecentDecl()->isInlined() &&
11093              (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
11094              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
11095       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11096   }
11097 
11098   // Normally the must current decl is marked used while processing the use and
11099   // any subsequent decls are marked used by decl merging. This fails with
11100   // template instantiation since marking can happen at the end of the file
11101   // and, because of the two phase lookup, this function is called with at
11102   // decl in the middle of a decl chain. We loop to maintain the invariant
11103   // that once a decl is used, all decls after it are also used.
11104   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
11105     F->setUsed(true);
11106     if (F == Func)
11107       break;
11108   }
11109 }
11110 
11111 static void
11112 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
11113                                    VarDecl *var, DeclContext *DC) {
11114   DeclContext *VarDC = var->getDeclContext();
11115 
11116   //  If the parameter still belongs to the translation unit, then
11117   //  we're actually just using one parameter in the declaration of
11118   //  the next.
11119   if (isa<ParmVarDecl>(var) &&
11120       isa<TranslationUnitDecl>(VarDC))
11121     return;
11122 
11123   // For C code, don't diagnose about capture if we're not actually in code
11124   // right now; it's impossible to write a non-constant expression outside of
11125   // function context, so we'll get other (more useful) diagnostics later.
11126   //
11127   // For C++, things get a bit more nasty... it would be nice to suppress this
11128   // diagnostic for certain cases like using a local variable in an array bound
11129   // for a member of a local class, but the correct predicate is not obvious.
11130   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
11131     return;
11132 
11133   if (isa<CXXMethodDecl>(VarDC) &&
11134       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
11135     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
11136       << var->getIdentifier();
11137   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
11138     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
11139       << var->getIdentifier() << fn->getDeclName();
11140   } else if (isa<BlockDecl>(VarDC)) {
11141     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
11142       << var->getIdentifier();
11143   } else {
11144     // FIXME: Is there any other context where a local variable can be
11145     // declared?
11146     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
11147       << var->getIdentifier();
11148   }
11149 
11150   S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
11151     << var->getIdentifier();
11152 
11153   // FIXME: Add additional diagnostic info about class etc. which prevents
11154   // capture.
11155 }
11156 
11157 /// \brief Capture the given variable in the captured region.
11158 static ExprResult captureInCapturedRegion(Sema &S, CapturedRegionScopeInfo *RSI,
11159                                           VarDecl *Var, QualType FieldType,
11160                                           QualType DeclRefType,
11161                                           SourceLocation Loc,
11162                                           bool RefersToEnclosingLocal) {
11163   // The current implemention assumes that all variables are captured
11164   // by references. Since there is no capture by copy, no expression evaluation
11165   // will be needed.
11166   //
11167   RecordDecl *RD = RSI->TheRecordDecl;
11168 
11169   FieldDecl *Field
11170     = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, FieldType,
11171                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
11172                         0, false, ICIS_NoInit);
11173   Field->setImplicit(true);
11174   Field->setAccess(AS_private);
11175   RD->addDecl(Field);
11176 
11177   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11178                                           DeclRefType, VK_LValue, Loc);
11179   Var->setReferenced(true);
11180   Var->setUsed(true);
11181 
11182   return Ref;
11183 }
11184 
11185 /// \brief Capture the given variable in the given lambda expression.
11186 static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
11187                                   VarDecl *Var, QualType FieldType,
11188                                   QualType DeclRefType,
11189                                   SourceLocation Loc,
11190                                   bool RefersToEnclosingLocal) {
11191   CXXRecordDecl *Lambda = LSI->Lambda;
11192 
11193   // Build the non-static data member.
11194   FieldDecl *Field
11195     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
11196                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
11197                         0, false, ICIS_NoInit);
11198   Field->setImplicit(true);
11199   Field->setAccess(AS_private);
11200   Lambda->addDecl(Field);
11201 
11202   // C++11 [expr.prim.lambda]p21:
11203   //   When the lambda-expression is evaluated, the entities that
11204   //   are captured by copy are used to direct-initialize each
11205   //   corresponding non-static data member of the resulting closure
11206   //   object. (For array members, the array elements are
11207   //   direct-initialized in increasing subscript order.) These
11208   //   initializations are performed in the (unspecified) order in
11209   //   which the non-static data members are declared.
11210 
11211   // Introduce a new evaluation context for the initialization, so
11212   // that temporaries introduced as part of the capture are retained
11213   // to be re-"exported" from the lambda expression itself.
11214   EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
11215 
11216   // C++ [expr.prim.labda]p12:
11217   //   An entity captured by a lambda-expression is odr-used (3.2) in
11218   //   the scope containing the lambda-expression.
11219   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11220                                           DeclRefType, VK_LValue, Loc);
11221   Var->setReferenced(true);
11222   Var->setUsed(true);
11223 
11224   // When the field has array type, create index variables for each
11225   // dimension of the array. We use these index variables to subscript
11226   // the source array, and other clients (e.g., CodeGen) will perform
11227   // the necessary iteration with these index variables.
11228   SmallVector<VarDecl *, 4> IndexVariables;
11229   QualType BaseType = FieldType;
11230   QualType SizeType = S.Context.getSizeType();
11231   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
11232   while (const ConstantArrayType *Array
11233                         = S.Context.getAsConstantArrayType(BaseType)) {
11234     // Create the iteration variable for this array index.
11235     IdentifierInfo *IterationVarName = 0;
11236     {
11237       SmallString<8> Str;
11238       llvm::raw_svector_ostream OS(Str);
11239       OS << "__i" << IndexVariables.size();
11240       IterationVarName = &S.Context.Idents.get(OS.str());
11241     }
11242     VarDecl *IterationVar
11243       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11244                         IterationVarName, SizeType,
11245                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11246                         SC_None);
11247     IndexVariables.push_back(IterationVar);
11248     LSI->ArrayIndexVars.push_back(IterationVar);
11249 
11250     // Create a reference to the iteration variable.
11251     ExprResult IterationVarRef
11252       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
11253     assert(!IterationVarRef.isInvalid() &&
11254            "Reference to invented variable cannot fail!");
11255     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
11256     assert(!IterationVarRef.isInvalid() &&
11257            "Conversion of invented variable cannot fail!");
11258 
11259     // Subscript the array with this iteration variable.
11260     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
11261                              Ref, Loc, IterationVarRef.take(), Loc);
11262     if (Subscript.isInvalid()) {
11263       S.CleanupVarDeclMarking();
11264       S.DiscardCleanupsInEvaluationContext();
11265       return ExprError();
11266     }
11267 
11268     Ref = Subscript.take();
11269     BaseType = Array->getElementType();
11270   }
11271 
11272   // Construct the entity that we will be initializing. For an array, this
11273   // will be first element in the array, which may require several levels
11274   // of array-subscript entities.
11275   SmallVector<InitializedEntity, 4> Entities;
11276   Entities.reserve(1 + IndexVariables.size());
11277   Entities.push_back(
11278     InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
11279   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
11280     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
11281                                                             0,
11282                                                             Entities.back()));
11283 
11284   InitializationKind InitKind
11285     = InitializationKind::CreateDirect(Loc, Loc, Loc);
11286   InitializationSequence Init(S, Entities.back(), InitKind, Ref);
11287   ExprResult Result(true);
11288   if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
11289     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
11290 
11291   // If this initialization requires any cleanups (e.g., due to a
11292   // default argument to a copy constructor), note that for the
11293   // lambda.
11294   if (S.ExprNeedsCleanups)
11295     LSI->ExprNeedsCleanups = true;
11296 
11297   // Exit the expression evaluation context used for the capture.
11298   S.CleanupVarDeclMarking();
11299   S.DiscardCleanupsInEvaluationContext();
11300   return Result;
11301 }
11302 
11303 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
11304                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
11305                               bool BuildAndDiagnose,
11306                               QualType &CaptureType,
11307                               QualType &DeclRefType) {
11308   bool Nested = false;
11309 
11310   DeclContext *DC = CurContext;
11311   if (Var->getDeclContext() == DC) return true;
11312   if (!Var->hasLocalStorage()) return true;
11313 
11314   bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11315 
11316   // Walk up the stack to determine whether we can capture the variable,
11317   // performing the "simple" checks that don't depend on type. We stop when
11318   // we've either hit the declared scope of the variable or find an existing
11319   // capture of that variable.
11320   CaptureType = Var->getType();
11321   DeclRefType = CaptureType.getNonReferenceType();
11322   bool Explicit = (Kind != TryCapture_Implicit);
11323   unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
11324   do {
11325     // Only block literals, captured statements, and lambda expressions can
11326     // capture; other scopes don't work.
11327     DeclContext *ParentDC;
11328     if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC))
11329       ParentDC = DC->getParent();
11330     else if (isa<CXXMethodDecl>(DC) &&
11331              cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
11332              cast<CXXRecordDecl>(DC->getParent())->isLambda())
11333       ParentDC = DC->getParent()->getParent();
11334     else {
11335       if (BuildAndDiagnose)
11336         diagnoseUncapturableValueReference(*this, Loc, Var, DC);
11337       return true;
11338     }
11339 
11340     CapturingScopeInfo *CSI =
11341       cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
11342 
11343     // Check whether we've already captured it.
11344     if (CSI->isCaptured(Var)) {
11345       const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
11346 
11347       // If we found a capture, any subcaptures are nested.
11348       Nested = true;
11349 
11350       // Retrieve the capture type for this variable.
11351       CaptureType = Cap.getCaptureType();
11352 
11353       // Compute the type of an expression that refers to this variable.
11354       DeclRefType = CaptureType.getNonReferenceType();
11355 
11356       if (Cap.isCopyCapture() &&
11357           !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
11358         DeclRefType.addConst();
11359       break;
11360     }
11361 
11362     bool IsBlock = isa<BlockScopeInfo>(CSI);
11363     bool IsLambda = isa<LambdaScopeInfo>(CSI);
11364 
11365     // Lambdas are not allowed to capture unnamed variables
11366     // (e.g. anonymous unions).
11367     // FIXME: The C++11 rule don't actually state this explicitly, but I'm
11368     // assuming that's the intent.
11369     if (IsLambda && !Var->getDeclName()) {
11370       if (BuildAndDiagnose) {
11371         Diag(Loc, diag::err_lambda_capture_anonymous_var);
11372         Diag(Var->getLocation(), diag::note_declared_at);
11373       }
11374       return true;
11375     }
11376 
11377     // Prohibit variably-modified types; they're difficult to deal with.
11378     if (Var->getType()->isVariablyModifiedType()) {
11379       if (BuildAndDiagnose) {
11380         if (IsBlock)
11381           Diag(Loc, diag::err_ref_vm_type);
11382         else
11383           Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
11384         Diag(Var->getLocation(), diag::note_previous_decl)
11385           << Var->getDeclName();
11386       }
11387       return true;
11388     }
11389     // Prohibit structs with flexible array members too.
11390     // We cannot capture what is in the tail end of the struct.
11391     if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
11392       if (VTTy->getDecl()->hasFlexibleArrayMember()) {
11393         if (BuildAndDiagnose) {
11394           if (IsBlock)
11395             Diag(Loc, diag::err_ref_flexarray_type);
11396           else
11397             Diag(Loc, diag::err_lambda_capture_flexarray_type)
11398               << Var->getDeclName();
11399           Diag(Var->getLocation(), diag::note_previous_decl)
11400             << Var->getDeclName();
11401         }
11402         return true;
11403       }
11404     }
11405     // Lambdas and captured statements are not allowed to capture __block
11406     // variables; they don't support the expected semantics.
11407     if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
11408       if (BuildAndDiagnose) {
11409         Diag(Loc, diag::err_capture_block_variable)
11410           << Var->getDeclName() << !IsLambda;
11411         Diag(Var->getLocation(), diag::note_previous_decl)
11412           << Var->getDeclName();
11413       }
11414       return true;
11415     }
11416 
11417     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
11418       // No capture-default
11419       if (BuildAndDiagnose) {
11420         Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
11421         Diag(Var->getLocation(), diag::note_previous_decl)
11422           << Var->getDeclName();
11423         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
11424              diag::note_lambda_decl);
11425       }
11426       return true;
11427     }
11428 
11429     FunctionScopesIndex--;
11430     DC = ParentDC;
11431     Explicit = false;
11432   } while (!Var->getDeclContext()->Equals(DC));
11433 
11434   // Walk back down the scope stack, computing the type of the capture at
11435   // each step, checking type-specific requirements, and adding captures if
11436   // requested.
11437   for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
11438        ++I) {
11439     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
11440 
11441     // Compute the type of the capture and of a reference to the capture within
11442     // this scope.
11443     if (isa<BlockScopeInfo>(CSI)) {
11444       Expr *CopyExpr = 0;
11445       bool ByRef = false;
11446 
11447       // Blocks are not allowed to capture arrays.
11448       if (CaptureType->isArrayType()) {
11449         if (BuildAndDiagnose) {
11450           Diag(Loc, diag::err_ref_array_type);
11451           Diag(Var->getLocation(), diag::note_previous_decl)
11452           << Var->getDeclName();
11453         }
11454         return true;
11455       }
11456 
11457       // Forbid the block-capture of autoreleasing variables.
11458       if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11459         if (BuildAndDiagnose) {
11460           Diag(Loc, diag::err_arc_autoreleasing_capture)
11461             << /*block*/ 0;
11462           Diag(Var->getLocation(), diag::note_previous_decl)
11463             << Var->getDeclName();
11464         }
11465         return true;
11466       }
11467 
11468       if (HasBlocksAttr || CaptureType->isReferenceType()) {
11469         // Block capture by reference does not change the capture or
11470         // declaration reference types.
11471         ByRef = true;
11472       } else {
11473         // Block capture by copy introduces 'const'.
11474         CaptureType = CaptureType.getNonReferenceType().withConst();
11475         DeclRefType = CaptureType;
11476 
11477         if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
11478           if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11479             // The capture logic needs the destructor, so make sure we mark it.
11480             // Usually this is unnecessary because most local variables have
11481             // their destructors marked at declaration time, but parameters are
11482             // an exception because it's technically only the call site that
11483             // actually requires the destructor.
11484             if (isa<ParmVarDecl>(Var))
11485               FinalizeVarWithDestructor(Var, Record);
11486 
11487             // Enter a new evaluation context to insulate the copy
11488             // full-expression.
11489             EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11490 
11491             // According to the blocks spec, the capture of a variable from
11492             // the stack requires a const copy constructor.  This is not true
11493             // of the copy/move done to move a __block variable to the heap.
11494             Expr *DeclRef = new (Context) DeclRefExpr(Var, Nested,
11495                                                       DeclRefType.withConst(),
11496                                                       VK_LValue, Loc);
11497 
11498             ExprResult Result
11499               = PerformCopyInitialization(
11500                   InitializedEntity::InitializeBlock(Var->getLocation(),
11501                                                      CaptureType, false),
11502                   Loc, Owned(DeclRef));
11503 
11504             // Build a full-expression copy expression if initialization
11505             // succeeded and used a non-trivial constructor.  Recover from
11506             // errors by pretending that the copy isn't necessary.
11507             if (!Result.isInvalid() &&
11508                 !cast<CXXConstructExpr>(Result.get())->getConstructor()
11509                    ->isTrivial()) {
11510               Result = MaybeCreateExprWithCleanups(Result);
11511               CopyExpr = Result.take();
11512             }
11513           }
11514         }
11515       }
11516 
11517       // Actually capture the variable.
11518       if (BuildAndDiagnose)
11519         CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11520                         SourceLocation(), CaptureType, CopyExpr);
11521       Nested = true;
11522       continue;
11523     }
11524 
11525     if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
11526       // By default, capture variables by reference.
11527       bool ByRef = true;
11528       // Using an LValue reference type is consistent with Lambdas (see below).
11529       CaptureType = Context.getLValueReferenceType(DeclRefType);
11530 
11531       Expr *CopyExpr = 0;
11532       if (BuildAndDiagnose) {
11533         ExprResult Result = captureInCapturedRegion(*this, RSI, Var,
11534                                                     CaptureType, DeclRefType,
11535                                                     Loc, Nested);
11536         if (!Result.isInvalid())
11537           CopyExpr = Result.take();
11538       }
11539 
11540       // Actually capture the variable.
11541       if (BuildAndDiagnose)
11542         CSI->addCapture(Var, /*isBlock*/false, ByRef, Nested, Loc,
11543                         SourceLocation(), CaptureType, CopyExpr);
11544       Nested = true;
11545       continue;
11546     }
11547 
11548     LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
11549 
11550     // Determine whether we are capturing by reference or by value.
11551     bool ByRef = false;
11552     if (I == N - 1 && Kind != TryCapture_Implicit) {
11553       ByRef = (Kind == TryCapture_ExplicitByRef);
11554     } else {
11555       ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
11556     }
11557 
11558     // Compute the type of the field that will capture this variable.
11559     if (ByRef) {
11560       // C++11 [expr.prim.lambda]p15:
11561       //   An entity is captured by reference if it is implicitly or
11562       //   explicitly captured but not captured by copy. It is
11563       //   unspecified whether additional unnamed non-static data
11564       //   members are declared in the closure type for entities
11565       //   captured by reference.
11566       //
11567       // FIXME: It is not clear whether we want to build an lvalue reference
11568       // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
11569       // to do the former, while EDG does the latter. Core issue 1249 will
11570       // clarify, but for now we follow GCC because it's a more permissive and
11571       // easily defensible position.
11572       CaptureType = Context.getLValueReferenceType(DeclRefType);
11573     } else {
11574       // C++11 [expr.prim.lambda]p14:
11575       //   For each entity captured by copy, an unnamed non-static
11576       //   data member is declared in the closure type. The
11577       //   declaration order of these members is unspecified. The type
11578       //   of such a data member is the type of the corresponding
11579       //   captured entity if the entity is not a reference to an
11580       //   object, or the referenced type otherwise. [Note: If the
11581       //   captured entity is a reference to a function, the
11582       //   corresponding data member is also a reference to a
11583       //   function. - end note ]
11584       if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
11585         if (!RefType->getPointeeType()->isFunctionType())
11586           CaptureType = RefType->getPointeeType();
11587       }
11588 
11589       // Forbid the lambda copy-capture of autoreleasing variables.
11590       if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11591         if (BuildAndDiagnose) {
11592           Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
11593           Diag(Var->getLocation(), diag::note_previous_decl)
11594             << Var->getDeclName();
11595         }
11596         return true;
11597       }
11598     }
11599 
11600     // Capture this variable in the lambda.
11601     Expr *CopyExpr = 0;
11602     if (BuildAndDiagnose) {
11603       ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
11604                                           DeclRefType, Loc,
11605                                           Nested);
11606       if (!Result.isInvalid())
11607         CopyExpr = Result.take();
11608     }
11609 
11610     // Compute the type of a reference to this captured variable.
11611     if (ByRef)
11612       DeclRefType = CaptureType.getNonReferenceType();
11613     else {
11614       // C++ [expr.prim.lambda]p5:
11615       //   The closure type for a lambda-expression has a public inline
11616       //   function call operator [...]. This function call operator is
11617       //   declared const (9.3.1) if and only if the lambda-expression’s
11618       //   parameter-declaration-clause is not followed by mutable.
11619       DeclRefType = CaptureType.getNonReferenceType();
11620       if (!LSI->Mutable && !CaptureType->isReferenceType())
11621         DeclRefType.addConst();
11622     }
11623 
11624     // Add the capture.
11625     if (BuildAndDiagnose)
11626       CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
11627                       EllipsisLoc, CaptureType, CopyExpr);
11628     Nested = true;
11629   }
11630 
11631   return false;
11632 }
11633 
11634 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
11635                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
11636   QualType CaptureType;
11637   QualType DeclRefType;
11638   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
11639                             /*BuildAndDiagnose=*/true, CaptureType,
11640                             DeclRefType);
11641 }
11642 
11643 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
11644   QualType CaptureType;
11645   QualType DeclRefType;
11646 
11647   // Determine whether we can capture this variable.
11648   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
11649                          /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
11650     return QualType();
11651 
11652   return DeclRefType;
11653 }
11654 
11655 static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
11656                                SourceLocation Loc) {
11657   // Keep track of used but undefined variables.
11658   // FIXME: We shouldn't suppress this warning for static data members.
11659   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
11660       !Var->isExternallyVisible() &&
11661       !(Var->isStaticDataMember() && Var->hasInit())) {
11662     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
11663     if (old.isInvalid()) old = Loc;
11664   }
11665 
11666   SemaRef.tryCaptureVariable(Var, Loc);
11667 
11668   Var->setUsed(true);
11669 }
11670 
11671 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
11672   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
11673   // an object that satisfies the requirements for appearing in a
11674   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
11675   // is immediately applied."  This function handles the lvalue-to-rvalue
11676   // conversion part.
11677   MaybeODRUseExprs.erase(E->IgnoreParens());
11678 }
11679 
11680 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
11681   if (!Res.isUsable())
11682     return Res;
11683 
11684   // If a constant-expression is a reference to a variable where we delay
11685   // deciding whether it is an odr-use, just assume we will apply the
11686   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
11687   // (a non-type template argument), we have special handling anyway.
11688   UpdateMarkingForLValueToRValue(Res.get());
11689   return Res;
11690 }
11691 
11692 void Sema::CleanupVarDeclMarking() {
11693   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
11694                                         e = MaybeODRUseExprs.end();
11695        i != e; ++i) {
11696     VarDecl *Var;
11697     SourceLocation Loc;
11698     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
11699       Var = cast<VarDecl>(DRE->getDecl());
11700       Loc = DRE->getLocation();
11701     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
11702       Var = cast<VarDecl>(ME->getMemberDecl());
11703       Loc = ME->getMemberLoc();
11704     } else {
11705       llvm_unreachable("Unexpcted expression");
11706     }
11707 
11708     MarkVarDeclODRUsed(*this, Var, Loc);
11709   }
11710 
11711   MaybeODRUseExprs.clear();
11712 }
11713 
11714 // Mark a VarDecl referenced, and perform the necessary handling to compute
11715 // odr-uses.
11716 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
11717                                     VarDecl *Var, Expr *E) {
11718   Var->setReferenced();
11719 
11720   if (!IsPotentiallyEvaluatedContext(SemaRef))
11721     return;
11722 
11723   VarTemplateSpecializationDecl *VarSpec =
11724       dyn_cast<VarTemplateSpecializationDecl>(Var);
11725 
11726   // Implicit instantiation of static data members, static data member
11727   // templates of class templates, and variable template specializations.
11728   // Delay instantiations of variable templates, except for those
11729   // that could be used in a constant expression.
11730   if (VarSpec || (Var->isStaticDataMember() &&
11731                   Var->getInstantiatedFromStaticDataMember())) {
11732     MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
11733     if (VarSpec)
11734       assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
11735              "Can't instantiate a partial template specialization.");
11736     if (Var->isStaticDataMember())
11737       assert(MSInfo && "Missing member specialization information?");
11738 
11739     SourceLocation PointOfInstantiation;
11740     bool InstantiationIsOkay = true;
11741     if (MSInfo) {
11742       bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
11743       TemplateSpecializationKind TSK = MSInfo->getTemplateSpecializationKind();
11744 
11745       if (TSK == TSK_ImplicitInstantiation &&
11746           (!AlreadyInstantiated ||
11747            Var->isUsableInConstantExpressions(SemaRef.Context))) {
11748         if (!AlreadyInstantiated) {
11749           // This is a modification of an existing AST node. Notify listeners.
11750           if (ASTMutationListener *L = SemaRef.getASTMutationListener())
11751             L->StaticDataMemberInstantiated(Var);
11752           MSInfo->setPointOfInstantiation(Loc);
11753         }
11754         PointOfInstantiation = MSInfo->getPointOfInstantiation();
11755       } else
11756         InstantiationIsOkay = false;
11757     } else {
11758       if (VarSpec->getPointOfInstantiation().isInvalid())
11759         VarSpec->setPointOfInstantiation(Loc);
11760       PointOfInstantiation = VarSpec->getPointOfInstantiation();
11761     }
11762 
11763     if (InstantiationIsOkay) {
11764       bool InstantiationDependent = false;
11765       bool IsNonDependent =
11766           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
11767                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
11768                   : true;
11769 
11770       // Do not instantiate specializations that are still type-dependent.
11771       if (IsNonDependent) {
11772         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
11773           // Do not defer instantiations of variables which could be used in a
11774           // constant expression.
11775           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
11776         } else {
11777           SemaRef.PendingInstantiations
11778               .push_back(std::make_pair(Var, PointOfInstantiation));
11779         }
11780       }
11781     }
11782   }
11783 
11784   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
11785   // the requirements for appearing in a constant expression (5.19) and, if
11786   // it is an object, the lvalue-to-rvalue conversion (4.1)
11787   // is immediately applied."  We check the first part here, and
11788   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
11789   // Note that we use the C++11 definition everywhere because nothing in
11790   // C++03 depends on whether we get the C++03 version correct. The second
11791   // part does not apply to references, since they are not objects.
11792   const VarDecl *DefVD;
11793   if (E && !isa<ParmVarDecl>(Var) &&
11794       Var->isUsableInConstantExpressions(SemaRef.Context) &&
11795       Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) {
11796     if (!Var->getType()->isReferenceType())
11797       SemaRef.MaybeODRUseExprs.insert(E);
11798   } else
11799     MarkVarDeclODRUsed(SemaRef, Var, Loc);
11800 }
11801 
11802 /// \brief Mark a variable referenced, and check whether it is odr-used
11803 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
11804 /// used directly for normal expressions referring to VarDecl.
11805 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
11806   DoMarkVarDeclReferenced(*this, Loc, Var, 0);
11807 }
11808 
11809 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
11810                                Decl *D, Expr *E, bool OdrUse) {
11811   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
11812     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
11813     return;
11814   }
11815 
11816   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
11817 
11818   // If this is a call to a method via a cast, also mark the method in the
11819   // derived class used in case codegen can devirtualize the call.
11820   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11821   if (!ME)
11822     return;
11823   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
11824   if (!MD)
11825     return;
11826   const Expr *Base = ME->getBase();
11827   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
11828   if (!MostDerivedClassDecl)
11829     return;
11830   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
11831   if (!DM || DM->isPure())
11832     return;
11833   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
11834 }
11835 
11836 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
11837 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
11838   // TODO: update this with DR# once a defect report is filed.
11839   // C++11 defect. The address of a pure member should not be an ODR use, even
11840   // if it's a qualified reference.
11841   bool OdrUse = true;
11842   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
11843     if (Method->isVirtual())
11844       OdrUse = false;
11845   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
11846 }
11847 
11848 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
11849 void Sema::MarkMemberReferenced(MemberExpr *E) {
11850   // C++11 [basic.def.odr]p2:
11851   //   A non-overloaded function whose name appears as a potentially-evaluated
11852   //   expression or a member of a set of candidate functions, if selected by
11853   //   overload resolution when referred to from a potentially-evaluated
11854   //   expression, is odr-used, unless it is a pure virtual function and its
11855   //   name is not explicitly qualified.
11856   bool OdrUse = true;
11857   if (!E->hasQualifier()) {
11858     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
11859       if (Method->isPure())
11860         OdrUse = false;
11861   }
11862   SourceLocation Loc = E->getMemberLoc().isValid() ?
11863                             E->getMemberLoc() : E->getLocStart();
11864   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
11865 }
11866 
11867 /// \brief Perform marking for a reference to an arbitrary declaration.  It
11868 /// marks the declaration referenced, and performs odr-use checking for functions
11869 /// and variables. This method should not be used when building an normal
11870 /// expression which refers to a variable.
11871 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
11872   if (OdrUse) {
11873     if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11874       MarkVariableReferenced(Loc, VD);
11875       return;
11876     }
11877     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
11878       MarkFunctionReferenced(Loc, FD);
11879       return;
11880     }
11881   }
11882   D->setReferenced();
11883 }
11884 
11885 namespace {
11886   // Mark all of the declarations referenced
11887   // FIXME: Not fully implemented yet! We need to have a better understanding
11888   // of when we're entering
11889   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11890     Sema &S;
11891     SourceLocation Loc;
11892 
11893   public:
11894     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
11895 
11896     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
11897 
11898     bool TraverseTemplateArgument(const TemplateArgument &Arg);
11899     bool TraverseRecordType(RecordType *T);
11900   };
11901 }
11902 
11903 bool MarkReferencedDecls::TraverseTemplateArgument(
11904   const TemplateArgument &Arg) {
11905   if (Arg.getKind() == TemplateArgument::Declaration) {
11906     if (Decl *D = Arg.getAsDecl())
11907       S.MarkAnyDeclReferenced(Loc, D, true);
11908   }
11909 
11910   return Inherited::TraverseTemplateArgument(Arg);
11911 }
11912 
11913 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
11914   if (ClassTemplateSpecializationDecl *Spec
11915                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11916     const TemplateArgumentList &Args = Spec->getTemplateArgs();
11917     return TraverseTemplateArguments(Args.data(), Args.size());
11918   }
11919 
11920   return true;
11921 }
11922 
11923 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11924   MarkReferencedDecls Marker(*this, Loc);
11925   Marker.TraverseType(Context.getCanonicalType(T));
11926 }
11927 
11928 namespace {
11929   /// \brief Helper class that marks all of the declarations referenced by
11930   /// potentially-evaluated subexpressions as "referenced".
11931   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11932     Sema &S;
11933     bool SkipLocalVariables;
11934 
11935   public:
11936     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11937 
11938     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11939       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
11940 
11941     void VisitDeclRefExpr(DeclRefExpr *E) {
11942       // If we were asked not to visit local variables, don't.
11943       if (SkipLocalVariables) {
11944         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11945           if (VD->hasLocalStorage())
11946             return;
11947       }
11948 
11949       S.MarkDeclRefReferenced(E);
11950     }
11951 
11952     void VisitMemberExpr(MemberExpr *E) {
11953       S.MarkMemberReferenced(E);
11954       Inherited::VisitMemberExpr(E);
11955     }
11956 
11957     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
11958       S.MarkFunctionReferenced(E->getLocStart(),
11959             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11960       Visit(E->getSubExpr());
11961     }
11962 
11963     void VisitCXXNewExpr(CXXNewExpr *E) {
11964       if (E->getOperatorNew())
11965         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
11966       if (E->getOperatorDelete())
11967         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11968       Inherited::VisitCXXNewExpr(E);
11969     }
11970 
11971     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11972       if (E->getOperatorDelete())
11973         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11974       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11975       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11976         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
11977         S.MarkFunctionReferenced(E->getLocStart(),
11978                                     S.LookupDestructor(Record));
11979       }
11980 
11981       Inherited::VisitCXXDeleteExpr(E);
11982     }
11983 
11984     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11985       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
11986       Inherited::VisitCXXConstructExpr(E);
11987     }
11988 
11989     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11990       Visit(E->getExpr());
11991     }
11992 
11993     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11994       Inherited::VisitImplicitCastExpr(E);
11995 
11996       if (E->getCastKind() == CK_LValueToRValue)
11997         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11998     }
11999   };
12000 }
12001 
12002 /// \brief Mark any declarations that appear within this expression or any
12003 /// potentially-evaluated subexpressions as "referenced".
12004 ///
12005 /// \param SkipLocalVariables If true, don't mark local variables as
12006 /// 'referenced'.
12007 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
12008                                             bool SkipLocalVariables) {
12009   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
12010 }
12011 
12012 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
12013 /// of the program being compiled.
12014 ///
12015 /// This routine emits the given diagnostic when the code currently being
12016 /// type-checked is "potentially evaluated", meaning that there is a
12017 /// possibility that the code will actually be executable. Code in sizeof()
12018 /// expressions, code used only during overload resolution, etc., are not
12019 /// potentially evaluated. This routine will suppress such diagnostics or,
12020 /// in the absolutely nutty case of potentially potentially evaluated
12021 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
12022 /// later.
12023 ///
12024 /// This routine should be used for all diagnostics that describe the run-time
12025 /// behavior of a program, such as passing a non-POD value through an ellipsis.
12026 /// Failure to do so will likely result in spurious diagnostics or failures
12027 /// during overload resolution or within sizeof/alignof/typeof/typeid.
12028 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
12029                                const PartialDiagnostic &PD) {
12030   switch (ExprEvalContexts.back().Context) {
12031   case Unevaluated:
12032   case UnevaluatedAbstract:
12033     // The argument will never be evaluated, so don't complain.
12034     break;
12035 
12036   case ConstantEvaluated:
12037     // Relevant diagnostics should be produced by constant evaluation.
12038     break;
12039 
12040   case PotentiallyEvaluated:
12041   case PotentiallyEvaluatedIfUsed:
12042     if (Statement && getCurFunctionOrMethodDecl()) {
12043       FunctionScopes.back()->PossiblyUnreachableDiags.
12044         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
12045     }
12046     else
12047       Diag(Loc, PD);
12048 
12049     return true;
12050   }
12051 
12052   return false;
12053 }
12054 
12055 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
12056                                CallExpr *CE, FunctionDecl *FD) {
12057   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
12058     return false;
12059 
12060   // If we're inside a decltype's expression, don't check for a valid return
12061   // type or construct temporaries until we know whether this is the last call.
12062   if (ExprEvalContexts.back().IsDecltype) {
12063     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
12064     return false;
12065   }
12066 
12067   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
12068     FunctionDecl *FD;
12069     CallExpr *CE;
12070 
12071   public:
12072     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
12073       : FD(FD), CE(CE) { }
12074 
12075     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
12076       if (!FD) {
12077         S.Diag(Loc, diag::err_call_incomplete_return)
12078           << T << CE->getSourceRange();
12079         return;
12080       }
12081 
12082       S.Diag(Loc, diag::err_call_function_incomplete_return)
12083         << CE->getSourceRange() << FD->getDeclName() << T;
12084       S.Diag(FD->getLocation(),
12085              diag::note_function_with_incomplete_return_type_declared_here)
12086         << FD->getDeclName();
12087     }
12088   } Diagnoser(FD, CE);
12089 
12090   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
12091     return true;
12092 
12093   return false;
12094 }
12095 
12096 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
12097 // will prevent this condition from triggering, which is what we want.
12098 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
12099   SourceLocation Loc;
12100 
12101   unsigned diagnostic = diag::warn_condition_is_assignment;
12102   bool IsOrAssign = false;
12103 
12104   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
12105     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
12106       return;
12107 
12108     IsOrAssign = Op->getOpcode() == BO_OrAssign;
12109 
12110     // Greylist some idioms by putting them into a warning subcategory.
12111     if (ObjCMessageExpr *ME
12112           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
12113       Selector Sel = ME->getSelector();
12114 
12115       // self = [<foo> init...]
12116       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
12117         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12118 
12119       // <foo> = [<bar> nextObject]
12120       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
12121         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12122     }
12123 
12124     Loc = Op->getOperatorLoc();
12125   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
12126     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
12127       return;
12128 
12129     IsOrAssign = Op->getOperator() == OO_PipeEqual;
12130     Loc = Op->getOperatorLoc();
12131   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
12132     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
12133   else {
12134     // Not an assignment.
12135     return;
12136   }
12137 
12138   Diag(Loc, diagnostic) << E->getSourceRange();
12139 
12140   SourceLocation Open = E->getLocStart();
12141   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
12142   Diag(Loc, diag::note_condition_assign_silence)
12143         << FixItHint::CreateInsertion(Open, "(")
12144         << FixItHint::CreateInsertion(Close, ")");
12145 
12146   if (IsOrAssign)
12147     Diag(Loc, diag::note_condition_or_assign_to_comparison)
12148       << FixItHint::CreateReplacement(Loc, "!=");
12149   else
12150     Diag(Loc, diag::note_condition_assign_to_comparison)
12151       << FixItHint::CreateReplacement(Loc, "==");
12152 }
12153 
12154 /// \brief Redundant parentheses over an equality comparison can indicate
12155 /// that the user intended an assignment used as condition.
12156 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
12157   // Don't warn if the parens came from a macro.
12158   SourceLocation parenLoc = ParenE->getLocStart();
12159   if (parenLoc.isInvalid() || parenLoc.isMacroID())
12160     return;
12161   // Don't warn for dependent expressions.
12162   if (ParenE->isTypeDependent())
12163     return;
12164 
12165   Expr *E = ParenE->IgnoreParens();
12166 
12167   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
12168     if (opE->getOpcode() == BO_EQ &&
12169         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
12170                                                            == Expr::MLV_Valid) {
12171       SourceLocation Loc = opE->getOperatorLoc();
12172 
12173       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
12174       SourceRange ParenERange = ParenE->getSourceRange();
12175       Diag(Loc, diag::note_equality_comparison_silence)
12176         << FixItHint::CreateRemoval(ParenERange.getBegin())
12177         << FixItHint::CreateRemoval(ParenERange.getEnd());
12178       Diag(Loc, diag::note_equality_comparison_to_assign)
12179         << FixItHint::CreateReplacement(Loc, "=");
12180     }
12181 }
12182 
12183 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
12184   DiagnoseAssignmentAsCondition(E);
12185   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
12186     DiagnoseEqualityWithExtraParens(parenE);
12187 
12188   ExprResult result = CheckPlaceholderExpr(E);
12189   if (result.isInvalid()) return ExprError();
12190   E = result.take();
12191 
12192   if (!E->isTypeDependent()) {
12193     if (getLangOpts().CPlusPlus)
12194       return CheckCXXBooleanCondition(E); // C++ 6.4p4
12195 
12196     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
12197     if (ERes.isInvalid())
12198       return ExprError();
12199     E = ERes.take();
12200 
12201     QualType T = E->getType();
12202     if (!T->isScalarType()) { // C99 6.8.4.1p1
12203       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
12204         << T << E->getSourceRange();
12205       return ExprError();
12206     }
12207   }
12208 
12209   return Owned(E);
12210 }
12211 
12212 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
12213                                        Expr *SubExpr) {
12214   if (!SubExpr)
12215     return ExprError();
12216 
12217   return CheckBooleanCondition(SubExpr, Loc);
12218 }
12219 
12220 namespace {
12221   /// A visitor for rebuilding a call to an __unknown_any expression
12222   /// to have an appropriate type.
12223   struct RebuildUnknownAnyFunction
12224     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
12225 
12226     Sema &S;
12227 
12228     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
12229 
12230     ExprResult VisitStmt(Stmt *S) {
12231       llvm_unreachable("unexpected statement!");
12232     }
12233 
12234     ExprResult VisitExpr(Expr *E) {
12235       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
12236         << E->getSourceRange();
12237       return ExprError();
12238     }
12239 
12240     /// Rebuild an expression which simply semantically wraps another
12241     /// expression which it shares the type and value kind of.
12242     template <class T> ExprResult rebuildSugarExpr(T *E) {
12243       ExprResult SubResult = Visit(E->getSubExpr());
12244       if (SubResult.isInvalid()) return ExprError();
12245 
12246       Expr *SubExpr = SubResult.take();
12247       E->setSubExpr(SubExpr);
12248       E->setType(SubExpr->getType());
12249       E->setValueKind(SubExpr->getValueKind());
12250       assert(E->getObjectKind() == OK_Ordinary);
12251       return E;
12252     }
12253 
12254     ExprResult VisitParenExpr(ParenExpr *E) {
12255       return rebuildSugarExpr(E);
12256     }
12257 
12258     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12259       return rebuildSugarExpr(E);
12260     }
12261 
12262     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12263       ExprResult SubResult = Visit(E->getSubExpr());
12264       if (SubResult.isInvalid()) return ExprError();
12265 
12266       Expr *SubExpr = SubResult.take();
12267       E->setSubExpr(SubExpr);
12268       E->setType(S.Context.getPointerType(SubExpr->getType()));
12269       assert(E->getValueKind() == VK_RValue);
12270       assert(E->getObjectKind() == OK_Ordinary);
12271       return E;
12272     }
12273 
12274     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
12275       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
12276 
12277       E->setType(VD->getType());
12278 
12279       assert(E->getValueKind() == VK_RValue);
12280       if (S.getLangOpts().CPlusPlus &&
12281           !(isa<CXXMethodDecl>(VD) &&
12282             cast<CXXMethodDecl>(VD)->isInstance()))
12283         E->setValueKind(VK_LValue);
12284 
12285       return E;
12286     }
12287 
12288     ExprResult VisitMemberExpr(MemberExpr *E) {
12289       return resolveDecl(E, E->getMemberDecl());
12290     }
12291 
12292     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12293       return resolveDecl(E, E->getDecl());
12294     }
12295   };
12296 }
12297 
12298 /// Given a function expression of unknown-any type, try to rebuild it
12299 /// to have a function type.
12300 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
12301   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
12302   if (Result.isInvalid()) return ExprError();
12303   return S.DefaultFunctionArrayConversion(Result.take());
12304 }
12305 
12306 namespace {
12307   /// A visitor for rebuilding an expression of type __unknown_anytype
12308   /// into one which resolves the type directly on the referring
12309   /// expression.  Strict preservation of the original source
12310   /// structure is not a goal.
12311   struct RebuildUnknownAnyExpr
12312     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
12313 
12314     Sema &S;
12315 
12316     /// The current destination type.
12317     QualType DestType;
12318 
12319     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
12320       : S(S), DestType(CastType) {}
12321 
12322     ExprResult VisitStmt(Stmt *S) {
12323       llvm_unreachable("unexpected statement!");
12324     }
12325 
12326     ExprResult VisitExpr(Expr *E) {
12327       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12328         << E->getSourceRange();
12329       return ExprError();
12330     }
12331 
12332     ExprResult VisitCallExpr(CallExpr *E);
12333     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
12334 
12335     /// Rebuild an expression which simply semantically wraps another
12336     /// expression which it shares the type and value kind of.
12337     template <class T> ExprResult rebuildSugarExpr(T *E) {
12338       ExprResult SubResult = Visit(E->getSubExpr());
12339       if (SubResult.isInvalid()) return ExprError();
12340       Expr *SubExpr = SubResult.take();
12341       E->setSubExpr(SubExpr);
12342       E->setType(SubExpr->getType());
12343       E->setValueKind(SubExpr->getValueKind());
12344       assert(E->getObjectKind() == OK_Ordinary);
12345       return E;
12346     }
12347 
12348     ExprResult VisitParenExpr(ParenExpr *E) {
12349       return rebuildSugarExpr(E);
12350     }
12351 
12352     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12353       return rebuildSugarExpr(E);
12354     }
12355 
12356     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12357       const PointerType *Ptr = DestType->getAs<PointerType>();
12358       if (!Ptr) {
12359         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
12360           << E->getSourceRange();
12361         return ExprError();
12362       }
12363       assert(E->getValueKind() == VK_RValue);
12364       assert(E->getObjectKind() == OK_Ordinary);
12365       E->setType(DestType);
12366 
12367       // Build the sub-expression as if it were an object of the pointee type.
12368       DestType = Ptr->getPointeeType();
12369       ExprResult SubResult = Visit(E->getSubExpr());
12370       if (SubResult.isInvalid()) return ExprError();
12371       E->setSubExpr(SubResult.take());
12372       return E;
12373     }
12374 
12375     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
12376 
12377     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
12378 
12379     ExprResult VisitMemberExpr(MemberExpr *E) {
12380       return resolveDecl(E, E->getMemberDecl());
12381     }
12382 
12383     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12384       return resolveDecl(E, E->getDecl());
12385     }
12386   };
12387 }
12388 
12389 /// Rebuilds a call expression which yielded __unknown_anytype.
12390 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
12391   Expr *CalleeExpr = E->getCallee();
12392 
12393   enum FnKind {
12394     FK_MemberFunction,
12395     FK_FunctionPointer,
12396     FK_BlockPointer
12397   };
12398 
12399   FnKind Kind;
12400   QualType CalleeType = CalleeExpr->getType();
12401   if (CalleeType == S.Context.BoundMemberTy) {
12402     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
12403     Kind = FK_MemberFunction;
12404     CalleeType = Expr::findBoundMemberType(CalleeExpr);
12405   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
12406     CalleeType = Ptr->getPointeeType();
12407     Kind = FK_FunctionPointer;
12408   } else {
12409     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
12410     Kind = FK_BlockPointer;
12411   }
12412   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
12413 
12414   // Verify that this is a legal result type of a function.
12415   if (DestType->isArrayType() || DestType->isFunctionType()) {
12416     unsigned diagID = diag::err_func_returning_array_function;
12417     if (Kind == FK_BlockPointer)
12418       diagID = diag::err_block_returning_array_function;
12419 
12420     S.Diag(E->getExprLoc(), diagID)
12421       << DestType->isFunctionType() << DestType;
12422     return ExprError();
12423   }
12424 
12425   // Otherwise, go ahead and set DestType as the call's result.
12426   E->setType(DestType.getNonLValueExprType(S.Context));
12427   E->setValueKind(Expr::getValueKindForType(DestType));
12428   assert(E->getObjectKind() == OK_Ordinary);
12429 
12430   // Rebuild the function type, replacing the result type with DestType.
12431   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
12432   if (Proto) {
12433     // __unknown_anytype(...) is a special case used by the debugger when
12434     // it has no idea what a function's signature is.
12435     //
12436     // We want to build this call essentially under the K&R
12437     // unprototyped rules, but making a FunctionNoProtoType in C++
12438     // would foul up all sorts of assumptions.  However, we cannot
12439     // simply pass all arguments as variadic arguments, nor can we
12440     // portably just call the function under a non-variadic type; see
12441     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
12442     // However, it turns out that in practice it is generally safe to
12443     // call a function declared as "A foo(B,C,D);" under the prototype
12444     // "A foo(B,C,D,...);".  The only known exception is with the
12445     // Windows ABI, where any variadic function is implicitly cdecl
12446     // regardless of its normal CC.  Therefore we change the parameter
12447     // types to match the types of the arguments.
12448     //
12449     // This is a hack, but it is far superior to moving the
12450     // corresponding target-specific code from IR-gen to Sema/AST.
12451 
12452     ArrayRef<QualType> ParamTypes = Proto->getArgTypes();
12453     SmallVector<QualType, 8> ArgTypes;
12454     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
12455       ArgTypes.reserve(E->getNumArgs());
12456       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
12457         Expr *Arg = E->getArg(i);
12458         QualType ArgType = Arg->getType();
12459         if (E->isLValue()) {
12460           ArgType = S.Context.getLValueReferenceType(ArgType);
12461         } else if (E->isXValue()) {
12462           ArgType = S.Context.getRValueReferenceType(ArgType);
12463         }
12464         ArgTypes.push_back(ArgType);
12465       }
12466       ParamTypes = ArgTypes;
12467     }
12468     DestType = S.Context.getFunctionType(DestType, ParamTypes,
12469                                          Proto->getExtProtoInfo());
12470   } else {
12471     DestType = S.Context.getFunctionNoProtoType(DestType,
12472                                                 FnType->getExtInfo());
12473   }
12474 
12475   // Rebuild the appropriate pointer-to-function type.
12476   switch (Kind) {
12477   case FK_MemberFunction:
12478     // Nothing to do.
12479     break;
12480 
12481   case FK_FunctionPointer:
12482     DestType = S.Context.getPointerType(DestType);
12483     break;
12484 
12485   case FK_BlockPointer:
12486     DestType = S.Context.getBlockPointerType(DestType);
12487     break;
12488   }
12489 
12490   // Finally, we can recurse.
12491   ExprResult CalleeResult = Visit(CalleeExpr);
12492   if (!CalleeResult.isUsable()) return ExprError();
12493   E->setCallee(CalleeResult.take());
12494 
12495   // Bind a temporary if necessary.
12496   return S.MaybeBindToTemporary(E);
12497 }
12498 
12499 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
12500   // Verify that this is a legal result type of a call.
12501   if (DestType->isArrayType() || DestType->isFunctionType()) {
12502     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
12503       << DestType->isFunctionType() << DestType;
12504     return ExprError();
12505   }
12506 
12507   // Rewrite the method result type if available.
12508   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
12509     assert(Method->getResultType() == S.Context.UnknownAnyTy);
12510     Method->setResultType(DestType);
12511   }
12512 
12513   // Change the type of the message.
12514   E->setType(DestType.getNonReferenceType());
12515   E->setValueKind(Expr::getValueKindForType(DestType));
12516 
12517   return S.MaybeBindToTemporary(E);
12518 }
12519 
12520 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
12521   // The only case we should ever see here is a function-to-pointer decay.
12522   if (E->getCastKind() == CK_FunctionToPointerDecay) {
12523     assert(E->getValueKind() == VK_RValue);
12524     assert(E->getObjectKind() == OK_Ordinary);
12525 
12526     E->setType(DestType);
12527 
12528     // Rebuild the sub-expression as the pointee (function) type.
12529     DestType = DestType->castAs<PointerType>()->getPointeeType();
12530 
12531     ExprResult Result = Visit(E->getSubExpr());
12532     if (!Result.isUsable()) return ExprError();
12533 
12534     E->setSubExpr(Result.take());
12535     return S.Owned(E);
12536   } else if (E->getCastKind() == CK_LValueToRValue) {
12537     assert(E->getValueKind() == VK_RValue);
12538     assert(E->getObjectKind() == OK_Ordinary);
12539 
12540     assert(isa<BlockPointerType>(E->getType()));
12541 
12542     E->setType(DestType);
12543 
12544     // The sub-expression has to be a lvalue reference, so rebuild it as such.
12545     DestType = S.Context.getLValueReferenceType(DestType);
12546 
12547     ExprResult Result = Visit(E->getSubExpr());
12548     if (!Result.isUsable()) return ExprError();
12549 
12550     E->setSubExpr(Result.take());
12551     return S.Owned(E);
12552   } else {
12553     llvm_unreachable("Unhandled cast type!");
12554   }
12555 }
12556 
12557 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
12558   ExprValueKind ValueKind = VK_LValue;
12559   QualType Type = DestType;
12560 
12561   // We know how to make this work for certain kinds of decls:
12562 
12563   //  - functions
12564   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
12565     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
12566       DestType = Ptr->getPointeeType();
12567       ExprResult Result = resolveDecl(E, VD);
12568       if (Result.isInvalid()) return ExprError();
12569       return S.ImpCastExprToType(Result.take(), Type,
12570                                  CK_FunctionToPointerDecay, VK_RValue);
12571     }
12572 
12573     if (!Type->isFunctionType()) {
12574       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
12575         << VD << E->getSourceRange();
12576       return ExprError();
12577     }
12578 
12579     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
12580       if (MD->isInstance()) {
12581         ValueKind = VK_RValue;
12582         Type = S.Context.BoundMemberTy;
12583       }
12584 
12585     // Function references aren't l-values in C.
12586     if (!S.getLangOpts().CPlusPlus)
12587       ValueKind = VK_RValue;
12588 
12589   //  - variables
12590   } else if (isa<VarDecl>(VD)) {
12591     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
12592       Type = RefTy->getPointeeType();
12593     } else if (Type->isFunctionType()) {
12594       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
12595         << VD << E->getSourceRange();
12596       return ExprError();
12597     }
12598 
12599   //  - nothing else
12600   } else {
12601     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
12602       << VD << E->getSourceRange();
12603     return ExprError();
12604   }
12605 
12606   // Modifying the declaration like this is friendly to IR-gen but
12607   // also really dangerous.
12608   VD->setType(DestType);
12609   E->setType(Type);
12610   E->setValueKind(ValueKind);
12611   return S.Owned(E);
12612 }
12613 
12614 /// Check a cast of an unknown-any type.  We intentionally only
12615 /// trigger this for C-style casts.
12616 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
12617                                      Expr *CastExpr, CastKind &CastKind,
12618                                      ExprValueKind &VK, CXXCastPath &Path) {
12619   // Rewrite the casted expression from scratch.
12620   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
12621   if (!result.isUsable()) return ExprError();
12622 
12623   CastExpr = result.take();
12624   VK = CastExpr->getValueKind();
12625   CastKind = CK_NoOp;
12626 
12627   return CastExpr;
12628 }
12629 
12630 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
12631   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
12632 }
12633 
12634 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
12635                                     Expr *arg, QualType &paramType) {
12636   // If the syntactic form of the argument is not an explicit cast of
12637   // any sort, just do default argument promotion.
12638   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
12639   if (!castArg) {
12640     ExprResult result = DefaultArgumentPromotion(arg);
12641     if (result.isInvalid()) return ExprError();
12642     paramType = result.get()->getType();
12643     return result;
12644   }
12645 
12646   // Otherwise, use the type that was written in the explicit cast.
12647   assert(!arg->hasPlaceholderType());
12648   paramType = castArg->getTypeAsWritten();
12649 
12650   // Copy-initialize a parameter of that type.
12651   InitializedEntity entity =
12652     InitializedEntity::InitializeParameter(Context, paramType,
12653                                            /*consumed*/ false);
12654   return PerformCopyInitialization(entity, callLoc, Owned(arg));
12655 }
12656 
12657 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
12658   Expr *orig = E;
12659   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
12660   while (true) {
12661     E = E->IgnoreParenImpCasts();
12662     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
12663       E = call->getCallee();
12664       diagID = diag::err_uncasted_call_of_unknown_any;
12665     } else {
12666       break;
12667     }
12668   }
12669 
12670   SourceLocation loc;
12671   NamedDecl *d;
12672   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
12673     loc = ref->getLocation();
12674     d = ref->getDecl();
12675   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
12676     loc = mem->getMemberLoc();
12677     d = mem->getMemberDecl();
12678   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
12679     diagID = diag::err_uncasted_call_of_unknown_any;
12680     loc = msg->getSelectorStartLoc();
12681     d = msg->getMethodDecl();
12682     if (!d) {
12683       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
12684         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
12685         << orig->getSourceRange();
12686       return ExprError();
12687     }
12688   } else {
12689     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12690       << E->getSourceRange();
12691     return ExprError();
12692   }
12693 
12694   S.Diag(loc, diagID) << d << orig->getSourceRange();
12695 
12696   // Never recoverable.
12697   return ExprError();
12698 }
12699 
12700 /// Check for operands with placeholder types and complain if found.
12701 /// Returns true if there was an error and no recovery was possible.
12702 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
12703   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
12704   if (!placeholderType) return Owned(E);
12705 
12706   switch (placeholderType->getKind()) {
12707 
12708   // Overloaded expressions.
12709   case BuiltinType::Overload: {
12710     // Try to resolve a single function template specialization.
12711     // This is obligatory.
12712     ExprResult result = Owned(E);
12713     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
12714       return result;
12715 
12716     // If that failed, try to recover with a call.
12717     } else {
12718       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
12719                            /*complain*/ true);
12720       return result;
12721     }
12722   }
12723 
12724   // Bound member functions.
12725   case BuiltinType::BoundMember: {
12726     ExprResult result = Owned(E);
12727     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
12728                          /*complain*/ true);
12729     return result;
12730   }
12731 
12732   // ARC unbridged casts.
12733   case BuiltinType::ARCUnbridgedCast: {
12734     Expr *realCast = stripARCUnbridgedCast(E);
12735     diagnoseARCUnbridgedCast(realCast);
12736     return Owned(realCast);
12737   }
12738 
12739   // Expressions of unknown type.
12740   case BuiltinType::UnknownAny:
12741     return diagnoseUnknownAnyExpr(*this, E);
12742 
12743   // Pseudo-objects.
12744   case BuiltinType::PseudoObject:
12745     return checkPseudoObjectRValue(E);
12746 
12747   case BuiltinType::BuiltinFn:
12748     Diag(E->getLocStart(), diag::err_builtin_fn_use);
12749     return ExprError();
12750 
12751   // Everything else should be impossible.
12752 #define BUILTIN_TYPE(Id, SingletonId) \
12753   case BuiltinType::Id:
12754 #define PLACEHOLDER_TYPE(Id, SingletonId)
12755 #include "clang/AST/BuiltinTypes.def"
12756     break;
12757   }
12758 
12759   llvm_unreachable("invalid placeholder type!");
12760 }
12761 
12762 bool Sema::CheckCaseExpression(Expr *E) {
12763   if (E->isTypeDependent())
12764     return true;
12765   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
12766     return E->getType()->isIntegralOrEnumerationType();
12767   return false;
12768 }
12769 
12770 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
12771 ExprResult
12772 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
12773   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
12774          "Unknown Objective-C Boolean value!");
12775   QualType BoolT = Context.ObjCBuiltinBoolTy;
12776   if (!Context.getBOOLDecl()) {
12777     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
12778                         Sema::LookupOrdinaryName);
12779     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
12780       NamedDecl *ND = Result.getFoundDecl();
12781       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
12782         Context.setBOOLDecl(TD);
12783     }
12784   }
12785   if (Context.getBOOLDecl())
12786     BoolT = Context.getBOOLType();
12787   return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
12788                                         BoolT, OpLoc));
12789 }
12790