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 or unavailable.
144 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
145   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
146 
147   if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
148     // If the method was explicitly defaulted, point at that declaration.
149     if (!Method->isImplicit())
150       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
151 
152     // Try to diagnose why this special member function was implicitly
153     // deleted. This might fail, if that reason no longer applies.
154     CXXSpecialMember CSM = getSpecialMember(Method);
155     if (CSM != CXXInvalid)
156       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
157 
158     return;
159   }
160 
161   Diag(Decl->getLocation(), diag::note_unavailable_here)
162     << 1 << Decl->isDeleted();
163 }
164 
165 /// \brief Determine whether a FunctionDecl was ever declared with an
166 /// explicit storage class.
167 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
168   for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
169                                      E = D->redecls_end();
170        I != E; ++I) {
171     if (I->getStorageClass() != SC_None)
172       return true;
173   }
174   return false;
175 }
176 
177 /// \brief Check whether we're in an extern inline function and referring to a
178 /// variable or function with internal linkage (C11 6.7.4p3).
179 ///
180 /// This is only a warning because we used to silently accept this code, but
181 /// in many cases it will not behave correctly. This is not enabled in C++ mode
182 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
183 /// and so while there may still be user mistakes, most of the time we can't
184 /// prove that there are errors.
185 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
186                                                       const NamedDecl *D,
187                                                       SourceLocation Loc) {
188   // This is disabled under C++; there are too many ways for this to fire in
189   // contexts where the warning is a false positive, or where it is technically
190   // correct but benign.
191   if (S.getLangOpts().CPlusPlus)
192     return;
193 
194   // Check if this is an inlined function or method.
195   FunctionDecl *Current = S.getCurFunctionDecl();
196   if (!Current)
197     return;
198   if (!Current->isInlined())
199     return;
200   if (!Current->isExternallyVisible())
201     return;
202 
203   // Check if the decl has internal linkage.
204   if (D->getFormalLinkage() != InternalLinkage)
205     return;
206 
207   // Downgrade from ExtWarn to Extension if
208   //  (1) the supposedly external inline function is in the main file,
209   //      and probably won't be included anywhere else.
210   //  (2) the thing we're referencing is a pure function.
211   //  (3) the thing we're referencing is another inline function.
212   // This last can give us false negatives, but it's better than warning on
213   // wrappers for simple C library functions.
214   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
215   bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
216   if (!DowngradeWarning && UsedFn)
217     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
218 
219   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
220                                : diag::warn_internal_in_extern_inline)
221     << /*IsVar=*/!UsedFn << D;
222 
223   S.MaybeSuggestAddingStaticToDecl(Current);
224 
225   S.Diag(D->getCanonicalDecl()->getLocation(),
226          diag::note_internal_decl_declared_here)
227     << D;
228 }
229 
230 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
231   const FunctionDecl *First = Cur->getFirstDeclaration();
232 
233   // Suggest "static" on the function, if possible.
234   if (!hasAnyExplicitStorageClass(First)) {
235     SourceLocation DeclBegin = First->getSourceRange().getBegin();
236     Diag(DeclBegin, diag::note_convert_inline_to_static)
237       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
238   }
239 }
240 
241 /// \brief Determine whether the use of this declaration is valid, and
242 /// emit any corresponding diagnostics.
243 ///
244 /// This routine diagnoses various problems with referencing
245 /// declarations that can occur when using a declaration. For example,
246 /// it might warn if a deprecated or unavailable declaration is being
247 /// used, or produce an error (and return true) if a C++0x deleted
248 /// function is being used.
249 ///
250 /// \returns true if there was an error (this declaration cannot be
251 /// referenced), false otherwise.
252 ///
253 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
254                              const ObjCInterfaceDecl *UnknownObjCClass) {
255   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
256     // If there were any diagnostics suppressed by template argument deduction,
257     // emit them now.
258     llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
259       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
260     if (Pos != SuppressedDiagnostics.end()) {
261       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
262       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
263         Diag(Suppressed[I].first, Suppressed[I].second);
264 
265       // Clear out the list of suppressed diagnostics, so that we don't emit
266       // them again for this specialization. However, we don't obsolete this
267       // entry from the table, because we want to avoid ever emitting these
268       // diagnostics again.
269       Suppressed.clear();
270     }
271   }
272 
273   // See if this is an auto-typed variable whose initializer we are parsing.
274   if (ParsingInitForAutoVars.count(D)) {
275     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
276       << D->getDeclName();
277     return true;
278   }
279 
280   // See if this is a deleted function.
281   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
282     if (FD->isDeleted()) {
283       Diag(Loc, diag::err_deleted_function_use);
284       NoteDeletedFunction(FD);
285       return true;
286     }
287 
288     // If the function has a deduced return type, and we can't deduce it,
289     // then we can't use it either.
290     if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() &&
291         DeduceReturnType(FD, Loc))
292       return true;
293   }
294   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
295 
296   DiagnoseUnusedOfDecl(*this, D, Loc);
297 
298   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
299 
300   return false;
301 }
302 
303 /// \brief Retrieve the message suffix that should be added to a
304 /// diagnostic complaining about the given function being deleted or
305 /// unavailable.
306 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
307   std::string Message;
308   if (FD->getAvailability(&Message))
309     return ": " + Message;
310 
311   return std::string();
312 }
313 
314 /// DiagnoseSentinelCalls - This routine checks whether a call or
315 /// message-send is to a declaration with the sentinel attribute, and
316 /// if so, it checks that the requirements of the sentinel are
317 /// satisfied.
318 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
319                                  ArrayRef<Expr *> Args) {
320   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
321   if (!attr)
322     return;
323 
324   // The number of formal parameters of the declaration.
325   unsigned numFormalParams;
326 
327   // The kind of declaration.  This is also an index into a %select in
328   // the diagnostic.
329   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
330 
331   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
332     numFormalParams = MD->param_size();
333     calleeType = CT_Method;
334   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
335     numFormalParams = FD->param_size();
336     calleeType = CT_Function;
337   } else if (isa<VarDecl>(D)) {
338     QualType type = cast<ValueDecl>(D)->getType();
339     const FunctionType *fn = 0;
340     if (const PointerType *ptr = type->getAs<PointerType>()) {
341       fn = ptr->getPointeeType()->getAs<FunctionType>();
342       if (!fn) return;
343       calleeType = CT_Function;
344     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
345       fn = ptr->getPointeeType()->castAs<FunctionType>();
346       calleeType = CT_Block;
347     } else {
348       return;
349     }
350 
351     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
352       numFormalParams = proto->getNumArgs();
353     } else {
354       numFormalParams = 0;
355     }
356   } else {
357     return;
358   }
359 
360   // "nullPos" is the number of formal parameters at the end which
361   // effectively count as part of the variadic arguments.  This is
362   // useful if you would prefer to not have *any* formal parameters,
363   // but the language forces you to have at least one.
364   unsigned nullPos = attr->getNullPos();
365   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
366   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
367 
368   // The number of arguments which should follow the sentinel.
369   unsigned numArgsAfterSentinel = attr->getSentinel();
370 
371   // If there aren't enough arguments for all the formal parameters,
372   // the sentinel, and the args after the sentinel, complain.
373   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
374     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
375     Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
376     return;
377   }
378 
379   // Otherwise, find the sentinel expression.
380   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
381   if (!sentinelExpr) return;
382   if (sentinelExpr->isValueDependent()) return;
383   if (Context.isSentinelNullExpr(sentinelExpr)) return;
384 
385   // Pick a reasonable string to insert.  Optimistically use 'nil' or
386   // 'NULL' if those are actually defined in the context.  Only use
387   // 'nil' for ObjC methods, where it's much more likely that the
388   // variadic arguments form a list of object pointers.
389   SourceLocation MissingNilLoc
390     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
391   std::string NullValue;
392   if (calleeType == CT_Method &&
393       PP.getIdentifierInfo("nil")->hasMacroDefinition())
394     NullValue = "nil";
395   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
396     NullValue = "NULL";
397   else
398     NullValue = "(void*) 0";
399 
400   if (MissingNilLoc.isInvalid())
401     Diag(Loc, diag::warn_missing_sentinel) << calleeType;
402   else
403     Diag(MissingNilLoc, diag::warn_missing_sentinel)
404       << calleeType
405       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
406   Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
407 }
408 
409 SourceRange Sema::getExprRange(Expr *E) const {
410   return E ? E->getSourceRange() : SourceRange();
411 }
412 
413 //===----------------------------------------------------------------------===//
414 //  Standard Promotions and Conversions
415 //===----------------------------------------------------------------------===//
416 
417 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
418 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
419   // Handle any placeholder expressions which made it here.
420   if (E->getType()->isPlaceholderType()) {
421     ExprResult result = CheckPlaceholderExpr(E);
422     if (result.isInvalid()) return ExprError();
423     E = result.take();
424   }
425 
426   QualType Ty = E->getType();
427   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
428 
429   if (Ty->isFunctionType())
430     E = ImpCastExprToType(E, Context.getPointerType(Ty),
431                           CK_FunctionToPointerDecay).take();
432   else if (Ty->isArrayType()) {
433     // In C90 mode, arrays only promote to pointers if the array expression is
434     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
435     // type 'array of type' is converted to an expression that has type 'pointer
436     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
437     // that has type 'array of type' ...".  The relevant change is "an lvalue"
438     // (C90) to "an expression" (C99).
439     //
440     // C++ 4.2p1:
441     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
442     // T" can be converted to an rvalue of type "pointer to T".
443     //
444     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
445       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
446                             CK_ArrayToPointerDecay).take();
447   }
448   return Owned(E);
449 }
450 
451 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
452   // Check to see if we are dereferencing a null pointer.  If so,
453   // and if not volatile-qualified, this is undefined behavior that the
454   // optimizer will delete, so warn about it.  People sometimes try to use this
455   // to get a deterministic trap and are surprised by clang's behavior.  This
456   // only handles the pattern "*null", which is a very syntactic check.
457   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
458     if (UO->getOpcode() == UO_Deref &&
459         UO->getSubExpr()->IgnoreParenCasts()->
460           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
461         !UO->getType().isVolatileQualified()) {
462     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
463                           S.PDiag(diag::warn_indirection_through_null)
464                             << UO->getSubExpr()->getSourceRange());
465     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
466                         S.PDiag(diag::note_indirection_through_null));
467   }
468 }
469 
470 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
471                                     SourceLocation AssignLoc,
472                                     const Expr* RHS) {
473   const ObjCIvarDecl *IV = OIRE->getDecl();
474   if (!IV)
475     return;
476 
477   DeclarationName MemberName = IV->getDeclName();
478   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
479   if (!Member || !Member->isStr("isa"))
480     return;
481 
482   const Expr *Base = OIRE->getBase();
483   QualType BaseType = Base->getType();
484   if (OIRE->isArrow())
485     BaseType = BaseType->getPointeeType();
486   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
487     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
488       ObjCInterfaceDecl *ClassDeclared = 0;
489       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
490       if (!ClassDeclared->getSuperClass()
491           && (*ClassDeclared->ivar_begin()) == IV) {
492         if (RHS) {
493           NamedDecl *ObjectSetClass =
494             S.LookupSingleName(S.TUScope,
495                                &S.Context.Idents.get("object_setClass"),
496                                SourceLocation(), S.LookupOrdinaryName);
497           if (ObjectSetClass) {
498             SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
499             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
500             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
501             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
502                                                      AssignLoc), ",") <<
503             FixItHint::CreateInsertion(RHSLocEnd, ")");
504           }
505           else
506             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
507         } else {
508           NamedDecl *ObjectGetClass =
509             S.LookupSingleName(S.TUScope,
510                                &S.Context.Idents.get("object_getClass"),
511                                SourceLocation(), S.LookupOrdinaryName);
512           if (ObjectGetClass)
513             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
514             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
515             FixItHint::CreateReplacement(
516                                          SourceRange(OIRE->getOpLoc(),
517                                                      OIRE->getLocEnd()), ")");
518           else
519             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
520         }
521         S.Diag(IV->getLocation(), diag::note_ivar_decl);
522       }
523     }
524 }
525 
526 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
527   // Handle any placeholder expressions which made it here.
528   if (E->getType()->isPlaceholderType()) {
529     ExprResult result = CheckPlaceholderExpr(E);
530     if (result.isInvalid()) return ExprError();
531     E = result.take();
532   }
533 
534   // C++ [conv.lval]p1:
535   //   A glvalue of a non-function, non-array type T can be
536   //   converted to a prvalue.
537   if (!E->isGLValue()) return Owned(E);
538 
539   QualType T = E->getType();
540   assert(!T.isNull() && "r-value conversion on typeless expression?");
541 
542   // We don't want to throw lvalue-to-rvalue casts on top of
543   // expressions of certain types in C++.
544   if (getLangOpts().CPlusPlus &&
545       (E->getType() == Context.OverloadTy ||
546        T->isDependentType() ||
547        T->isRecordType()))
548     return Owned(E);
549 
550   // The C standard is actually really unclear on this point, and
551   // DR106 tells us what the result should be but not why.  It's
552   // generally best to say that void types just doesn't undergo
553   // lvalue-to-rvalue at all.  Note that expressions of unqualified
554   // 'void' type are never l-values, but qualified void can be.
555   if (T->isVoidType())
556     return Owned(E);
557 
558   // OpenCL usually rejects direct accesses to values of 'half' type.
559   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
560       T->isHalfType()) {
561     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
562       << 0 << T;
563     return ExprError();
564   }
565 
566   CheckForNullPointerDereference(*this, E);
567   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
568     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
569                                      &Context.Idents.get("object_getClass"),
570                                      SourceLocation(), LookupOrdinaryName);
571     if (ObjectGetClass)
572       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
573         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
574         FixItHint::CreateReplacement(
575                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
576     else
577       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
578   }
579   else if (const ObjCIvarRefExpr *OIRE =
580             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
581     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0);
582 
583   // C++ [conv.lval]p1:
584   //   [...] If T is a non-class type, the type of the prvalue is the
585   //   cv-unqualified version of T. Otherwise, the type of the
586   //   rvalue is T.
587   //
588   // C99 6.3.2.1p2:
589   //   If the lvalue has qualified type, the value has the unqualified
590   //   version of the type of the lvalue; otherwise, the value has the
591   //   type of the lvalue.
592   if (T.hasQualifiers())
593     T = T.getUnqualifiedType();
594 
595   UpdateMarkingForLValueToRValue(E);
596 
597   // Loading a __weak object implicitly retains the value, so we need a cleanup to
598   // balance that.
599   if (getLangOpts().ObjCAutoRefCount &&
600       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
601     ExprNeedsCleanups = true;
602 
603   ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
604                                                   E, 0, VK_RValue));
605 
606   // C11 6.3.2.1p2:
607   //   ... if the lvalue has atomic type, the value has the non-atomic version
608   //   of the type of the lvalue ...
609   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
610     T = Atomic->getValueType().getUnqualifiedType();
611     Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
612                                          Res.get(), 0, VK_RValue));
613   }
614 
615   return Res;
616 }
617 
618 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
619   ExprResult Res = DefaultFunctionArrayConversion(E);
620   if (Res.isInvalid())
621     return ExprError();
622   Res = DefaultLvalueConversion(Res.take());
623   if (Res.isInvalid())
624     return ExprError();
625   return Res;
626 }
627 
628 
629 /// UsualUnaryConversions - Performs various conversions that are common to most
630 /// operators (C99 6.3). The conversions of array and function types are
631 /// sometimes suppressed. For example, the array->pointer conversion doesn't
632 /// apply if the array is an argument to the sizeof or address (&) operators.
633 /// In these instances, this routine should *not* be called.
634 ExprResult Sema::UsualUnaryConversions(Expr *E) {
635   // First, convert to an r-value.
636   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
637   if (Res.isInvalid())
638     return ExprError();
639   E = Res.take();
640 
641   QualType Ty = E->getType();
642   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
643 
644   // Half FP have to be promoted to float unless it is natively supported
645   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
646     return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
647 
648   // Try to perform integral promotions if the object has a theoretically
649   // promotable type.
650   if (Ty->isIntegralOrUnscopedEnumerationType()) {
651     // C99 6.3.1.1p2:
652     //
653     //   The following may be used in an expression wherever an int or
654     //   unsigned int may be used:
655     //     - an object or expression with an integer type whose integer
656     //       conversion rank is less than or equal to the rank of int
657     //       and unsigned int.
658     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
659     //
660     //   If an int can represent all values of the original type, the
661     //   value is converted to an int; otherwise, it is converted to an
662     //   unsigned int. These are called the integer promotions. All
663     //   other types are unchanged by the integer promotions.
664 
665     QualType PTy = Context.isPromotableBitField(E);
666     if (!PTy.isNull()) {
667       E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
668       return Owned(E);
669     }
670     if (Ty->isPromotableIntegerType()) {
671       QualType PT = Context.getPromotedIntegerType(Ty);
672       E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
673       return Owned(E);
674     }
675   }
676   return Owned(E);
677 }
678 
679 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
680 /// do not have a prototype. Arguments that have type float or __fp16
681 /// are promoted to double. All other argument types are converted by
682 /// UsualUnaryConversions().
683 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
684   QualType Ty = E->getType();
685   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
686 
687   ExprResult Res = UsualUnaryConversions(E);
688   if (Res.isInvalid())
689     return ExprError();
690   E = Res.take();
691 
692   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
693   // double.
694   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
695   if (BTy && (BTy->getKind() == BuiltinType::Half ||
696               BTy->getKind() == BuiltinType::Float))
697     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
698 
699   // C++ performs lvalue-to-rvalue conversion as a default argument
700   // promotion, even on class types, but note:
701   //   C++11 [conv.lval]p2:
702   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
703   //     operand or a subexpression thereof the value contained in the
704   //     referenced object is not accessed. Otherwise, if the glvalue
705   //     has a class type, the conversion copy-initializes a temporary
706   //     of type T from the glvalue and the result of the conversion
707   //     is a prvalue for the temporary.
708   // FIXME: add some way to gate this entire thing for correctness in
709   // potentially potentially evaluated contexts.
710   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
711     ExprResult Temp = PerformCopyInitialization(
712                        InitializedEntity::InitializeTemporary(E->getType()),
713                                                 E->getExprLoc(),
714                                                 Owned(E));
715     if (Temp.isInvalid())
716       return ExprError();
717     E = Temp.get();
718   }
719 
720   return Owned(E);
721 }
722 
723 /// Determine the degree of POD-ness for an expression.
724 /// Incomplete types are considered POD, since this check can be performed
725 /// when we're in an unevaluated context.
726 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
727   if (Ty->isIncompleteType()) {
728     if (Ty->isObjCObjectType())
729       return VAK_Invalid;
730     return VAK_Valid;
731   }
732 
733   if (Ty.isCXX98PODType(Context))
734     return VAK_Valid;
735 
736   // C++11 [expr.call]p7:
737   //   Passing a potentially-evaluated argument of class type (Clause 9)
738   //   having a non-trivial copy constructor, a non-trivial move constructor,
739   //   or a non-trivial destructor, with no corresponding parameter,
740   //   is conditionally-supported with implementation-defined semantics.
741   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
742     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
743       if (!Record->hasNonTrivialCopyConstructor() &&
744           !Record->hasNonTrivialMoveConstructor() &&
745           !Record->hasNonTrivialDestructor())
746         return VAK_ValidInCXX11;
747 
748   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
749     return VAK_Valid;
750   return VAK_Invalid;
751 }
752 
753 bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
754   // Don't allow one to pass an Objective-C interface to a vararg.
755   const QualType & Ty = E->getType();
756 
757   // Complain about passing non-POD types through varargs.
758   switch (isValidVarArgType(Ty)) {
759   case VAK_Valid:
760     break;
761   case VAK_ValidInCXX11:
762     DiagRuntimeBehavior(E->getLocStart(), 0,
763         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
764         << E->getType() << CT);
765     break;
766   case VAK_Invalid: {
767     if (Ty->isObjCObjectType())
768       return DiagRuntimeBehavior(E->getLocStart(), 0,
769                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
770                             << Ty << CT);
771 
772     return DiagRuntimeBehavior(E->getLocStart(), 0,
773                    PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
774                    << getLangOpts().CPlusPlus11 << Ty << CT);
775   }
776   }
777   // c++ rules are enforced elsewhere.
778   return false;
779 }
780 
781 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
782 /// will create a trap if the resulting type is not a POD type.
783 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
784                                                   FunctionDecl *FDecl) {
785   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
786     // Strip the unbridged-cast placeholder expression off, if applicable.
787     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
788         (CT == VariadicMethod ||
789          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
790       E = stripARCUnbridgedCast(E);
791 
792     // Otherwise, do normal placeholder checking.
793     } else {
794       ExprResult ExprRes = CheckPlaceholderExpr(E);
795       if (ExprRes.isInvalid())
796         return ExprError();
797       E = ExprRes.take();
798     }
799   }
800 
801   ExprResult ExprRes = DefaultArgumentPromotion(E);
802   if (ExprRes.isInvalid())
803     return ExprError();
804   E = ExprRes.take();
805 
806   // Diagnostics regarding non-POD argument types are
807   // emitted along with format string checking in Sema::CheckFunctionCall().
808   if (isValidVarArgType(E->getType()) == VAK_Invalid) {
809     // Turn this into a trap.
810     CXXScopeSpec SS;
811     SourceLocation TemplateKWLoc;
812     UnqualifiedId Name;
813     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
814                        E->getLocStart());
815     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
816                                           Name, true, false);
817     if (TrapFn.isInvalid())
818       return ExprError();
819 
820     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
821                                     E->getLocStart(), None,
822                                     E->getLocEnd());
823     if (Call.isInvalid())
824       return ExprError();
825 
826     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
827                                   Call.get(), E);
828     if (Comma.isInvalid())
829       return ExprError();
830     return Comma.get();
831   }
832 
833   if (!getLangOpts().CPlusPlus &&
834       RequireCompleteType(E->getExprLoc(), E->getType(),
835                           diag::err_call_incomplete_argument))
836     return ExprError();
837 
838   return Owned(E);
839 }
840 
841 /// \brief Converts an integer to complex float type.  Helper function of
842 /// UsualArithmeticConversions()
843 ///
844 /// \return false if the integer expression is an integer type and is
845 /// successfully converted to the complex type.
846 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
847                                                   ExprResult &ComplexExpr,
848                                                   QualType IntTy,
849                                                   QualType ComplexTy,
850                                                   bool SkipCast) {
851   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
852   if (SkipCast) return false;
853   if (IntTy->isIntegerType()) {
854     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
855     IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
856     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
857                                   CK_FloatingRealToComplex);
858   } else {
859     assert(IntTy->isComplexIntegerType());
860     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
861                                   CK_IntegralComplexToFloatingComplex);
862   }
863   return false;
864 }
865 
866 /// \brief Takes two complex float types and converts them to the same type.
867 /// Helper function of UsualArithmeticConversions()
868 static QualType
869 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
870                                             ExprResult &RHS, QualType LHSType,
871                                             QualType RHSType,
872                                             bool IsCompAssign) {
873   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
874 
875   if (order < 0) {
876     // _Complex float -> _Complex double
877     if (!IsCompAssign)
878       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
879     return RHSType;
880   }
881   if (order > 0)
882     // _Complex float -> _Complex double
883     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
884   return LHSType;
885 }
886 
887 /// \brief Converts otherExpr to complex float and promotes complexExpr if
888 /// necessary.  Helper function of UsualArithmeticConversions()
889 static QualType handleOtherComplexFloatConversion(Sema &S,
890                                                   ExprResult &ComplexExpr,
891                                                   ExprResult &OtherExpr,
892                                                   QualType ComplexTy,
893                                                   QualType OtherTy,
894                                                   bool ConvertComplexExpr,
895                                                   bool ConvertOtherExpr) {
896   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
897 
898   // If just the complexExpr is complex, the otherExpr needs to be converted,
899   // and the complexExpr might need to be promoted.
900   if (order > 0) { // complexExpr is wider
901     // float -> _Complex double
902     if (ConvertOtherExpr) {
903       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
904       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
905       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
906                                       CK_FloatingRealToComplex);
907     }
908     return ComplexTy;
909   }
910 
911   // otherTy is at least as wide.  Find its corresponding complex type.
912   QualType result = (order == 0 ? ComplexTy :
913                                   S.Context.getComplexType(OtherTy));
914 
915   // double -> _Complex double
916   if (ConvertOtherExpr)
917     OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
918                                     CK_FloatingRealToComplex);
919 
920   // _Complex float -> _Complex double
921   if (ConvertComplexExpr && order < 0)
922     ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
923                                       CK_FloatingComplexCast);
924 
925   return result;
926 }
927 
928 /// \brief Handle arithmetic conversion with complex types.  Helper function of
929 /// UsualArithmeticConversions()
930 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
931                                              ExprResult &RHS, QualType LHSType,
932                                              QualType RHSType,
933                                              bool IsCompAssign) {
934   // if we have an integer operand, the result is the complex type.
935   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
936                                              /*skipCast*/false))
937     return LHSType;
938   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
939                                              /*skipCast*/IsCompAssign))
940     return RHSType;
941 
942   // This handles complex/complex, complex/float, or float/complex.
943   // When both operands are complex, the shorter operand is converted to the
944   // type of the longer, and that is the type of the result. This corresponds
945   // to what is done when combining two real floating-point operands.
946   // The fun begins when size promotion occur across type domains.
947   // From H&S 6.3.4: When one operand is complex and the other is a real
948   // floating-point type, the less precise type is converted, within it's
949   // real or complex domain, to the precision of the other type. For example,
950   // when combining a "long double" with a "double _Complex", the
951   // "double _Complex" is promoted to "long double _Complex".
952 
953   bool LHSComplexFloat = LHSType->isComplexType();
954   bool RHSComplexFloat = RHSType->isComplexType();
955 
956   // If both are complex, just cast to the more precise type.
957   if (LHSComplexFloat && RHSComplexFloat)
958     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
959                                                        LHSType, RHSType,
960                                                        IsCompAssign);
961 
962   // If only one operand is complex, promote it if necessary and convert the
963   // other operand to complex.
964   if (LHSComplexFloat)
965     return handleOtherComplexFloatConversion(
966         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
967         /*convertOtherExpr*/ true);
968 
969   assert(RHSComplexFloat);
970   return handleOtherComplexFloatConversion(
971       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
972       /*convertOtherExpr*/ !IsCompAssign);
973 }
974 
975 /// \brief Hande arithmetic conversion from integer to float.  Helper function
976 /// of UsualArithmeticConversions()
977 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
978                                            ExprResult &IntExpr,
979                                            QualType FloatTy, QualType IntTy,
980                                            bool ConvertFloat, bool ConvertInt) {
981   if (IntTy->isIntegerType()) {
982     if (ConvertInt)
983       // Convert intExpr to the lhs floating point type.
984       IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
985                                     CK_IntegralToFloating);
986     return FloatTy;
987   }
988 
989   // Convert both sides to the appropriate complex float.
990   assert(IntTy->isComplexIntegerType());
991   QualType result = S.Context.getComplexType(FloatTy);
992 
993   // _Complex int -> _Complex float
994   if (ConvertInt)
995     IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
996                                   CK_IntegralComplexToFloatingComplex);
997 
998   // float -> _Complex float
999   if (ConvertFloat)
1000     FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
1001                                     CK_FloatingRealToComplex);
1002 
1003   return result;
1004 }
1005 
1006 /// \brief Handle arithmethic conversion with floating point types.  Helper
1007 /// function of UsualArithmeticConversions()
1008 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1009                                       ExprResult &RHS, QualType LHSType,
1010                                       QualType RHSType, bool IsCompAssign) {
1011   bool LHSFloat = LHSType->isRealFloatingType();
1012   bool RHSFloat = RHSType->isRealFloatingType();
1013 
1014   // If we have two real floating types, convert the smaller operand
1015   // to the bigger result.
1016   if (LHSFloat && RHSFloat) {
1017     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1018     if (order > 0) {
1019       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
1020       return LHSType;
1021     }
1022 
1023     assert(order < 0 && "illegal float comparison");
1024     if (!IsCompAssign)
1025       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
1026     return RHSType;
1027   }
1028 
1029   if (LHSFloat)
1030     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1031                                       /*convertFloat=*/!IsCompAssign,
1032                                       /*convertInt=*/ true);
1033   assert(RHSFloat);
1034   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1035                                     /*convertInt=*/ true,
1036                                     /*convertFloat=*/!IsCompAssign);
1037 }
1038 
1039 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1040 
1041 namespace {
1042 /// These helper callbacks are placed in an anonymous namespace to
1043 /// permit their use as function template parameters.
1044 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1045   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1046 }
1047 
1048 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1049   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1050                              CK_IntegralComplexCast);
1051 }
1052 }
1053 
1054 /// \brief Handle integer arithmetic conversions.  Helper function of
1055 /// UsualArithmeticConversions()
1056 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1057 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1058                                         ExprResult &RHS, QualType LHSType,
1059                                         QualType RHSType, bool IsCompAssign) {
1060   // The rules for this case are in C99 6.3.1.8
1061   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1062   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1063   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1064   if (LHSSigned == RHSSigned) {
1065     // Same signedness; use the higher-ranked type
1066     if (order >= 0) {
1067       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1068       return LHSType;
1069     } else if (!IsCompAssign)
1070       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1071     return RHSType;
1072   } else if (order != (LHSSigned ? 1 : -1)) {
1073     // The unsigned type has greater than or equal rank to the
1074     // signed type, so use the unsigned type
1075     if (RHSSigned) {
1076       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1077       return LHSType;
1078     } else if (!IsCompAssign)
1079       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1080     return RHSType;
1081   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1082     // The two types are different widths; if we are here, that
1083     // means the signed type is larger than the unsigned type, so
1084     // use the signed type.
1085     if (LHSSigned) {
1086       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1087       return LHSType;
1088     } else if (!IsCompAssign)
1089       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1090     return RHSType;
1091   } else {
1092     // The signed type is higher-ranked than the unsigned type,
1093     // but isn't actually any bigger (like unsigned int and long
1094     // on most 32-bit systems).  Use the unsigned type corresponding
1095     // to the signed type.
1096     QualType result =
1097       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1098     RHS = (*doRHSCast)(S, RHS.take(), result);
1099     if (!IsCompAssign)
1100       LHS = (*doLHSCast)(S, LHS.take(), result);
1101     return result;
1102   }
1103 }
1104 
1105 /// \brief Handle conversions with GCC complex int extension.  Helper function
1106 /// of UsualArithmeticConversions()
1107 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1108                                            ExprResult &RHS, QualType LHSType,
1109                                            QualType RHSType,
1110                                            bool IsCompAssign) {
1111   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1112   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1113 
1114   if (LHSComplexInt && RHSComplexInt) {
1115     QualType LHSEltType = LHSComplexInt->getElementType();
1116     QualType RHSEltType = RHSComplexInt->getElementType();
1117     QualType ScalarType =
1118       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1119         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1120 
1121     return S.Context.getComplexType(ScalarType);
1122   }
1123 
1124   if (LHSComplexInt) {
1125     QualType LHSEltType = LHSComplexInt->getElementType();
1126     QualType ScalarType =
1127       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1128         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1129     QualType ComplexType = S.Context.getComplexType(ScalarType);
1130     RHS = S.ImpCastExprToType(RHS.take(), ComplexType,
1131                               CK_IntegralRealToComplex);
1132 
1133     return ComplexType;
1134   }
1135 
1136   assert(RHSComplexInt);
1137 
1138   QualType RHSEltType = RHSComplexInt->getElementType();
1139   QualType ScalarType =
1140     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1141       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1142   QualType ComplexType = S.Context.getComplexType(ScalarType);
1143 
1144   if (!IsCompAssign)
1145     LHS = S.ImpCastExprToType(LHS.take(), ComplexType,
1146                               CK_IntegralRealToComplex);
1147   return ComplexType;
1148 }
1149 
1150 /// UsualArithmeticConversions - Performs various conversions that are common to
1151 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1152 /// routine returns the first non-arithmetic type found. The client is
1153 /// responsible for emitting appropriate error diagnostics.
1154 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1155                                           bool IsCompAssign) {
1156   if (!IsCompAssign) {
1157     LHS = UsualUnaryConversions(LHS.take());
1158     if (LHS.isInvalid())
1159       return QualType();
1160   }
1161 
1162   RHS = UsualUnaryConversions(RHS.take());
1163   if (RHS.isInvalid())
1164     return QualType();
1165 
1166   // For conversion purposes, we ignore any qualifiers.
1167   // For example, "const float" and "float" are equivalent.
1168   QualType LHSType =
1169     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1170   QualType RHSType =
1171     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1172 
1173   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1174   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1175     LHSType = AtomicLHS->getValueType();
1176 
1177   // If both types are identical, no conversion is needed.
1178   if (LHSType == RHSType)
1179     return LHSType;
1180 
1181   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1182   // The caller can deal with this (e.g. pointer + int).
1183   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1184     return QualType();
1185 
1186   // Apply unary and bitfield promotions to the LHS's type.
1187   QualType LHSUnpromotedType = LHSType;
1188   if (LHSType->isPromotableIntegerType())
1189     LHSType = Context.getPromotedIntegerType(LHSType);
1190   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1191   if (!LHSBitfieldPromoteTy.isNull())
1192     LHSType = LHSBitfieldPromoteTy;
1193   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1194     LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
1195 
1196   // If both types are identical, no conversion is needed.
1197   if (LHSType == RHSType)
1198     return LHSType;
1199 
1200   // At this point, we have two different arithmetic types.
1201 
1202   // Handle complex types first (C99 6.3.1.8p1).
1203   if (LHSType->isComplexType() || RHSType->isComplexType())
1204     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1205                                         IsCompAssign);
1206 
1207   // Now handle "real" floating types (i.e. float, double, long double).
1208   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1209     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1210                                  IsCompAssign);
1211 
1212   // Handle GCC complex int extension.
1213   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1214     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1215                                       IsCompAssign);
1216 
1217   // Finally, we have two differing integer types.
1218   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1219            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1220 }
1221 
1222 
1223 //===----------------------------------------------------------------------===//
1224 //  Semantic Analysis for various Expression Types
1225 //===----------------------------------------------------------------------===//
1226 
1227 
1228 ExprResult
1229 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1230                                 SourceLocation DefaultLoc,
1231                                 SourceLocation RParenLoc,
1232                                 Expr *ControllingExpr,
1233                                 ArrayRef<ParsedType> ArgTypes,
1234                                 ArrayRef<Expr *> ArgExprs) {
1235   unsigned NumAssocs = ArgTypes.size();
1236   assert(NumAssocs == ArgExprs.size());
1237 
1238   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1239   for (unsigned i = 0; i < NumAssocs; ++i) {
1240     if (ArgTypes[i])
1241       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1242     else
1243       Types[i] = 0;
1244   }
1245 
1246   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1247                                              ControllingExpr,
1248                                              llvm::makeArrayRef(Types, NumAssocs),
1249                                              ArgExprs);
1250   delete [] Types;
1251   return ER;
1252 }
1253 
1254 ExprResult
1255 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1256                                  SourceLocation DefaultLoc,
1257                                  SourceLocation RParenLoc,
1258                                  Expr *ControllingExpr,
1259                                  ArrayRef<TypeSourceInfo *> Types,
1260                                  ArrayRef<Expr *> Exprs) {
1261   unsigned NumAssocs = Types.size();
1262   assert(NumAssocs == Exprs.size());
1263   if (ControllingExpr->getType()->isPlaceholderType()) {
1264     ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1265     if (result.isInvalid()) return ExprError();
1266     ControllingExpr = result.take();
1267   }
1268 
1269   bool TypeErrorFound = false,
1270        IsResultDependent = ControllingExpr->isTypeDependent(),
1271        ContainsUnexpandedParameterPack
1272          = ControllingExpr->containsUnexpandedParameterPack();
1273 
1274   for (unsigned i = 0; i < NumAssocs; ++i) {
1275     if (Exprs[i]->containsUnexpandedParameterPack())
1276       ContainsUnexpandedParameterPack = true;
1277 
1278     if (Types[i]) {
1279       if (Types[i]->getType()->containsUnexpandedParameterPack())
1280         ContainsUnexpandedParameterPack = true;
1281 
1282       if (Types[i]->getType()->isDependentType()) {
1283         IsResultDependent = true;
1284       } else {
1285         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1286         // complete object type other than a variably modified type."
1287         unsigned D = 0;
1288         if (Types[i]->getType()->isIncompleteType())
1289           D = diag::err_assoc_type_incomplete;
1290         else if (!Types[i]->getType()->isObjectType())
1291           D = diag::err_assoc_type_nonobject;
1292         else if (Types[i]->getType()->isVariablyModifiedType())
1293           D = diag::err_assoc_type_variably_modified;
1294 
1295         if (D != 0) {
1296           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1297             << Types[i]->getTypeLoc().getSourceRange()
1298             << Types[i]->getType();
1299           TypeErrorFound = true;
1300         }
1301 
1302         // C11 6.5.1.1p2 "No two generic associations in the same generic
1303         // selection shall specify compatible types."
1304         for (unsigned j = i+1; j < NumAssocs; ++j)
1305           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1306               Context.typesAreCompatible(Types[i]->getType(),
1307                                          Types[j]->getType())) {
1308             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1309                  diag::err_assoc_compatible_types)
1310               << Types[j]->getTypeLoc().getSourceRange()
1311               << Types[j]->getType()
1312               << Types[i]->getType();
1313             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1314                  diag::note_compat_assoc)
1315               << Types[i]->getTypeLoc().getSourceRange()
1316               << Types[i]->getType();
1317             TypeErrorFound = true;
1318           }
1319       }
1320     }
1321   }
1322   if (TypeErrorFound)
1323     return ExprError();
1324 
1325   // If we determined that the generic selection is result-dependent, don't
1326   // try to compute the result expression.
1327   if (IsResultDependent)
1328     return Owned(new (Context) GenericSelectionExpr(
1329                    Context, KeyLoc, ControllingExpr,
1330                    Types, Exprs,
1331                    DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
1332 
1333   SmallVector<unsigned, 1> CompatIndices;
1334   unsigned DefaultIndex = -1U;
1335   for (unsigned i = 0; i < NumAssocs; ++i) {
1336     if (!Types[i])
1337       DefaultIndex = i;
1338     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1339                                         Types[i]->getType()))
1340       CompatIndices.push_back(i);
1341   }
1342 
1343   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1344   // type compatible with at most one of the types named in its generic
1345   // association list."
1346   if (CompatIndices.size() > 1) {
1347     // We strip parens here because the controlling expression is typically
1348     // parenthesized in macro definitions.
1349     ControllingExpr = ControllingExpr->IgnoreParens();
1350     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1351       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1352       << (unsigned) CompatIndices.size();
1353     for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
1354          E = CompatIndices.end(); I != E; ++I) {
1355       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1356            diag::note_compat_assoc)
1357         << Types[*I]->getTypeLoc().getSourceRange()
1358         << Types[*I]->getType();
1359     }
1360     return ExprError();
1361   }
1362 
1363   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1364   // its controlling expression shall have type compatible with exactly one of
1365   // the types named in its generic association list."
1366   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1367     // We strip parens here because the controlling expression is typically
1368     // parenthesized in macro definitions.
1369     ControllingExpr = ControllingExpr->IgnoreParens();
1370     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1371       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1372     return ExprError();
1373   }
1374 
1375   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1376   // type name that is compatible with the type of the controlling expression,
1377   // then the result expression of the generic selection is the expression
1378   // in that generic association. Otherwise, the result expression of the
1379   // generic selection is the expression in the default generic association."
1380   unsigned ResultIndex =
1381     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1382 
1383   return Owned(new (Context) GenericSelectionExpr(
1384                  Context, KeyLoc, ControllingExpr,
1385                  Types, Exprs,
1386                  DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
1387                  ResultIndex));
1388 }
1389 
1390 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1391 /// location of the token and the offset of the ud-suffix within it.
1392 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1393                                      unsigned Offset) {
1394   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1395                                         S.getLangOpts());
1396 }
1397 
1398 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1399 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1400 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1401                                                  IdentifierInfo *UDSuffix,
1402                                                  SourceLocation UDSuffixLoc,
1403                                                  ArrayRef<Expr*> Args,
1404                                                  SourceLocation LitEndLoc) {
1405   assert(Args.size() <= 2 && "too many arguments for literal operator");
1406 
1407   QualType ArgTy[2];
1408   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1409     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1410     if (ArgTy[ArgIdx]->isArrayType())
1411       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1412   }
1413 
1414   DeclarationName OpName =
1415     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1416   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1417   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1418 
1419   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1420   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1421                               /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1422     return ExprError();
1423 
1424   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1425 }
1426 
1427 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1428 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1429 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1430 /// multiple tokens.  However, the common case is that StringToks points to one
1431 /// string.
1432 ///
1433 ExprResult
1434 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1435                          Scope *UDLScope) {
1436   assert(NumStringToks && "Must have at least one string!");
1437 
1438   StringLiteralParser Literal(StringToks, NumStringToks, PP);
1439   if (Literal.hadError)
1440     return ExprError();
1441 
1442   SmallVector<SourceLocation, 4> StringTokLocs;
1443   for (unsigned i = 0; i != NumStringToks; ++i)
1444     StringTokLocs.push_back(StringToks[i].getLocation());
1445 
1446   QualType StrTy = Context.CharTy;
1447   if (Literal.isWide())
1448     StrTy = Context.getWideCharType();
1449   else if (Literal.isUTF16())
1450     StrTy = Context.Char16Ty;
1451   else if (Literal.isUTF32())
1452     StrTy = Context.Char32Ty;
1453   else if (Literal.isPascal())
1454     StrTy = Context.UnsignedCharTy;
1455 
1456   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1457   if (Literal.isWide())
1458     Kind = StringLiteral::Wide;
1459   else if (Literal.isUTF8())
1460     Kind = StringLiteral::UTF8;
1461   else if (Literal.isUTF16())
1462     Kind = StringLiteral::UTF16;
1463   else if (Literal.isUTF32())
1464     Kind = StringLiteral::UTF32;
1465 
1466   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1467   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1468     StrTy.addConst();
1469 
1470   // Get an array type for the string, according to C99 6.4.5.  This includes
1471   // the nul terminator character as well as the string length for pascal
1472   // strings.
1473   StrTy = Context.getConstantArrayType(StrTy,
1474                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1475                                        ArrayType::Normal, 0);
1476 
1477   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1478   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1479                                              Kind, Literal.Pascal, StrTy,
1480                                              &StringTokLocs[0],
1481                                              StringTokLocs.size());
1482   if (Literal.getUDSuffix().empty())
1483     return Owned(Lit);
1484 
1485   // We're building a user-defined literal.
1486   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1487   SourceLocation UDSuffixLoc =
1488     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1489                    Literal.getUDSuffixOffset());
1490 
1491   // Make sure we're allowed user-defined literals here.
1492   if (!UDLScope)
1493     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1494 
1495   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1496   //   operator "" X (str, len)
1497   QualType SizeType = Context.getSizeType();
1498   llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1499   IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1500                                                   StringTokLocs[0]);
1501   Expr *Args[] = { Lit, LenArg };
1502   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1503                                         Args, StringTokLocs.back());
1504 }
1505 
1506 ExprResult
1507 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1508                        SourceLocation Loc,
1509                        const CXXScopeSpec *SS) {
1510   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1511   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1512 }
1513 
1514 /// BuildDeclRefExpr - Build an expression that references a
1515 /// declaration that does not require a closure capture.
1516 ExprResult
1517 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1518                        const DeclarationNameInfo &NameInfo,
1519                        const CXXScopeSpec *SS, NamedDecl *FoundD) {
1520   if (getLangOpts().CUDA)
1521     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1522       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1523         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1524                            CalleeTarget = IdentifyCUDATarget(Callee);
1525         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1526           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1527             << CalleeTarget << D->getIdentifier() << CallerTarget;
1528           Diag(D->getLocation(), diag::note_previous_decl)
1529             << D->getIdentifier();
1530           return ExprError();
1531         }
1532       }
1533 
1534   bool refersToEnclosingScope =
1535     (CurContext != D->getDeclContext() &&
1536      D->getDeclContext()->isFunctionOrMethod());
1537 
1538   DeclRefExpr *E = DeclRefExpr::Create(Context,
1539                                        SS ? SS->getWithLocInContext(Context)
1540                                               : NestedNameSpecifierLoc(),
1541                                        SourceLocation(),
1542                                        D, refersToEnclosingScope,
1543                                        NameInfo, Ty, VK, FoundD);
1544 
1545   MarkDeclRefReferenced(E);
1546 
1547   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1548       Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1549     DiagnosticsEngine::Level Level =
1550       Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1551                                E->getLocStart());
1552     if (Level != DiagnosticsEngine::Ignored)
1553       recordUseOfEvaluatedWeak(E);
1554   }
1555 
1556   // Just in case we're building an illegal pointer-to-member.
1557   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1558   if (FD && FD->isBitField())
1559     E->setObjectKind(OK_BitField);
1560 
1561   return Owned(E);
1562 }
1563 
1564 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1565 /// possibly a list of template arguments.
1566 ///
1567 /// If this produces template arguments, it is permitted to call
1568 /// DecomposeTemplateName.
1569 ///
1570 /// This actually loses a lot of source location information for
1571 /// non-standard name kinds; we should consider preserving that in
1572 /// some way.
1573 void
1574 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1575                              TemplateArgumentListInfo &Buffer,
1576                              DeclarationNameInfo &NameInfo,
1577                              const TemplateArgumentListInfo *&TemplateArgs) {
1578   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1579     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1580     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1581 
1582     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1583                                        Id.TemplateId->NumArgs);
1584     translateTemplateArguments(TemplateArgsPtr, Buffer);
1585 
1586     TemplateName TName = Id.TemplateId->Template.get();
1587     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1588     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1589     TemplateArgs = &Buffer;
1590   } else {
1591     NameInfo = GetNameFromUnqualifiedId(Id);
1592     TemplateArgs = 0;
1593   }
1594 }
1595 
1596 /// Diagnose an empty lookup.
1597 ///
1598 /// \return false if new lookup candidates were found
1599 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1600                                CorrectionCandidateCallback &CCC,
1601                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1602                                llvm::ArrayRef<Expr *> Args) {
1603   DeclarationName Name = R.getLookupName();
1604 
1605   unsigned diagnostic = diag::err_undeclared_var_use;
1606   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1607   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1608       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1609       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1610     diagnostic = diag::err_undeclared_use;
1611     diagnostic_suggest = diag::err_undeclared_use_suggest;
1612   }
1613 
1614   // If the original lookup was an unqualified lookup, fake an
1615   // unqualified lookup.  This is useful when (for example) the
1616   // original lookup would not have found something because it was a
1617   // dependent name.
1618   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1619     ? CurContext : 0;
1620   while (DC) {
1621     if (isa<CXXRecordDecl>(DC)) {
1622       LookupQualifiedName(R, DC);
1623 
1624       if (!R.empty()) {
1625         // Don't give errors about ambiguities in this lookup.
1626         R.suppressDiagnostics();
1627 
1628         // During a default argument instantiation the CurContext points
1629         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1630         // function parameter list, hence add an explicit check.
1631         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1632                               ActiveTemplateInstantiations.back().Kind ==
1633             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1634         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1635         bool isInstance = CurMethod &&
1636                           CurMethod->isInstance() &&
1637                           DC == CurMethod->getParent() && !isDefaultArgument;
1638 
1639 
1640         // Give a code modification hint to insert 'this->'.
1641         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1642         // Actually quite difficult!
1643         if (getLangOpts().MicrosoftMode)
1644           diagnostic = diag::warn_found_via_dependent_bases_lookup;
1645         if (isInstance) {
1646           Diag(R.getNameLoc(), diagnostic) << Name
1647             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1648           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1649               CallsUndergoingInstantiation.back()->getCallee());
1650 
1651           CXXMethodDecl *DepMethod;
1652           if (CurMethod->isDependentContext())
1653             DepMethod = CurMethod;
1654           else if (CurMethod->getTemplatedKind() ==
1655               FunctionDecl::TK_FunctionTemplateSpecialization)
1656             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1657                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1658           else
1659             DepMethod = cast<CXXMethodDecl>(
1660                 CurMethod->getInstantiatedFromMemberFunction());
1661           assert(DepMethod && "No template pattern found");
1662 
1663           QualType DepThisType = DepMethod->getThisType(Context);
1664           CheckCXXThisCapture(R.getNameLoc());
1665           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1666                                      R.getNameLoc(), DepThisType, false);
1667           TemplateArgumentListInfo TList;
1668           if (ULE->hasExplicitTemplateArgs())
1669             ULE->copyTemplateArgumentsInto(TList);
1670 
1671           CXXScopeSpec SS;
1672           SS.Adopt(ULE->getQualifierLoc());
1673           CXXDependentScopeMemberExpr *DepExpr =
1674               CXXDependentScopeMemberExpr::Create(
1675                   Context, DepThis, DepThisType, true, SourceLocation(),
1676                   SS.getWithLocInContext(Context),
1677                   ULE->getTemplateKeywordLoc(), 0,
1678                   R.getLookupNameInfo(),
1679                   ULE->hasExplicitTemplateArgs() ? &TList : 0);
1680           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1681         } else {
1682           Diag(R.getNameLoc(), diagnostic) << Name;
1683         }
1684 
1685         // Do we really want to note all of these?
1686         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1687           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1688 
1689         // Return true if we are inside a default argument instantiation
1690         // and the found name refers to an instance member function, otherwise
1691         // the function calling DiagnoseEmptyLookup will try to create an
1692         // implicit member call and this is wrong for default argument.
1693         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1694           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1695           return true;
1696         }
1697 
1698         // Tell the callee to try to recover.
1699         return false;
1700       }
1701 
1702       R.clear();
1703     }
1704 
1705     // In Microsoft mode, if we are performing lookup from within a friend
1706     // function definition declared at class scope then we must set
1707     // DC to the lexical parent to be able to search into the parent
1708     // class.
1709     if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
1710         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1711         DC->getLexicalParent()->isRecord())
1712       DC = DC->getLexicalParent();
1713     else
1714       DC = DC->getParent();
1715   }
1716 
1717   // We didn't find anything, so try to correct for a typo.
1718   TypoCorrection Corrected;
1719   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1720                                     S, &SS, CCC))) {
1721     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1722     std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
1723     R.setLookupName(Corrected.getCorrection());
1724 
1725     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
1726       if (Corrected.isOverloaded()) {
1727         OverloadCandidateSet OCS(R.getNameLoc());
1728         OverloadCandidateSet::iterator Best;
1729         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1730                                         CDEnd = Corrected.end();
1731              CD != CDEnd; ++CD) {
1732           if (FunctionTemplateDecl *FTD =
1733                    dyn_cast<FunctionTemplateDecl>(*CD))
1734             AddTemplateOverloadCandidate(
1735                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1736                 Args, OCS);
1737           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1738             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1739               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1740                                    Args, OCS);
1741         }
1742         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1743           case OR_Success:
1744             ND = Best->Function;
1745             break;
1746           default:
1747             break;
1748         }
1749       }
1750       R.addDecl(ND);
1751       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
1752         if (SS.isEmpty())
1753           Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1754             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1755         else
1756           Diag(R.getNameLoc(), diag::err_no_member_suggest)
1757             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1758             << SS.getRange()
1759             << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
1760                                             CorrectedStr);
1761 
1762         unsigned diag = isa<ImplicitParamDecl>(ND)
1763           ? diag::note_implicit_param_decl
1764           : diag::note_previous_decl;
1765 
1766         Diag(ND->getLocation(), diag)
1767           << CorrectedQuotedStr;
1768 
1769         // Tell the callee to try to recover.
1770         return false;
1771       }
1772 
1773       if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
1774         // FIXME: If we ended up with a typo for a type name or
1775         // Objective-C class name, we're in trouble because the parser
1776         // is in the wrong place to recover. Suggest the typo
1777         // correction, but don't make it a fix-it since we're not going
1778         // to recover well anyway.
1779         if (SS.isEmpty())
1780           Diag(R.getNameLoc(), diagnostic_suggest)
1781             << Name << CorrectedQuotedStr;
1782         else
1783           Diag(R.getNameLoc(), diag::err_no_member_suggest)
1784             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1785             << SS.getRange();
1786 
1787         // Don't try to recover; it won't work.
1788         return true;
1789       }
1790     } else {
1791       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1792       // because we aren't able to recover.
1793       if (SS.isEmpty())
1794         Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
1795       else
1796         Diag(R.getNameLoc(), diag::err_no_member_suggest)
1797         << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1798         << SS.getRange();
1799       return true;
1800     }
1801   }
1802   R.clear();
1803 
1804   // Emit a special diagnostic for failed member lookups.
1805   // FIXME: computing the declaration context might fail here (?)
1806   if (!SS.isEmpty()) {
1807     Diag(R.getNameLoc(), diag::err_no_member)
1808       << Name << computeDeclContext(SS, false)
1809       << SS.getRange();
1810     return true;
1811   }
1812 
1813   // Give up, we can't recover.
1814   Diag(R.getNameLoc(), diagnostic) << Name;
1815   return true;
1816 }
1817 
1818 ExprResult Sema::ActOnIdExpression(Scope *S,
1819                                    CXXScopeSpec &SS,
1820                                    SourceLocation TemplateKWLoc,
1821                                    UnqualifiedId &Id,
1822                                    bool HasTrailingLParen,
1823                                    bool IsAddressOfOperand,
1824                                    CorrectionCandidateCallback *CCC,
1825                                    bool IsInlineAsmIdentifier) {
1826   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1827          "cannot be direct & operand and have a trailing lparen");
1828 
1829   if (SS.isInvalid())
1830     return ExprError();
1831 
1832   TemplateArgumentListInfo TemplateArgsBuffer;
1833 
1834   // Decompose the UnqualifiedId into the following data.
1835   DeclarationNameInfo NameInfo;
1836   const TemplateArgumentListInfo *TemplateArgs;
1837   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1838 
1839   DeclarationName Name = NameInfo.getName();
1840   IdentifierInfo *II = Name.getAsIdentifierInfo();
1841   SourceLocation NameLoc = NameInfo.getLoc();
1842 
1843   // C++ [temp.dep.expr]p3:
1844   //   An id-expression is type-dependent if it contains:
1845   //     -- an identifier that was declared with a dependent type,
1846   //        (note: handled after lookup)
1847   //     -- a template-id that is dependent,
1848   //        (note: handled in BuildTemplateIdExpr)
1849   //     -- a conversion-function-id that specifies a dependent type,
1850   //     -- a nested-name-specifier that contains a class-name that
1851   //        names a dependent type.
1852   // Determine whether this is a member of an unknown specialization;
1853   // we need to handle these differently.
1854   bool DependentID = false;
1855   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1856       Name.getCXXNameType()->isDependentType()) {
1857     DependentID = true;
1858   } else if (SS.isSet()) {
1859     if (DeclContext *DC = computeDeclContext(SS, false)) {
1860       if (RequireCompleteDeclContext(SS, DC))
1861         return ExprError();
1862     } else {
1863       DependentID = true;
1864     }
1865   }
1866 
1867   if (DependentID)
1868     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1869                                       IsAddressOfOperand, TemplateArgs);
1870 
1871   // Perform the required lookup.
1872   LookupResult R(*this, NameInfo,
1873                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1874                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1875   if (TemplateArgs) {
1876     // Lookup the template name again to correctly establish the context in
1877     // which it was found. This is really unfortunate as we already did the
1878     // lookup to determine that it was a template name in the first place. If
1879     // this becomes a performance hit, we can work harder to preserve those
1880     // results until we get here but it's likely not worth it.
1881     bool MemberOfUnknownSpecialization;
1882     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1883                        MemberOfUnknownSpecialization);
1884 
1885     if (MemberOfUnknownSpecialization ||
1886         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1887       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1888                                         IsAddressOfOperand, TemplateArgs);
1889   } else {
1890     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
1891     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1892 
1893     // If the result might be in a dependent base class, this is a dependent
1894     // id-expression.
1895     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1896       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1897                                         IsAddressOfOperand, TemplateArgs);
1898 
1899     // If this reference is in an Objective-C method, then we need to do
1900     // some special Objective-C lookup, too.
1901     if (IvarLookupFollowUp) {
1902       ExprResult E(LookupInObjCMethod(R, S, II, true));
1903       if (E.isInvalid())
1904         return ExprError();
1905 
1906       if (Expr *Ex = E.takeAs<Expr>())
1907         return Owned(Ex);
1908     }
1909   }
1910 
1911   if (R.isAmbiguous())
1912     return ExprError();
1913 
1914   // Determine whether this name might be a candidate for
1915   // argument-dependent lookup.
1916   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1917 
1918   if (R.empty() && !ADL) {
1919     // Otherwise, this could be an implicitly declared function reference (legal
1920     // in C90, extension in C99, forbidden in C++).
1921     if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
1922       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1923       if (D) R.addDecl(D);
1924     }
1925 
1926     // If this name wasn't predeclared and if this is not a function
1927     // call, diagnose the problem.
1928     if (R.empty()) {
1929       // In Microsoft mode, if we are inside a template class member function
1930       // whose parent class has dependent base classes, and we can't resolve
1931       // an identifier, then assume the identifier is type dependent.  The
1932       // goal is to postpone name lookup to instantiation time to be able to
1933       // search into the type dependent base classes.
1934       if (getLangOpts().MicrosoftMode) {
1935         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
1936         if (MD && MD->getParent()->hasAnyDependentBases())
1937           return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1938                                             IsAddressOfOperand, TemplateArgs);
1939       }
1940 
1941       // Don't diagnose an empty lookup for inline assmebly.
1942       if (IsInlineAsmIdentifier)
1943         return ExprError();
1944 
1945       CorrectionCandidateCallback DefaultValidator;
1946       if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
1947         return ExprError();
1948 
1949       assert(!R.empty() &&
1950              "DiagnoseEmptyLookup returned false but added no results");
1951 
1952       // If we found an Objective-C instance variable, let
1953       // LookupInObjCMethod build the appropriate expression to
1954       // reference the ivar.
1955       if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1956         R.clear();
1957         ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1958         // In a hopelessly buggy code, Objective-C instance variable
1959         // lookup fails and no expression will be built to reference it.
1960         if (!E.isInvalid() && !E.get())
1961           return ExprError();
1962         return E;
1963       }
1964     }
1965   }
1966 
1967   // This is guaranteed from this point on.
1968   assert(!R.empty() || ADL);
1969 
1970   // Check whether this might be a C++ implicit instance member access.
1971   // C++ [class.mfct.non-static]p3:
1972   //   When an id-expression that is not part of a class member access
1973   //   syntax and not used to form a pointer to member is used in the
1974   //   body of a non-static member function of class X, if name lookup
1975   //   resolves the name in the id-expression to a non-static non-type
1976   //   member of some class C, the id-expression is transformed into a
1977   //   class member access expression using (*this) as the
1978   //   postfix-expression to the left of the . operator.
1979   //
1980   // But we don't actually need to do this for '&' operands if R
1981   // resolved to a function or overloaded function set, because the
1982   // expression is ill-formed if it actually works out to be a
1983   // non-static member function:
1984   //
1985   // C++ [expr.ref]p4:
1986   //   Otherwise, if E1.E2 refers to a non-static member function. . .
1987   //   [t]he expression can be used only as the left-hand operand of a
1988   //   member function call.
1989   //
1990   // There are other safeguards against such uses, but it's important
1991   // to get this right here so that we don't end up making a
1992   // spuriously dependent expression if we're inside a dependent
1993   // instance method.
1994   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1995     bool MightBeImplicitMember;
1996     if (!IsAddressOfOperand)
1997       MightBeImplicitMember = true;
1998     else if (!SS.isEmpty())
1999       MightBeImplicitMember = false;
2000     else if (R.isOverloadedResult())
2001       MightBeImplicitMember = false;
2002     else if (R.isUnresolvableResult())
2003       MightBeImplicitMember = true;
2004     else
2005       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2006                               isa<IndirectFieldDecl>(R.getFoundDecl());
2007 
2008     if (MightBeImplicitMember)
2009       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2010                                              R, TemplateArgs);
2011   }
2012 
2013   if (TemplateArgs || TemplateKWLoc.isValid())
2014     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2015 
2016   return BuildDeclarationNameExpr(SS, R, ADL);
2017 }
2018 
2019 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2020 /// declaration name, generally during template instantiation.
2021 /// There's a large number of things which don't need to be done along
2022 /// this path.
2023 ExprResult
2024 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2025                                         const DeclarationNameInfo &NameInfo,
2026                                         bool IsAddressOfOperand) {
2027   DeclContext *DC = computeDeclContext(SS, false);
2028   if (!DC)
2029     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2030                                      NameInfo, /*TemplateArgs=*/0);
2031 
2032   if (RequireCompleteDeclContext(SS, DC))
2033     return ExprError();
2034 
2035   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2036   LookupQualifiedName(R, DC);
2037 
2038   if (R.isAmbiguous())
2039     return ExprError();
2040 
2041   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2042     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2043                                      NameInfo, /*TemplateArgs=*/0);
2044 
2045   if (R.empty()) {
2046     Diag(NameInfo.getLoc(), diag::err_no_member)
2047       << NameInfo.getName() << DC << SS.getRange();
2048     return ExprError();
2049   }
2050 
2051   // Defend against this resolving to an implicit member access. We usually
2052   // won't get here if this might be a legitimate a class member (we end up in
2053   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2054   // a pointer-to-member or in an unevaluated context in C++11.
2055   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2056     return BuildPossibleImplicitMemberExpr(SS,
2057                                            /*TemplateKWLoc=*/SourceLocation(),
2058                                            R, /*TemplateArgs=*/0);
2059 
2060   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2061 }
2062 
2063 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2064 /// detected that we're currently inside an ObjC method.  Perform some
2065 /// additional lookup.
2066 ///
2067 /// Ideally, most of this would be done by lookup, but there's
2068 /// actually quite a lot of extra work involved.
2069 ///
2070 /// Returns a null sentinel to indicate trivial success.
2071 ExprResult
2072 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2073                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2074   SourceLocation Loc = Lookup.getNameLoc();
2075   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2076 
2077   // Check for error condition which is already reported.
2078   if (!CurMethod)
2079     return ExprError();
2080 
2081   // There are two cases to handle here.  1) scoped lookup could have failed,
2082   // in which case we should look for an ivar.  2) scoped lookup could have
2083   // found a decl, but that decl is outside the current instance method (i.e.
2084   // a global variable).  In these two cases, we do a lookup for an ivar with
2085   // this name, if the lookup sucedes, we replace it our current decl.
2086 
2087   // If we're in a class method, we don't normally want to look for
2088   // ivars.  But if we don't find anything else, and there's an
2089   // ivar, that's an error.
2090   bool IsClassMethod = CurMethod->isClassMethod();
2091 
2092   bool LookForIvars;
2093   if (Lookup.empty())
2094     LookForIvars = true;
2095   else if (IsClassMethod)
2096     LookForIvars = false;
2097   else
2098     LookForIvars = (Lookup.isSingleResult() &&
2099                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2100   ObjCInterfaceDecl *IFace = 0;
2101   if (LookForIvars) {
2102     IFace = CurMethod->getClassInterface();
2103     ObjCInterfaceDecl *ClassDeclared;
2104     ObjCIvarDecl *IV = 0;
2105     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2106       // Diagnose using an ivar in a class method.
2107       if (IsClassMethod)
2108         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2109                          << IV->getDeclName());
2110 
2111       // If we're referencing an invalid decl, just return this as a silent
2112       // error node.  The error diagnostic was already emitted on the decl.
2113       if (IV->isInvalidDecl())
2114         return ExprError();
2115 
2116       // Check if referencing a field with __attribute__((deprecated)).
2117       if (DiagnoseUseOfDecl(IV, Loc))
2118         return ExprError();
2119 
2120       // Diagnose the use of an ivar outside of the declaring class.
2121       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2122           !declaresSameEntity(ClassDeclared, IFace) &&
2123           !getLangOpts().DebuggerSupport)
2124         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2125 
2126       // FIXME: This should use a new expr for a direct reference, don't
2127       // turn this into Self->ivar, just return a BareIVarExpr or something.
2128       IdentifierInfo &II = Context.Idents.get("self");
2129       UnqualifiedId SelfName;
2130       SelfName.setIdentifier(&II, SourceLocation());
2131       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2132       CXXScopeSpec SelfScopeSpec;
2133       SourceLocation TemplateKWLoc;
2134       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2135                                               SelfName, false, false);
2136       if (SelfExpr.isInvalid())
2137         return ExprError();
2138 
2139       SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2140       if (SelfExpr.isInvalid())
2141         return ExprError();
2142 
2143       MarkAnyDeclReferenced(Loc, IV, true);
2144 
2145       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2146       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2147           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2148         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2149 
2150       ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2151                                                               Loc, IV->getLocation(),
2152                                                               SelfExpr.take(),
2153                                                               true, true);
2154 
2155       if (getLangOpts().ObjCAutoRefCount) {
2156         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2157           DiagnosticsEngine::Level Level =
2158             Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2159           if (Level != DiagnosticsEngine::Ignored)
2160             recordUseOfEvaluatedWeak(Result);
2161         }
2162         if (CurContext->isClosure())
2163           Diag(Loc, diag::warn_implicitly_retains_self)
2164             << FixItHint::CreateInsertion(Loc, "self->");
2165       }
2166 
2167       return Owned(Result);
2168     }
2169   } else if (CurMethod->isInstanceMethod()) {
2170     // We should warn if a local variable hides an ivar.
2171     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2172       ObjCInterfaceDecl *ClassDeclared;
2173       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2174         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2175             declaresSameEntity(IFace, ClassDeclared))
2176           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2177       }
2178     }
2179   } else if (Lookup.isSingleResult() &&
2180              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2181     // If accessing a stand-alone ivar in a class method, this is an error.
2182     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2183       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2184                        << IV->getDeclName());
2185   }
2186 
2187   if (Lookup.empty() && II && AllowBuiltinCreation) {
2188     // FIXME. Consolidate this with similar code in LookupName.
2189     if (unsigned BuiltinID = II->getBuiltinID()) {
2190       if (!(getLangOpts().CPlusPlus &&
2191             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2192         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2193                                            S, Lookup.isForRedeclaration(),
2194                                            Lookup.getNameLoc());
2195         if (D) Lookup.addDecl(D);
2196       }
2197     }
2198   }
2199   // Sentinel value saying that we didn't do anything special.
2200   return Owned((Expr*) 0);
2201 }
2202 
2203 /// \brief Cast a base object to a member's actual type.
2204 ///
2205 /// Logically this happens in three phases:
2206 ///
2207 /// * First we cast from the base type to the naming class.
2208 ///   The naming class is the class into which we were looking
2209 ///   when we found the member;  it's the qualifier type if a
2210 ///   qualifier was provided, and otherwise it's the base type.
2211 ///
2212 /// * Next we cast from the naming class to the declaring class.
2213 ///   If the member we found was brought into a class's scope by
2214 ///   a using declaration, this is that class;  otherwise it's
2215 ///   the class declaring the member.
2216 ///
2217 /// * Finally we cast from the declaring class to the "true"
2218 ///   declaring class of the member.  This conversion does not
2219 ///   obey access control.
2220 ExprResult
2221 Sema::PerformObjectMemberConversion(Expr *From,
2222                                     NestedNameSpecifier *Qualifier,
2223                                     NamedDecl *FoundDecl,
2224                                     NamedDecl *Member) {
2225   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2226   if (!RD)
2227     return Owned(From);
2228 
2229   QualType DestRecordType;
2230   QualType DestType;
2231   QualType FromRecordType;
2232   QualType FromType = From->getType();
2233   bool PointerConversions = false;
2234   if (isa<FieldDecl>(Member)) {
2235     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2236 
2237     if (FromType->getAs<PointerType>()) {
2238       DestType = Context.getPointerType(DestRecordType);
2239       FromRecordType = FromType->getPointeeType();
2240       PointerConversions = true;
2241     } else {
2242       DestType = DestRecordType;
2243       FromRecordType = FromType;
2244     }
2245   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2246     if (Method->isStatic())
2247       return Owned(From);
2248 
2249     DestType = Method->getThisType(Context);
2250     DestRecordType = DestType->getPointeeType();
2251 
2252     if (FromType->getAs<PointerType>()) {
2253       FromRecordType = FromType->getPointeeType();
2254       PointerConversions = true;
2255     } else {
2256       FromRecordType = FromType;
2257       DestType = DestRecordType;
2258     }
2259   } else {
2260     // No conversion necessary.
2261     return Owned(From);
2262   }
2263 
2264   if (DestType->isDependentType() || FromType->isDependentType())
2265     return Owned(From);
2266 
2267   // If the unqualified types are the same, no conversion is necessary.
2268   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2269     return Owned(From);
2270 
2271   SourceRange FromRange = From->getSourceRange();
2272   SourceLocation FromLoc = FromRange.getBegin();
2273 
2274   ExprValueKind VK = From->getValueKind();
2275 
2276   // C++ [class.member.lookup]p8:
2277   //   [...] Ambiguities can often be resolved by qualifying a name with its
2278   //   class name.
2279   //
2280   // If the member was a qualified name and the qualified referred to a
2281   // specific base subobject type, we'll cast to that intermediate type
2282   // first and then to the object in which the member is declared. That allows
2283   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2284   //
2285   //   class Base { public: int x; };
2286   //   class Derived1 : public Base { };
2287   //   class Derived2 : public Base { };
2288   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2289   //
2290   //   void VeryDerived::f() {
2291   //     x = 17; // error: ambiguous base subobjects
2292   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2293   //   }
2294   if (Qualifier) {
2295     QualType QType = QualType(Qualifier->getAsType(), 0);
2296     assert(!QType.isNull() && "lookup done with dependent qualifier?");
2297     assert(QType->isRecordType() && "lookup done with non-record type");
2298 
2299     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2300 
2301     // In C++98, the qualifier type doesn't actually have to be a base
2302     // type of the object type, in which case we just ignore it.
2303     // Otherwise build the appropriate casts.
2304     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2305       CXXCastPath BasePath;
2306       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2307                                        FromLoc, FromRange, &BasePath))
2308         return ExprError();
2309 
2310       if (PointerConversions)
2311         QType = Context.getPointerType(QType);
2312       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2313                                VK, &BasePath).take();
2314 
2315       FromType = QType;
2316       FromRecordType = QRecordType;
2317 
2318       // If the qualifier type was the same as the destination type,
2319       // we're done.
2320       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2321         return Owned(From);
2322     }
2323   }
2324 
2325   bool IgnoreAccess = false;
2326 
2327   // If we actually found the member through a using declaration, cast
2328   // down to the using declaration's type.
2329   //
2330   // Pointer equality is fine here because only one declaration of a
2331   // class ever has member declarations.
2332   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2333     assert(isa<UsingShadowDecl>(FoundDecl));
2334     QualType URecordType = Context.getTypeDeclType(
2335                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2336 
2337     // We only need to do this if the naming-class to declaring-class
2338     // conversion is non-trivial.
2339     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2340       assert(IsDerivedFrom(FromRecordType, URecordType));
2341       CXXCastPath BasePath;
2342       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2343                                        FromLoc, FromRange, &BasePath))
2344         return ExprError();
2345 
2346       QualType UType = URecordType;
2347       if (PointerConversions)
2348         UType = Context.getPointerType(UType);
2349       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2350                                VK, &BasePath).take();
2351       FromType = UType;
2352       FromRecordType = URecordType;
2353     }
2354 
2355     // We don't do access control for the conversion from the
2356     // declaring class to the true declaring class.
2357     IgnoreAccess = true;
2358   }
2359 
2360   CXXCastPath BasePath;
2361   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2362                                    FromLoc, FromRange, &BasePath,
2363                                    IgnoreAccess))
2364     return ExprError();
2365 
2366   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2367                            VK, &BasePath);
2368 }
2369 
2370 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2371                                       const LookupResult &R,
2372                                       bool HasTrailingLParen) {
2373   // Only when used directly as the postfix-expression of a call.
2374   if (!HasTrailingLParen)
2375     return false;
2376 
2377   // Never if a scope specifier was provided.
2378   if (SS.isSet())
2379     return false;
2380 
2381   // Only in C++ or ObjC++.
2382   if (!getLangOpts().CPlusPlus)
2383     return false;
2384 
2385   // Turn off ADL when we find certain kinds of declarations during
2386   // normal lookup:
2387   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2388     NamedDecl *D = *I;
2389 
2390     // C++0x [basic.lookup.argdep]p3:
2391     //     -- a declaration of a class member
2392     // Since using decls preserve this property, we check this on the
2393     // original decl.
2394     if (D->isCXXClassMember())
2395       return false;
2396 
2397     // C++0x [basic.lookup.argdep]p3:
2398     //     -- a block-scope function declaration that is not a
2399     //        using-declaration
2400     // NOTE: we also trigger this for function templates (in fact, we
2401     // don't check the decl type at all, since all other decl types
2402     // turn off ADL anyway).
2403     if (isa<UsingShadowDecl>(D))
2404       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2405     else if (D->getDeclContext()->isFunctionOrMethod())
2406       return false;
2407 
2408     // C++0x [basic.lookup.argdep]p3:
2409     //     -- a declaration that is neither a function or a function
2410     //        template
2411     // And also for builtin functions.
2412     if (isa<FunctionDecl>(D)) {
2413       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2414 
2415       // But also builtin functions.
2416       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2417         return false;
2418     } else if (!isa<FunctionTemplateDecl>(D))
2419       return false;
2420   }
2421 
2422   return true;
2423 }
2424 
2425 
2426 /// Diagnoses obvious problems with the use of the given declaration
2427 /// as an expression.  This is only actually called for lookups that
2428 /// were not overloaded, and it doesn't promise that the declaration
2429 /// will in fact be used.
2430 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2431   if (isa<TypedefNameDecl>(D)) {
2432     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2433     return true;
2434   }
2435 
2436   if (isa<ObjCInterfaceDecl>(D)) {
2437     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2438     return true;
2439   }
2440 
2441   if (isa<NamespaceDecl>(D)) {
2442     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2443     return true;
2444   }
2445 
2446   return false;
2447 }
2448 
2449 ExprResult
2450 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2451                                LookupResult &R,
2452                                bool NeedsADL) {
2453   // If this is a single, fully-resolved result and we don't need ADL,
2454   // just build an ordinary singleton decl ref.
2455   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2456     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2457                                     R.getRepresentativeDecl());
2458 
2459   // We only need to check the declaration if there's exactly one
2460   // result, because in the overloaded case the results can only be
2461   // functions and function templates.
2462   if (R.isSingleResult() &&
2463       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2464     return ExprError();
2465 
2466   // Otherwise, just build an unresolved lookup expression.  Suppress
2467   // any lookup-related diagnostics; we'll hash these out later, when
2468   // we've picked a target.
2469   R.suppressDiagnostics();
2470 
2471   UnresolvedLookupExpr *ULE
2472     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2473                                    SS.getWithLocInContext(Context),
2474                                    R.getLookupNameInfo(),
2475                                    NeedsADL, R.isOverloadedResult(),
2476                                    R.begin(), R.end());
2477 
2478   return Owned(ULE);
2479 }
2480 
2481 /// \brief Complete semantic analysis for a reference to the given declaration.
2482 ExprResult
2483 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2484                                const DeclarationNameInfo &NameInfo,
2485                                NamedDecl *D, NamedDecl *FoundD) {
2486   assert(D && "Cannot refer to a NULL declaration");
2487   assert(!isa<FunctionTemplateDecl>(D) &&
2488          "Cannot refer unambiguously to a function template");
2489 
2490   SourceLocation Loc = NameInfo.getLoc();
2491   if (CheckDeclInExpr(*this, Loc, D))
2492     return ExprError();
2493 
2494   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2495     // Specifically diagnose references to class templates that are missing
2496     // a template argument list.
2497     Diag(Loc, diag::err_template_decl_ref)
2498       << Template << SS.getRange();
2499     Diag(Template->getLocation(), diag::note_template_decl_here);
2500     return ExprError();
2501   }
2502 
2503   // Make sure that we're referring to a value.
2504   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2505   if (!VD) {
2506     Diag(Loc, diag::err_ref_non_value)
2507       << D << SS.getRange();
2508     Diag(D->getLocation(), diag::note_declared_at);
2509     return ExprError();
2510   }
2511 
2512   // Check whether this declaration can be used. Note that we suppress
2513   // this check when we're going to perform argument-dependent lookup
2514   // on this function name, because this might not be the function
2515   // that overload resolution actually selects.
2516   if (DiagnoseUseOfDecl(VD, Loc))
2517     return ExprError();
2518 
2519   // Only create DeclRefExpr's for valid Decl's.
2520   if (VD->isInvalidDecl())
2521     return ExprError();
2522 
2523   // Handle members of anonymous structs and unions.  If we got here,
2524   // and the reference is to a class member indirect field, then this
2525   // must be the subject of a pointer-to-member expression.
2526   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2527     if (!indirectField->isCXXClassMember())
2528       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2529                                                       indirectField);
2530 
2531   {
2532     QualType type = VD->getType();
2533     ExprValueKind valueKind = VK_RValue;
2534 
2535     switch (D->getKind()) {
2536     // Ignore all the non-ValueDecl kinds.
2537 #define ABSTRACT_DECL(kind)
2538 #define VALUE(type, base)
2539 #define DECL(type, base) \
2540     case Decl::type:
2541 #include "clang/AST/DeclNodes.inc"
2542       llvm_unreachable("invalid value decl kind");
2543 
2544     // These shouldn't make it here.
2545     case Decl::ObjCAtDefsField:
2546     case Decl::ObjCIvar:
2547       llvm_unreachable("forming non-member reference to ivar?");
2548 
2549     // Enum constants are always r-values and never references.
2550     // Unresolved using declarations are dependent.
2551     case Decl::EnumConstant:
2552     case Decl::UnresolvedUsingValue:
2553       valueKind = VK_RValue;
2554       break;
2555 
2556     // Fields and indirect fields that got here must be for
2557     // pointer-to-member expressions; we just call them l-values for
2558     // internal consistency, because this subexpression doesn't really
2559     // exist in the high-level semantics.
2560     case Decl::Field:
2561     case Decl::IndirectField:
2562       assert(getLangOpts().CPlusPlus &&
2563              "building reference to field in C?");
2564 
2565       // These can't have reference type in well-formed programs, but
2566       // for internal consistency we do this anyway.
2567       type = type.getNonReferenceType();
2568       valueKind = VK_LValue;
2569       break;
2570 
2571     // Non-type template parameters are either l-values or r-values
2572     // depending on the type.
2573     case Decl::NonTypeTemplateParm: {
2574       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2575         type = reftype->getPointeeType();
2576         valueKind = VK_LValue; // even if the parameter is an r-value reference
2577         break;
2578       }
2579 
2580       // For non-references, we need to strip qualifiers just in case
2581       // the template parameter was declared as 'const int' or whatever.
2582       valueKind = VK_RValue;
2583       type = type.getUnqualifiedType();
2584       break;
2585     }
2586 
2587     case Decl::Var:
2588       // In C, "extern void blah;" is valid and is an r-value.
2589       if (!getLangOpts().CPlusPlus &&
2590           !type.hasQualifiers() &&
2591           type->isVoidType()) {
2592         valueKind = VK_RValue;
2593         break;
2594       }
2595       // fallthrough
2596 
2597     case Decl::ImplicitParam:
2598     case Decl::ParmVar: {
2599       // These are always l-values.
2600       valueKind = VK_LValue;
2601       type = type.getNonReferenceType();
2602 
2603       // FIXME: Does the addition of const really only apply in
2604       // potentially-evaluated contexts? Since the variable isn't actually
2605       // captured in an unevaluated context, it seems that the answer is no.
2606       if (!isUnevaluatedContext()) {
2607         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2608         if (!CapturedType.isNull())
2609           type = CapturedType;
2610       }
2611 
2612       break;
2613     }
2614 
2615     case Decl::Function: {
2616       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2617         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2618           type = Context.BuiltinFnTy;
2619           valueKind = VK_RValue;
2620           break;
2621         }
2622       }
2623 
2624       const FunctionType *fty = type->castAs<FunctionType>();
2625 
2626       // If we're referring to a function with an __unknown_anytype
2627       // result type, make the entire expression __unknown_anytype.
2628       if (fty->getResultType() == Context.UnknownAnyTy) {
2629         type = Context.UnknownAnyTy;
2630         valueKind = VK_RValue;
2631         break;
2632       }
2633 
2634       // Functions are l-values in C++.
2635       if (getLangOpts().CPlusPlus) {
2636         valueKind = VK_LValue;
2637         break;
2638       }
2639 
2640       // C99 DR 316 says that, if a function type comes from a
2641       // function definition (without a prototype), that type is only
2642       // used for checking compatibility. Therefore, when referencing
2643       // the function, we pretend that we don't have the full function
2644       // type.
2645       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2646           isa<FunctionProtoType>(fty))
2647         type = Context.getFunctionNoProtoType(fty->getResultType(),
2648                                               fty->getExtInfo());
2649 
2650       // Functions are r-values in C.
2651       valueKind = VK_RValue;
2652       break;
2653     }
2654 
2655     case Decl::MSProperty:
2656       valueKind = VK_LValue;
2657       break;
2658 
2659     case Decl::CXXMethod:
2660       // If we're referring to a method with an __unknown_anytype
2661       // result type, make the entire expression __unknown_anytype.
2662       // This should only be possible with a type written directly.
2663       if (const FunctionProtoType *proto
2664             = dyn_cast<FunctionProtoType>(VD->getType()))
2665         if (proto->getResultType() == Context.UnknownAnyTy) {
2666           type = Context.UnknownAnyTy;
2667           valueKind = VK_RValue;
2668           break;
2669         }
2670 
2671       // C++ methods are l-values if static, r-values if non-static.
2672       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2673         valueKind = VK_LValue;
2674         break;
2675       }
2676       // fallthrough
2677 
2678     case Decl::CXXConversion:
2679     case Decl::CXXDestructor:
2680     case Decl::CXXConstructor:
2681       valueKind = VK_RValue;
2682       break;
2683     }
2684 
2685     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD);
2686   }
2687 }
2688 
2689 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2690   PredefinedExpr::IdentType IT;
2691 
2692   switch (Kind) {
2693   default: llvm_unreachable("Unknown simple primary expr!");
2694   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2695   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2696   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2697   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2698   }
2699 
2700   // Pre-defined identifiers are of type char[x], where x is the length of the
2701   // string.
2702 
2703   Decl *currentDecl = getCurFunctionOrMethodDecl();
2704   // Blocks and lambdas can occur at global scope. Don't emit a warning.
2705   if (!currentDecl) {
2706     if (const BlockScopeInfo *BSI = getCurBlock())
2707       currentDecl = BSI->TheDecl;
2708     else if (const LambdaScopeInfo *LSI = getCurLambda())
2709       currentDecl = LSI->CallOperator;
2710   }
2711 
2712   if (!currentDecl) {
2713     Diag(Loc, diag::ext_predef_outside_function);
2714     currentDecl = Context.getTranslationUnitDecl();
2715   }
2716 
2717   QualType ResTy;
2718   if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2719     ResTy = Context.DependentTy;
2720   } else {
2721     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2722 
2723     llvm::APInt LengthI(32, Length + 1);
2724     if (IT == PredefinedExpr::LFunction)
2725       ResTy = Context.WideCharTy.withConst();
2726     else
2727       ResTy = Context.CharTy.withConst();
2728     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2729   }
2730   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2731 }
2732 
2733 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2734   SmallString<16> CharBuffer;
2735   bool Invalid = false;
2736   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2737   if (Invalid)
2738     return ExprError();
2739 
2740   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2741                             PP, Tok.getKind());
2742   if (Literal.hadError())
2743     return ExprError();
2744 
2745   QualType Ty;
2746   if (Literal.isWide())
2747     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
2748   else if (Literal.isUTF16())
2749     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2750   else if (Literal.isUTF32())
2751     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2752   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2753     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2754   else
2755     Ty = Context.CharTy;  // 'x' -> char in C++
2756 
2757   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2758   if (Literal.isWide())
2759     Kind = CharacterLiteral::Wide;
2760   else if (Literal.isUTF16())
2761     Kind = CharacterLiteral::UTF16;
2762   else if (Literal.isUTF32())
2763     Kind = CharacterLiteral::UTF32;
2764 
2765   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2766                                              Tok.getLocation());
2767 
2768   if (Literal.getUDSuffix().empty())
2769     return Owned(Lit);
2770 
2771   // We're building a user-defined literal.
2772   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2773   SourceLocation UDSuffixLoc =
2774     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2775 
2776   // Make sure we're allowed user-defined literals here.
2777   if (!UDLScope)
2778     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2779 
2780   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2781   //   operator "" X (ch)
2782   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2783                                         Lit, Tok.getLocation());
2784 }
2785 
2786 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2787   unsigned IntSize = Context.getTargetInfo().getIntWidth();
2788   return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2789                                       Context.IntTy, Loc));
2790 }
2791 
2792 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2793                                   QualType Ty, SourceLocation Loc) {
2794   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2795 
2796   using llvm::APFloat;
2797   APFloat Val(Format);
2798 
2799   APFloat::opStatus result = Literal.GetFloatValue(Val);
2800 
2801   // Overflow is always an error, but underflow is only an error if
2802   // we underflowed to zero (APFloat reports denormals as underflow).
2803   if ((result & APFloat::opOverflow) ||
2804       ((result & APFloat::opUnderflow) && Val.isZero())) {
2805     unsigned diagnostic;
2806     SmallString<20> buffer;
2807     if (result & APFloat::opOverflow) {
2808       diagnostic = diag::warn_float_overflow;
2809       APFloat::getLargest(Format).toString(buffer);
2810     } else {
2811       diagnostic = diag::warn_float_underflow;
2812       APFloat::getSmallest(Format).toString(buffer);
2813     }
2814 
2815     S.Diag(Loc, diagnostic)
2816       << Ty
2817       << StringRef(buffer.data(), buffer.size());
2818   }
2819 
2820   bool isExact = (result == APFloat::opOK);
2821   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2822 }
2823 
2824 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
2825   // Fast path for a single digit (which is quite common).  A single digit
2826   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
2827   if (Tok.getLength() == 1) {
2828     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2829     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
2830   }
2831 
2832   SmallString<128> SpellingBuffer;
2833   // NumericLiteralParser wants to overread by one character.  Add padding to
2834   // the buffer in case the token is copied to the buffer.  If getSpelling()
2835   // returns a StringRef to the memory buffer, it should have a null char at
2836   // the EOF, so it is also safe.
2837   SpellingBuffer.resize(Tok.getLength() + 1);
2838 
2839   // Get the spelling of the token, which eliminates trigraphs, etc.
2840   bool Invalid = false;
2841   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
2842   if (Invalid)
2843     return ExprError();
2844 
2845   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
2846   if (Literal.hadError)
2847     return ExprError();
2848 
2849   if (Literal.hasUDSuffix()) {
2850     // We're building a user-defined literal.
2851     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2852     SourceLocation UDSuffixLoc =
2853       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2854 
2855     // Make sure we're allowed user-defined literals here.
2856     if (!UDLScope)
2857       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
2858 
2859     QualType CookedTy;
2860     if (Literal.isFloatingLiteral()) {
2861       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2862       // long double, the literal is treated as a call of the form
2863       //   operator "" X (f L)
2864       CookedTy = Context.LongDoubleTy;
2865     } else {
2866       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2867       // unsigned long long, the literal is treated as a call of the form
2868       //   operator "" X (n ULL)
2869       CookedTy = Context.UnsignedLongLongTy;
2870     }
2871 
2872     DeclarationName OpName =
2873       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2874     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2875     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2876 
2877     // Perform literal operator lookup to determine if we're building a raw
2878     // literal or a cooked one.
2879     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2880     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
2881                                   /*AllowRawAndTemplate*/true)) {
2882     case LOLR_Error:
2883       return ExprError();
2884 
2885     case LOLR_Cooked: {
2886       Expr *Lit;
2887       if (Literal.isFloatingLiteral()) {
2888         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2889       } else {
2890         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2891         if (Literal.GetIntegerValue(ResultVal))
2892           Diag(Tok.getLocation(), diag::warn_integer_too_large);
2893         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2894                                      Tok.getLocation());
2895       }
2896       return BuildLiteralOperatorCall(R, OpNameInfo, Lit,
2897                                       Tok.getLocation());
2898     }
2899 
2900     case LOLR_Raw: {
2901       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2902       // literal is treated as a call of the form
2903       //   operator "" X ("n")
2904       SourceLocation TokLoc = Tok.getLocation();
2905       unsigned Length = Literal.getUDSuffixOffset();
2906       QualType StrTy = Context.getConstantArrayType(
2907           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
2908           ArrayType::Normal, 0);
2909       Expr *Lit = StringLiteral::Create(
2910           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
2911           /*Pascal*/false, StrTy, &TokLoc, 1);
2912       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
2913     }
2914 
2915     case LOLR_Template:
2916       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2917       // template), L is treated as a call fo the form
2918       //   operator "" X <'c1', 'c2', ... 'ck'>()
2919       // where n is the source character sequence c1 c2 ... ck.
2920       TemplateArgumentListInfo ExplicitArgs;
2921       unsigned CharBits = Context.getIntWidth(Context.CharTy);
2922       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2923       llvm::APSInt Value(CharBits, CharIsUnsigned);
2924       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2925         Value = TokSpelling[I];
2926         TemplateArgument Arg(Context, Value, Context.CharTy);
2927         TemplateArgumentLocInfo ArgInfo;
2928         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2929       }
2930       return BuildLiteralOperatorCall(R, OpNameInfo, None, Tok.getLocation(),
2931                                       &ExplicitArgs);
2932     }
2933 
2934     llvm_unreachable("unexpected literal operator lookup result");
2935   }
2936 
2937   Expr *Res;
2938 
2939   if (Literal.isFloatingLiteral()) {
2940     QualType Ty;
2941     if (Literal.isFloat)
2942       Ty = Context.FloatTy;
2943     else if (!Literal.isLong)
2944       Ty = Context.DoubleTy;
2945     else
2946       Ty = Context.LongDoubleTy;
2947 
2948     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
2949 
2950     if (Ty == Context.DoubleTy) {
2951       if (getLangOpts().SinglePrecisionConstants) {
2952         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2953       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2954         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2955         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2956       }
2957     }
2958   } else if (!Literal.isIntegerLiteral()) {
2959     return ExprError();
2960   } else {
2961     QualType Ty;
2962 
2963     // 'long long' is a C99 or C++11 feature.
2964     if (!getLangOpts().C99 && Literal.isLongLong) {
2965       if (getLangOpts().CPlusPlus)
2966         Diag(Tok.getLocation(),
2967              getLangOpts().CPlusPlus11 ?
2968              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
2969       else
2970         Diag(Tok.getLocation(), diag::ext_c99_longlong);
2971     }
2972 
2973     // Get the value in the widest-possible width.
2974     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2975     // The microsoft literal suffix extensions support 128-bit literals, which
2976     // may be wider than [u]intmax_t.
2977     // FIXME: Actually, they don't. We seem to have accidentally invented the
2978     //        i128 suffix.
2979     if (Literal.isMicrosoftInteger && MaxWidth < 128 &&
2980         PP.getTargetInfo().hasInt128Type())
2981       MaxWidth = 128;
2982     llvm::APInt ResultVal(MaxWidth, 0);
2983 
2984     if (Literal.GetIntegerValue(ResultVal)) {
2985       // If this value didn't fit into uintmax_t, warn and force to ull.
2986       Diag(Tok.getLocation(), diag::warn_integer_too_large);
2987       Ty = Context.UnsignedLongLongTy;
2988       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
2989              "long long is not intmax_t?");
2990     } else {
2991       // If this value fits into a ULL, try to figure out what else it fits into
2992       // according to the rules of C99 6.4.4.1p5.
2993 
2994       // Octal, Hexadecimal, and integers with a U suffix are allowed to
2995       // be an unsigned int.
2996       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2997 
2998       // Check from smallest to largest, picking the smallest type we can.
2999       unsigned Width = 0;
3000       if (!Literal.isLong && !Literal.isLongLong) {
3001         // Are int/unsigned possibilities?
3002         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3003 
3004         // Does it fit in a unsigned int?
3005         if (ResultVal.isIntN(IntSize)) {
3006           // Does it fit in a signed int?
3007           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3008             Ty = Context.IntTy;
3009           else if (AllowUnsigned)
3010             Ty = Context.UnsignedIntTy;
3011           Width = IntSize;
3012         }
3013       }
3014 
3015       // Are long/unsigned long possibilities?
3016       if (Ty.isNull() && !Literal.isLongLong) {
3017         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3018 
3019         // Does it fit in a unsigned long?
3020         if (ResultVal.isIntN(LongSize)) {
3021           // Does it fit in a signed long?
3022           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3023             Ty = Context.LongTy;
3024           else if (AllowUnsigned)
3025             Ty = Context.UnsignedLongTy;
3026           Width = LongSize;
3027         }
3028       }
3029 
3030       // Check long long if needed.
3031       if (Ty.isNull()) {
3032         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3033 
3034         // Does it fit in a unsigned long long?
3035         if (ResultVal.isIntN(LongLongSize)) {
3036           // Does it fit in a signed long long?
3037           // To be compatible with MSVC, hex integer literals ending with the
3038           // LL or i64 suffix are always signed in Microsoft mode.
3039           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3040               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3041             Ty = Context.LongLongTy;
3042           else if (AllowUnsigned)
3043             Ty = Context.UnsignedLongLongTy;
3044           Width = LongLongSize;
3045         }
3046       }
3047 
3048       // If it doesn't fit in unsigned long long, and we're using Microsoft
3049       // extensions, then its a 128-bit integer literal.
3050       if (Ty.isNull() && Literal.isMicrosoftInteger &&
3051           PP.getTargetInfo().hasInt128Type()) {
3052         if (Literal.isUnsigned)
3053           Ty = Context.UnsignedInt128Ty;
3054         else
3055           Ty = Context.Int128Ty;
3056         Width = 128;
3057       }
3058 
3059       // If we still couldn't decide a type, we probably have something that
3060       // does not fit in a signed long long, but has no U suffix.
3061       if (Ty.isNull()) {
3062         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
3063         Ty = Context.UnsignedLongLongTy;
3064         Width = Context.getTargetInfo().getLongLongWidth();
3065       }
3066 
3067       if (ResultVal.getBitWidth() != Width)
3068         ResultVal = ResultVal.trunc(Width);
3069     }
3070     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3071   }
3072 
3073   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3074   if (Literal.isImaginary)
3075     Res = new (Context) ImaginaryLiteral(Res,
3076                                         Context.getComplexType(Res->getType()));
3077 
3078   return Owned(Res);
3079 }
3080 
3081 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3082   assert((E != 0) && "ActOnParenExpr() missing expr");
3083   return Owned(new (Context) ParenExpr(L, R, E));
3084 }
3085 
3086 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3087                                          SourceLocation Loc,
3088                                          SourceRange ArgRange) {
3089   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3090   // scalar or vector data type argument..."
3091   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3092   // type (C99 6.2.5p18) or void.
3093   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3094     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3095       << T << ArgRange;
3096     return true;
3097   }
3098 
3099   assert((T->isVoidType() || !T->isIncompleteType()) &&
3100          "Scalar types should always be complete");
3101   return false;
3102 }
3103 
3104 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3105                                            SourceLocation Loc,
3106                                            SourceRange ArgRange,
3107                                            UnaryExprOrTypeTrait TraitKind) {
3108   // C99 6.5.3.4p1:
3109   if (T->isFunctionType() &&
3110       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3111     // sizeof(function)/alignof(function) is allowed as an extension.
3112     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3113       << TraitKind << ArgRange;
3114     return false;
3115   }
3116 
3117   // Allow sizeof(void)/alignof(void) as an extension.
3118   if (T->isVoidType()) {
3119     S.Diag(Loc, diag::ext_sizeof_alignof_void_type) << TraitKind << ArgRange;
3120     return false;
3121   }
3122 
3123   return true;
3124 }
3125 
3126 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3127                                              SourceLocation Loc,
3128                                              SourceRange ArgRange,
3129                                              UnaryExprOrTypeTrait TraitKind) {
3130   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3131   // runtime doesn't allow it.
3132   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3133     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3134       << T << (TraitKind == UETT_SizeOf)
3135       << ArgRange;
3136     return true;
3137   }
3138 
3139   return false;
3140 }
3141 
3142 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3143 /// pointer type is equal to T) and emit a warning if it is.
3144 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3145                                      Expr *E) {
3146   // Don't warn if the operation changed the type.
3147   if (T != E->getType())
3148     return;
3149 
3150   // Now look for array decays.
3151   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3152   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3153     return;
3154 
3155   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3156                                              << ICE->getType()
3157                                              << ICE->getSubExpr()->getType();
3158 }
3159 
3160 /// \brief Check the constrains on expression operands to unary type expression
3161 /// and type traits.
3162 ///
3163 /// Completes any types necessary and validates the constraints on the operand
3164 /// expression. The logic mostly mirrors the type-based overload, but may modify
3165 /// the expression as it completes the type for that expression through template
3166 /// instantiation, etc.
3167 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3168                                             UnaryExprOrTypeTrait ExprKind) {
3169   QualType ExprTy = E->getType();
3170   assert(!ExprTy->isReferenceType());
3171 
3172   if (ExprKind == UETT_VecStep)
3173     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3174                                         E->getSourceRange());
3175 
3176   // Whitelist some types as extensions
3177   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3178                                       E->getSourceRange(), ExprKind))
3179     return false;
3180 
3181   if (RequireCompleteExprType(E,
3182                               diag::err_sizeof_alignof_incomplete_type,
3183                               ExprKind, E->getSourceRange()))
3184     return true;
3185 
3186   // Completing the expression's type may have changed it.
3187   ExprTy = E->getType();
3188   assert(!ExprTy->isReferenceType());
3189 
3190   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3191                                        E->getSourceRange(), ExprKind))
3192     return true;
3193 
3194   if (ExprKind == UETT_SizeOf) {
3195     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3196       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3197         QualType OType = PVD->getOriginalType();
3198         QualType Type = PVD->getType();
3199         if (Type->isPointerType() && OType->isArrayType()) {
3200           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3201             << Type << OType;
3202           Diag(PVD->getLocation(), diag::note_declared_at);
3203         }
3204       }
3205     }
3206 
3207     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3208     // decays into a pointer and returns an unintended result. This is most
3209     // likely a typo for "sizeof(array) op x".
3210     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3211       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3212                                BO->getLHS());
3213       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3214                                BO->getRHS());
3215     }
3216   }
3217 
3218   return false;
3219 }
3220 
3221 /// \brief Check the constraints on operands to unary expression and type
3222 /// traits.
3223 ///
3224 /// This will complete any types necessary, and validate the various constraints
3225 /// on those operands.
3226 ///
3227 /// The UsualUnaryConversions() function is *not* called by this routine.
3228 /// C99 6.3.2.1p[2-4] all state:
3229 ///   Except when it is the operand of the sizeof operator ...
3230 ///
3231 /// C++ [expr.sizeof]p4
3232 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3233 ///   standard conversions are not applied to the operand of sizeof.
3234 ///
3235 /// This policy is followed for all of the unary trait expressions.
3236 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3237                                             SourceLocation OpLoc,
3238                                             SourceRange ExprRange,
3239                                             UnaryExprOrTypeTrait ExprKind) {
3240   if (ExprType->isDependentType())
3241     return false;
3242 
3243   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3244   //   the result is the size of the referenced type."
3245   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3246   //   result shall be the alignment of the referenced type."
3247   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3248     ExprType = Ref->getPointeeType();
3249 
3250   if (ExprKind == UETT_VecStep)
3251     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3252 
3253   // Whitelist some types as extensions
3254   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3255                                       ExprKind))
3256     return false;
3257 
3258   if (RequireCompleteType(OpLoc, ExprType,
3259                           diag::err_sizeof_alignof_incomplete_type,
3260                           ExprKind, ExprRange))
3261     return true;
3262 
3263   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3264                                        ExprKind))
3265     return true;
3266 
3267   return false;
3268 }
3269 
3270 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3271   E = E->IgnoreParens();
3272 
3273   // Cannot know anything else if the expression is dependent.
3274   if (E->isTypeDependent())
3275     return false;
3276 
3277   if (E->getObjectKind() == OK_BitField) {
3278     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3279        << 1 << E->getSourceRange();
3280     return true;
3281   }
3282 
3283   ValueDecl *D = 0;
3284   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3285     D = DRE->getDecl();
3286   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3287     D = ME->getMemberDecl();
3288   }
3289 
3290   // If it's a field, require the containing struct to have a
3291   // complete definition so that we can compute the layout.
3292   //
3293   // This requires a very particular set of circumstances.  For a
3294   // field to be contained within an incomplete type, we must in the
3295   // process of parsing that type.  To have an expression refer to a
3296   // field, it must be an id-expression or a member-expression, but
3297   // the latter are always ill-formed when the base type is
3298   // incomplete, including only being partially complete.  An
3299   // id-expression can never refer to a field in C because fields
3300   // are not in the ordinary namespace.  In C++, an id-expression
3301   // can implicitly be a member access, but only if there's an
3302   // implicit 'this' value, and all such contexts are subject to
3303   // delayed parsing --- except for trailing return types in C++11.
3304   // And if an id-expression referring to a field occurs in a
3305   // context that lacks a 'this' value, it's ill-formed --- except,
3306   // agian, in C++11, where such references are allowed in an
3307   // unevaluated context.  So C++11 introduces some new complexity.
3308   //
3309   // For the record, since __alignof__ on expressions is a GCC
3310   // extension, GCC seems to permit this but always gives the
3311   // nonsensical answer 0.
3312   //
3313   // We don't really need the layout here --- we could instead just
3314   // directly check for all the appropriate alignment-lowing
3315   // attributes --- but that would require duplicating a lot of
3316   // logic that just isn't worth duplicating for such a marginal
3317   // use-case.
3318   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3319     // Fast path this check, since we at least know the record has a
3320     // definition if we can find a member of it.
3321     if (!FD->getParent()->isCompleteDefinition()) {
3322       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3323         << E->getSourceRange();
3324       return true;
3325     }
3326 
3327     // Otherwise, if it's a field, and the field doesn't have
3328     // reference type, then it must have a complete type (or be a
3329     // flexible array member, which we explicitly want to
3330     // white-list anyway), which makes the following checks trivial.
3331     if (!FD->getType()->isReferenceType())
3332       return false;
3333   }
3334 
3335   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3336 }
3337 
3338 bool Sema::CheckVecStepExpr(Expr *E) {
3339   E = E->IgnoreParens();
3340 
3341   // Cannot know anything else if the expression is dependent.
3342   if (E->isTypeDependent())
3343     return false;
3344 
3345   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3346 }
3347 
3348 /// \brief Build a sizeof or alignof expression given a type operand.
3349 ExprResult
3350 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3351                                      SourceLocation OpLoc,
3352                                      UnaryExprOrTypeTrait ExprKind,
3353                                      SourceRange R) {
3354   if (!TInfo)
3355     return ExprError();
3356 
3357   QualType T = TInfo->getType();
3358 
3359   if (!T->isDependentType() &&
3360       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3361     return ExprError();
3362 
3363   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3364   return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3365                                                       Context.getSizeType(),
3366                                                       OpLoc, R.getEnd()));
3367 }
3368 
3369 /// \brief Build a sizeof or alignof expression given an expression
3370 /// operand.
3371 ExprResult
3372 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3373                                      UnaryExprOrTypeTrait ExprKind) {
3374   ExprResult PE = CheckPlaceholderExpr(E);
3375   if (PE.isInvalid())
3376     return ExprError();
3377 
3378   E = PE.get();
3379 
3380   // Verify that the operand is valid.
3381   bool isInvalid = false;
3382   if (E->isTypeDependent()) {
3383     // Delay type-checking for type-dependent expressions.
3384   } else if (ExprKind == UETT_AlignOf) {
3385     isInvalid = CheckAlignOfExpr(*this, E);
3386   } else if (ExprKind == UETT_VecStep) {
3387     isInvalid = CheckVecStepExpr(E);
3388   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3389     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3390     isInvalid = true;
3391   } else {
3392     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3393   }
3394 
3395   if (isInvalid)
3396     return ExprError();
3397 
3398   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3399     PE = TransformToPotentiallyEvaluated(E);
3400     if (PE.isInvalid()) return ExprError();
3401     E = PE.take();
3402   }
3403 
3404   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3405   return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3406       ExprKind, E, Context.getSizeType(), OpLoc,
3407       E->getSourceRange().getEnd()));
3408 }
3409 
3410 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3411 /// expr and the same for @c alignof and @c __alignof
3412 /// Note that the ArgRange is invalid if isType is false.
3413 ExprResult
3414 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3415                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3416                                     void *TyOrEx, const SourceRange &ArgRange) {
3417   // If error parsing type, ignore.
3418   if (TyOrEx == 0) return ExprError();
3419 
3420   if (IsType) {
3421     TypeSourceInfo *TInfo;
3422     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3423     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3424   }
3425 
3426   Expr *ArgEx = (Expr *)TyOrEx;
3427   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3428   return Result;
3429 }
3430 
3431 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3432                                      bool IsReal) {
3433   if (V.get()->isTypeDependent())
3434     return S.Context.DependentTy;
3435 
3436   // _Real and _Imag are only l-values for normal l-values.
3437   if (V.get()->getObjectKind() != OK_Ordinary) {
3438     V = S.DefaultLvalueConversion(V.take());
3439     if (V.isInvalid())
3440       return QualType();
3441   }
3442 
3443   // These operators return the element type of a complex type.
3444   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3445     return CT->getElementType();
3446 
3447   // Otherwise they pass through real integer and floating point types here.
3448   if (V.get()->getType()->isArithmeticType())
3449     return V.get()->getType();
3450 
3451   // Test for placeholders.
3452   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3453   if (PR.isInvalid()) return QualType();
3454   if (PR.get() != V.get()) {
3455     V = PR;
3456     return CheckRealImagOperand(S, V, Loc, IsReal);
3457   }
3458 
3459   // Reject anything else.
3460   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3461     << (IsReal ? "__real" : "__imag");
3462   return QualType();
3463 }
3464 
3465 
3466 
3467 ExprResult
3468 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3469                           tok::TokenKind Kind, Expr *Input) {
3470   UnaryOperatorKind Opc;
3471   switch (Kind) {
3472   default: llvm_unreachable("Unknown unary op!");
3473   case tok::plusplus:   Opc = UO_PostInc; break;
3474   case tok::minusminus: Opc = UO_PostDec; break;
3475   }
3476 
3477   // Since this might is a postfix expression, get rid of ParenListExprs.
3478   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3479   if (Result.isInvalid()) return ExprError();
3480   Input = Result.take();
3481 
3482   return BuildUnaryOp(S, OpLoc, Opc, Input);
3483 }
3484 
3485 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3486 ///
3487 /// \return true on error
3488 static bool checkArithmeticOnObjCPointer(Sema &S,
3489                                          SourceLocation opLoc,
3490                                          Expr *op) {
3491   assert(op->getType()->isObjCObjectPointerType());
3492   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3493     return false;
3494 
3495   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3496     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3497     << op->getSourceRange();
3498   return true;
3499 }
3500 
3501 ExprResult
3502 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3503                               Expr *idx, SourceLocation rbLoc) {
3504   // Since this might be a postfix expression, get rid of ParenListExprs.
3505   if (isa<ParenListExpr>(base)) {
3506     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3507     if (result.isInvalid()) return ExprError();
3508     base = result.take();
3509   }
3510 
3511   // Handle any non-overload placeholder types in the base and index
3512   // expressions.  We can't handle overloads here because the other
3513   // operand might be an overloadable type, in which case the overload
3514   // resolution for the operator overload should get the first crack
3515   // at the overload.
3516   if (base->getType()->isNonOverloadPlaceholderType()) {
3517     ExprResult result = CheckPlaceholderExpr(base);
3518     if (result.isInvalid()) return ExprError();
3519     base = result.take();
3520   }
3521   if (idx->getType()->isNonOverloadPlaceholderType()) {
3522     ExprResult result = CheckPlaceholderExpr(idx);
3523     if (result.isInvalid()) return ExprError();
3524     idx = result.take();
3525   }
3526 
3527   // Build an unanalyzed expression if either operand is type-dependent.
3528   if (getLangOpts().CPlusPlus &&
3529       (base->isTypeDependent() || idx->isTypeDependent())) {
3530     return Owned(new (Context) ArraySubscriptExpr(base, idx,
3531                                                   Context.DependentTy,
3532                                                   VK_LValue, OK_Ordinary,
3533                                                   rbLoc));
3534   }
3535 
3536   // Use C++ overloaded-operator rules if either operand has record
3537   // type.  The spec says to do this if either type is *overloadable*,
3538   // but enum types can't declare subscript operators or conversion
3539   // operators, so there's nothing interesting for overload resolution
3540   // to do if there aren't any record types involved.
3541   //
3542   // ObjC pointers have their own subscripting logic that is not tied
3543   // to overload resolution and so should not take this path.
3544   if (getLangOpts().CPlusPlus &&
3545       (base->getType()->isRecordType() ||
3546        (!base->getType()->isObjCObjectPointerType() &&
3547         idx->getType()->isRecordType()))) {
3548     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3549   }
3550 
3551   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3552 }
3553 
3554 ExprResult
3555 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3556                                       Expr *Idx, SourceLocation RLoc) {
3557   Expr *LHSExp = Base;
3558   Expr *RHSExp = Idx;
3559 
3560   // Perform default conversions.
3561   if (!LHSExp->getType()->getAs<VectorType>()) {
3562     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3563     if (Result.isInvalid())
3564       return ExprError();
3565     LHSExp = Result.take();
3566   }
3567   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3568   if (Result.isInvalid())
3569     return ExprError();
3570   RHSExp = Result.take();
3571 
3572   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3573   ExprValueKind VK = VK_LValue;
3574   ExprObjectKind OK = OK_Ordinary;
3575 
3576   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3577   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3578   // in the subscript position. As a result, we need to derive the array base
3579   // and index from the expression types.
3580   Expr *BaseExpr, *IndexExpr;
3581   QualType ResultType;
3582   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3583     BaseExpr = LHSExp;
3584     IndexExpr = RHSExp;
3585     ResultType = Context.DependentTy;
3586   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3587     BaseExpr = LHSExp;
3588     IndexExpr = RHSExp;
3589     ResultType = PTy->getPointeeType();
3590   } else if (const ObjCObjectPointerType *PTy =
3591                LHSTy->getAs<ObjCObjectPointerType>()) {
3592     BaseExpr = LHSExp;
3593     IndexExpr = RHSExp;
3594 
3595     // Use custom logic if this should be the pseudo-object subscript
3596     // expression.
3597     if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3598       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3599 
3600     ResultType = PTy->getPointeeType();
3601     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3602       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3603         << ResultType << BaseExpr->getSourceRange();
3604       return ExprError();
3605     }
3606   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3607      // Handle the uncommon case of "123[Ptr]".
3608     BaseExpr = RHSExp;
3609     IndexExpr = LHSExp;
3610     ResultType = PTy->getPointeeType();
3611   } else if (const ObjCObjectPointerType *PTy =
3612                RHSTy->getAs<ObjCObjectPointerType>()) {
3613      // Handle the uncommon case of "123[Ptr]".
3614     BaseExpr = RHSExp;
3615     IndexExpr = LHSExp;
3616     ResultType = PTy->getPointeeType();
3617     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3618       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3619         << ResultType << BaseExpr->getSourceRange();
3620       return ExprError();
3621     }
3622   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3623     BaseExpr = LHSExp;    // vectors: V[123]
3624     IndexExpr = RHSExp;
3625     VK = LHSExp->getValueKind();
3626     if (VK != VK_RValue)
3627       OK = OK_VectorComponent;
3628 
3629     // FIXME: need to deal with const...
3630     ResultType = VTy->getElementType();
3631   } else if (LHSTy->isArrayType()) {
3632     // If we see an array that wasn't promoted by
3633     // DefaultFunctionArrayLvalueConversion, it must be an array that
3634     // wasn't promoted because of the C90 rule that doesn't
3635     // allow promoting non-lvalue arrays.  Warn, then
3636     // force the promotion here.
3637     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3638         LHSExp->getSourceRange();
3639     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3640                                CK_ArrayToPointerDecay).take();
3641     LHSTy = LHSExp->getType();
3642 
3643     BaseExpr = LHSExp;
3644     IndexExpr = RHSExp;
3645     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3646   } else if (RHSTy->isArrayType()) {
3647     // Same as previous, except for 123[f().a] case
3648     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3649         RHSExp->getSourceRange();
3650     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3651                                CK_ArrayToPointerDecay).take();
3652     RHSTy = RHSExp->getType();
3653 
3654     BaseExpr = RHSExp;
3655     IndexExpr = LHSExp;
3656     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3657   } else {
3658     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3659        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3660   }
3661   // C99 6.5.2.1p1
3662   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3663     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3664                      << IndexExpr->getSourceRange());
3665 
3666   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3667        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3668          && !IndexExpr->isTypeDependent())
3669     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3670 
3671   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3672   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3673   // type. Note that Functions are not objects, and that (in C99 parlance)
3674   // incomplete types are not object types.
3675   if (ResultType->isFunctionType()) {
3676     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3677       << ResultType << BaseExpr->getSourceRange();
3678     return ExprError();
3679   }
3680 
3681   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3682     // GNU extension: subscripting on pointer to void
3683     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3684       << BaseExpr->getSourceRange();
3685 
3686     // C forbids expressions of unqualified void type from being l-values.
3687     // See IsCForbiddenLValueType.
3688     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3689   } else if (!ResultType->isDependentType() &&
3690       RequireCompleteType(LLoc, ResultType,
3691                           diag::err_subscript_incomplete_type, BaseExpr))
3692     return ExprError();
3693 
3694   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3695          !ResultType.isCForbiddenLValueType());
3696 
3697   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3698                                                 ResultType, VK, OK, RLoc));
3699 }
3700 
3701 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3702                                         FunctionDecl *FD,
3703                                         ParmVarDecl *Param) {
3704   if (Param->hasUnparsedDefaultArg()) {
3705     Diag(CallLoc,
3706          diag::err_use_of_default_argument_to_function_declared_later) <<
3707       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3708     Diag(UnparsedDefaultArgLocs[Param],
3709          diag::note_default_argument_declared_here);
3710     return ExprError();
3711   }
3712 
3713   if (Param->hasUninstantiatedDefaultArg()) {
3714     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3715 
3716     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3717                                                  Param);
3718 
3719     // Instantiate the expression.
3720     MultiLevelTemplateArgumentList MutiLevelArgList
3721       = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3722 
3723     InstantiatingTemplate Inst(*this, CallLoc, Param,
3724                                MutiLevelArgList.getInnermost());
3725     if (Inst)
3726       return ExprError();
3727 
3728     ExprResult Result;
3729     {
3730       // C++ [dcl.fct.default]p5:
3731       //   The names in the [default argument] expression are bound, and
3732       //   the semantic constraints are checked, at the point where the
3733       //   default argument expression appears.
3734       ContextRAII SavedContext(*this, FD);
3735       LocalInstantiationScope Local(*this);
3736       Result = SubstExpr(UninstExpr, MutiLevelArgList);
3737     }
3738     if (Result.isInvalid())
3739       return ExprError();
3740 
3741     // Check the expression as an initializer for the parameter.
3742     InitializedEntity Entity
3743       = InitializedEntity::InitializeParameter(Context, Param);
3744     InitializationKind Kind
3745       = InitializationKind::CreateCopy(Param->getLocation(),
3746              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3747     Expr *ResultE = Result.takeAs<Expr>();
3748 
3749     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3750     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3751     if (Result.isInvalid())
3752       return ExprError();
3753 
3754     Expr *Arg = Result.takeAs<Expr>();
3755     CheckCompletedExpr(Arg, Param->getOuterLocStart());
3756     // Build the default argument expression.
3757     return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
3758   }
3759 
3760   // If the default expression creates temporaries, we need to
3761   // push them to the current stack of expression temporaries so they'll
3762   // be properly destroyed.
3763   // FIXME: We should really be rebuilding the default argument with new
3764   // bound temporaries; see the comment in PR5810.
3765   // We don't need to do that with block decls, though, because
3766   // blocks in default argument expression can never capture anything.
3767   if (isa<ExprWithCleanups>(Param->getInit())) {
3768     // Set the "needs cleanups" bit regardless of whether there are
3769     // any explicit objects.
3770     ExprNeedsCleanups = true;
3771 
3772     // Append all the objects to the cleanup list.  Right now, this
3773     // should always be a no-op, because blocks in default argument
3774     // expressions should never be able to capture anything.
3775     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3776            "default argument expression has capturing blocks?");
3777   }
3778 
3779   // We already type-checked the argument, so we know it works.
3780   // Just mark all of the declarations in this potentially-evaluated expression
3781   // as being "referenced".
3782   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3783                                    /*SkipLocalVariables=*/true);
3784   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3785 }
3786 
3787 
3788 Sema::VariadicCallType
3789 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3790                           Expr *Fn) {
3791   if (Proto && Proto->isVariadic()) {
3792     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3793       return VariadicConstructor;
3794     else if (Fn && Fn->getType()->isBlockPointerType())
3795       return VariadicBlock;
3796     else if (FDecl) {
3797       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3798         if (Method->isInstance())
3799           return VariadicMethod;
3800     }
3801     return VariadicFunction;
3802   }
3803   return VariadicDoesNotApply;
3804 }
3805 
3806 /// ConvertArgumentsForCall - Converts the arguments specified in
3807 /// Args/NumArgs to the parameter types of the function FDecl with
3808 /// function prototype Proto. Call is the call expression itself, and
3809 /// Fn is the function expression. For a C++ member function, this
3810 /// routine does not attempt to convert the object argument. Returns
3811 /// true if the call is ill-formed.
3812 bool
3813 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3814                               FunctionDecl *FDecl,
3815                               const FunctionProtoType *Proto,
3816                               ArrayRef<Expr *> Args,
3817                               SourceLocation RParenLoc,
3818                               bool IsExecConfig) {
3819   // Bail out early if calling a builtin with custom typechecking.
3820   // We don't need to do this in the
3821   if (FDecl)
3822     if (unsigned ID = FDecl->getBuiltinID())
3823       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3824         return false;
3825 
3826   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
3827   // assignment, to the types of the corresponding parameter, ...
3828   unsigned NumArgsInProto = Proto->getNumArgs();
3829   bool Invalid = false;
3830   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
3831   unsigned FnKind = Fn->getType()->isBlockPointerType()
3832                        ? 1 /* block */
3833                        : (IsExecConfig ? 3 /* kernel function (exec config) */
3834                                        : 0 /* function */);
3835 
3836   // If too few arguments are available (and we don't have default
3837   // arguments for the remaining parameters), don't make the call.
3838   if (Args.size() < NumArgsInProto) {
3839     if (Args.size() < MinArgs) {
3840       if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3841         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3842                           ? diag::err_typecheck_call_too_few_args_one
3843                           : diag::err_typecheck_call_too_few_args_at_least_one)
3844           << FnKind
3845           << FDecl->getParamDecl(0) << Fn->getSourceRange();
3846       else
3847         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3848                           ? diag::err_typecheck_call_too_few_args
3849                           : diag::err_typecheck_call_too_few_args_at_least)
3850           << FnKind
3851           << MinArgs << static_cast<unsigned>(Args.size())
3852           << Fn->getSourceRange();
3853 
3854       // Emit the location of the prototype.
3855       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3856         Diag(FDecl->getLocStart(), diag::note_callee_decl)
3857           << FDecl;
3858 
3859       return true;
3860     }
3861     Call->setNumArgs(Context, NumArgsInProto);
3862   }
3863 
3864   // If too many are passed and not variadic, error on the extras and drop
3865   // them.
3866   if (Args.size() > NumArgsInProto) {
3867     if (!Proto->isVariadic()) {
3868       if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3869         Diag(Args[NumArgsInProto]->getLocStart(),
3870              MinArgs == NumArgsInProto
3871                ? diag::err_typecheck_call_too_many_args_one
3872                : diag::err_typecheck_call_too_many_args_at_most_one)
3873           << FnKind
3874           << FDecl->getParamDecl(0) << static_cast<unsigned>(Args.size())
3875           << Fn->getSourceRange()
3876           << SourceRange(Args[NumArgsInProto]->getLocStart(),
3877                          Args.back()->getLocEnd());
3878       else
3879         Diag(Args[NumArgsInProto]->getLocStart(),
3880              MinArgs == NumArgsInProto
3881                ? diag::err_typecheck_call_too_many_args
3882                : diag::err_typecheck_call_too_many_args_at_most)
3883           << FnKind
3884           << NumArgsInProto << static_cast<unsigned>(Args.size())
3885           << Fn->getSourceRange()
3886           << SourceRange(Args[NumArgsInProto]->getLocStart(),
3887                          Args.back()->getLocEnd());
3888 
3889       // Emit the location of the prototype.
3890       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3891         Diag(FDecl->getLocStart(), diag::note_callee_decl)
3892           << FDecl;
3893 
3894       // This deletes the extra arguments.
3895       Call->setNumArgs(Context, NumArgsInProto);
3896       return true;
3897     }
3898   }
3899   SmallVector<Expr *, 8> AllArgs;
3900   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3901 
3902   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
3903                                    Proto, 0, Args, AllArgs, CallType);
3904   if (Invalid)
3905     return true;
3906   unsigned TotalNumArgs = AllArgs.size();
3907   for (unsigned i = 0; i < TotalNumArgs; ++i)
3908     Call->setArg(i, AllArgs[i]);
3909 
3910   return false;
3911 }
3912 
3913 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3914                                   FunctionDecl *FDecl,
3915                                   const FunctionProtoType *Proto,
3916                                   unsigned FirstProtoArg,
3917                                   ArrayRef<Expr *> Args,
3918                                   SmallVector<Expr *, 8> &AllArgs,
3919                                   VariadicCallType CallType,
3920                                   bool AllowExplicit,
3921                                   bool IsListInitialization) {
3922   unsigned NumArgsInProto = Proto->getNumArgs();
3923   unsigned NumArgsToCheck = Args.size();
3924   bool Invalid = false;
3925   if (Args.size() != NumArgsInProto)
3926     // Use default arguments for missing arguments
3927     NumArgsToCheck = NumArgsInProto;
3928   unsigned ArgIx = 0;
3929   // Continue to check argument types (even if we have too few/many args).
3930   for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
3931     QualType ProtoArgType = Proto->getArgType(i);
3932 
3933     Expr *Arg;
3934     ParmVarDecl *Param;
3935     if (ArgIx < Args.size()) {
3936       Arg = Args[ArgIx++];
3937 
3938       if (RequireCompleteType(Arg->getLocStart(),
3939                               ProtoArgType,
3940                               diag::err_call_incomplete_argument, Arg))
3941         return true;
3942 
3943       // Pass the argument
3944       Param = 0;
3945       if (FDecl && i < FDecl->getNumParams())
3946         Param = FDecl->getParamDecl(i);
3947 
3948       // Strip the unbridged-cast placeholder expression off, if applicable.
3949       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3950           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3951           (!Param || !Param->hasAttr<CFConsumedAttr>()))
3952         Arg = stripARCUnbridgedCast(Arg);
3953 
3954       InitializedEntity Entity = Param ?
3955           InitializedEntity::InitializeParameter(Context, Param, ProtoArgType)
3956         : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3957                                                  Proto->isArgConsumed(i));
3958       ExprResult ArgE = PerformCopyInitialization(Entity,
3959                                                   SourceLocation(),
3960                                                   Owned(Arg),
3961                                                   IsListInitialization,
3962                                                   AllowExplicit);
3963       if (ArgE.isInvalid())
3964         return true;
3965 
3966       Arg = ArgE.takeAs<Expr>();
3967     } else {
3968       assert(FDecl && "can't use default arguments without a known callee");
3969       Param = FDecl->getParamDecl(i);
3970 
3971       ExprResult ArgExpr =
3972         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
3973       if (ArgExpr.isInvalid())
3974         return true;
3975 
3976       Arg = ArgExpr.takeAs<Expr>();
3977     }
3978 
3979     // Check for array bounds violations for each argument to the call. This
3980     // check only triggers warnings when the argument isn't a more complex Expr
3981     // with its own checking, such as a BinaryOperator.
3982     CheckArrayAccess(Arg);
3983 
3984     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3985     CheckStaticArrayArgument(CallLoc, Param, Arg);
3986 
3987     AllArgs.push_back(Arg);
3988   }
3989 
3990   // If this is a variadic call, handle args passed through "...".
3991   if (CallType != VariadicDoesNotApply) {
3992     // Assume that extern "C" functions with variadic arguments that
3993     // return __unknown_anytype aren't *really* variadic.
3994     if (Proto->getResultType() == Context.UnknownAnyTy &&
3995         FDecl && FDecl->isExternC()) {
3996       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
3997         QualType paramType; // ignored
3998         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
3999         Invalid |= arg.isInvalid();
4000         AllArgs.push_back(arg.take());
4001       }
4002 
4003     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4004     } else {
4005       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4006         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4007                                                           FDecl);
4008         Invalid |= Arg.isInvalid();
4009         AllArgs.push_back(Arg.take());
4010       }
4011     }
4012 
4013     // Check for array bounds violations.
4014     for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4015       CheckArrayAccess(Args[i]);
4016   }
4017   return Invalid;
4018 }
4019 
4020 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4021   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4022   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4023     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4024       << ATL.getLocalSourceRange();
4025 }
4026 
4027 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4028 /// array parameter, check that it is non-null, and that if it is formed by
4029 /// array-to-pointer decay, the underlying array is sufficiently large.
4030 ///
4031 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4032 /// array type derivation, then for each call to the function, the value of the
4033 /// corresponding actual argument shall provide access to the first element of
4034 /// an array with at least as many elements as specified by the size expression.
4035 void
4036 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4037                                ParmVarDecl *Param,
4038                                const Expr *ArgExpr) {
4039   // Static array parameters are not supported in C++.
4040   if (!Param || getLangOpts().CPlusPlus)
4041     return;
4042 
4043   QualType OrigTy = Param->getOriginalType();
4044 
4045   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4046   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4047     return;
4048 
4049   if (ArgExpr->isNullPointerConstant(Context,
4050                                      Expr::NPC_NeverValueDependent)) {
4051     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4052     DiagnoseCalleeStaticArrayParam(*this, Param);
4053     return;
4054   }
4055 
4056   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4057   if (!CAT)
4058     return;
4059 
4060   const ConstantArrayType *ArgCAT =
4061     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4062   if (!ArgCAT)
4063     return;
4064 
4065   if (ArgCAT->getSize().ult(CAT->getSize())) {
4066     Diag(CallLoc, diag::warn_static_array_too_small)
4067       << ArgExpr->getSourceRange()
4068       << (unsigned) ArgCAT->getSize().getZExtValue()
4069       << (unsigned) CAT->getSize().getZExtValue();
4070     DiagnoseCalleeStaticArrayParam(*this, Param);
4071   }
4072 }
4073 
4074 /// Given a function expression of unknown-any type, try to rebuild it
4075 /// to have a function type.
4076 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4077 
4078 /// Is the given type a placeholder that we need to lower out
4079 /// immediately during argument processing?
4080 static bool isPlaceholderToRemoveAsArg(QualType type) {
4081   // Placeholders are never sugared.
4082   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4083   if (!placeholder) return false;
4084 
4085   switch (placeholder->getKind()) {
4086   // Ignore all the non-placeholder types.
4087 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4088 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4089 #include "clang/AST/BuiltinTypes.def"
4090     return false;
4091 
4092   // We cannot lower out overload sets; they might validly be resolved
4093   // by the call machinery.
4094   case BuiltinType::Overload:
4095     return false;
4096 
4097   // Unbridged casts in ARC can be handled in some call positions and
4098   // should be left in place.
4099   case BuiltinType::ARCUnbridgedCast:
4100     return false;
4101 
4102   // Pseudo-objects should be converted as soon as possible.
4103   case BuiltinType::PseudoObject:
4104     return true;
4105 
4106   // The debugger mode could theoretically but currently does not try
4107   // to resolve unknown-typed arguments based on known parameter types.
4108   case BuiltinType::UnknownAny:
4109     return true;
4110 
4111   // These are always invalid as call arguments and should be reported.
4112   case BuiltinType::BoundMember:
4113   case BuiltinType::BuiltinFn:
4114     return true;
4115   }
4116   llvm_unreachable("bad builtin type kind");
4117 }
4118 
4119 /// Check an argument list for placeholders that we won't try to
4120 /// handle later.
4121 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4122   // Apply this processing to all the arguments at once instead of
4123   // dying at the first failure.
4124   bool hasInvalid = false;
4125   for (size_t i = 0, e = args.size(); i != e; i++) {
4126     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4127       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4128       if (result.isInvalid()) hasInvalid = true;
4129       else args[i] = result.take();
4130     }
4131   }
4132   return hasInvalid;
4133 }
4134 
4135 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4136 /// This provides the location of the left/right parens and a list of comma
4137 /// locations.
4138 ExprResult
4139 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4140                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
4141                     Expr *ExecConfig, bool IsExecConfig) {
4142   // Since this might be a postfix expression, get rid of ParenListExprs.
4143   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4144   if (Result.isInvalid()) return ExprError();
4145   Fn = Result.take();
4146 
4147   if (checkArgsForPlaceholders(*this, ArgExprs))
4148     return ExprError();
4149 
4150   if (getLangOpts().CPlusPlus) {
4151     // If this is a pseudo-destructor expression, build the call immediately.
4152     if (isa<CXXPseudoDestructorExpr>(Fn)) {
4153       if (!ArgExprs.empty()) {
4154         // Pseudo-destructor calls should not have any arguments.
4155         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4156           << FixItHint::CreateRemoval(
4157                                     SourceRange(ArgExprs[0]->getLocStart(),
4158                                                 ArgExprs.back()->getLocEnd()));
4159       }
4160 
4161       return Owned(new (Context) CallExpr(Context, Fn, None,
4162                                           Context.VoidTy, VK_RValue,
4163                                           RParenLoc));
4164     }
4165     if (Fn->getType() == Context.PseudoObjectTy) {
4166       ExprResult result = CheckPlaceholderExpr(Fn);
4167       if (result.isInvalid()) return ExprError();
4168       Fn = result.take();
4169     }
4170 
4171     // Determine whether this is a dependent call inside a C++ template,
4172     // in which case we won't do any semantic analysis now.
4173     // FIXME: Will need to cache the results of name lookup (including ADL) in
4174     // Fn.
4175     bool Dependent = false;
4176     if (Fn->isTypeDependent())
4177       Dependent = true;
4178     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4179       Dependent = true;
4180 
4181     if (Dependent) {
4182       if (ExecConfig) {
4183         return Owned(new (Context) CUDAKernelCallExpr(
4184             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4185             Context.DependentTy, VK_RValue, RParenLoc));
4186       } else {
4187         return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
4188                                             Context.DependentTy, VK_RValue,
4189                                             RParenLoc));
4190       }
4191     }
4192 
4193     // Determine whether this is a call to an object (C++ [over.call.object]).
4194     if (Fn->getType()->isRecordType())
4195       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
4196                                                 ArgExprs, RParenLoc));
4197 
4198     if (Fn->getType() == Context.UnknownAnyTy) {
4199       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4200       if (result.isInvalid()) return ExprError();
4201       Fn = result.take();
4202     }
4203 
4204     if (Fn->getType() == Context.BoundMemberTy) {
4205       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4206     }
4207   }
4208 
4209   // Check for overloaded calls.  This can happen even in C due to extensions.
4210   if (Fn->getType() == Context.OverloadTy) {
4211     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4212 
4213     // We aren't supposed to apply this logic for if there's an '&' involved.
4214     if (!find.HasFormOfMemberPointer) {
4215       OverloadExpr *ovl = find.Expression;
4216       if (isa<UnresolvedLookupExpr>(ovl)) {
4217         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4218         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4219                                        RParenLoc, ExecConfig);
4220       } else {
4221         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4222                                          RParenLoc);
4223       }
4224     }
4225   }
4226 
4227   // If we're directly calling a function, get the appropriate declaration.
4228   if (Fn->getType() == Context.UnknownAnyTy) {
4229     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4230     if (result.isInvalid()) return ExprError();
4231     Fn = result.take();
4232   }
4233 
4234   Expr *NakedFn = Fn->IgnoreParens();
4235 
4236   NamedDecl *NDecl = 0;
4237   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4238     if (UnOp->getOpcode() == UO_AddrOf)
4239       NakedFn = UnOp->getSubExpr()->IgnoreParens();
4240 
4241   if (isa<DeclRefExpr>(NakedFn))
4242     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4243   else if (isa<MemberExpr>(NakedFn))
4244     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4245 
4246   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4247                                ExecConfig, IsExecConfig);
4248 }
4249 
4250 ExprResult
4251 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4252                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
4253   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4254   if (!ConfigDecl)
4255     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4256                           << "cudaConfigureCall");
4257   QualType ConfigQTy = ConfigDecl->getType();
4258 
4259   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4260       ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
4261   MarkFunctionReferenced(LLLLoc, ConfigDecl);
4262 
4263   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
4264                        /*IsExecConfig=*/true);
4265 }
4266 
4267 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4268 ///
4269 /// __builtin_astype( value, dst type )
4270 ///
4271 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4272                                  SourceLocation BuiltinLoc,
4273                                  SourceLocation RParenLoc) {
4274   ExprValueKind VK = VK_RValue;
4275   ExprObjectKind OK = OK_Ordinary;
4276   QualType DstTy = GetTypeFromParser(ParsedDestTy);
4277   QualType SrcTy = E->getType();
4278   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4279     return ExprError(Diag(BuiltinLoc,
4280                           diag::err_invalid_astype_of_different_size)
4281                      << DstTy
4282                      << SrcTy
4283                      << E->getSourceRange());
4284   return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
4285                RParenLoc));
4286 }
4287 
4288 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4289 /// i.e. an expression not of \p OverloadTy.  The expression should
4290 /// unary-convert to an expression of function-pointer or
4291 /// block-pointer type.
4292 ///
4293 /// \param NDecl the declaration being called, if available
4294 ExprResult
4295 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4296                             SourceLocation LParenLoc,
4297                             ArrayRef<Expr *> Args,
4298                             SourceLocation RParenLoc,
4299                             Expr *Config, bool IsExecConfig) {
4300   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4301   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4302 
4303   // Promote the function operand.
4304   // We special-case function promotion here because we only allow promoting
4305   // builtin functions to function pointers in the callee of a call.
4306   ExprResult Result;
4307   if (BuiltinID &&
4308       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4309     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4310                                CK_BuiltinFnToFnPtr).take();
4311   } else {
4312     Result = UsualUnaryConversions(Fn);
4313   }
4314   if (Result.isInvalid())
4315     return ExprError();
4316   Fn = Result.take();
4317 
4318   // Make the call expr early, before semantic checks.  This guarantees cleanup
4319   // of arguments and function on error.
4320   CallExpr *TheCall;
4321   if (Config)
4322     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4323                                                cast<CallExpr>(Config), Args,
4324                                                Context.BoolTy, VK_RValue,
4325                                                RParenLoc);
4326   else
4327     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4328                                      VK_RValue, RParenLoc);
4329 
4330   // Bail out early if calling a builtin with custom typechecking.
4331   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4332     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4333 
4334  retry:
4335   const FunctionType *FuncT;
4336   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4337     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4338     // have type pointer to function".
4339     FuncT = PT->getPointeeType()->getAs<FunctionType>();
4340     if (FuncT == 0)
4341       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4342                          << Fn->getType() << Fn->getSourceRange());
4343   } else if (const BlockPointerType *BPT =
4344                Fn->getType()->getAs<BlockPointerType>()) {
4345     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4346   } else {
4347     // Handle calls to expressions of unknown-any type.
4348     if (Fn->getType() == Context.UnknownAnyTy) {
4349       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4350       if (rewrite.isInvalid()) return ExprError();
4351       Fn = rewrite.take();
4352       TheCall->setCallee(Fn);
4353       goto retry;
4354     }
4355 
4356     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4357       << Fn->getType() << Fn->getSourceRange());
4358   }
4359 
4360   if (getLangOpts().CUDA) {
4361     if (Config) {
4362       // CUDA: Kernel calls must be to global functions
4363       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4364         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4365             << FDecl->getName() << Fn->getSourceRange());
4366 
4367       // CUDA: Kernel function must have 'void' return type
4368       if (!FuncT->getResultType()->isVoidType())
4369         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4370             << Fn->getType() << Fn->getSourceRange());
4371     } else {
4372       // CUDA: Calls to global functions must be configured
4373       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4374         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4375             << FDecl->getName() << Fn->getSourceRange());
4376     }
4377   }
4378 
4379   // Check for a valid return type
4380   if (CheckCallReturnType(FuncT->getResultType(),
4381                           Fn->getLocStart(), TheCall,
4382                           FDecl))
4383     return ExprError();
4384 
4385   // We know the result type of the call, set it.
4386   TheCall->setType(FuncT->getCallResultType(Context));
4387   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
4388 
4389   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4390   if (Proto) {
4391     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4392                                 IsExecConfig))
4393       return ExprError();
4394   } else {
4395     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4396 
4397     if (FDecl) {
4398       // Check if we have too few/too many template arguments, based
4399       // on our knowledge of the function definition.
4400       const FunctionDecl *Def = 0;
4401       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
4402         Proto = Def->getType()->getAs<FunctionProtoType>();
4403        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
4404           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4405           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
4406       }
4407 
4408       // If the function we're calling isn't a function prototype, but we have
4409       // a function prototype from a prior declaratiom, use that prototype.
4410       if (!FDecl->hasPrototype())
4411         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4412     }
4413 
4414     // Promote the arguments (C99 6.5.2.2p6).
4415     for (unsigned i = 0, e = Args.size(); i != e; i++) {
4416       Expr *Arg = Args[i];
4417 
4418       if (Proto && i < Proto->getNumArgs()) {
4419         InitializedEntity Entity
4420           = InitializedEntity::InitializeParameter(Context,
4421                                                    Proto->getArgType(i),
4422                                                    Proto->isArgConsumed(i));
4423         ExprResult ArgE = PerformCopyInitialization(Entity,
4424                                                     SourceLocation(),
4425                                                     Owned(Arg));
4426         if (ArgE.isInvalid())
4427           return true;
4428 
4429         Arg = ArgE.takeAs<Expr>();
4430 
4431       } else {
4432         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4433 
4434         if (ArgE.isInvalid())
4435           return true;
4436 
4437         Arg = ArgE.takeAs<Expr>();
4438       }
4439 
4440       if (RequireCompleteType(Arg->getLocStart(),
4441                               Arg->getType(),
4442                               diag::err_call_incomplete_argument, Arg))
4443         return ExprError();
4444 
4445       TheCall->setArg(i, Arg);
4446     }
4447   }
4448 
4449   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4450     if (!Method->isStatic())
4451       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4452         << Fn->getSourceRange());
4453 
4454   // Check for sentinels
4455   if (NDecl)
4456     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
4457 
4458   // Do special checking on direct calls to functions.
4459   if (FDecl) {
4460     if (CheckFunctionCall(FDecl, TheCall, Proto))
4461       return ExprError();
4462 
4463     if (BuiltinID)
4464       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4465   } else if (NDecl) {
4466     if (CheckBlockCall(NDecl, TheCall, Proto))
4467       return ExprError();
4468   }
4469 
4470   return MaybeBindToTemporary(TheCall);
4471 }
4472 
4473 ExprResult
4474 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4475                            SourceLocation RParenLoc, Expr *InitExpr) {
4476   assert(Ty && "ActOnCompoundLiteral(): missing type");
4477   // FIXME: put back this assert when initializers are worked out.
4478   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4479 
4480   TypeSourceInfo *TInfo;
4481   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4482   if (!TInfo)
4483     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4484 
4485   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4486 }
4487 
4488 ExprResult
4489 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4490                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4491   QualType literalType = TInfo->getType();
4492 
4493   if (literalType->isArrayType()) {
4494     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4495           diag::err_illegal_decl_array_incomplete_type,
4496           SourceRange(LParenLoc,
4497                       LiteralExpr->getSourceRange().getEnd())))
4498       return ExprError();
4499     if (literalType->isVariableArrayType())
4500       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4501         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4502   } else if (!literalType->isDependentType() &&
4503              RequireCompleteType(LParenLoc, literalType,
4504                diag::err_typecheck_decl_incomplete_type,
4505                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4506     return ExprError();
4507 
4508   InitializedEntity Entity
4509     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
4510   InitializationKind Kind
4511     = InitializationKind::CreateCStyleCast(LParenLoc,
4512                                            SourceRange(LParenLoc, RParenLoc),
4513                                            /*InitList=*/true);
4514   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
4515   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4516                                       &literalType);
4517   if (Result.isInvalid())
4518     return ExprError();
4519   LiteralExpr = Result.get();
4520 
4521   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4522   if (isFileScope) { // 6.5.2.5p3
4523     if (CheckForConstantInitializer(LiteralExpr, literalType))
4524       return ExprError();
4525   }
4526 
4527   // In C, compound literals are l-values for some reason.
4528   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4529 
4530   return MaybeBindToTemporary(
4531            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4532                                              VK, LiteralExpr, isFileScope));
4533 }
4534 
4535 ExprResult
4536 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4537                     SourceLocation RBraceLoc) {
4538   // Immediately handle non-overload placeholders.  Overloads can be
4539   // resolved contextually, but everything else here can't.
4540   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4541     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4542       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4543 
4544       // Ignore failures; dropping the entire initializer list because
4545       // of one failure would be terrible for indexing/etc.
4546       if (result.isInvalid()) continue;
4547 
4548       InitArgList[I] = result.take();
4549     }
4550   }
4551 
4552   // Semantic analysis for initializers is done by ActOnDeclarator() and
4553   // CheckInitializer() - it requires knowledge of the object being intialized.
4554 
4555   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4556                                                RBraceLoc);
4557   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4558   return Owned(E);
4559 }
4560 
4561 /// Do an explicit extend of the given block pointer if we're in ARC.
4562 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4563   assert(E.get()->getType()->isBlockPointerType());
4564   assert(E.get()->isRValue());
4565 
4566   // Only do this in an r-value context.
4567   if (!S.getLangOpts().ObjCAutoRefCount) return;
4568 
4569   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4570                                CK_ARCExtendBlockObject, E.get(),
4571                                /*base path*/ 0, VK_RValue);
4572   S.ExprNeedsCleanups = true;
4573 }
4574 
4575 /// Prepare a conversion of the given expression to an ObjC object
4576 /// pointer type.
4577 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4578   QualType type = E.get()->getType();
4579   if (type->isObjCObjectPointerType()) {
4580     return CK_BitCast;
4581   } else if (type->isBlockPointerType()) {
4582     maybeExtendBlockObject(*this, E);
4583     return CK_BlockPointerToObjCPointerCast;
4584   } else {
4585     assert(type->isPointerType());
4586     return CK_CPointerToObjCPointerCast;
4587   }
4588 }
4589 
4590 /// Prepares for a scalar cast, performing all the necessary stages
4591 /// except the final cast and returning the kind required.
4592 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4593   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4594   // Also, callers should have filtered out the invalid cases with
4595   // pointers.  Everything else should be possible.
4596 
4597   QualType SrcTy = Src.get()->getType();
4598   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4599     return CK_NoOp;
4600 
4601   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4602   case Type::STK_MemberPointer:
4603     llvm_unreachable("member pointer type in C");
4604 
4605   case Type::STK_CPointer:
4606   case Type::STK_BlockPointer:
4607   case Type::STK_ObjCObjectPointer:
4608     switch (DestTy->getScalarTypeKind()) {
4609     case Type::STK_CPointer:
4610       return CK_BitCast;
4611     case Type::STK_BlockPointer:
4612       return (SrcKind == Type::STK_BlockPointer
4613                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4614     case Type::STK_ObjCObjectPointer:
4615       if (SrcKind == Type::STK_ObjCObjectPointer)
4616         return CK_BitCast;
4617       if (SrcKind == Type::STK_CPointer)
4618         return CK_CPointerToObjCPointerCast;
4619       maybeExtendBlockObject(*this, Src);
4620       return CK_BlockPointerToObjCPointerCast;
4621     case Type::STK_Bool:
4622       return CK_PointerToBoolean;
4623     case Type::STK_Integral:
4624       return CK_PointerToIntegral;
4625     case Type::STK_Floating:
4626     case Type::STK_FloatingComplex:
4627     case Type::STK_IntegralComplex:
4628     case Type::STK_MemberPointer:
4629       llvm_unreachable("illegal cast from pointer");
4630     }
4631     llvm_unreachable("Should have returned before this");
4632 
4633   case Type::STK_Bool: // casting from bool is like casting from an integer
4634   case Type::STK_Integral:
4635     switch (DestTy->getScalarTypeKind()) {
4636     case Type::STK_CPointer:
4637     case Type::STK_ObjCObjectPointer:
4638     case Type::STK_BlockPointer:
4639       if (Src.get()->isNullPointerConstant(Context,
4640                                            Expr::NPC_ValueDependentIsNull))
4641         return CK_NullToPointer;
4642       return CK_IntegralToPointer;
4643     case Type::STK_Bool:
4644       return CK_IntegralToBoolean;
4645     case Type::STK_Integral:
4646       return CK_IntegralCast;
4647     case Type::STK_Floating:
4648       return CK_IntegralToFloating;
4649     case Type::STK_IntegralComplex:
4650       Src = ImpCastExprToType(Src.take(),
4651                               DestTy->castAs<ComplexType>()->getElementType(),
4652                               CK_IntegralCast);
4653       return CK_IntegralRealToComplex;
4654     case Type::STK_FloatingComplex:
4655       Src = ImpCastExprToType(Src.take(),
4656                               DestTy->castAs<ComplexType>()->getElementType(),
4657                               CK_IntegralToFloating);
4658       return CK_FloatingRealToComplex;
4659     case Type::STK_MemberPointer:
4660       llvm_unreachable("member pointer type in C");
4661     }
4662     llvm_unreachable("Should have returned before this");
4663 
4664   case Type::STK_Floating:
4665     switch (DestTy->getScalarTypeKind()) {
4666     case Type::STK_Floating:
4667       return CK_FloatingCast;
4668     case Type::STK_Bool:
4669       return CK_FloatingToBoolean;
4670     case Type::STK_Integral:
4671       return CK_FloatingToIntegral;
4672     case Type::STK_FloatingComplex:
4673       Src = ImpCastExprToType(Src.take(),
4674                               DestTy->castAs<ComplexType>()->getElementType(),
4675                               CK_FloatingCast);
4676       return CK_FloatingRealToComplex;
4677     case Type::STK_IntegralComplex:
4678       Src = ImpCastExprToType(Src.take(),
4679                               DestTy->castAs<ComplexType>()->getElementType(),
4680                               CK_FloatingToIntegral);
4681       return CK_IntegralRealToComplex;
4682     case Type::STK_CPointer:
4683     case Type::STK_ObjCObjectPointer:
4684     case Type::STK_BlockPointer:
4685       llvm_unreachable("valid float->pointer cast?");
4686     case Type::STK_MemberPointer:
4687       llvm_unreachable("member pointer type in C");
4688     }
4689     llvm_unreachable("Should have returned before this");
4690 
4691   case Type::STK_FloatingComplex:
4692     switch (DestTy->getScalarTypeKind()) {
4693     case Type::STK_FloatingComplex:
4694       return CK_FloatingComplexCast;
4695     case Type::STK_IntegralComplex:
4696       return CK_FloatingComplexToIntegralComplex;
4697     case Type::STK_Floating: {
4698       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4699       if (Context.hasSameType(ET, DestTy))
4700         return CK_FloatingComplexToReal;
4701       Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4702       return CK_FloatingCast;
4703     }
4704     case Type::STK_Bool:
4705       return CK_FloatingComplexToBoolean;
4706     case Type::STK_Integral:
4707       Src = ImpCastExprToType(Src.take(),
4708                               SrcTy->castAs<ComplexType>()->getElementType(),
4709                               CK_FloatingComplexToReal);
4710       return CK_FloatingToIntegral;
4711     case Type::STK_CPointer:
4712     case Type::STK_ObjCObjectPointer:
4713     case Type::STK_BlockPointer:
4714       llvm_unreachable("valid complex float->pointer cast?");
4715     case Type::STK_MemberPointer:
4716       llvm_unreachable("member pointer type in C");
4717     }
4718     llvm_unreachable("Should have returned before this");
4719 
4720   case Type::STK_IntegralComplex:
4721     switch (DestTy->getScalarTypeKind()) {
4722     case Type::STK_FloatingComplex:
4723       return CK_IntegralComplexToFloatingComplex;
4724     case Type::STK_IntegralComplex:
4725       return CK_IntegralComplexCast;
4726     case Type::STK_Integral: {
4727       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4728       if (Context.hasSameType(ET, DestTy))
4729         return CK_IntegralComplexToReal;
4730       Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
4731       return CK_IntegralCast;
4732     }
4733     case Type::STK_Bool:
4734       return CK_IntegralComplexToBoolean;
4735     case Type::STK_Floating:
4736       Src = ImpCastExprToType(Src.take(),
4737                               SrcTy->castAs<ComplexType>()->getElementType(),
4738                               CK_IntegralComplexToReal);
4739       return CK_IntegralToFloating;
4740     case Type::STK_CPointer:
4741     case Type::STK_ObjCObjectPointer:
4742     case Type::STK_BlockPointer:
4743       llvm_unreachable("valid complex int->pointer cast?");
4744     case Type::STK_MemberPointer:
4745       llvm_unreachable("member pointer type in C");
4746     }
4747     llvm_unreachable("Should have returned before this");
4748   }
4749 
4750   llvm_unreachable("Unhandled scalar cast");
4751 }
4752 
4753 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
4754                            CastKind &Kind) {
4755   assert(VectorTy->isVectorType() && "Not a vector type!");
4756 
4757   if (Ty->isVectorType() || Ty->isIntegerType()) {
4758     if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
4759       return Diag(R.getBegin(),
4760                   Ty->isVectorType() ?
4761                   diag::err_invalid_conversion_between_vectors :
4762                   diag::err_invalid_conversion_between_vector_and_integer)
4763         << VectorTy << Ty << R;
4764   } else
4765     return Diag(R.getBegin(),
4766                 diag::err_invalid_conversion_between_vector_and_scalar)
4767       << VectorTy << Ty << R;
4768 
4769   Kind = CK_BitCast;
4770   return false;
4771 }
4772 
4773 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4774                                     Expr *CastExpr, CastKind &Kind) {
4775   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
4776 
4777   QualType SrcTy = CastExpr->getType();
4778 
4779   // If SrcTy is a VectorType, the total size must match to explicitly cast to
4780   // an ExtVectorType.
4781   // In OpenCL, casts between vectors of different types are not allowed.
4782   // (See OpenCL 6.2).
4783   if (SrcTy->isVectorType()) {
4784     if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4785         || (getLangOpts().OpenCL &&
4786             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
4787       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4788         << DestTy << SrcTy << R;
4789       return ExprError();
4790     }
4791     Kind = CK_BitCast;
4792     return Owned(CastExpr);
4793   }
4794 
4795   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
4796   // conversion will take place first from scalar to elt type, and then
4797   // splat from elt type to vector.
4798   if (SrcTy->isPointerType())
4799     return Diag(R.getBegin(),
4800                 diag::err_invalid_conversion_between_vector_and_scalar)
4801       << DestTy << SrcTy << R;
4802 
4803   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4804   ExprResult CastExprRes = Owned(CastExpr);
4805   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
4806   if (CastExprRes.isInvalid())
4807     return ExprError();
4808   CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
4809 
4810   Kind = CK_VectorSplat;
4811   return Owned(CastExpr);
4812 }
4813 
4814 ExprResult
4815 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4816                     Declarator &D, ParsedType &Ty,
4817                     SourceLocation RParenLoc, Expr *CastExpr) {
4818   assert(!D.isInvalidType() && (CastExpr != 0) &&
4819          "ActOnCastExpr(): missing type or expr");
4820 
4821   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
4822   if (D.isInvalidType())
4823     return ExprError();
4824 
4825   if (getLangOpts().CPlusPlus) {
4826     // Check that there are no default arguments (C++ only).
4827     CheckExtraCXXDefaultArguments(D);
4828   }
4829 
4830   checkUnusedDeclAttributes(D);
4831 
4832   QualType castType = castTInfo->getType();
4833   Ty = CreateParsedType(castType, castTInfo);
4834 
4835   bool isVectorLiteral = false;
4836 
4837   // Check for an altivec or OpenCL literal,
4838   // i.e. all the elements are integer constants.
4839   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4840   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
4841   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
4842        && castType->isVectorType() && (PE || PLE)) {
4843     if (PLE && PLE->getNumExprs() == 0) {
4844       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4845       return ExprError();
4846     }
4847     if (PE || PLE->getNumExprs() == 1) {
4848       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4849       if (!E->getType()->isVectorType())
4850         isVectorLiteral = true;
4851     }
4852     else
4853       isVectorLiteral = true;
4854   }
4855 
4856   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4857   // then handle it as such.
4858   if (isVectorLiteral)
4859     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
4860 
4861   // If the Expr being casted is a ParenListExpr, handle it specially.
4862   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4863   // sequence of BinOp comma operators.
4864   if (isa<ParenListExpr>(CastExpr)) {
4865     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
4866     if (Result.isInvalid()) return ExprError();
4867     CastExpr = Result.take();
4868   }
4869 
4870   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
4871 }
4872 
4873 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4874                                     SourceLocation RParenLoc, Expr *E,
4875                                     TypeSourceInfo *TInfo) {
4876   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4877          "Expected paren or paren list expression");
4878 
4879   Expr **exprs;
4880   unsigned numExprs;
4881   Expr *subExpr;
4882   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
4883   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4884     LiteralLParenLoc = PE->getLParenLoc();
4885     LiteralRParenLoc = PE->getRParenLoc();
4886     exprs = PE->getExprs();
4887     numExprs = PE->getNumExprs();
4888   } else { // isa<ParenExpr> by assertion at function entrance
4889     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
4890     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
4891     subExpr = cast<ParenExpr>(E)->getSubExpr();
4892     exprs = &subExpr;
4893     numExprs = 1;
4894   }
4895 
4896   QualType Ty = TInfo->getType();
4897   assert(Ty->isVectorType() && "Expected vector type");
4898 
4899   SmallVector<Expr *, 8> initExprs;
4900   const VectorType *VTy = Ty->getAs<VectorType>();
4901   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4902 
4903   // '(...)' form of vector initialization in AltiVec: the number of
4904   // initializers must be one or must match the size of the vector.
4905   // If a single value is specified in the initializer then it will be
4906   // replicated to all the components of the vector
4907   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
4908     // The number of initializers must be one or must match the size of the
4909     // vector. If a single value is specified in the initializer then it will
4910     // be replicated to all the components of the vector
4911     if (numExprs == 1) {
4912       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4913       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4914       if (Literal.isInvalid())
4915         return ExprError();
4916       Literal = ImpCastExprToType(Literal.take(), ElemTy,
4917                                   PrepareScalarCast(Literal, ElemTy));
4918       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4919     }
4920     else if (numExprs < numElems) {
4921       Diag(E->getExprLoc(),
4922            diag::err_incorrect_number_of_vector_initializers);
4923       return ExprError();
4924     }
4925     else
4926       initExprs.append(exprs, exprs + numExprs);
4927   }
4928   else {
4929     // For OpenCL, when the number of initializers is a single value,
4930     // it will be replicated to all components of the vector.
4931     if (getLangOpts().OpenCL &&
4932         VTy->getVectorKind() == VectorType::GenericVector &&
4933         numExprs == 1) {
4934         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4935         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4936         if (Literal.isInvalid())
4937           return ExprError();
4938         Literal = ImpCastExprToType(Literal.take(), ElemTy,
4939                                     PrepareScalarCast(Literal, ElemTy));
4940         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4941     }
4942 
4943     initExprs.append(exprs, exprs + numExprs);
4944   }
4945   // FIXME: This means that pretty-printing the final AST will produce curly
4946   // braces instead of the original commas.
4947   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
4948                                                    initExprs, LiteralRParenLoc);
4949   initE->setType(Ty);
4950   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4951 }
4952 
4953 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4954 /// the ParenListExpr into a sequence of comma binary operators.
4955 ExprResult
4956 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4957   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
4958   if (!E)
4959     return Owned(OrigExpr);
4960 
4961   ExprResult Result(E->getExpr(0));
4962 
4963   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4964     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4965                         E->getExpr(i));
4966 
4967   if (Result.isInvalid()) return ExprError();
4968 
4969   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
4970 }
4971 
4972 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4973                                     SourceLocation R,
4974                                     MultiExprArg Val) {
4975   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
4976   return Owned(expr);
4977 }
4978 
4979 /// \brief Emit a specialized diagnostic when one expression is a null pointer
4980 /// constant and the other is not a pointer.  Returns true if a diagnostic is
4981 /// emitted.
4982 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
4983                                       SourceLocation QuestionLoc) {
4984   Expr *NullExpr = LHSExpr;
4985   Expr *NonPointerExpr = RHSExpr;
4986   Expr::NullPointerConstantKind NullKind =
4987       NullExpr->isNullPointerConstant(Context,
4988                                       Expr::NPC_ValueDependentIsNotNull);
4989 
4990   if (NullKind == Expr::NPCK_NotNull) {
4991     NullExpr = RHSExpr;
4992     NonPointerExpr = LHSExpr;
4993     NullKind =
4994         NullExpr->isNullPointerConstant(Context,
4995                                         Expr::NPC_ValueDependentIsNotNull);
4996   }
4997 
4998   if (NullKind == Expr::NPCK_NotNull)
4999     return false;
5000 
5001   if (NullKind == Expr::NPCK_ZeroExpression)
5002     return false;
5003 
5004   if (NullKind == Expr::NPCK_ZeroLiteral) {
5005     // In this case, check to make sure that we got here from a "NULL"
5006     // string in the source code.
5007     NullExpr = NullExpr->IgnoreParenImpCasts();
5008     SourceLocation loc = NullExpr->getExprLoc();
5009     if (!findMacroSpelling(loc, "NULL"))
5010       return false;
5011   }
5012 
5013   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5014   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5015       << NonPointerExpr->getType() << DiagType
5016       << NonPointerExpr->getSourceRange();
5017   return true;
5018 }
5019 
5020 /// \brief Return false if the condition expression is valid, true otherwise.
5021 static bool checkCondition(Sema &S, Expr *Cond) {
5022   QualType CondTy = Cond->getType();
5023 
5024   // C99 6.5.15p2
5025   if (CondTy->isScalarType()) return false;
5026 
5027   // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
5028   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
5029     return false;
5030 
5031   // Emit the proper error message.
5032   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
5033                               diag::err_typecheck_cond_expect_scalar :
5034                               diag::err_typecheck_cond_expect_scalar_or_vector)
5035     << CondTy;
5036   return true;
5037 }
5038 
5039 /// \brief Return false if the two expressions can be converted to a vector,
5040 /// true otherwise
5041 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
5042                                                     ExprResult &RHS,
5043                                                     QualType CondTy) {
5044   // Both operands should be of scalar type.
5045   if (!LHS.get()->getType()->isScalarType()) {
5046     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5047       << CondTy;
5048     return true;
5049   }
5050   if (!RHS.get()->getType()->isScalarType()) {
5051     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5052       << CondTy;
5053     return true;
5054   }
5055 
5056   // Implicity convert these scalars to the type of the condition.
5057   LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5058   RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
5059   return false;
5060 }
5061 
5062 /// \brief Handle when one or both operands are void type.
5063 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5064                                          ExprResult &RHS) {
5065     Expr *LHSExpr = LHS.get();
5066     Expr *RHSExpr = RHS.get();
5067 
5068     if (!LHSExpr->getType()->isVoidType())
5069       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5070         << RHSExpr->getSourceRange();
5071     if (!RHSExpr->getType()->isVoidType())
5072       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5073         << LHSExpr->getSourceRange();
5074     LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
5075     RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
5076     return S.Context.VoidTy;
5077 }
5078 
5079 /// \brief Return false if the NullExpr can be promoted to PointerTy,
5080 /// true otherwise.
5081 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5082                                         QualType PointerTy) {
5083   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5084       !NullExpr.get()->isNullPointerConstant(S.Context,
5085                                             Expr::NPC_ValueDependentIsNull))
5086     return true;
5087 
5088   NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
5089   return false;
5090 }
5091 
5092 /// \brief Checks compatibility between two pointers and return the resulting
5093 /// type.
5094 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5095                                                      ExprResult &RHS,
5096                                                      SourceLocation Loc) {
5097   QualType LHSTy = LHS.get()->getType();
5098   QualType RHSTy = RHS.get()->getType();
5099 
5100   if (S.Context.hasSameType(LHSTy, RHSTy)) {
5101     // Two identical pointers types are always compatible.
5102     return LHSTy;
5103   }
5104 
5105   QualType lhptee, rhptee;
5106 
5107   // Get the pointee types.
5108   bool IsBlockPointer = false;
5109   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5110     lhptee = LHSBTy->getPointeeType();
5111     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5112     IsBlockPointer = true;
5113   } else {
5114     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5115     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5116   }
5117 
5118   // C99 6.5.15p6: If both operands are pointers to compatible types or to
5119   // differently qualified versions of compatible types, the result type is
5120   // a pointer to an appropriately qualified version of the composite
5121   // type.
5122 
5123   // Only CVR-qualifiers exist in the standard, and the differently-qualified
5124   // clause doesn't make sense for our extensions. E.g. address space 2 should
5125   // be incompatible with address space 3: they may live on different devices or
5126   // anything.
5127   Qualifiers lhQual = lhptee.getQualifiers();
5128   Qualifiers rhQual = rhptee.getQualifiers();
5129 
5130   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5131   lhQual.removeCVRQualifiers();
5132   rhQual.removeCVRQualifiers();
5133 
5134   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5135   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5136 
5137   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5138 
5139   if (CompositeTy.isNull()) {
5140     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
5141       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5142       << RHS.get()->getSourceRange();
5143     // In this situation, we assume void* type. No especially good
5144     // reason, but this is what gcc does, and we do have to pick
5145     // to get a consistent AST.
5146     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5147     LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5148     RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5149     return incompatTy;
5150   }
5151 
5152   // The pointer types are compatible.
5153   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5154   if (IsBlockPointer)
5155     ResultTy = S.Context.getBlockPointerType(ResultTy);
5156   else
5157     ResultTy = S.Context.getPointerType(ResultTy);
5158 
5159   LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
5160   RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
5161   return ResultTy;
5162 }
5163 
5164 /// \brief Return the resulting type when the operands are both block pointers.
5165 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5166                                                           ExprResult &LHS,
5167                                                           ExprResult &RHS,
5168                                                           SourceLocation Loc) {
5169   QualType LHSTy = LHS.get()->getType();
5170   QualType RHSTy = RHS.get()->getType();
5171 
5172   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5173     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5174       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5175       LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5176       RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5177       return destType;
5178     }
5179     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5180       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5181       << RHS.get()->getSourceRange();
5182     return QualType();
5183   }
5184 
5185   // We have 2 block pointer types.
5186   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5187 }
5188 
5189 /// \brief Return the resulting type when the operands are both pointers.
5190 static QualType
5191 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5192                                             ExprResult &RHS,
5193                                             SourceLocation Loc) {
5194   // get the pointer types
5195   QualType LHSTy = LHS.get()->getType();
5196   QualType RHSTy = RHS.get()->getType();
5197 
5198   // get the "pointed to" types
5199   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5200   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5201 
5202   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5203   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5204     // Figure out necessary qualifiers (C99 6.5.15p6)
5205     QualType destPointee
5206       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5207     QualType destType = S.Context.getPointerType(destPointee);
5208     // Add qualifiers if necessary.
5209     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5210     // Promote to void*.
5211     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5212     return destType;
5213   }
5214   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5215     QualType destPointee
5216       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5217     QualType destType = S.Context.getPointerType(destPointee);
5218     // Add qualifiers if necessary.
5219     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5220     // Promote to void*.
5221     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5222     return destType;
5223   }
5224 
5225   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5226 }
5227 
5228 /// \brief Return false if the first expression is not an integer and the second
5229 /// expression is not a pointer, true otherwise.
5230 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5231                                         Expr* PointerExpr, SourceLocation Loc,
5232                                         bool IsIntFirstExpr) {
5233   if (!PointerExpr->getType()->isPointerType() ||
5234       !Int.get()->getType()->isIntegerType())
5235     return false;
5236 
5237   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5238   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5239 
5240   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5241     << Expr1->getType() << Expr2->getType()
5242     << Expr1->getSourceRange() << Expr2->getSourceRange();
5243   Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
5244                             CK_IntegralToPointer);
5245   return true;
5246 }
5247 
5248 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5249 /// In that case, LHS = cond.
5250 /// C99 6.5.15
5251 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5252                                         ExprResult &RHS, ExprValueKind &VK,
5253                                         ExprObjectKind &OK,
5254                                         SourceLocation QuestionLoc) {
5255 
5256   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5257   if (!LHSResult.isUsable()) return QualType();
5258   LHS = LHSResult;
5259 
5260   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5261   if (!RHSResult.isUsable()) return QualType();
5262   RHS = RHSResult;
5263 
5264   // C++ is sufficiently different to merit its own checker.
5265   if (getLangOpts().CPlusPlus)
5266     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5267 
5268   VK = VK_RValue;
5269   OK = OK_Ordinary;
5270 
5271   Cond = UsualUnaryConversions(Cond.take());
5272   if (Cond.isInvalid())
5273     return QualType();
5274   LHS = UsualUnaryConversions(LHS.take());
5275   if (LHS.isInvalid())
5276     return QualType();
5277   RHS = UsualUnaryConversions(RHS.take());
5278   if (RHS.isInvalid())
5279     return QualType();
5280 
5281   QualType CondTy = Cond.get()->getType();
5282   QualType LHSTy = LHS.get()->getType();
5283   QualType RHSTy = RHS.get()->getType();
5284 
5285   // first, check the condition.
5286   if (checkCondition(*this, Cond.get()))
5287     return QualType();
5288 
5289   // Now check the two expressions.
5290   if (LHSTy->isVectorType() || RHSTy->isVectorType())
5291     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5292 
5293   // If the condition is a vector, and both operands are scalar,
5294   // attempt to implicity convert them to the vector type to act like the
5295   // built in select. (OpenCL v1.1 s6.3.i)
5296   if (getLangOpts().OpenCL && CondTy->isVectorType())
5297     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5298       return QualType();
5299 
5300   // If both operands have arithmetic type, do the usual arithmetic conversions
5301   // to find a common type: C99 6.5.15p3,5.
5302   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5303     UsualArithmeticConversions(LHS, RHS);
5304     if (LHS.isInvalid() || RHS.isInvalid())
5305       return QualType();
5306     return LHS.get()->getType();
5307   }
5308 
5309   // If both operands are the same structure or union type, the result is that
5310   // type.
5311   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5312     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5313       if (LHSRT->getDecl() == RHSRT->getDecl())
5314         // "If both the operands have structure or union type, the result has
5315         // that type."  This implies that CV qualifiers are dropped.
5316         return LHSTy.getUnqualifiedType();
5317     // FIXME: Type of conditional expression must be complete in C mode.
5318   }
5319 
5320   // C99 6.5.15p5: "If both operands have void type, the result has void type."
5321   // The following || allows only one side to be void (a GCC-ism).
5322   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5323     return checkConditionalVoidType(*this, LHS, RHS);
5324   }
5325 
5326   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5327   // the type of the other operand."
5328   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5329   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5330 
5331   // All objective-c pointer type analysis is done here.
5332   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5333                                                         QuestionLoc);
5334   if (LHS.isInvalid() || RHS.isInvalid())
5335     return QualType();
5336   if (!compositeType.isNull())
5337     return compositeType;
5338 
5339 
5340   // Handle block pointer types.
5341   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5342     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5343                                                      QuestionLoc);
5344 
5345   // Check constraints for C object pointers types (C99 6.5.15p3,6).
5346   if (LHSTy->isPointerType() && RHSTy->isPointerType())
5347     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5348                                                        QuestionLoc);
5349 
5350   // GCC compatibility: soften pointer/integer mismatch.  Note that
5351   // null pointers have been filtered out by this point.
5352   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5353       /*isIntFirstExpr=*/true))
5354     return RHSTy;
5355   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5356       /*isIntFirstExpr=*/false))
5357     return LHSTy;
5358 
5359   // Emit a better diagnostic if one of the expressions is a null pointer
5360   // constant and the other is not a pointer type. In this case, the user most
5361   // likely forgot to take the address of the other expression.
5362   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5363     return QualType();
5364 
5365   // Otherwise, the operands are not compatible.
5366   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5367     << LHSTy << RHSTy << LHS.get()->getSourceRange()
5368     << RHS.get()->getSourceRange();
5369   return QualType();
5370 }
5371 
5372 /// FindCompositeObjCPointerType - Helper method to find composite type of
5373 /// two objective-c pointer types of the two input expressions.
5374 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5375                                             SourceLocation QuestionLoc) {
5376   QualType LHSTy = LHS.get()->getType();
5377   QualType RHSTy = RHS.get()->getType();
5378 
5379   // Handle things like Class and struct objc_class*.  Here we case the result
5380   // to the pseudo-builtin, because that will be implicitly cast back to the
5381   // redefinition type if an attempt is made to access its fields.
5382   if (LHSTy->isObjCClassType() &&
5383       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5384     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5385     return LHSTy;
5386   }
5387   if (RHSTy->isObjCClassType() &&
5388       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5389     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5390     return RHSTy;
5391   }
5392   // And the same for struct objc_object* / id
5393   if (LHSTy->isObjCIdType() &&
5394       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5395     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5396     return LHSTy;
5397   }
5398   if (RHSTy->isObjCIdType() &&
5399       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5400     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5401     return RHSTy;
5402   }
5403   // And the same for struct objc_selector* / SEL
5404   if (Context.isObjCSelType(LHSTy) &&
5405       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5406     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
5407     return LHSTy;
5408   }
5409   if (Context.isObjCSelType(RHSTy) &&
5410       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5411     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
5412     return RHSTy;
5413   }
5414   // Check constraints for Objective-C object pointers types.
5415   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5416 
5417     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5418       // Two identical object pointer types are always compatible.
5419       return LHSTy;
5420     }
5421     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5422     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5423     QualType compositeType = LHSTy;
5424 
5425     // If both operands are interfaces and either operand can be
5426     // assigned to the other, use that type as the composite
5427     // type. This allows
5428     //   xxx ? (A*) a : (B*) b
5429     // where B is a subclass of A.
5430     //
5431     // Additionally, as for assignment, if either type is 'id'
5432     // allow silent coercion. Finally, if the types are
5433     // incompatible then make sure to use 'id' as the composite
5434     // type so the result is acceptable for sending messages to.
5435 
5436     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5437     // It could return the composite type.
5438     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5439       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5440     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5441       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5442     } else if ((LHSTy->isObjCQualifiedIdType() ||
5443                 RHSTy->isObjCQualifiedIdType()) &&
5444                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5445       // Need to handle "id<xx>" explicitly.
5446       // GCC allows qualified id and any Objective-C type to devolve to
5447       // id. Currently localizing to here until clear this should be
5448       // part of ObjCQualifiedIdTypesAreCompatible.
5449       compositeType = Context.getObjCIdType();
5450     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5451       compositeType = Context.getObjCIdType();
5452     } else if (!(compositeType =
5453                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5454       ;
5455     else {
5456       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5457       << LHSTy << RHSTy
5458       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5459       QualType incompatTy = Context.getObjCIdType();
5460       LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5461       RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5462       return incompatTy;
5463     }
5464     // The object pointer types are compatible.
5465     LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5466     RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
5467     return compositeType;
5468   }
5469   // Check Objective-C object pointer types and 'void *'
5470   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5471     if (getLangOpts().ObjCAutoRefCount) {
5472       // ARC forbids the implicit conversion of object pointers to 'void *',
5473       // so these types are not compatible.
5474       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5475           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5476       LHS = RHS = true;
5477       return QualType();
5478     }
5479     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5480     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5481     QualType destPointee
5482     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5483     QualType destType = Context.getPointerType(destPointee);
5484     // Add qualifiers if necessary.
5485     LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5486     // Promote to void*.
5487     RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5488     return destType;
5489   }
5490   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5491     if (getLangOpts().ObjCAutoRefCount) {
5492       // ARC forbids the implicit conversion of object pointers to 'void *',
5493       // so these types are not compatible.
5494       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5495           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5496       LHS = RHS = true;
5497       return QualType();
5498     }
5499     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5500     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5501     QualType destPointee
5502     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5503     QualType destType = Context.getPointerType(destPointee);
5504     // Add qualifiers if necessary.
5505     RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5506     // Promote to void*.
5507     LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5508     return destType;
5509   }
5510   return QualType();
5511 }
5512 
5513 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5514 /// ParenRange in parentheses.
5515 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5516                                const PartialDiagnostic &Note,
5517                                SourceRange ParenRange) {
5518   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5519   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5520       EndLoc.isValid()) {
5521     Self.Diag(Loc, Note)
5522       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5523       << FixItHint::CreateInsertion(EndLoc, ")");
5524   } else {
5525     // We can't display the parentheses, so just show the bare note.
5526     Self.Diag(Loc, Note) << ParenRange;
5527   }
5528 }
5529 
5530 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5531   return Opc >= BO_Mul && Opc <= BO_Shr;
5532 }
5533 
5534 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5535 /// expression, either using a built-in or overloaded operator,
5536 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5537 /// expression.
5538 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5539                                    Expr **RHSExprs) {
5540   // Don't strip parenthesis: we should not warn if E is in parenthesis.
5541   E = E->IgnoreImpCasts();
5542   E = E->IgnoreConversionOperator();
5543   E = E->IgnoreImpCasts();
5544 
5545   // Built-in binary operator.
5546   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5547     if (IsArithmeticOp(OP->getOpcode())) {
5548       *Opcode = OP->getOpcode();
5549       *RHSExprs = OP->getRHS();
5550       return true;
5551     }
5552   }
5553 
5554   // Overloaded operator.
5555   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5556     if (Call->getNumArgs() != 2)
5557       return false;
5558 
5559     // Make sure this is really a binary operator that is safe to pass into
5560     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5561     OverloadedOperatorKind OO = Call->getOperator();
5562     if (OO < OO_Plus || OO > OO_Arrow ||
5563         OO == OO_PlusPlus || OO == OO_MinusMinus)
5564       return false;
5565 
5566     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5567     if (IsArithmeticOp(OpKind)) {
5568       *Opcode = OpKind;
5569       *RHSExprs = Call->getArg(1);
5570       return true;
5571     }
5572   }
5573 
5574   return false;
5575 }
5576 
5577 static bool IsLogicOp(BinaryOperatorKind Opc) {
5578   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5579 }
5580 
5581 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5582 /// or is a logical expression such as (x==y) which has int type, but is
5583 /// commonly interpreted as boolean.
5584 static bool ExprLooksBoolean(Expr *E) {
5585   E = E->IgnoreParenImpCasts();
5586 
5587   if (E->getType()->isBooleanType())
5588     return true;
5589   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5590     return IsLogicOp(OP->getOpcode());
5591   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5592     return OP->getOpcode() == UO_LNot;
5593 
5594   return false;
5595 }
5596 
5597 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5598 /// and binary operator are mixed in a way that suggests the programmer assumed
5599 /// the conditional operator has higher precedence, for example:
5600 /// "int x = a + someBinaryCondition ? 1 : 2".
5601 static void DiagnoseConditionalPrecedence(Sema &Self,
5602                                           SourceLocation OpLoc,
5603                                           Expr *Condition,
5604                                           Expr *LHSExpr,
5605                                           Expr *RHSExpr) {
5606   BinaryOperatorKind CondOpcode;
5607   Expr *CondRHS;
5608 
5609   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5610     return;
5611   if (!ExprLooksBoolean(CondRHS))
5612     return;
5613 
5614   // The condition is an arithmetic binary expression, with a right-
5615   // hand side that looks boolean, so warn.
5616 
5617   Self.Diag(OpLoc, diag::warn_precedence_conditional)
5618       << Condition->getSourceRange()
5619       << BinaryOperator::getOpcodeStr(CondOpcode);
5620 
5621   SuggestParentheses(Self, OpLoc,
5622     Self.PDiag(diag::note_precedence_silence)
5623       << BinaryOperator::getOpcodeStr(CondOpcode),
5624     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5625 
5626   SuggestParentheses(Self, OpLoc,
5627     Self.PDiag(diag::note_precedence_conditional_first),
5628     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5629 }
5630 
5631 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5632 /// in the case of a the GNU conditional expr extension.
5633 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5634                                     SourceLocation ColonLoc,
5635                                     Expr *CondExpr, Expr *LHSExpr,
5636                                     Expr *RHSExpr) {
5637   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5638   // was the condition.
5639   OpaqueValueExpr *opaqueValue = 0;
5640   Expr *commonExpr = 0;
5641   if (LHSExpr == 0) {
5642     commonExpr = CondExpr;
5643     // Lower out placeholder types first.  This is important so that we don't
5644     // try to capture a placeholder. This happens in few cases in C++; such
5645     // as Objective-C++'s dictionary subscripting syntax.
5646     if (commonExpr->hasPlaceholderType()) {
5647       ExprResult result = CheckPlaceholderExpr(commonExpr);
5648       if (!result.isUsable()) return ExprError();
5649       commonExpr = result.take();
5650     }
5651     // We usually want to apply unary conversions *before* saving, except
5652     // in the special case of a C++ l-value conditional.
5653     if (!(getLangOpts().CPlusPlus
5654           && !commonExpr->isTypeDependent()
5655           && commonExpr->getValueKind() == RHSExpr->getValueKind()
5656           && commonExpr->isGLValue()
5657           && commonExpr->isOrdinaryOrBitFieldObject()
5658           && RHSExpr->isOrdinaryOrBitFieldObject()
5659           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5660       ExprResult commonRes = UsualUnaryConversions(commonExpr);
5661       if (commonRes.isInvalid())
5662         return ExprError();
5663       commonExpr = commonRes.take();
5664     }
5665 
5666     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5667                                                 commonExpr->getType(),
5668                                                 commonExpr->getValueKind(),
5669                                                 commonExpr->getObjectKind(),
5670                                                 commonExpr);
5671     LHSExpr = CondExpr = opaqueValue;
5672   }
5673 
5674   ExprValueKind VK = VK_RValue;
5675   ExprObjectKind OK = OK_Ordinary;
5676   ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5677   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
5678                                              VK, OK, QuestionLoc);
5679   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5680       RHS.isInvalid())
5681     return ExprError();
5682 
5683   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5684                                 RHS.get());
5685 
5686   if (!commonExpr)
5687     return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5688                                                    LHS.take(), ColonLoc,
5689                                                    RHS.take(), result, VK, OK));
5690 
5691   return Owned(new (Context)
5692     BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5693                               RHS.take(), QuestionLoc, ColonLoc, result, VK,
5694                               OK));
5695 }
5696 
5697 // checkPointerTypesForAssignment - This is a very tricky routine (despite
5698 // being closely modeled after the C99 spec:-). The odd characteristic of this
5699 // routine is it effectively iqnores the qualifiers on the top level pointee.
5700 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5701 // FIXME: add a couple examples in this comment.
5702 static Sema::AssignConvertType
5703 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5704   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5705   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5706 
5707   // get the "pointed to" type (ignoring qualifiers at the top level)
5708   const Type *lhptee, *rhptee;
5709   Qualifiers lhq, rhq;
5710   llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5711   llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
5712 
5713   Sema::AssignConvertType ConvTy = Sema::Compatible;
5714 
5715   // C99 6.5.16.1p1: This following citation is common to constraints
5716   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5717   // qualifiers of the type *pointed to* by the right;
5718   Qualifiers lq;
5719 
5720   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5721   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5722       lhq.compatiblyIncludesObjCLifetime(rhq)) {
5723     // Ignore lifetime for further calculation.
5724     lhq.removeObjCLifetime();
5725     rhq.removeObjCLifetime();
5726   }
5727 
5728   if (!lhq.compatiblyIncludes(rhq)) {
5729     // Treat address-space mismatches as fatal.  TODO: address subspaces
5730     if (lhq.getAddressSpace() != rhq.getAddressSpace())
5731       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5732 
5733     // It's okay to add or remove GC or lifetime qualifiers when converting to
5734     // and from void*.
5735     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
5736                         .compatiblyIncludes(
5737                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
5738              && (lhptee->isVoidType() || rhptee->isVoidType()))
5739       ; // keep old
5740 
5741     // Treat lifetime mismatches as fatal.
5742     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5743       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5744 
5745     // For GCC compatibility, other qualifier mismatches are treated
5746     // as still compatible in C.
5747     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5748   }
5749 
5750   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5751   // incomplete type and the other is a pointer to a qualified or unqualified
5752   // version of void...
5753   if (lhptee->isVoidType()) {
5754     if (rhptee->isIncompleteOrObjectType())
5755       return ConvTy;
5756 
5757     // As an extension, we allow cast to/from void* to function pointer.
5758     assert(rhptee->isFunctionType());
5759     return Sema::FunctionVoidPointer;
5760   }
5761 
5762   if (rhptee->isVoidType()) {
5763     if (lhptee->isIncompleteOrObjectType())
5764       return ConvTy;
5765 
5766     // As an extension, we allow cast to/from void* to function pointer.
5767     assert(lhptee->isFunctionType());
5768     return Sema::FunctionVoidPointer;
5769   }
5770 
5771   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
5772   // unqualified versions of compatible types, ...
5773   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5774   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
5775     // Check if the pointee types are compatible ignoring the sign.
5776     // We explicitly check for char so that we catch "char" vs
5777     // "unsigned char" on systems where "char" is unsigned.
5778     if (lhptee->isCharType())
5779       ltrans = S.Context.UnsignedCharTy;
5780     else if (lhptee->hasSignedIntegerRepresentation())
5781       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
5782 
5783     if (rhptee->isCharType())
5784       rtrans = S.Context.UnsignedCharTy;
5785     else if (rhptee->hasSignedIntegerRepresentation())
5786       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
5787 
5788     if (ltrans == rtrans) {
5789       // Types are compatible ignoring the sign. Qualifier incompatibility
5790       // takes priority over sign incompatibility because the sign
5791       // warning can be disabled.
5792       if (ConvTy != Sema::Compatible)
5793         return ConvTy;
5794 
5795       return Sema::IncompatiblePointerSign;
5796     }
5797 
5798     // If we are a multi-level pointer, it's possible that our issue is simply
5799     // one of qualification - e.g. char ** -> const char ** is not allowed. If
5800     // the eventual target type is the same and the pointers have the same
5801     // level of indirection, this must be the issue.
5802     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
5803       do {
5804         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5805         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
5806       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
5807 
5808       if (lhptee == rhptee)
5809         return Sema::IncompatibleNestedPointerQualifiers;
5810     }
5811 
5812     // General pointer incompatibility takes priority over qualifiers.
5813     return Sema::IncompatiblePointer;
5814   }
5815   if (!S.getLangOpts().CPlusPlus &&
5816       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5817     return Sema::IncompatiblePointer;
5818   return ConvTy;
5819 }
5820 
5821 /// checkBlockPointerTypesForAssignment - This routine determines whether two
5822 /// block pointer types are compatible or whether a block and normal pointer
5823 /// are compatible. It is more restrict than comparing two function pointer
5824 // types.
5825 static Sema::AssignConvertType
5826 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5827                                     QualType RHSType) {
5828   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5829   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5830 
5831   QualType lhptee, rhptee;
5832 
5833   // get the "pointed to" type (ignoring qualifiers at the top level)
5834   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5835   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
5836 
5837   // In C++, the types have to match exactly.
5838   if (S.getLangOpts().CPlusPlus)
5839     return Sema::IncompatibleBlockPointer;
5840 
5841   Sema::AssignConvertType ConvTy = Sema::Compatible;
5842 
5843   // For blocks we enforce that qualifiers are identical.
5844   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5845     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5846 
5847   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
5848     return Sema::IncompatibleBlockPointer;
5849 
5850   return ConvTy;
5851 }
5852 
5853 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
5854 /// for assignment compatibility.
5855 static Sema::AssignConvertType
5856 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5857                                    QualType RHSType) {
5858   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5859   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
5860 
5861   if (LHSType->isObjCBuiltinType()) {
5862     // Class is not compatible with ObjC object pointers.
5863     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5864         !RHSType->isObjCQualifiedClassType())
5865       return Sema::IncompatiblePointer;
5866     return Sema::Compatible;
5867   }
5868   if (RHSType->isObjCBuiltinType()) {
5869     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5870         !LHSType->isObjCQualifiedClassType())
5871       return Sema::IncompatiblePointer;
5872     return Sema::Compatible;
5873   }
5874   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5875   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5876 
5877   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5878       // make an exception for id<P>
5879       !LHSType->isObjCQualifiedIdType())
5880     return Sema::CompatiblePointerDiscardsQualifiers;
5881 
5882   if (S.Context.typesAreCompatible(LHSType, RHSType))
5883     return Sema::Compatible;
5884   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
5885     return Sema::IncompatibleObjCQualifiedId;
5886   return Sema::IncompatiblePointer;
5887 }
5888 
5889 Sema::AssignConvertType
5890 Sema::CheckAssignmentConstraints(SourceLocation Loc,
5891                                  QualType LHSType, QualType RHSType) {
5892   // Fake up an opaque expression.  We don't actually care about what
5893   // cast operations are required, so if CheckAssignmentConstraints
5894   // adds casts to this they'll be wasted, but fortunately that doesn't
5895   // usually happen on valid code.
5896   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5897   ExprResult RHSPtr = &RHSExpr;
5898   CastKind K = CK_Invalid;
5899 
5900   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
5901 }
5902 
5903 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5904 /// has code to accommodate several GCC extensions when type checking
5905 /// pointers. Here are some objectionable examples that GCC considers warnings:
5906 ///
5907 ///  int a, *pint;
5908 ///  short *pshort;
5909 ///  struct foo *pfoo;
5910 ///
5911 ///  pint = pshort; // warning: assignment from incompatible pointer type
5912 ///  a = pint; // warning: assignment makes integer from pointer without a cast
5913 ///  pint = a; // warning: assignment makes pointer from integer without a cast
5914 ///  pint = pfoo; // warning: assignment from incompatible pointer type
5915 ///
5916 /// As a result, the code for dealing with pointers is more complex than the
5917 /// C99 spec dictates.
5918 ///
5919 /// Sets 'Kind' for any result kind except Incompatible.
5920 Sema::AssignConvertType
5921 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5922                                  CastKind &Kind) {
5923   QualType RHSType = RHS.get()->getType();
5924   QualType OrigLHSType = LHSType;
5925 
5926   // Get canonical types.  We're not formatting these types, just comparing
5927   // them.
5928   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5929   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
5930 
5931   // Common case: no conversion required.
5932   if (LHSType == RHSType) {
5933     Kind = CK_NoOp;
5934     return Compatible;
5935   }
5936 
5937   // If we have an atomic type, try a non-atomic assignment, then just add an
5938   // atomic qualification step.
5939   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
5940     Sema::AssignConvertType result =
5941       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5942     if (result != Compatible)
5943       return result;
5944     if (Kind != CK_NoOp)
5945       RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5946     Kind = CK_NonAtomicToAtomic;
5947     return Compatible;
5948   }
5949 
5950   // If the left-hand side is a reference type, then we are in a
5951   // (rare!) case where we've allowed the use of references in C,
5952   // e.g., as a parameter type in a built-in function. In this case,
5953   // just make sure that the type referenced is compatible with the
5954   // right-hand side type. The caller is responsible for adjusting
5955   // LHSType so that the resulting expression does not have reference
5956   // type.
5957   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5958     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
5959       Kind = CK_LValueBitCast;
5960       return Compatible;
5961     }
5962     return Incompatible;
5963   }
5964 
5965   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5966   // to the same ExtVector type.
5967   if (LHSType->isExtVectorType()) {
5968     if (RHSType->isExtVectorType())
5969       return Incompatible;
5970     if (RHSType->isArithmeticType()) {
5971       // CK_VectorSplat does T -> vector T, so first cast to the
5972       // element type.
5973       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5974       if (elType != RHSType) {
5975         Kind = PrepareScalarCast(RHS, elType);
5976         RHS = ImpCastExprToType(RHS.take(), elType, Kind);
5977       }
5978       Kind = CK_VectorSplat;
5979       return Compatible;
5980     }
5981   }
5982 
5983   // Conversions to or from vector type.
5984   if (LHSType->isVectorType() || RHSType->isVectorType()) {
5985     if (LHSType->isVectorType() && RHSType->isVectorType()) {
5986       // Allow assignments of an AltiVec vector type to an equivalent GCC
5987       // vector type and vice versa
5988       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5989         Kind = CK_BitCast;
5990         return Compatible;
5991       }
5992 
5993       // If we are allowing lax vector conversions, and LHS and RHS are both
5994       // vectors, the total size only needs to be the same. This is a bitcast;
5995       // no bits are changed but the result type is different.
5996       if (getLangOpts().LaxVectorConversions &&
5997           (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
5998         Kind = CK_BitCast;
5999         return IncompatibleVectors;
6000       }
6001     }
6002     return Incompatible;
6003   }
6004 
6005   // Arithmetic conversions.
6006   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
6007       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
6008     Kind = PrepareScalarCast(RHS, LHSType);
6009     return Compatible;
6010   }
6011 
6012   // Conversions to normal pointers.
6013   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
6014     // U* -> T*
6015     if (isa<PointerType>(RHSType)) {
6016       Kind = CK_BitCast;
6017       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
6018     }
6019 
6020     // int -> T*
6021     if (RHSType->isIntegerType()) {
6022       Kind = CK_IntegralToPointer; // FIXME: null?
6023       return IntToPointer;
6024     }
6025 
6026     // C pointers are not compatible with ObjC object pointers,
6027     // with two exceptions:
6028     if (isa<ObjCObjectPointerType>(RHSType)) {
6029       //  - conversions to void*
6030       if (LHSPointer->getPointeeType()->isVoidType()) {
6031         Kind = CK_BitCast;
6032         return Compatible;
6033       }
6034 
6035       //  - conversions from 'Class' to the redefinition type
6036       if (RHSType->isObjCClassType() &&
6037           Context.hasSameType(LHSType,
6038                               Context.getObjCClassRedefinitionType())) {
6039         Kind = CK_BitCast;
6040         return Compatible;
6041       }
6042 
6043       Kind = CK_BitCast;
6044       return IncompatiblePointer;
6045     }
6046 
6047     // U^ -> void*
6048     if (RHSType->getAs<BlockPointerType>()) {
6049       if (LHSPointer->getPointeeType()->isVoidType()) {
6050         Kind = CK_BitCast;
6051         return Compatible;
6052       }
6053     }
6054 
6055     return Incompatible;
6056   }
6057 
6058   // Conversions to block pointers.
6059   if (isa<BlockPointerType>(LHSType)) {
6060     // U^ -> T^
6061     if (RHSType->isBlockPointerType()) {
6062       Kind = CK_BitCast;
6063       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
6064     }
6065 
6066     // int or null -> T^
6067     if (RHSType->isIntegerType()) {
6068       Kind = CK_IntegralToPointer; // FIXME: null
6069       return IntToBlockPointer;
6070     }
6071 
6072     // id -> T^
6073     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
6074       Kind = CK_AnyPointerToBlockPointerCast;
6075       return Compatible;
6076     }
6077 
6078     // void* -> T^
6079     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
6080       if (RHSPT->getPointeeType()->isVoidType()) {
6081         Kind = CK_AnyPointerToBlockPointerCast;
6082         return Compatible;
6083       }
6084 
6085     return Incompatible;
6086   }
6087 
6088   // Conversions to Objective-C pointers.
6089   if (isa<ObjCObjectPointerType>(LHSType)) {
6090     // A* -> B*
6091     if (RHSType->isObjCObjectPointerType()) {
6092       Kind = CK_BitCast;
6093       Sema::AssignConvertType result =
6094         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
6095       if (getLangOpts().ObjCAutoRefCount &&
6096           result == Compatible &&
6097           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
6098         result = IncompatibleObjCWeakRef;
6099       return result;
6100     }
6101 
6102     // int or null -> A*
6103     if (RHSType->isIntegerType()) {
6104       Kind = CK_IntegralToPointer; // FIXME: null
6105       return IntToPointer;
6106     }
6107 
6108     // In general, C pointers are not compatible with ObjC object pointers,
6109     // with two exceptions:
6110     if (isa<PointerType>(RHSType)) {
6111       Kind = CK_CPointerToObjCPointerCast;
6112 
6113       //  - conversions from 'void*'
6114       if (RHSType->isVoidPointerType()) {
6115         return Compatible;
6116       }
6117 
6118       //  - conversions to 'Class' from its redefinition type
6119       if (LHSType->isObjCClassType() &&
6120           Context.hasSameType(RHSType,
6121                               Context.getObjCClassRedefinitionType())) {
6122         return Compatible;
6123       }
6124 
6125       return IncompatiblePointer;
6126     }
6127 
6128     // T^ -> A*
6129     if (RHSType->isBlockPointerType()) {
6130       maybeExtendBlockObject(*this, RHS);
6131       Kind = CK_BlockPointerToObjCPointerCast;
6132       return Compatible;
6133     }
6134 
6135     return Incompatible;
6136   }
6137 
6138   // Conversions from pointers that are not covered by the above.
6139   if (isa<PointerType>(RHSType)) {
6140     // T* -> _Bool
6141     if (LHSType == Context.BoolTy) {
6142       Kind = CK_PointerToBoolean;
6143       return Compatible;
6144     }
6145 
6146     // T* -> int
6147     if (LHSType->isIntegerType()) {
6148       Kind = CK_PointerToIntegral;
6149       return PointerToInt;
6150     }
6151 
6152     return Incompatible;
6153   }
6154 
6155   // Conversions from Objective-C pointers that are not covered by the above.
6156   if (isa<ObjCObjectPointerType>(RHSType)) {
6157     // T* -> _Bool
6158     if (LHSType == Context.BoolTy) {
6159       Kind = CK_PointerToBoolean;
6160       return Compatible;
6161     }
6162 
6163     // T* -> int
6164     if (LHSType->isIntegerType()) {
6165       Kind = CK_PointerToIntegral;
6166       return PointerToInt;
6167     }
6168 
6169     return Incompatible;
6170   }
6171 
6172   // struct A -> struct B
6173   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6174     if (Context.typesAreCompatible(LHSType, RHSType)) {
6175       Kind = CK_NoOp;
6176       return Compatible;
6177     }
6178   }
6179 
6180   return Incompatible;
6181 }
6182 
6183 /// \brief Constructs a transparent union from an expression that is
6184 /// used to initialize the transparent union.
6185 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6186                                       ExprResult &EResult, QualType UnionType,
6187                                       FieldDecl *Field) {
6188   // Build an initializer list that designates the appropriate member
6189   // of the transparent union.
6190   Expr *E = EResult.take();
6191   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6192                                                    E, SourceLocation());
6193   Initializer->setType(UnionType);
6194   Initializer->setInitializedFieldInUnion(Field);
6195 
6196   // Build a compound literal constructing a value of the transparent
6197   // union type from this initializer list.
6198   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6199   EResult = S.Owned(
6200     new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6201                                 VK_RValue, Initializer, false));
6202 }
6203 
6204 Sema::AssignConvertType
6205 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
6206                                                ExprResult &RHS) {
6207   QualType RHSType = RHS.get()->getType();
6208 
6209   // If the ArgType is a Union type, we want to handle a potential
6210   // transparent_union GCC extension.
6211   const RecordType *UT = ArgType->getAsUnionType();
6212   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6213     return Incompatible;
6214 
6215   // The field to initialize within the transparent union.
6216   RecordDecl *UD = UT->getDecl();
6217   FieldDecl *InitField = 0;
6218   // It's compatible if the expression matches any of the fields.
6219   for (RecordDecl::field_iterator it = UD->field_begin(),
6220          itend = UD->field_end();
6221        it != itend; ++it) {
6222     if (it->getType()->isPointerType()) {
6223       // If the transparent union contains a pointer type, we allow:
6224       // 1) void pointer
6225       // 2) null pointer constant
6226       if (RHSType->isPointerType())
6227         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6228           RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
6229           InitField = *it;
6230           break;
6231         }
6232 
6233       if (RHS.get()->isNullPointerConstant(Context,
6234                                            Expr::NPC_ValueDependentIsNull)) {
6235         RHS = ImpCastExprToType(RHS.take(), it->getType(),
6236                                 CK_NullToPointer);
6237         InitField = *it;
6238         break;
6239       }
6240     }
6241 
6242     CastKind Kind = CK_Invalid;
6243     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6244           == Compatible) {
6245       RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
6246       InitField = *it;
6247       break;
6248     }
6249   }
6250 
6251   if (!InitField)
6252     return Incompatible;
6253 
6254   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6255   return Compatible;
6256 }
6257 
6258 Sema::AssignConvertType
6259 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6260                                        bool Diagnose) {
6261   if (getLangOpts().CPlusPlus) {
6262     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6263       // C++ 5.17p3: If the left operand is not of class type, the
6264       // expression is implicitly converted (C++ 4) to the
6265       // cv-unqualified type of the left operand.
6266       ExprResult Res;
6267       if (Diagnose) {
6268         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6269                                         AA_Assigning);
6270       } else {
6271         ImplicitConversionSequence ICS =
6272             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6273                                   /*SuppressUserConversions=*/false,
6274                                   /*AllowExplicit=*/false,
6275                                   /*InOverloadResolution=*/false,
6276                                   /*CStyle=*/false,
6277                                   /*AllowObjCWritebackConversion=*/false);
6278         if (ICS.isFailure())
6279           return Incompatible;
6280         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6281                                         ICS, AA_Assigning);
6282       }
6283       if (Res.isInvalid())
6284         return Incompatible;
6285       Sema::AssignConvertType result = Compatible;
6286       if (getLangOpts().ObjCAutoRefCount &&
6287           !CheckObjCARCUnavailableWeakConversion(LHSType,
6288                                                  RHS.get()->getType()))
6289         result = IncompatibleObjCWeakRef;
6290       RHS = Res;
6291       return result;
6292     }
6293 
6294     // FIXME: Currently, we fall through and treat C++ classes like C
6295     // structures.
6296     // FIXME: We also fall through for atomics; not sure what should
6297     // happen there, though.
6298   }
6299 
6300   // C99 6.5.16.1p1: the left operand is a pointer and the right is
6301   // a null pointer constant.
6302   if ((LHSType->isPointerType() ||
6303        LHSType->isObjCObjectPointerType() ||
6304        LHSType->isBlockPointerType())
6305       && RHS.get()->isNullPointerConstant(Context,
6306                                           Expr::NPC_ValueDependentIsNull)) {
6307     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
6308     return Compatible;
6309   }
6310 
6311   // This check seems unnatural, however it is necessary to ensure the proper
6312   // conversion of functions/arrays. If the conversion were done for all
6313   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6314   // expressions that suppress this implicit conversion (&, sizeof).
6315   //
6316   // Suppress this for references: C++ 8.5.3p5.
6317   if (!LHSType->isReferenceType()) {
6318     RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6319     if (RHS.isInvalid())
6320       return Incompatible;
6321   }
6322 
6323   CastKind Kind = CK_Invalid;
6324   Sema::AssignConvertType result =
6325     CheckAssignmentConstraints(LHSType, RHS, Kind);
6326 
6327   // C99 6.5.16.1p2: The value of the right operand is converted to the
6328   // type of the assignment expression.
6329   // CheckAssignmentConstraints allows the left-hand side to be a reference,
6330   // so that we can use references in built-in functions even in C.
6331   // The getNonReferenceType() call makes sure that the resulting expression
6332   // does not have reference type.
6333   if (result != Incompatible && RHS.get()->getType() != LHSType)
6334     RHS = ImpCastExprToType(RHS.take(),
6335                             LHSType.getNonLValueExprType(Context), Kind);
6336   return result;
6337 }
6338 
6339 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6340                                ExprResult &RHS) {
6341   Diag(Loc, diag::err_typecheck_invalid_operands)
6342     << LHS.get()->getType() << RHS.get()->getType()
6343     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6344   return QualType();
6345 }
6346 
6347 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6348                                    SourceLocation Loc, bool IsCompAssign) {
6349   if (!IsCompAssign) {
6350     LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6351     if (LHS.isInvalid())
6352       return QualType();
6353   }
6354   RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6355   if (RHS.isInvalid())
6356     return QualType();
6357 
6358   // For conversion purposes, we ignore any qualifiers.
6359   // For example, "const float" and "float" are equivalent.
6360   QualType LHSType =
6361     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6362   QualType RHSType =
6363     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6364 
6365   // If the vector types are identical, return.
6366   if (LHSType == RHSType)
6367     return LHSType;
6368 
6369   // Handle the case of equivalent AltiVec and GCC vector types
6370   if (LHSType->isVectorType() && RHSType->isVectorType() &&
6371       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6372     if (LHSType->isExtVectorType()) {
6373       RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6374       return LHSType;
6375     }
6376 
6377     if (!IsCompAssign)
6378       LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6379     return RHSType;
6380   }
6381 
6382   if (getLangOpts().LaxVectorConversions &&
6383       Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
6384     // If we are allowing lax vector conversions, and LHS and RHS are both
6385     // vectors, the total size only needs to be the same. This is a
6386     // bitcast; no bits are changed but the result type is different.
6387     // FIXME: Should we really be allowing this?
6388     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6389     return LHSType;
6390   }
6391 
6392   // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6393   // swap back (so that we don't reverse the inputs to a subtract, for instance.
6394   bool swapped = false;
6395   if (RHSType->isExtVectorType() && !IsCompAssign) {
6396     swapped = true;
6397     std::swap(RHS, LHS);
6398     std::swap(RHSType, LHSType);
6399   }
6400 
6401   // Handle the case of an ext vector and scalar.
6402   if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
6403     QualType EltTy = LV->getElementType();
6404     if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6405       int order = Context.getIntegerTypeOrder(EltTy, RHSType);
6406       if (order > 0)
6407         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
6408       if (order >= 0) {
6409         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6410         if (swapped) std::swap(RHS, LHS);
6411         return LHSType;
6412       }
6413     }
6414     if (EltTy->isRealFloatingType() && RHSType->isScalarType()) {
6415       if (RHSType->isRealFloatingType()) {
6416         int order = Context.getFloatingTypeOrder(EltTy, RHSType);
6417         if (order > 0)
6418           RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
6419         if (order >= 0) {
6420           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6421           if (swapped) std::swap(RHS, LHS);
6422           return LHSType;
6423         }
6424       }
6425       if (RHSType->isIntegralType(Context)) {
6426         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralToFloating);
6427         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6428         if (swapped) std::swap(RHS, LHS);
6429         return LHSType;
6430       }
6431     }
6432   }
6433 
6434   // Vectors of different size or scalar and non-ext-vector are errors.
6435   if (swapped) std::swap(RHS, LHS);
6436   Diag(Loc, diag::err_typecheck_vector_not_convertable)
6437     << LHS.get()->getType() << RHS.get()->getType()
6438     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6439   return QualType();
6440 }
6441 
6442 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6443 // expression.  These are mainly cases where the null pointer is used as an
6444 // integer instead of a pointer.
6445 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6446                                 SourceLocation Loc, bool IsCompare) {
6447   // The canonical way to check for a GNU null is with isNullPointerConstant,
6448   // but we use a bit of a hack here for speed; this is a relatively
6449   // hot path, and isNullPointerConstant is slow.
6450   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6451   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6452 
6453   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6454 
6455   // Avoid analyzing cases where the result will either be invalid (and
6456   // diagnosed as such) or entirely valid and not something to warn about.
6457   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6458       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6459     return;
6460 
6461   // Comparison operations would not make sense with a null pointer no matter
6462   // what the other expression is.
6463   if (!IsCompare) {
6464     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6465         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6466         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6467     return;
6468   }
6469 
6470   // The rest of the operations only make sense with a null pointer
6471   // if the other expression is a pointer.
6472   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6473       NonNullType->canDecayToPointerType())
6474     return;
6475 
6476   S.Diag(Loc, diag::warn_null_in_comparison_operation)
6477       << LHSNull /* LHS is NULL */ << NonNullType
6478       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6479 }
6480 
6481 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6482                                            SourceLocation Loc,
6483                                            bool IsCompAssign, bool IsDiv) {
6484   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6485 
6486   if (LHS.get()->getType()->isVectorType() ||
6487       RHS.get()->getType()->isVectorType())
6488     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6489 
6490   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6491   if (LHS.isInvalid() || RHS.isInvalid())
6492     return QualType();
6493 
6494 
6495   if (compType.isNull() || !compType->isArithmeticType())
6496     return InvalidOperands(Loc, LHS, RHS);
6497 
6498   // Check for division by zero.
6499   llvm::APSInt RHSValue;
6500   if (IsDiv && !RHS.get()->isValueDependent() &&
6501       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6502     DiagRuntimeBehavior(Loc, RHS.get(),
6503                         PDiag(diag::warn_division_by_zero)
6504                           << RHS.get()->getSourceRange());
6505 
6506   return compType;
6507 }
6508 
6509 QualType Sema::CheckRemainderOperands(
6510   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6511   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6512 
6513   if (LHS.get()->getType()->isVectorType() ||
6514       RHS.get()->getType()->isVectorType()) {
6515     if (LHS.get()->getType()->hasIntegerRepresentation() &&
6516         RHS.get()->getType()->hasIntegerRepresentation())
6517       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6518     return InvalidOperands(Loc, LHS, RHS);
6519   }
6520 
6521   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6522   if (LHS.isInvalid() || RHS.isInvalid())
6523     return QualType();
6524 
6525   if (compType.isNull() || !compType->isIntegerType())
6526     return InvalidOperands(Loc, LHS, RHS);
6527 
6528   // Check for remainder by zero.
6529   llvm::APSInt RHSValue;
6530   if (!RHS.get()->isValueDependent() &&
6531       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6532     DiagRuntimeBehavior(Loc, RHS.get(),
6533                         PDiag(diag::warn_remainder_by_zero)
6534                           << RHS.get()->getSourceRange());
6535 
6536   return compType;
6537 }
6538 
6539 /// \brief Diagnose invalid arithmetic on two void pointers.
6540 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
6541                                                 Expr *LHSExpr, Expr *RHSExpr) {
6542   S.Diag(Loc, S.getLangOpts().CPlusPlus
6543                 ? diag::err_typecheck_pointer_arith_void_type
6544                 : diag::ext_gnu_void_ptr)
6545     << 1 /* two pointers */ << LHSExpr->getSourceRange()
6546                             << RHSExpr->getSourceRange();
6547 }
6548 
6549 /// \brief Diagnose invalid arithmetic on a void pointer.
6550 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6551                                             Expr *Pointer) {
6552   S.Diag(Loc, S.getLangOpts().CPlusPlus
6553                 ? diag::err_typecheck_pointer_arith_void_type
6554                 : diag::ext_gnu_void_ptr)
6555     << 0 /* one pointer */ << Pointer->getSourceRange();
6556 }
6557 
6558 /// \brief Diagnose invalid arithmetic on two function pointers.
6559 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6560                                                     Expr *LHS, Expr *RHS) {
6561   assert(LHS->getType()->isAnyPointerType());
6562   assert(RHS->getType()->isAnyPointerType());
6563   S.Diag(Loc, S.getLangOpts().CPlusPlus
6564                 ? diag::err_typecheck_pointer_arith_function_type
6565                 : diag::ext_gnu_ptr_func_arith)
6566     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6567     // We only show the second type if it differs from the first.
6568     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6569                                                    RHS->getType())
6570     << RHS->getType()->getPointeeType()
6571     << LHS->getSourceRange() << RHS->getSourceRange();
6572 }
6573 
6574 /// \brief Diagnose invalid arithmetic on a function pointer.
6575 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6576                                                 Expr *Pointer) {
6577   assert(Pointer->getType()->isAnyPointerType());
6578   S.Diag(Loc, S.getLangOpts().CPlusPlus
6579                 ? diag::err_typecheck_pointer_arith_function_type
6580                 : diag::ext_gnu_ptr_func_arith)
6581     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6582     << 0 /* one pointer, so only one type */
6583     << Pointer->getSourceRange();
6584 }
6585 
6586 /// \brief Emit error if Operand is incomplete pointer type
6587 ///
6588 /// \returns True if pointer has incomplete type
6589 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6590                                                  Expr *Operand) {
6591   assert(Operand->getType()->isAnyPointerType() &&
6592          !Operand->getType()->isDependentType());
6593   QualType PointeeTy = Operand->getType()->getPointeeType();
6594   return S.RequireCompleteType(Loc, PointeeTy,
6595                                diag::err_typecheck_arithmetic_incomplete_type,
6596                                PointeeTy, Operand->getSourceRange());
6597 }
6598 
6599 /// \brief Check the validity of an arithmetic pointer operand.
6600 ///
6601 /// If the operand has pointer type, this code will check for pointer types
6602 /// which are invalid in arithmetic operations. These will be diagnosed
6603 /// appropriately, including whether or not the use is supported as an
6604 /// extension.
6605 ///
6606 /// \returns True when the operand is valid to use (even if as an extension).
6607 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6608                                             Expr *Operand) {
6609   if (!Operand->getType()->isAnyPointerType()) return true;
6610 
6611   QualType PointeeTy = Operand->getType()->getPointeeType();
6612   if (PointeeTy->isVoidType()) {
6613     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6614     return !S.getLangOpts().CPlusPlus;
6615   }
6616   if (PointeeTy->isFunctionType()) {
6617     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6618     return !S.getLangOpts().CPlusPlus;
6619   }
6620 
6621   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
6622 
6623   return true;
6624 }
6625 
6626 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6627 /// operands.
6628 ///
6629 /// This routine will diagnose any invalid arithmetic on pointer operands much
6630 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
6631 /// for emitting a single diagnostic even for operations where both LHS and RHS
6632 /// are (potentially problematic) pointers.
6633 ///
6634 /// \returns True when the operand is valid to use (even if as an extension).
6635 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
6636                                                 Expr *LHSExpr, Expr *RHSExpr) {
6637   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6638   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
6639   if (!isLHSPointer && !isRHSPointer) return true;
6640 
6641   QualType LHSPointeeTy, RHSPointeeTy;
6642   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6643   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
6644 
6645   // Check for arithmetic on pointers to incomplete types.
6646   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6647   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6648   if (isLHSVoidPtr || isRHSVoidPtr) {
6649     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6650     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6651     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
6652 
6653     return !S.getLangOpts().CPlusPlus;
6654   }
6655 
6656   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6657   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6658   if (isLHSFuncPtr || isRHSFuncPtr) {
6659     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6660     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6661                                                                 RHSExpr);
6662     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
6663 
6664     return !S.getLangOpts().CPlusPlus;
6665   }
6666 
6667   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6668     return false;
6669   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6670     return false;
6671 
6672   return true;
6673 }
6674 
6675 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6676 /// literal.
6677 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6678                                   Expr *LHSExpr, Expr *RHSExpr) {
6679   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6680   Expr* IndexExpr = RHSExpr;
6681   if (!StrExpr) {
6682     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6683     IndexExpr = LHSExpr;
6684   }
6685 
6686   bool IsStringPlusInt = StrExpr &&
6687       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6688   if (!IsStringPlusInt)
6689     return;
6690 
6691   llvm::APSInt index;
6692   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6693     unsigned StrLenWithNull = StrExpr->getLength() + 1;
6694     if (index.isNonNegative() &&
6695         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6696                               index.isUnsigned()))
6697       return;
6698   }
6699 
6700   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6701   Self.Diag(OpLoc, diag::warn_string_plus_int)
6702       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6703 
6704   // Only print a fixit for "str" + int, not for int + "str".
6705   if (IndexExpr == RHSExpr) {
6706     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6707     Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6708         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6709         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6710         << FixItHint::CreateInsertion(EndLoc, "]");
6711   } else
6712     Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6713 }
6714 
6715 /// \brief Emit error when two pointers are incompatible.
6716 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
6717                                            Expr *LHSExpr, Expr *RHSExpr) {
6718   assert(LHSExpr->getType()->isAnyPointerType());
6719   assert(RHSExpr->getType()->isAnyPointerType());
6720   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6721     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6722     << RHSExpr->getSourceRange();
6723 }
6724 
6725 QualType Sema::CheckAdditionOperands( // C99 6.5.6
6726     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6727     QualType* CompLHSTy) {
6728   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6729 
6730   if (LHS.get()->getType()->isVectorType() ||
6731       RHS.get()->getType()->isVectorType()) {
6732     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6733     if (CompLHSTy) *CompLHSTy = compType;
6734     return compType;
6735   }
6736 
6737   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6738   if (LHS.isInvalid() || RHS.isInvalid())
6739     return QualType();
6740 
6741   // Diagnose "string literal" '+' int.
6742   if (Opc == BO_Add)
6743     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6744 
6745   // handle the common case first (both operands are arithmetic).
6746   if (!compType.isNull() && compType->isArithmeticType()) {
6747     if (CompLHSTy) *CompLHSTy = compType;
6748     return compType;
6749   }
6750 
6751   // Type-checking.  Ultimately the pointer's going to be in PExp;
6752   // note that we bias towards the LHS being the pointer.
6753   Expr *PExp = LHS.get(), *IExp = RHS.get();
6754 
6755   bool isObjCPointer;
6756   if (PExp->getType()->isPointerType()) {
6757     isObjCPointer = false;
6758   } else if (PExp->getType()->isObjCObjectPointerType()) {
6759     isObjCPointer = true;
6760   } else {
6761     std::swap(PExp, IExp);
6762     if (PExp->getType()->isPointerType()) {
6763       isObjCPointer = false;
6764     } else if (PExp->getType()->isObjCObjectPointerType()) {
6765       isObjCPointer = true;
6766     } else {
6767       return InvalidOperands(Loc, LHS, RHS);
6768     }
6769   }
6770   assert(PExp->getType()->isAnyPointerType());
6771 
6772   if (!IExp->getType()->isIntegerType())
6773     return InvalidOperands(Loc, LHS, RHS);
6774 
6775   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6776     return QualType();
6777 
6778   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
6779     return QualType();
6780 
6781   // Check array bounds for pointer arithemtic
6782   CheckArrayAccess(PExp, IExp);
6783 
6784   if (CompLHSTy) {
6785     QualType LHSTy = Context.isPromotableBitField(LHS.get());
6786     if (LHSTy.isNull()) {
6787       LHSTy = LHS.get()->getType();
6788       if (LHSTy->isPromotableIntegerType())
6789         LHSTy = Context.getPromotedIntegerType(LHSTy);
6790     }
6791     *CompLHSTy = LHSTy;
6792   }
6793 
6794   return PExp->getType();
6795 }
6796 
6797 // C99 6.5.6
6798 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
6799                                         SourceLocation Loc,
6800                                         QualType* CompLHSTy) {
6801   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6802 
6803   if (LHS.get()->getType()->isVectorType() ||
6804       RHS.get()->getType()->isVectorType()) {
6805     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6806     if (CompLHSTy) *CompLHSTy = compType;
6807     return compType;
6808   }
6809 
6810   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6811   if (LHS.isInvalid() || RHS.isInvalid())
6812     return QualType();
6813 
6814   // Enforce type constraints: C99 6.5.6p3.
6815 
6816   // Handle the common case first (both operands are arithmetic).
6817   if (!compType.isNull() && compType->isArithmeticType()) {
6818     if (CompLHSTy) *CompLHSTy = compType;
6819     return compType;
6820   }
6821 
6822   // Either ptr - int   or   ptr - ptr.
6823   if (LHS.get()->getType()->isAnyPointerType()) {
6824     QualType lpointee = LHS.get()->getType()->getPointeeType();
6825 
6826     // Diagnose bad cases where we step over interface counts.
6827     if (LHS.get()->getType()->isObjCObjectPointerType() &&
6828         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
6829       return QualType();
6830 
6831     // The result type of a pointer-int computation is the pointer type.
6832     if (RHS.get()->getType()->isIntegerType()) {
6833       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
6834         return QualType();
6835 
6836       // Check array bounds for pointer arithemtic
6837       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6838                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
6839 
6840       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6841       return LHS.get()->getType();
6842     }
6843 
6844     // Handle pointer-pointer subtractions.
6845     if (const PointerType *RHSPTy
6846           = RHS.get()->getType()->getAs<PointerType>()) {
6847       QualType rpointee = RHSPTy->getPointeeType();
6848 
6849       if (getLangOpts().CPlusPlus) {
6850         // Pointee types must be the same: C++ [expr.add]
6851         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6852           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6853         }
6854       } else {
6855         // Pointee types must be compatible C99 6.5.6p3
6856         if (!Context.typesAreCompatible(
6857                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6858                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6859           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6860           return QualType();
6861         }
6862       }
6863 
6864       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6865                                                LHS.get(), RHS.get()))
6866         return QualType();
6867 
6868       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6869       return Context.getPointerDiffType();
6870     }
6871   }
6872 
6873   return InvalidOperands(Loc, LHS, RHS);
6874 }
6875 
6876 static bool isScopedEnumerationType(QualType T) {
6877   if (const EnumType *ET = dyn_cast<EnumType>(T))
6878     return ET->getDecl()->isScoped();
6879   return false;
6880 }
6881 
6882 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
6883                                    SourceLocation Loc, unsigned Opc,
6884                                    QualType LHSType) {
6885   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
6886   // so skip remaining warnings as we don't want to modify values within Sema.
6887   if (S.getLangOpts().OpenCL)
6888     return;
6889 
6890   llvm::APSInt Right;
6891   // Check right/shifter operand
6892   if (RHS.get()->isValueDependent() ||
6893       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
6894     return;
6895 
6896   if (Right.isNegative()) {
6897     S.DiagRuntimeBehavior(Loc, RHS.get(),
6898                           S.PDiag(diag::warn_shift_negative)
6899                             << RHS.get()->getSourceRange());
6900     return;
6901   }
6902   llvm::APInt LeftBits(Right.getBitWidth(),
6903                        S.Context.getTypeSize(LHS.get()->getType()));
6904   if (Right.uge(LeftBits)) {
6905     S.DiagRuntimeBehavior(Loc, RHS.get(),
6906                           S.PDiag(diag::warn_shift_gt_typewidth)
6907                             << RHS.get()->getSourceRange());
6908     return;
6909   }
6910   if (Opc != BO_Shl)
6911     return;
6912 
6913   // When left shifting an ICE which is signed, we can check for overflow which
6914   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6915   // integers have defined behavior modulo one more than the maximum value
6916   // representable in the result type, so never warn for those.
6917   llvm::APSInt Left;
6918   if (LHS.get()->isValueDependent() ||
6919       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6920       LHSType->hasUnsignedIntegerRepresentation())
6921     return;
6922   llvm::APInt ResultBits =
6923       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6924   if (LeftBits.uge(ResultBits))
6925     return;
6926   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6927   Result = Result.shl(Right);
6928 
6929   // Print the bit representation of the signed integer as an unsigned
6930   // hexadecimal number.
6931   SmallString<40> HexResult;
6932   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6933 
6934   // If we are only missing a sign bit, this is less likely to result in actual
6935   // bugs -- if the result is cast back to an unsigned type, it will have the
6936   // expected value. Thus we place this behind a different warning that can be
6937   // turned off separately if needed.
6938   if (LeftBits == ResultBits - 1) {
6939     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6940         << HexResult.str() << LHSType
6941         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6942     return;
6943   }
6944 
6945   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6946     << HexResult.str() << Result.getMinSignedBits() << LHSType
6947     << Left.getBitWidth() << LHS.get()->getSourceRange()
6948     << RHS.get()->getSourceRange();
6949 }
6950 
6951 // C99 6.5.7
6952 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
6953                                   SourceLocation Loc, unsigned Opc,
6954                                   bool IsCompAssign) {
6955   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6956 
6957   // Vector shifts promote their scalar inputs to vector type.
6958   if (LHS.get()->getType()->isVectorType() ||
6959       RHS.get()->getType()->isVectorType())
6960     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6961 
6962   // Shifts don't perform usual arithmetic conversions, they just do integer
6963   // promotions on each operand. C99 6.5.7p3
6964 
6965   // For the LHS, do usual unary conversions, but then reset them away
6966   // if this is a compound assignment.
6967   ExprResult OldLHS = LHS;
6968   LHS = UsualUnaryConversions(LHS.take());
6969   if (LHS.isInvalid())
6970     return QualType();
6971   QualType LHSType = LHS.get()->getType();
6972   if (IsCompAssign) LHS = OldLHS;
6973 
6974   // The RHS is simpler.
6975   RHS = UsualUnaryConversions(RHS.take());
6976   if (RHS.isInvalid())
6977     return QualType();
6978   QualType RHSType = RHS.get()->getType();
6979 
6980   // C99 6.5.7p2: Each of the operands shall have integer type.
6981   if (!LHSType->hasIntegerRepresentation() ||
6982       !RHSType->hasIntegerRepresentation())
6983     return InvalidOperands(Loc, LHS, RHS);
6984 
6985   // C++0x: Don't allow scoped enums. FIXME: Use something better than
6986   // hasIntegerRepresentation() above instead of this.
6987   if (isScopedEnumerationType(LHSType) ||
6988       isScopedEnumerationType(RHSType)) {
6989     return InvalidOperands(Loc, LHS, RHS);
6990   }
6991   // Sanity-check shift operands
6992   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
6993 
6994   // "The type of the result is that of the promoted left operand."
6995   return LHSType;
6996 }
6997 
6998 static bool IsWithinTemplateSpecialization(Decl *D) {
6999   if (DeclContext *DC = D->getDeclContext()) {
7000     if (isa<ClassTemplateSpecializationDecl>(DC))
7001       return true;
7002     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7003       return FD->isFunctionTemplateSpecialization();
7004   }
7005   return false;
7006 }
7007 
7008 /// If two different enums are compared, raise a warning.
7009 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
7010                                 Expr *RHS) {
7011   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
7012   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
7013 
7014   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
7015   if (!LHSEnumType)
7016     return;
7017   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
7018   if (!RHSEnumType)
7019     return;
7020 
7021   // Ignore anonymous enums.
7022   if (!LHSEnumType->getDecl()->getIdentifier())
7023     return;
7024   if (!RHSEnumType->getDecl()->getIdentifier())
7025     return;
7026 
7027   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
7028     return;
7029 
7030   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7031       << LHSStrippedType << RHSStrippedType
7032       << LHS->getSourceRange() << RHS->getSourceRange();
7033 }
7034 
7035 /// \brief Diagnose bad pointer comparisons.
7036 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
7037                                               ExprResult &LHS, ExprResult &RHS,
7038                                               bool IsError) {
7039   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
7040                       : diag::ext_typecheck_comparison_of_distinct_pointers)
7041     << LHS.get()->getType() << RHS.get()->getType()
7042     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7043 }
7044 
7045 /// \brief Returns false if the pointers are converted to a composite type,
7046 /// true otherwise.
7047 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
7048                                            ExprResult &LHS, ExprResult &RHS) {
7049   // C++ [expr.rel]p2:
7050   //   [...] Pointer conversions (4.10) and qualification
7051   //   conversions (4.4) are performed on pointer operands (or on
7052   //   a pointer operand and a null pointer constant) to bring
7053   //   them to their composite pointer type. [...]
7054   //
7055   // C++ [expr.eq]p1 uses the same notion for (in)equality
7056   // comparisons of pointers.
7057 
7058   // C++ [expr.eq]p2:
7059   //   In addition, pointers to members can be compared, or a pointer to
7060   //   member and a null pointer constant. Pointer to member conversions
7061   //   (4.11) and qualification conversions (4.4) are performed to bring
7062   //   them to a common type. If one operand is a null pointer constant,
7063   //   the common type is the type of the other operand. Otherwise, the
7064   //   common type is a pointer to member type similar (4.4) to the type
7065   //   of one of the operands, with a cv-qualification signature (4.4)
7066   //   that is the union of the cv-qualification signatures of the operand
7067   //   types.
7068 
7069   QualType LHSType = LHS.get()->getType();
7070   QualType RHSType = RHS.get()->getType();
7071   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
7072          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
7073 
7074   bool NonStandardCompositeType = false;
7075   bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
7076   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
7077   if (T.isNull()) {
7078     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
7079     return true;
7080   }
7081 
7082   if (NonStandardCompositeType)
7083     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
7084       << LHSType << RHSType << T << LHS.get()->getSourceRange()
7085       << RHS.get()->getSourceRange();
7086 
7087   LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
7088   RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
7089   return false;
7090 }
7091 
7092 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
7093                                                     ExprResult &LHS,
7094                                                     ExprResult &RHS,
7095                                                     bool IsError) {
7096   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
7097                       : diag::ext_typecheck_comparison_of_fptr_to_void)
7098     << LHS.get()->getType() << RHS.get()->getType()
7099     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7100 }
7101 
7102 static bool isObjCObjectLiteral(ExprResult &E) {
7103   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
7104   case Stmt::ObjCArrayLiteralClass:
7105   case Stmt::ObjCDictionaryLiteralClass:
7106   case Stmt::ObjCStringLiteralClass:
7107   case Stmt::ObjCBoxedExprClass:
7108     return true;
7109   default:
7110     // Note that ObjCBoolLiteral is NOT an object literal!
7111     return false;
7112   }
7113 }
7114 
7115 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
7116   const ObjCObjectPointerType *Type =
7117     LHS->getType()->getAs<ObjCObjectPointerType>();
7118 
7119   // If this is not actually an Objective-C object, bail out.
7120   if (!Type)
7121     return false;
7122 
7123   // Get the LHS object's interface type.
7124   QualType InterfaceType = Type->getPointeeType();
7125   if (const ObjCObjectType *iQFaceTy =
7126       InterfaceType->getAsObjCQualifiedInterfaceType())
7127     InterfaceType = iQFaceTy->getBaseType();
7128 
7129   // If the RHS isn't an Objective-C object, bail out.
7130   if (!RHS->getType()->isObjCObjectPointerType())
7131     return false;
7132 
7133   // Try to find the -isEqual: method.
7134   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
7135   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
7136                                                       InterfaceType,
7137                                                       /*instance=*/true);
7138   if (!Method) {
7139     if (Type->isObjCIdType()) {
7140       // For 'id', just check the global pool.
7141       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
7142                                                   /*receiverId=*/true,
7143                                                   /*warn=*/false);
7144     } else {
7145       // Check protocols.
7146       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
7147                                              /*instance=*/true);
7148     }
7149   }
7150 
7151   if (!Method)
7152     return false;
7153 
7154   QualType T = Method->param_begin()[0]->getType();
7155   if (!T->isObjCObjectPointerType())
7156     return false;
7157 
7158   QualType R = Method->getResultType();
7159   if (!R->isScalarType())
7160     return false;
7161 
7162   return true;
7163 }
7164 
7165 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
7166   FromE = FromE->IgnoreParenImpCasts();
7167   switch (FromE->getStmtClass()) {
7168     default:
7169       break;
7170     case Stmt::ObjCStringLiteralClass:
7171       // "string literal"
7172       return LK_String;
7173     case Stmt::ObjCArrayLiteralClass:
7174       // "array literal"
7175       return LK_Array;
7176     case Stmt::ObjCDictionaryLiteralClass:
7177       // "dictionary literal"
7178       return LK_Dictionary;
7179     case Stmt::BlockExprClass:
7180       return LK_Block;
7181     case Stmt::ObjCBoxedExprClass: {
7182       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
7183       switch (Inner->getStmtClass()) {
7184         case Stmt::IntegerLiteralClass:
7185         case Stmt::FloatingLiteralClass:
7186         case Stmt::CharacterLiteralClass:
7187         case Stmt::ObjCBoolLiteralExprClass:
7188         case Stmt::CXXBoolLiteralExprClass:
7189           // "numeric literal"
7190           return LK_Numeric;
7191         case Stmt::ImplicitCastExprClass: {
7192           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
7193           // Boolean literals can be represented by implicit casts.
7194           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
7195             return LK_Numeric;
7196           break;
7197         }
7198         default:
7199           break;
7200       }
7201       return LK_Boxed;
7202     }
7203   }
7204   return LK_None;
7205 }
7206 
7207 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
7208                                           ExprResult &LHS, ExprResult &RHS,
7209                                           BinaryOperator::Opcode Opc){
7210   Expr *Literal;
7211   Expr *Other;
7212   if (isObjCObjectLiteral(LHS)) {
7213     Literal = LHS.get();
7214     Other = RHS.get();
7215   } else {
7216     Literal = RHS.get();
7217     Other = LHS.get();
7218   }
7219 
7220   // Don't warn on comparisons against nil.
7221   Other = Other->IgnoreParenCasts();
7222   if (Other->isNullPointerConstant(S.getASTContext(),
7223                                    Expr::NPC_ValueDependentIsNotNull))
7224     return;
7225 
7226   // This should be kept in sync with warn_objc_literal_comparison.
7227   // LK_String should always be after the other literals, since it has its own
7228   // warning flag.
7229   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
7230   assert(LiteralKind != Sema::LK_Block);
7231   if (LiteralKind == Sema::LK_None) {
7232     llvm_unreachable("Unknown Objective-C object literal kind");
7233   }
7234 
7235   if (LiteralKind == Sema::LK_String)
7236     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7237       << Literal->getSourceRange();
7238   else
7239     S.Diag(Loc, diag::warn_objc_literal_comparison)
7240       << LiteralKind << Literal->getSourceRange();
7241 
7242   if (BinaryOperator::isEqualityOp(Opc) &&
7243       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7244     SourceLocation Start = LHS.get()->getLocStart();
7245     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
7246     CharSourceRange OpRange =
7247       CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
7248 
7249     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7250       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
7251       << FixItHint::CreateReplacement(OpRange, " isEqual:")
7252       << FixItHint::CreateInsertion(End, "]");
7253   }
7254 }
7255 
7256 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
7257                                                 ExprResult &RHS,
7258                                                 SourceLocation Loc,
7259                                                 unsigned OpaqueOpc) {
7260   // This checking requires bools.
7261   if (!S.getLangOpts().Bool) return;
7262 
7263   // Check that left hand side is !something.
7264   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get());
7265   if (!UO || UO->getOpcode() != UO_LNot) return;
7266 
7267   // Only check if the right hand side is non-bool arithmetic type.
7268   if (RHS.get()->getType()->isBooleanType()) return;
7269 
7270   // Make sure that the something in !something is not bool.
7271   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
7272   if (SubExpr->getType()->isBooleanType()) return;
7273 
7274   // Emit warning.
7275   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
7276       << Loc;
7277 
7278   // First note suggest !(x < y)
7279   SourceLocation FirstOpen = SubExpr->getLocStart();
7280   SourceLocation FirstClose = RHS.get()->getLocEnd();
7281   FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
7282   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
7283       << FixItHint::CreateInsertion(FirstOpen, "(")
7284       << FixItHint::CreateInsertion(FirstClose, ")");
7285 
7286   // Second note suggests (!x) < y
7287   SourceLocation SecondOpen = LHS.get()->getLocStart();
7288   SourceLocation SecondClose = LHS.get()->getLocEnd();
7289   SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
7290   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
7291       << FixItHint::CreateInsertion(SecondOpen, "(")
7292       << FixItHint::CreateInsertion(SecondClose, ")");
7293 }
7294 
7295 // C99 6.5.8, C++ [expr.rel]
7296 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
7297                                     SourceLocation Loc, unsigned OpaqueOpc,
7298                                     bool IsRelational) {
7299   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7300 
7301   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7302 
7303   // Handle vector comparisons separately.
7304   if (LHS.get()->getType()->isVectorType() ||
7305       RHS.get()->getType()->isVectorType())
7306     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
7307 
7308   QualType LHSType = LHS.get()->getType();
7309   QualType RHSType = RHS.get()->getType();
7310 
7311   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7312   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
7313 
7314   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
7315   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
7316 
7317   if (!LHSType->hasFloatingRepresentation() &&
7318       !(LHSType->isBlockPointerType() && IsRelational) &&
7319       !LHS.get()->getLocStart().isMacroID() &&
7320       !RHS.get()->getLocStart().isMacroID()) {
7321     // For non-floating point types, check for self-comparisons of the form
7322     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7323     // often indicate logic errors in the program.
7324     //
7325     // NOTE: Don't warn about comparison expressions resulting from macro
7326     // expansion. Also don't warn about comparisons which are only self
7327     // comparisons within a template specialization. The warnings should catch
7328     // obvious cases in the definition of the template anyways. The idea is to
7329     // warn when the typed comparison operator will always evaluate to the same
7330     // result.
7331     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
7332       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
7333         if (DRL->getDecl() == DRR->getDecl() &&
7334             !IsWithinTemplateSpecialization(DRL->getDecl())) {
7335           DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7336                               << 0 // self-
7337                               << (Opc == BO_EQ
7338                                   || Opc == BO_LE
7339                                   || Opc == BO_GE));
7340         } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
7341                    !DRL->getDecl()->getType()->isReferenceType() &&
7342                    !DRR->getDecl()->getType()->isReferenceType()) {
7343             // what is it always going to eval to?
7344             char always_evals_to;
7345             switch(Opc) {
7346             case BO_EQ: // e.g. array1 == array2
7347               always_evals_to = 0; // false
7348               break;
7349             case BO_NE: // e.g. array1 != array2
7350               always_evals_to = 1; // true
7351               break;
7352             default:
7353               // best we can say is 'a constant'
7354               always_evals_to = 2; // e.g. array1 <= array2
7355               break;
7356             }
7357             DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7358                                 << 1 // array
7359                                 << always_evals_to);
7360         }
7361       }
7362     }
7363 
7364     if (isa<CastExpr>(LHSStripped))
7365       LHSStripped = LHSStripped->IgnoreParenCasts();
7366     if (isa<CastExpr>(RHSStripped))
7367       RHSStripped = RHSStripped->IgnoreParenCasts();
7368 
7369     // Warn about comparisons against a string constant (unless the other
7370     // operand is null), the user probably wants strcmp.
7371     Expr *literalString = 0;
7372     Expr *literalStringStripped = 0;
7373     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7374         !RHSStripped->isNullPointerConstant(Context,
7375                                             Expr::NPC_ValueDependentIsNull)) {
7376       literalString = LHS.get();
7377       literalStringStripped = LHSStripped;
7378     } else if ((isa<StringLiteral>(RHSStripped) ||
7379                 isa<ObjCEncodeExpr>(RHSStripped)) &&
7380                !LHSStripped->isNullPointerConstant(Context,
7381                                             Expr::NPC_ValueDependentIsNull)) {
7382       literalString = RHS.get();
7383       literalStringStripped = RHSStripped;
7384     }
7385 
7386     if (literalString) {
7387       DiagRuntimeBehavior(Loc, 0,
7388         PDiag(diag::warn_stringcompare)
7389           << isa<ObjCEncodeExpr>(literalStringStripped)
7390           << literalString->getSourceRange());
7391     }
7392   }
7393 
7394   // C99 6.5.8p3 / C99 6.5.9p4
7395   if (LHS.get()->getType()->isArithmeticType() &&
7396       RHS.get()->getType()->isArithmeticType()) {
7397     UsualArithmeticConversions(LHS, RHS);
7398     if (LHS.isInvalid() || RHS.isInvalid())
7399       return QualType();
7400   }
7401   else {
7402     LHS = UsualUnaryConversions(LHS.take());
7403     if (LHS.isInvalid())
7404       return QualType();
7405 
7406     RHS = UsualUnaryConversions(RHS.take());
7407     if (RHS.isInvalid())
7408       return QualType();
7409   }
7410 
7411   LHSType = LHS.get()->getType();
7412   RHSType = RHS.get()->getType();
7413 
7414   // The result of comparisons is 'bool' in C++, 'int' in C.
7415   QualType ResultTy = Context.getLogicalOperationType();
7416 
7417   if (IsRelational) {
7418     if (LHSType->isRealType() && RHSType->isRealType())
7419       return ResultTy;
7420   } else {
7421     // Check for comparisons of floating point operands using != and ==.
7422     if (LHSType->hasFloatingRepresentation())
7423       CheckFloatComparison(Loc, LHS.get(), RHS.get());
7424 
7425     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7426       return ResultTy;
7427   }
7428 
7429   bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
7430                                               Expr::NPC_ValueDependentIsNull);
7431   bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
7432                                               Expr::NPC_ValueDependentIsNull);
7433 
7434   // All of the following pointer-related warnings are GCC extensions, except
7435   // when handling null pointer constants.
7436   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7437     QualType LCanPointeeTy =
7438       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7439     QualType RCanPointeeTy =
7440       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7441 
7442     if (getLangOpts().CPlusPlus) {
7443       if (LCanPointeeTy == RCanPointeeTy)
7444         return ResultTy;
7445       if (!IsRelational &&
7446           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7447         // Valid unless comparison between non-null pointer and function pointer
7448         // This is a gcc extension compatibility comparison.
7449         // In a SFINAE context, we treat this as a hard error to maintain
7450         // conformance with the C++ standard.
7451         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7452             && !LHSIsNull && !RHSIsNull) {
7453           diagnoseFunctionPointerToVoidComparison(
7454               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
7455 
7456           if (isSFINAEContext())
7457             return QualType();
7458 
7459           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7460           return ResultTy;
7461         }
7462       }
7463 
7464       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7465         return QualType();
7466       else
7467         return ResultTy;
7468     }
7469     // C99 6.5.9p2 and C99 6.5.8p2
7470     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7471                                    RCanPointeeTy.getUnqualifiedType())) {
7472       // Valid unless a relational comparison of function pointers
7473       if (IsRelational && LCanPointeeTy->isFunctionType()) {
7474         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7475           << LHSType << RHSType << LHS.get()->getSourceRange()
7476           << RHS.get()->getSourceRange();
7477       }
7478     } else if (!IsRelational &&
7479                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7480       // Valid unless comparison between non-null pointer and function pointer
7481       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7482           && !LHSIsNull && !RHSIsNull)
7483         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
7484                                                 /*isError*/false);
7485     } else {
7486       // Invalid
7487       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
7488     }
7489     if (LCanPointeeTy != RCanPointeeTy) {
7490       if (LHSIsNull && !RHSIsNull)
7491         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7492       else
7493         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7494     }
7495     return ResultTy;
7496   }
7497 
7498   if (getLangOpts().CPlusPlus) {
7499     // Comparison of nullptr_t with itself.
7500     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
7501       return ResultTy;
7502 
7503     // Comparison of pointers with null pointer constants and equality
7504     // comparisons of member pointers to null pointer constants.
7505     if (RHSIsNull &&
7506         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
7507          (!IsRelational &&
7508           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7509       RHS = ImpCastExprToType(RHS.take(), LHSType,
7510                         LHSType->isMemberPointerType()
7511                           ? CK_NullToMemberPointer
7512                           : CK_NullToPointer);
7513       return ResultTy;
7514     }
7515     if (LHSIsNull &&
7516         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
7517          (!IsRelational &&
7518           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7519       LHS = ImpCastExprToType(LHS.take(), RHSType,
7520                         RHSType->isMemberPointerType()
7521                           ? CK_NullToMemberPointer
7522                           : CK_NullToPointer);
7523       return ResultTy;
7524     }
7525 
7526     // Comparison of member pointers.
7527     if (!IsRelational &&
7528         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7529       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7530         return QualType();
7531       else
7532         return ResultTy;
7533     }
7534 
7535     // Handle scoped enumeration types specifically, since they don't promote
7536     // to integers.
7537     if (LHS.get()->getType()->isEnumeralType() &&
7538         Context.hasSameUnqualifiedType(LHS.get()->getType(),
7539                                        RHS.get()->getType()))
7540       return ResultTy;
7541   }
7542 
7543   // Handle block pointer types.
7544   if (!IsRelational && LHSType->isBlockPointerType() &&
7545       RHSType->isBlockPointerType()) {
7546     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7547     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
7548 
7549     if (!LHSIsNull && !RHSIsNull &&
7550         !Context.typesAreCompatible(lpointee, rpointee)) {
7551       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7552         << LHSType << RHSType << LHS.get()->getSourceRange()
7553         << RHS.get()->getSourceRange();
7554     }
7555     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7556     return ResultTy;
7557   }
7558 
7559   // Allow block pointers to be compared with null pointer constants.
7560   if (!IsRelational
7561       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7562           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
7563     if (!LHSIsNull && !RHSIsNull) {
7564       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
7565              ->getPointeeType()->isVoidType())
7566             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
7567                 ->getPointeeType()->isVoidType())))
7568         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7569           << LHSType << RHSType << LHS.get()->getSourceRange()
7570           << RHS.get()->getSourceRange();
7571     }
7572     if (LHSIsNull && !RHSIsNull)
7573       LHS = ImpCastExprToType(LHS.take(), RHSType,
7574                               RHSType->isPointerType() ? CK_BitCast
7575                                 : CK_AnyPointerToBlockPointerCast);
7576     else
7577       RHS = ImpCastExprToType(RHS.take(), LHSType,
7578                               LHSType->isPointerType() ? CK_BitCast
7579                                 : CK_AnyPointerToBlockPointerCast);
7580     return ResultTy;
7581   }
7582 
7583   if (LHSType->isObjCObjectPointerType() ||
7584       RHSType->isObjCObjectPointerType()) {
7585     const PointerType *LPT = LHSType->getAs<PointerType>();
7586     const PointerType *RPT = RHSType->getAs<PointerType>();
7587     if (LPT || RPT) {
7588       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7589       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
7590 
7591       if (!LPtrToVoid && !RPtrToVoid &&
7592           !Context.typesAreCompatible(LHSType, RHSType)) {
7593         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7594                                           /*isError*/false);
7595       }
7596       if (LHSIsNull && !RHSIsNull)
7597         LHS = ImpCastExprToType(LHS.take(), RHSType,
7598                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7599       else
7600         RHS = ImpCastExprToType(RHS.take(), LHSType,
7601                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7602       return ResultTy;
7603     }
7604     if (LHSType->isObjCObjectPointerType() &&
7605         RHSType->isObjCObjectPointerType()) {
7606       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7607         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7608                                           /*isError*/false);
7609       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7610         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
7611 
7612       if (LHSIsNull && !RHSIsNull)
7613         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7614       else
7615         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7616       return ResultTy;
7617     }
7618   }
7619   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7620       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
7621     unsigned DiagID = 0;
7622     bool isError = false;
7623     if (LangOpts.DebuggerSupport) {
7624       // Under a debugger, allow the comparison of pointers to integers,
7625       // since users tend to want to compare addresses.
7626     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
7627         (RHSIsNull && RHSType->isIntegerType())) {
7628       if (IsRelational && !getLangOpts().CPlusPlus)
7629         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
7630     } else if (IsRelational && !getLangOpts().CPlusPlus)
7631       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
7632     else if (getLangOpts().CPlusPlus) {
7633       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7634       isError = true;
7635     } else
7636       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
7637 
7638     if (DiagID) {
7639       Diag(Loc, DiagID)
7640         << LHSType << RHSType << LHS.get()->getSourceRange()
7641         << RHS.get()->getSourceRange();
7642       if (isError)
7643         return QualType();
7644     }
7645 
7646     if (LHSType->isIntegerType())
7647       LHS = ImpCastExprToType(LHS.take(), RHSType,
7648                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7649     else
7650       RHS = ImpCastExprToType(RHS.take(), LHSType,
7651                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7652     return ResultTy;
7653   }
7654 
7655   // Handle block pointers.
7656   if (!IsRelational && RHSIsNull
7657       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7658     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
7659     return ResultTy;
7660   }
7661   if (!IsRelational && LHSIsNull
7662       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7663     LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
7664     return ResultTy;
7665   }
7666 
7667   return InvalidOperands(Loc, LHS, RHS);
7668 }
7669 
7670 
7671 // Return a signed type that is of identical size and number of elements.
7672 // For floating point vectors, return an integer type of identical size
7673 // and number of elements.
7674 QualType Sema::GetSignedVectorType(QualType V) {
7675   const VectorType *VTy = V->getAs<VectorType>();
7676   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7677   if (TypeSize == Context.getTypeSize(Context.CharTy))
7678     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7679   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7680     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7681   else if (TypeSize == Context.getTypeSize(Context.IntTy))
7682     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7683   else if (TypeSize == Context.getTypeSize(Context.LongTy))
7684     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7685   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7686          "Unhandled vector element size in vector compare");
7687   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7688 }
7689 
7690 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7691 /// operates on extended vector types.  Instead of producing an IntTy result,
7692 /// like a scalar comparison, a vector comparison produces a vector of integer
7693 /// types.
7694 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7695                                           SourceLocation Loc,
7696                                           bool IsRelational) {
7697   // Check to make sure we're operating on vectors of the same type and width,
7698   // Allowing one side to be a scalar of element type.
7699   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
7700   if (vType.isNull())
7701     return vType;
7702 
7703   QualType LHSType = LHS.get()->getType();
7704 
7705   // If AltiVec, the comparison results in a numeric type, i.e.
7706   // bool for C++, int for C
7707   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
7708     return Context.getLogicalOperationType();
7709 
7710   // For non-floating point types, check for self-comparisons of the form
7711   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7712   // often indicate logic errors in the program.
7713   if (!LHSType->hasFloatingRepresentation()) {
7714     if (DeclRefExpr* DRL
7715           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7716       if (DeclRefExpr* DRR
7717             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
7718         if (DRL->getDecl() == DRR->getDecl())
7719           DiagRuntimeBehavior(Loc, 0,
7720                               PDiag(diag::warn_comparison_always)
7721                                 << 0 // self-
7722                                 << 2 // "a constant"
7723                               );
7724   }
7725 
7726   // Check for comparisons of floating point operands using != and ==.
7727   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
7728     assert (RHS.get()->getType()->hasFloatingRepresentation());
7729     CheckFloatComparison(Loc, LHS.get(), RHS.get());
7730   }
7731 
7732   // Return a signed type for the vector.
7733   return GetSignedVectorType(LHSType);
7734 }
7735 
7736 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7737                                           SourceLocation Loc) {
7738   // Ensure that either both operands are of the same vector type, or
7739   // one operand is of a vector type and the other is of its element type.
7740   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7741   if (vType.isNull())
7742     return InvalidOperands(Loc, LHS, RHS);
7743   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
7744       vType->hasFloatingRepresentation())
7745     return InvalidOperands(Loc, LHS, RHS);
7746 
7747   return GetSignedVectorType(LHS.get()->getType());
7748 }
7749 
7750 inline QualType Sema::CheckBitwiseOperands(
7751   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7752   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7753 
7754   if (LHS.get()->getType()->isVectorType() ||
7755       RHS.get()->getType()->isVectorType()) {
7756     if (LHS.get()->getType()->hasIntegerRepresentation() &&
7757         RHS.get()->getType()->hasIntegerRepresentation())
7758       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7759 
7760     return InvalidOperands(Loc, LHS, RHS);
7761   }
7762 
7763   ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7764   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
7765                                                  IsCompAssign);
7766   if (LHSResult.isInvalid() || RHSResult.isInvalid())
7767     return QualType();
7768   LHS = LHSResult.take();
7769   RHS = RHSResult.take();
7770 
7771   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
7772     return compType;
7773   return InvalidOperands(Loc, LHS, RHS);
7774 }
7775 
7776 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
7777   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
7778 
7779   // Check vector operands differently.
7780   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7781     return CheckVectorLogicalOperands(LHS, RHS, Loc);
7782 
7783   // Diagnose cases where the user write a logical and/or but probably meant a
7784   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
7785   // is a constant.
7786   if (LHS.get()->getType()->isIntegerType() &&
7787       !LHS.get()->getType()->isBooleanType() &&
7788       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
7789       // Don't warn in macros or template instantiations.
7790       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
7791     // If the RHS can be constant folded, and if it constant folds to something
7792     // that isn't 0 or 1 (which indicate a potential logical operation that
7793     // happened to fold to true/false) then warn.
7794     // Parens on the RHS are ignored.
7795     llvm::APSInt Result;
7796     if (RHS.get()->EvaluateAsInt(Result, Context))
7797       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
7798           (Result != 0 && Result != 1)) {
7799         Diag(Loc, diag::warn_logical_instead_of_bitwise)
7800           << RHS.get()->getSourceRange()
7801           << (Opc == BO_LAnd ? "&&" : "||");
7802         // Suggest replacing the logical operator with the bitwise version
7803         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7804             << (Opc == BO_LAnd ? "&" : "|")
7805             << FixItHint::CreateReplacement(SourceRange(
7806                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
7807                                                 getLangOpts())),
7808                                             Opc == BO_LAnd ? "&" : "|");
7809         if (Opc == BO_LAnd)
7810           // Suggest replacing "Foo() && kNonZero" with "Foo()"
7811           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7812               << FixItHint::CreateRemoval(
7813                   SourceRange(
7814                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
7815                                                  0, getSourceManager(),
7816                                                  getLangOpts()),
7817                       RHS.get()->getLocEnd()));
7818       }
7819   }
7820 
7821   if (!Context.getLangOpts().CPlusPlus) {
7822     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
7823     // not operate on the built-in scalar and vector float types.
7824     if (Context.getLangOpts().OpenCL &&
7825         Context.getLangOpts().OpenCLVersion < 120) {
7826       if (LHS.get()->getType()->isFloatingType() ||
7827           RHS.get()->getType()->isFloatingType())
7828         return InvalidOperands(Loc, LHS, RHS);
7829     }
7830 
7831     LHS = UsualUnaryConversions(LHS.take());
7832     if (LHS.isInvalid())
7833       return QualType();
7834 
7835     RHS = UsualUnaryConversions(RHS.take());
7836     if (RHS.isInvalid())
7837       return QualType();
7838 
7839     if (!LHS.get()->getType()->isScalarType() ||
7840         !RHS.get()->getType()->isScalarType())
7841       return InvalidOperands(Loc, LHS, RHS);
7842 
7843     return Context.IntTy;
7844   }
7845 
7846   // The following is safe because we only use this method for
7847   // non-overloadable operands.
7848 
7849   // C++ [expr.log.and]p1
7850   // C++ [expr.log.or]p1
7851   // The operands are both contextually converted to type bool.
7852   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7853   if (LHSRes.isInvalid())
7854     return InvalidOperands(Loc, LHS, RHS);
7855   LHS = LHSRes;
7856 
7857   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7858   if (RHSRes.isInvalid())
7859     return InvalidOperands(Loc, LHS, RHS);
7860   RHS = RHSRes;
7861 
7862   // C++ [expr.log.and]p2
7863   // C++ [expr.log.or]p2
7864   // The result is a bool.
7865   return Context.BoolTy;
7866 }
7867 
7868 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7869 /// is a read-only property; return true if so. A readonly property expression
7870 /// depends on various declarations and thus must be treated specially.
7871 ///
7872 static bool IsReadonlyProperty(Expr *E, Sema &S) {
7873   const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7874   if (!PropExpr) return false;
7875   if (PropExpr->isImplicitProperty()) return false;
7876 
7877   ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7878   QualType BaseType = PropExpr->isSuperReceiver() ?
7879                             PropExpr->getSuperReceiverType() :
7880                             PropExpr->getBase()->getType();
7881 
7882   if (const ObjCObjectPointerType *OPT =
7883       BaseType->getAsObjCInterfacePointerType())
7884     if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7885       if (S.isPropertyReadonly(PDecl, IFace))
7886         return true;
7887   return false;
7888 }
7889 
7890 static bool IsReadonlyMessage(Expr *E, Sema &S) {
7891   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7892   if (!ME) return false;
7893   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7894   ObjCMessageExpr *Base =
7895     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7896   if (!Base) return false;
7897   return Base->getMethodDecl() != 0;
7898 }
7899 
7900 /// Is the given expression (which must be 'const') a reference to a
7901 /// variable which was originally non-const, but which has become
7902 /// 'const' due to being captured within a block?
7903 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7904 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7905   assert(E->isLValue() && E->getType().isConstQualified());
7906   E = E->IgnoreParens();
7907 
7908   // Must be a reference to a declaration from an enclosing scope.
7909   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7910   if (!DRE) return NCCK_None;
7911   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7912 
7913   // The declaration must be a variable which is not declared 'const'.
7914   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7915   if (!var) return NCCK_None;
7916   if (var->getType().isConstQualified()) return NCCK_None;
7917   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7918 
7919   // Decide whether the first capture was for a block or a lambda.
7920   DeclContext *DC = S.CurContext;
7921   while (DC->getParent() != var->getDeclContext())
7922     DC = DC->getParent();
7923   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7924 }
7925 
7926 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
7927 /// emit an error and return true.  If so, return false.
7928 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
7929   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
7930   SourceLocation OrigLoc = Loc;
7931   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
7932                                                               &Loc);
7933   if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7934     IsLV = Expr::MLV_ReadonlyProperty;
7935   else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7936     IsLV = Expr::MLV_InvalidMessageExpression;
7937   if (IsLV == Expr::MLV_Valid)
7938     return false;
7939 
7940   unsigned Diag = 0;
7941   bool NeedType = false;
7942   switch (IsLV) { // C99 6.5.16p2
7943   case Expr::MLV_ConstQualified:
7944     Diag = diag::err_typecheck_assign_const;
7945 
7946     // Use a specialized diagnostic when we're assigning to an object
7947     // from an enclosing function or block.
7948     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7949       if (NCCK == NCCK_Block)
7950         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7951       else
7952         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7953       break;
7954     }
7955 
7956     // In ARC, use some specialized diagnostics for occasions where we
7957     // infer 'const'.  These are always pseudo-strong variables.
7958     if (S.getLangOpts().ObjCAutoRefCount) {
7959       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7960       if (declRef && isa<VarDecl>(declRef->getDecl())) {
7961         VarDecl *var = cast<VarDecl>(declRef->getDecl());
7962 
7963         // Use the normal diagnostic if it's pseudo-__strong but the
7964         // user actually wrote 'const'.
7965         if (var->isARCPseudoStrong() &&
7966             (!var->getTypeSourceInfo() ||
7967              !var->getTypeSourceInfo()->getType().isConstQualified())) {
7968           // There are two pseudo-strong cases:
7969           //  - self
7970           ObjCMethodDecl *method = S.getCurMethodDecl();
7971           if (method && var == method->getSelfDecl())
7972             Diag = method->isClassMethod()
7973               ? diag::err_typecheck_arc_assign_self_class_method
7974               : diag::err_typecheck_arc_assign_self;
7975 
7976           //  - fast enumeration variables
7977           else
7978             Diag = diag::err_typecheck_arr_assign_enumeration;
7979 
7980           SourceRange Assign;
7981           if (Loc != OrigLoc)
7982             Assign = SourceRange(OrigLoc, OrigLoc);
7983           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7984           // We need to preserve the AST regardless, so migration tool
7985           // can do its job.
7986           return false;
7987         }
7988       }
7989     }
7990 
7991     break;
7992   case Expr::MLV_ArrayType:
7993   case Expr::MLV_ArrayTemporary:
7994     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7995     NeedType = true;
7996     break;
7997   case Expr::MLV_NotObjectType:
7998     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7999     NeedType = true;
8000     break;
8001   case Expr::MLV_LValueCast:
8002     Diag = diag::err_typecheck_lvalue_casts_not_supported;
8003     break;
8004   case Expr::MLV_Valid:
8005     llvm_unreachable("did not take early return for MLV_Valid");
8006   case Expr::MLV_InvalidExpression:
8007   case Expr::MLV_MemberFunction:
8008   case Expr::MLV_ClassTemporary:
8009     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8010     break;
8011   case Expr::MLV_IncompleteType:
8012   case Expr::MLV_IncompleteVoidType:
8013     return S.RequireCompleteType(Loc, E->getType(),
8014              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
8015   case Expr::MLV_DuplicateVectorComponents:
8016     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8017     break;
8018   case Expr::MLV_ReadonlyProperty:
8019   case Expr::MLV_NoSetterProperty:
8020     llvm_unreachable("readonly properties should be processed differently");
8021   case Expr::MLV_InvalidMessageExpression:
8022     Diag = diag::error_readonly_message_assignment;
8023     break;
8024   case Expr::MLV_SubObjCPropertySetting:
8025     Diag = diag::error_no_subobject_property_setting;
8026     break;
8027   }
8028 
8029   SourceRange Assign;
8030   if (Loc != OrigLoc)
8031     Assign = SourceRange(OrigLoc, OrigLoc);
8032   if (NeedType)
8033     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
8034   else
8035     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8036   return true;
8037 }
8038 
8039 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
8040                                          SourceLocation Loc,
8041                                          Sema &Sema) {
8042   // C / C++ fields
8043   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
8044   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
8045   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
8046     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
8047       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
8048   }
8049 
8050   // Objective-C instance variables
8051   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
8052   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
8053   if (OL && OR && OL->getDecl() == OR->getDecl()) {
8054     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
8055     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
8056     if (RL && RR && RL->getDecl() == RR->getDecl())
8057       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
8058   }
8059 }
8060 
8061 // C99 6.5.16.1
8062 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
8063                                        SourceLocation Loc,
8064                                        QualType CompoundType) {
8065   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
8066 
8067   // Verify that LHS is a modifiable lvalue, and emit error if not.
8068   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
8069     return QualType();
8070 
8071   QualType LHSType = LHSExpr->getType();
8072   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
8073                                              CompoundType;
8074   AssignConvertType ConvTy;
8075   if (CompoundType.isNull()) {
8076     Expr *RHSCheck = RHS.get();
8077 
8078     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
8079 
8080     QualType LHSTy(LHSType);
8081     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
8082     if (RHS.isInvalid())
8083       return QualType();
8084     // Special case of NSObject attributes on c-style pointer types.
8085     if (ConvTy == IncompatiblePointer &&
8086         ((Context.isObjCNSObjectType(LHSType) &&
8087           RHSType->isObjCObjectPointerType()) ||
8088          (Context.isObjCNSObjectType(RHSType) &&
8089           LHSType->isObjCObjectPointerType())))
8090       ConvTy = Compatible;
8091 
8092     if (ConvTy == Compatible &&
8093         LHSType->isObjCObjectType())
8094         Diag(Loc, diag::err_objc_object_assignment)
8095           << LHSType;
8096 
8097     // If the RHS is a unary plus or minus, check to see if they = and + are
8098     // right next to each other.  If so, the user may have typo'd "x =+ 4"
8099     // instead of "x += 4".
8100     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8101       RHSCheck = ICE->getSubExpr();
8102     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
8103       if ((UO->getOpcode() == UO_Plus ||
8104            UO->getOpcode() == UO_Minus) &&
8105           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
8106           // Only if the two operators are exactly adjacent.
8107           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
8108           // And there is a space or other character before the subexpr of the
8109           // unary +/-.  We don't want to warn on "x=-1".
8110           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8111           UO->getSubExpr()->getLocStart().isFileID()) {
8112         Diag(Loc, diag::warn_not_compound_assign)
8113           << (UO->getOpcode() == UO_Plus ? "+" : "-")
8114           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
8115       }
8116     }
8117 
8118     if (ConvTy == Compatible) {
8119       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
8120         // Warn about retain cycles where a block captures the LHS, but
8121         // not if the LHS is a simple variable into which the block is
8122         // being stored...unless that variable can be captured by reference!
8123         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
8124         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
8125         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
8126           checkRetainCycles(LHSExpr, RHS.get());
8127 
8128         // It is safe to assign a weak reference into a strong variable.
8129         // Although this code can still have problems:
8130         //   id x = self.weakProp;
8131         //   id y = self.weakProp;
8132         // we do not warn to warn spuriously when 'x' and 'y' are on separate
8133         // paths through the function. This should be revisited if
8134         // -Wrepeated-use-of-weak is made flow-sensitive.
8135         DiagnosticsEngine::Level Level =
8136           Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8137                                    RHS.get()->getLocStart());
8138         if (Level != DiagnosticsEngine::Ignored)
8139           getCurFunction()->markSafeWeakUse(RHS.get());
8140 
8141       } else if (getLangOpts().ObjCAutoRefCount) {
8142         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
8143       }
8144     }
8145   } else {
8146     // Compound assignment "x += y"
8147     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
8148   }
8149 
8150   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
8151                                RHS.get(), AA_Assigning))
8152     return QualType();
8153 
8154   CheckForNullPointerDereference(*this, LHSExpr);
8155 
8156   // C99 6.5.16p3: The type of an assignment expression is the type of the
8157   // left operand unless the left operand has qualified type, in which case
8158   // it is the unqualified version of the type of the left operand.
8159   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8160   // is converted to the type of the assignment expression (above).
8161   // C++ 5.17p1: the type of the assignment expression is that of its left
8162   // operand.
8163   return (getLangOpts().CPlusPlus
8164           ? LHSType : LHSType.getUnqualifiedType());
8165 }
8166 
8167 // C99 6.5.17
8168 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
8169                                    SourceLocation Loc) {
8170   LHS = S.CheckPlaceholderExpr(LHS.take());
8171   RHS = S.CheckPlaceholderExpr(RHS.take());
8172   if (LHS.isInvalid() || RHS.isInvalid())
8173     return QualType();
8174 
8175   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8176   // operands, but not unary promotions.
8177   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
8178 
8179   // So we treat the LHS as a ignored value, and in C++ we allow the
8180   // containing site to determine what should be done with the RHS.
8181   LHS = S.IgnoredValueConversions(LHS.take());
8182   if (LHS.isInvalid())
8183     return QualType();
8184 
8185   S.DiagnoseUnusedExprResult(LHS.get());
8186 
8187   if (!S.getLangOpts().CPlusPlus) {
8188     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8189     if (RHS.isInvalid())
8190       return QualType();
8191     if (!RHS.get()->getType()->isVoidType())
8192       S.RequireCompleteType(Loc, RHS.get()->getType(),
8193                             diag::err_incomplete_type);
8194   }
8195 
8196   return RHS.get()->getType();
8197 }
8198 
8199 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8200 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
8201 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8202                                                ExprValueKind &VK,
8203                                                SourceLocation OpLoc,
8204                                                bool IsInc, bool IsPrefix) {
8205   if (Op->isTypeDependent())
8206     return S.Context.DependentTy;
8207 
8208   QualType ResType = Op->getType();
8209   // Atomic types can be used for increment / decrement where the non-atomic
8210   // versions can, so ignore the _Atomic() specifier for the purpose of
8211   // checking.
8212   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8213     ResType = ResAtomicType->getValueType();
8214 
8215   assert(!ResType.isNull() && "no type for increment/decrement expression");
8216 
8217   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
8218     // Decrement of bool is not allowed.
8219     if (!IsInc) {
8220       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8221       return QualType();
8222     }
8223     // Increment of bool sets it to true, but is deprecated.
8224     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8225   } else if (ResType->isRealType()) {
8226     // OK!
8227   } else if (ResType->isPointerType()) {
8228     // C99 6.5.2.4p2, 6.5.6p2
8229     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
8230       return QualType();
8231   } else if (ResType->isObjCObjectPointerType()) {
8232     // On modern runtimes, ObjC pointer arithmetic is forbidden.
8233     // Otherwise, we just need a complete type.
8234     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8235         checkArithmeticOnObjCPointer(S, OpLoc, Op))
8236       return QualType();
8237   } else if (ResType->isAnyComplexType()) {
8238     // C99 does not support ++/-- on complex types, we allow as an extension.
8239     S.Diag(OpLoc, diag::ext_integer_increment_complex)
8240       << ResType << Op->getSourceRange();
8241   } else if (ResType->isPlaceholderType()) {
8242     ExprResult PR = S.CheckPlaceholderExpr(Op);
8243     if (PR.isInvalid()) return QualType();
8244     return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8245                                           IsInc, IsPrefix);
8246   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
8247     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8248   } else {
8249     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8250       << ResType << int(IsInc) << Op->getSourceRange();
8251     return QualType();
8252   }
8253   // At this point, we know we have a real, complex or pointer type.
8254   // Now make sure the operand is a modifiable lvalue.
8255   if (CheckForModifiableLvalue(Op, OpLoc, S))
8256     return QualType();
8257   // In C++, a prefix increment is the same type as the operand. Otherwise
8258   // (in C or with postfix), the increment is the unqualified type of the
8259   // operand.
8260   if (IsPrefix && S.getLangOpts().CPlusPlus) {
8261     VK = VK_LValue;
8262     return ResType;
8263   } else {
8264     VK = VK_RValue;
8265     return ResType.getUnqualifiedType();
8266   }
8267 }
8268 
8269 
8270 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8271 /// This routine allows us to typecheck complex/recursive expressions
8272 /// where the declaration is needed for type checking. We only need to
8273 /// handle cases when the expression references a function designator
8274 /// or is an lvalue. Here are some examples:
8275 ///  - &(x) => x
8276 ///  - &*****f => f for f a function designator.
8277 ///  - &s.xx => s
8278 ///  - &s.zz[1].yy -> s, if zz is an array
8279 ///  - *(x + 1) -> x, if x is an array
8280 ///  - &"123"[2] -> 0
8281 ///  - & __real__ x -> x
8282 static ValueDecl *getPrimaryDecl(Expr *E) {
8283   switch (E->getStmtClass()) {
8284   case Stmt::DeclRefExprClass:
8285     return cast<DeclRefExpr>(E)->getDecl();
8286   case Stmt::MemberExprClass:
8287     // If this is an arrow operator, the address is an offset from
8288     // the base's value, so the object the base refers to is
8289     // irrelevant.
8290     if (cast<MemberExpr>(E)->isArrow())
8291       return 0;
8292     // Otherwise, the expression refers to a part of the base
8293     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8294   case Stmt::ArraySubscriptExprClass: {
8295     // FIXME: This code shouldn't be necessary!  We should catch the implicit
8296     // promotion of register arrays earlier.
8297     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8298     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8299       if (ICE->getSubExpr()->getType()->isArrayType())
8300         return getPrimaryDecl(ICE->getSubExpr());
8301     }
8302     return 0;
8303   }
8304   case Stmt::UnaryOperatorClass: {
8305     UnaryOperator *UO = cast<UnaryOperator>(E);
8306 
8307     switch(UO->getOpcode()) {
8308     case UO_Real:
8309     case UO_Imag:
8310     case UO_Extension:
8311       return getPrimaryDecl(UO->getSubExpr());
8312     default:
8313       return 0;
8314     }
8315   }
8316   case Stmt::ParenExprClass:
8317     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8318   case Stmt::ImplicitCastExprClass:
8319     // If the result of an implicit cast is an l-value, we care about
8320     // the sub-expression; otherwise, the result here doesn't matter.
8321     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8322   default:
8323     return 0;
8324   }
8325 }
8326 
8327 namespace {
8328   enum {
8329     AO_Bit_Field = 0,
8330     AO_Vector_Element = 1,
8331     AO_Property_Expansion = 2,
8332     AO_Register_Variable = 3,
8333     AO_No_Error = 4
8334   };
8335 }
8336 /// \brief Diagnose invalid operand for address of operations.
8337 ///
8338 /// \param Type The type of operand which cannot have its address taken.
8339 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8340                                          Expr *E, unsigned Type) {
8341   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8342 }
8343 
8344 /// CheckAddressOfOperand - The operand of & must be either a function
8345 /// designator or an lvalue designating an object. If it is an lvalue, the
8346 /// object cannot be declared with storage class register or be a bit field.
8347 /// Note: The usual conversions are *not* applied to the operand of the &
8348 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8349 /// In C++, the operand might be an overloaded function name, in which case
8350 /// we allow the '&' but retain the overloaded-function type.
8351 static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
8352                                       SourceLocation OpLoc) {
8353   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8354     if (PTy->getKind() == BuiltinType::Overload) {
8355       if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
8356         assert(cast<UnaryOperator>(OrigOp.get()->IgnoreParens())->getOpcode()
8357                  == UO_AddrOf);
8358         S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
8359           << OrigOp.get()->getSourceRange();
8360         return QualType();
8361       }
8362 
8363       OverloadExpr *Ovl = cast<OverloadExpr>(OrigOp.get()->IgnoreParens());
8364       if (isa<UnresolvedMemberExpr>(Ovl))
8365         if (!S.ResolveSingleFunctionTemplateSpecialization(Ovl)) {
8366           S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8367             << OrigOp.get()->getSourceRange();
8368           return QualType();
8369         }
8370 
8371       return S.Context.OverloadTy;
8372     }
8373 
8374     if (PTy->getKind() == BuiltinType::UnknownAny)
8375       return S.Context.UnknownAnyTy;
8376 
8377     if (PTy->getKind() == BuiltinType::BoundMember) {
8378       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8379         << OrigOp.get()->getSourceRange();
8380       return QualType();
8381     }
8382 
8383     OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
8384     if (OrigOp.isInvalid()) return QualType();
8385   }
8386 
8387   if (OrigOp.get()->isTypeDependent())
8388     return S.Context.DependentTy;
8389 
8390   assert(!OrigOp.get()->getType()->isPlaceholderType());
8391 
8392   // Make sure to ignore parentheses in subsequent checks
8393   Expr *op = OrigOp.get()->IgnoreParens();
8394 
8395   if (S.getLangOpts().C99) {
8396     // Implement C99-only parts of addressof rules.
8397     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8398       if (uOp->getOpcode() == UO_Deref)
8399         // Per C99 6.5.3.2, the address of a deref always returns a valid result
8400         // (assuming the deref expression is valid).
8401         return uOp->getSubExpr()->getType();
8402     }
8403     // Technically, there should be a check for array subscript
8404     // expressions here, but the result of one is always an lvalue anyway.
8405   }
8406   ValueDecl *dcl = getPrimaryDecl(op);
8407   Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
8408   unsigned AddressOfError = AO_No_Error;
8409 
8410   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
8411     bool sfinae = (bool)S.isSFINAEContext();
8412     S.Diag(OpLoc, S.isSFINAEContext() ? diag::err_typecheck_addrof_temporary
8413                          : diag::ext_typecheck_addrof_temporary)
8414       << op->getType() << op->getSourceRange();
8415     if (sfinae)
8416       return QualType();
8417     // Materialize the temporary as an lvalue so that we can take its address.
8418     OrigOp = op = new (S.Context)
8419         MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true, 0);
8420   } else if (isa<ObjCSelectorExpr>(op)) {
8421     return S.Context.getPointerType(op->getType());
8422   } else if (lval == Expr::LV_MemberFunction) {
8423     // If it's an instance method, make a member pointer.
8424     // The expression must have exactly the form &A::foo.
8425 
8426     // If the underlying expression isn't a decl ref, give up.
8427     if (!isa<DeclRefExpr>(op)) {
8428       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8429         << OrigOp.get()->getSourceRange();
8430       return QualType();
8431     }
8432     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8433     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8434 
8435     // The id-expression was parenthesized.
8436     if (OrigOp.get() != DRE) {
8437       S.Diag(OpLoc, diag::err_parens_pointer_member_function)
8438         << OrigOp.get()->getSourceRange();
8439 
8440     // The method was named without a qualifier.
8441     } else if (!DRE->getQualifier()) {
8442       if (MD->getParent()->getName().empty())
8443         S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8444           << op->getSourceRange();
8445       else {
8446         SmallString<32> Str;
8447         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8448         S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8449           << op->getSourceRange()
8450           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8451       }
8452     }
8453 
8454     return S.Context.getMemberPointerType(op->getType(),
8455               S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
8456   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
8457     // C99 6.5.3.2p1
8458     // The operand must be either an l-value or a function designator
8459     if (!op->getType()->isFunctionType()) {
8460       // Use a special diagnostic for loads from property references.
8461       if (isa<PseudoObjectExpr>(op)) {
8462         AddressOfError = AO_Property_Expansion;
8463       } else {
8464         S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8465           << op->getType() << op->getSourceRange();
8466         return QualType();
8467       }
8468     }
8469   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
8470     // The operand cannot be a bit-field
8471     AddressOfError = AO_Bit_Field;
8472   } else if (op->getObjectKind() == OK_VectorComponent) {
8473     // The operand cannot be an element of a vector
8474     AddressOfError = AO_Vector_Element;
8475   } else if (dcl) { // C99 6.5.3.2p1
8476     // We have an lvalue with a decl. Make sure the decl is not declared
8477     // with the register storage-class specifier.
8478     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
8479       // in C++ it is not error to take address of a register
8480       // variable (c++03 7.1.1P3)
8481       if (vd->getStorageClass() == SC_Register &&
8482           !S.getLangOpts().CPlusPlus) {
8483         AddressOfError = AO_Register_Variable;
8484       }
8485     } else if (isa<FunctionTemplateDecl>(dcl)) {
8486       return S.Context.OverloadTy;
8487     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8488       // Okay: we can take the address of a field.
8489       // Could be a pointer to member, though, if there is an explicit
8490       // scope qualifier for the class.
8491       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8492         DeclContext *Ctx = dcl->getDeclContext();
8493         if (Ctx && Ctx->isRecord()) {
8494           if (dcl->getType()->isReferenceType()) {
8495             S.Diag(OpLoc,
8496                    diag::err_cannot_form_pointer_to_member_of_reference_type)
8497               << dcl->getDeclName() << dcl->getType();
8498             return QualType();
8499           }
8500 
8501           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8502             Ctx = Ctx->getParent();
8503           return S.Context.getMemberPointerType(op->getType(),
8504                 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8505         }
8506       }
8507     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
8508       llvm_unreachable("Unknown/unexpected decl type");
8509   }
8510 
8511   if (AddressOfError != AO_No_Error) {
8512     diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8513     return QualType();
8514   }
8515 
8516   if (lval == Expr::LV_IncompleteVoidType) {
8517     // Taking the address of a void variable is technically illegal, but we
8518     // allow it in cases which are otherwise valid.
8519     // Example: "extern void x; void* y = &x;".
8520     S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
8521   }
8522 
8523   // If the operand has type "type", the result has type "pointer to type".
8524   if (op->getType()->isObjCObjectType())
8525     return S.Context.getObjCObjectPointerType(op->getType());
8526   return S.Context.getPointerType(op->getType());
8527 }
8528 
8529 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
8530 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8531                                         SourceLocation OpLoc) {
8532   if (Op->isTypeDependent())
8533     return S.Context.DependentTy;
8534 
8535   ExprResult ConvResult = S.UsualUnaryConversions(Op);
8536   if (ConvResult.isInvalid())
8537     return QualType();
8538   Op = ConvResult.take();
8539   QualType OpTy = Op->getType();
8540   QualType Result;
8541 
8542   if (isa<CXXReinterpretCastExpr>(Op)) {
8543     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8544     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8545                                      Op->getSourceRange());
8546   }
8547 
8548   // Note that per both C89 and C99, indirection is always legal, even if OpTy
8549   // is an incomplete type or void.  It would be possible to warn about
8550   // dereferencing a void pointer, but it's completely well-defined, and such a
8551   // warning is unlikely to catch any mistakes.
8552   if (const PointerType *PT = OpTy->getAs<PointerType>())
8553     Result = PT->getPointeeType();
8554   else if (const ObjCObjectPointerType *OPT =
8555              OpTy->getAs<ObjCObjectPointerType>())
8556     Result = OPT->getPointeeType();
8557   else {
8558     ExprResult PR = S.CheckPlaceholderExpr(Op);
8559     if (PR.isInvalid()) return QualType();
8560     if (PR.take() != Op)
8561       return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
8562   }
8563 
8564   if (Result.isNull()) {
8565     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
8566       << OpTy << Op->getSourceRange();
8567     return QualType();
8568   }
8569 
8570   // Dereferences are usually l-values...
8571   VK = VK_LValue;
8572 
8573   // ...except that certain expressions are never l-values in C.
8574   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
8575     VK = VK_RValue;
8576 
8577   return Result;
8578 }
8579 
8580 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
8581   tok::TokenKind Kind) {
8582   BinaryOperatorKind Opc;
8583   switch (Kind) {
8584   default: llvm_unreachable("Unknown binop!");
8585   case tok::periodstar:           Opc = BO_PtrMemD; break;
8586   case tok::arrowstar:            Opc = BO_PtrMemI; break;
8587   case tok::star:                 Opc = BO_Mul; break;
8588   case tok::slash:                Opc = BO_Div; break;
8589   case tok::percent:              Opc = BO_Rem; break;
8590   case tok::plus:                 Opc = BO_Add; break;
8591   case tok::minus:                Opc = BO_Sub; break;
8592   case tok::lessless:             Opc = BO_Shl; break;
8593   case tok::greatergreater:       Opc = BO_Shr; break;
8594   case tok::lessequal:            Opc = BO_LE; break;
8595   case tok::less:                 Opc = BO_LT; break;
8596   case tok::greaterequal:         Opc = BO_GE; break;
8597   case tok::greater:              Opc = BO_GT; break;
8598   case tok::exclaimequal:         Opc = BO_NE; break;
8599   case tok::equalequal:           Opc = BO_EQ; break;
8600   case tok::amp:                  Opc = BO_And; break;
8601   case tok::caret:                Opc = BO_Xor; break;
8602   case tok::pipe:                 Opc = BO_Or; break;
8603   case tok::ampamp:               Opc = BO_LAnd; break;
8604   case tok::pipepipe:             Opc = BO_LOr; break;
8605   case tok::equal:                Opc = BO_Assign; break;
8606   case tok::starequal:            Opc = BO_MulAssign; break;
8607   case tok::slashequal:           Opc = BO_DivAssign; break;
8608   case tok::percentequal:         Opc = BO_RemAssign; break;
8609   case tok::plusequal:            Opc = BO_AddAssign; break;
8610   case tok::minusequal:           Opc = BO_SubAssign; break;
8611   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
8612   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
8613   case tok::ampequal:             Opc = BO_AndAssign; break;
8614   case tok::caretequal:           Opc = BO_XorAssign; break;
8615   case tok::pipeequal:            Opc = BO_OrAssign; break;
8616   case tok::comma:                Opc = BO_Comma; break;
8617   }
8618   return Opc;
8619 }
8620 
8621 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
8622   tok::TokenKind Kind) {
8623   UnaryOperatorKind Opc;
8624   switch (Kind) {
8625   default: llvm_unreachable("Unknown unary op!");
8626   case tok::plusplus:     Opc = UO_PreInc; break;
8627   case tok::minusminus:   Opc = UO_PreDec; break;
8628   case tok::amp:          Opc = UO_AddrOf; break;
8629   case tok::star:         Opc = UO_Deref; break;
8630   case tok::plus:         Opc = UO_Plus; break;
8631   case tok::minus:        Opc = UO_Minus; break;
8632   case tok::tilde:        Opc = UO_Not; break;
8633   case tok::exclaim:      Opc = UO_LNot; break;
8634   case tok::kw___real:    Opc = UO_Real; break;
8635   case tok::kw___imag:    Opc = UO_Imag; break;
8636   case tok::kw___extension__: Opc = UO_Extension; break;
8637   }
8638   return Opc;
8639 }
8640 
8641 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8642 /// This warning is only emitted for builtin assignment operations. It is also
8643 /// suppressed in the event of macro expansions.
8644 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
8645                                    SourceLocation OpLoc) {
8646   if (!S.ActiveTemplateInstantiations.empty())
8647     return;
8648   if (OpLoc.isInvalid() || OpLoc.isMacroID())
8649     return;
8650   LHSExpr = LHSExpr->IgnoreParenImpCasts();
8651   RHSExpr = RHSExpr->IgnoreParenImpCasts();
8652   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8653   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8654   if (!LHSDeclRef || !RHSDeclRef ||
8655       LHSDeclRef->getLocation().isMacroID() ||
8656       RHSDeclRef->getLocation().isMacroID())
8657     return;
8658   const ValueDecl *LHSDecl =
8659     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8660   const ValueDecl *RHSDecl =
8661     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8662   if (LHSDecl != RHSDecl)
8663     return;
8664   if (LHSDecl->getType().isVolatileQualified())
8665     return;
8666   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
8667     if (RefTy->getPointeeType().isVolatileQualified())
8668       return;
8669 
8670   S.Diag(OpLoc, diag::warn_self_assignment)
8671       << LHSDeclRef->getType()
8672       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8673 }
8674 
8675 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
8676 /// is usually indicative of introspection within the Objective-C pointer.
8677 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
8678                                           SourceLocation OpLoc) {
8679   if (!S.getLangOpts().ObjC1)
8680     return;
8681 
8682   const Expr *ObjCPointerExpr = 0, *OtherExpr = 0;
8683   const Expr *LHS = L.get();
8684   const Expr *RHS = R.get();
8685 
8686   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
8687     ObjCPointerExpr = LHS;
8688     OtherExpr = RHS;
8689   }
8690   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
8691     ObjCPointerExpr = RHS;
8692     OtherExpr = LHS;
8693   }
8694 
8695   // This warning is deliberately made very specific to reduce false
8696   // positives with logic that uses '&' for hashing.  This logic mainly
8697   // looks for code trying to introspect into tagged pointers, which
8698   // code should generally never do.
8699   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
8700     S.Diag(OpLoc, diag::warn_objc_pointer_masking)
8701       << ObjCPointerExpr->getSourceRange();
8702   }
8703 }
8704 
8705 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
8706 /// operator @p Opc at location @c TokLoc. This routine only supports
8707 /// built-in operations; ActOnBinOp handles overloaded operators.
8708 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
8709                                     BinaryOperatorKind Opc,
8710                                     Expr *LHSExpr, Expr *RHSExpr) {
8711   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
8712     // The syntax only allows initializer lists on the RHS of assignment,
8713     // so we don't need to worry about accepting invalid code for
8714     // non-assignment operators.
8715     // C++11 5.17p9:
8716     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8717     //   of x = {} is x = T().
8718     InitializationKind Kind =
8719         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8720     InitializedEntity Entity =
8721         InitializedEntity::InitializeTemporary(LHSExpr->getType());
8722     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
8723     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
8724     if (Init.isInvalid())
8725       return Init;
8726     RHSExpr = Init.take();
8727   }
8728 
8729   ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
8730   QualType ResultTy;     // Result type of the binary operator.
8731   // The following two variables are used for compound assignment operators
8732   QualType CompLHSTy;    // Type of LHS after promotions for computation
8733   QualType CompResultTy; // Type of computation result
8734   ExprValueKind VK = VK_RValue;
8735   ExprObjectKind OK = OK_Ordinary;
8736 
8737   switch (Opc) {
8738   case BO_Assign:
8739     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
8740     if (getLangOpts().CPlusPlus &&
8741         LHS.get()->getObjectKind() != OK_ObjCProperty) {
8742       VK = LHS.get()->getValueKind();
8743       OK = LHS.get()->getObjectKind();
8744     }
8745     if (!ResultTy.isNull())
8746       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
8747     break;
8748   case BO_PtrMemD:
8749   case BO_PtrMemI:
8750     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
8751                                             Opc == BO_PtrMemI);
8752     break;
8753   case BO_Mul:
8754   case BO_Div:
8755     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
8756                                            Opc == BO_Div);
8757     break;
8758   case BO_Rem:
8759     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
8760     break;
8761   case BO_Add:
8762     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
8763     break;
8764   case BO_Sub:
8765     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
8766     break;
8767   case BO_Shl:
8768   case BO_Shr:
8769     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
8770     break;
8771   case BO_LE:
8772   case BO_LT:
8773   case BO_GE:
8774   case BO_GT:
8775     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
8776     break;
8777   case BO_EQ:
8778   case BO_NE:
8779     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
8780     break;
8781   case BO_And:
8782     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
8783   case BO_Xor:
8784   case BO_Or:
8785     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
8786     break;
8787   case BO_LAnd:
8788   case BO_LOr:
8789     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
8790     break;
8791   case BO_MulAssign:
8792   case BO_DivAssign:
8793     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
8794                                                Opc == BO_DivAssign);
8795     CompLHSTy = CompResultTy;
8796     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8797       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8798     break;
8799   case BO_RemAssign:
8800     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
8801     CompLHSTy = CompResultTy;
8802     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8803       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8804     break;
8805   case BO_AddAssign:
8806     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
8807     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8808       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8809     break;
8810   case BO_SubAssign:
8811     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8812     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8813       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8814     break;
8815   case BO_ShlAssign:
8816   case BO_ShrAssign:
8817     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
8818     CompLHSTy = CompResultTy;
8819     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8820       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8821     break;
8822   case BO_AndAssign:
8823   case BO_XorAssign:
8824   case BO_OrAssign:
8825     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
8826     CompLHSTy = CompResultTy;
8827     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8828       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8829     break;
8830   case BO_Comma:
8831     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
8832     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
8833       VK = RHS.get()->getValueKind();
8834       OK = RHS.get()->getObjectKind();
8835     }
8836     break;
8837   }
8838   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
8839     return ExprError();
8840 
8841   // Check for array bounds violations for both sides of the BinaryOperator
8842   CheckArrayAccess(LHS.get());
8843   CheckArrayAccess(RHS.get());
8844 
8845   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
8846     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
8847                                                  &Context.Idents.get("object_setClass"),
8848                                                  SourceLocation(), LookupOrdinaryName);
8849     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
8850       SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
8851       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
8852       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
8853       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
8854       FixItHint::CreateInsertion(RHSLocEnd, ")");
8855     }
8856     else
8857       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
8858   }
8859   else if (const ObjCIvarRefExpr *OIRE =
8860            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
8861     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
8862 
8863   if (CompResultTy.isNull())
8864     return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
8865                                               ResultTy, VK, OK, OpLoc,
8866                                               FPFeatures.fp_contract));
8867   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
8868       OK_ObjCProperty) {
8869     VK = VK_LValue;
8870     OK = LHS.get()->getObjectKind();
8871   }
8872   return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
8873                                                     ResultTy, VK, OK, CompLHSTy,
8874                                                     CompResultTy, OpLoc,
8875                                                     FPFeatures.fp_contract));
8876 }
8877 
8878 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8879 /// operators are mixed in a way that suggests that the programmer forgot that
8880 /// comparison operators have higher precedence. The most typical example of
8881 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
8882 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
8883                                       SourceLocation OpLoc, Expr *LHSExpr,
8884                                       Expr *RHSExpr) {
8885   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
8886   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
8887 
8888   // Check that one of the sides is a comparison operator.
8889   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
8890   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
8891   if (!isLeftComp && !isRightComp)
8892     return;
8893 
8894   // Bitwise operations are sometimes used as eager logical ops.
8895   // Don't diagnose this.
8896   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
8897   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
8898   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
8899     return;
8900 
8901   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8902                                                    OpLoc)
8903                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
8904   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
8905   SourceRange ParensRange = isLeftComp ?
8906       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
8907     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
8908 
8909   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8910     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
8911   SuggestParentheses(Self, OpLoc,
8912     Self.PDiag(diag::note_precedence_silence) << OpStr,
8913     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
8914   SuggestParentheses(Self, OpLoc,
8915     Self.PDiag(diag::note_precedence_bitwise_first)
8916       << BinaryOperator::getOpcodeStr(Opc),
8917     ParensRange);
8918 }
8919 
8920 /// \brief It accepts a '&' expr that is inside a '|' one.
8921 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8922 /// in parentheses.
8923 static void
8924 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8925                                        BinaryOperator *Bop) {
8926   assert(Bop->getOpcode() == BO_And);
8927   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8928       << Bop->getSourceRange() << OpLoc;
8929   SuggestParentheses(Self, Bop->getOperatorLoc(),
8930     Self.PDiag(diag::note_precedence_silence)
8931       << Bop->getOpcodeStr(),
8932     Bop->getSourceRange());
8933 }
8934 
8935 /// \brief It accepts a '&&' expr that is inside a '||' one.
8936 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8937 /// in parentheses.
8938 static void
8939 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8940                                        BinaryOperator *Bop) {
8941   assert(Bop->getOpcode() == BO_LAnd);
8942   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8943       << Bop->getSourceRange() << OpLoc;
8944   SuggestParentheses(Self, Bop->getOperatorLoc(),
8945     Self.PDiag(diag::note_precedence_silence)
8946       << Bop->getOpcodeStr(),
8947     Bop->getSourceRange());
8948 }
8949 
8950 /// \brief Returns true if the given expression can be evaluated as a constant
8951 /// 'true'.
8952 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8953   bool Res;
8954   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8955 }
8956 
8957 /// \brief Returns true if the given expression can be evaluated as a constant
8958 /// 'false'.
8959 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8960   bool Res;
8961   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8962 }
8963 
8964 /// \brief Look for '&&' in the left hand of a '||' expr.
8965 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
8966                                              Expr *LHSExpr, Expr *RHSExpr) {
8967   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
8968     if (Bop->getOpcode() == BO_LAnd) {
8969       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8970       if (EvaluatesAsFalse(S, RHSExpr))
8971         return;
8972       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8973       if (!EvaluatesAsTrue(S, Bop->getLHS()))
8974         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8975     } else if (Bop->getOpcode() == BO_LOr) {
8976       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8977         // If it's "a || b && 1 || c" we didn't warn earlier for
8978         // "a || b && 1", but warn now.
8979         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8980           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8981       }
8982     }
8983   }
8984 }
8985 
8986 /// \brief Look for '&&' in the right hand of a '||' expr.
8987 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
8988                                              Expr *LHSExpr, Expr *RHSExpr) {
8989   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
8990     if (Bop->getOpcode() == BO_LAnd) {
8991       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8992       if (EvaluatesAsFalse(S, LHSExpr))
8993         return;
8994       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8995       if (!EvaluatesAsTrue(S, Bop->getRHS()))
8996         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8997     }
8998   }
8999 }
9000 
9001 /// \brief Look for '&' in the left or right hand of a '|' expr.
9002 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
9003                                              Expr *OrArg) {
9004   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
9005     if (Bop->getOpcode() == BO_And)
9006       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
9007   }
9008 }
9009 
9010 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
9011                                     Expr *SubExpr, StringRef Shift) {
9012   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
9013     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
9014       StringRef Op = Bop->getOpcodeStr();
9015       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
9016           << Bop->getSourceRange() << OpLoc << Shift << Op;
9017       SuggestParentheses(S, Bop->getOperatorLoc(),
9018           S.PDiag(diag::note_precedence_silence) << Op,
9019           Bop->getSourceRange());
9020     }
9021   }
9022 }
9023 
9024 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
9025                                  Expr *LHSExpr, Expr *RHSExpr) {
9026   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
9027   if (!OCE)
9028     return;
9029 
9030   FunctionDecl *FD = OCE->getDirectCallee();
9031   if (!FD || !FD->isOverloadedOperator())
9032     return;
9033 
9034   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
9035   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
9036     return;
9037 
9038   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
9039       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
9040       << (Kind == OO_LessLess);
9041   SuggestParentheses(S, OCE->getOperatorLoc(),
9042                      S.PDiag(diag::note_precedence_silence)
9043                          << (Kind == OO_LessLess ? "<<" : ">>"),
9044                      OCE->getSourceRange());
9045   SuggestParentheses(S, OpLoc,
9046                      S.PDiag(diag::note_evaluate_comparison_first),
9047                      SourceRange(OCE->getArg(1)->getLocStart(),
9048                                  RHSExpr->getLocEnd()));
9049 }
9050 
9051 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
9052 /// precedence.
9053 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
9054                                     SourceLocation OpLoc, Expr *LHSExpr,
9055                                     Expr *RHSExpr){
9056   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
9057   if (BinaryOperator::isBitwiseOp(Opc))
9058     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
9059 
9060   // Diagnose "arg1 & arg2 | arg3"
9061   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9062     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
9063     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
9064   }
9065 
9066   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9067   // We don't warn for 'assert(a || b && "bad")' since this is safe.
9068   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9069     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
9070     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
9071   }
9072 
9073   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
9074       || Opc == BO_Shr) {
9075     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
9076     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
9077     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
9078   }
9079 
9080   // Warn on overloaded shift operators and comparisons, such as:
9081   // cout << 5 == 4;
9082   if (BinaryOperator::isComparisonOp(Opc))
9083     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
9084 }
9085 
9086 // Binary Operators.  'Tok' is the token for the operator.
9087 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
9088                             tok::TokenKind Kind,
9089                             Expr *LHSExpr, Expr *RHSExpr) {
9090   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
9091   assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
9092   assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
9093 
9094   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9095   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
9096 
9097   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
9098 }
9099 
9100 /// Build an overloaded binary operator expression in the given scope.
9101 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
9102                                        BinaryOperatorKind Opc,
9103                                        Expr *LHS, Expr *RHS) {
9104   // Find all of the overloaded operators visible from this
9105   // point. We perform both an operator-name lookup from the local
9106   // scope and an argument-dependent lookup based on the types of
9107   // the arguments.
9108   UnresolvedSet<16> Functions;
9109   OverloadedOperatorKind OverOp
9110     = BinaryOperator::getOverloadedOperator(Opc);
9111   if (Sc && OverOp != OO_None)
9112     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
9113                                    RHS->getType(), Functions);
9114 
9115   // Build the (potentially-overloaded, potentially-dependent)
9116   // binary operation.
9117   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
9118 }
9119 
9120 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
9121                             BinaryOperatorKind Opc,
9122                             Expr *LHSExpr, Expr *RHSExpr) {
9123   // We want to end up calling one of checkPseudoObjectAssignment
9124   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
9125   // both expressions are overloadable or either is type-dependent),
9126   // or CreateBuiltinBinOp (in any other case).  We also want to get
9127   // any placeholder types out of the way.
9128 
9129   // Handle pseudo-objects in the LHS.
9130   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
9131     // Assignments with a pseudo-object l-value need special analysis.
9132     if (pty->getKind() == BuiltinType::PseudoObject &&
9133         BinaryOperator::isAssignmentOp(Opc))
9134       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
9135 
9136     // Don't resolve overloads if the other type is overloadable.
9137     if (pty->getKind() == BuiltinType::Overload) {
9138       // We can't actually test that if we still have a placeholder,
9139       // though.  Fortunately, none of the exceptions we see in that
9140       // code below are valid when the LHS is an overload set.  Note
9141       // that an overload set can be dependently-typed, but it never
9142       // instantiates to having an overloadable type.
9143       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9144       if (resolvedRHS.isInvalid()) return ExprError();
9145       RHSExpr = resolvedRHS.take();
9146 
9147       if (RHSExpr->isTypeDependent() ||
9148           RHSExpr->getType()->isOverloadableType())
9149         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9150     }
9151 
9152     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
9153     if (LHS.isInvalid()) return ExprError();
9154     LHSExpr = LHS.take();
9155   }
9156 
9157   // Handle pseudo-objects in the RHS.
9158   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
9159     // An overload in the RHS can potentially be resolved by the type
9160     // being assigned to.
9161     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
9162       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9163         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9164 
9165       if (LHSExpr->getType()->isOverloadableType())
9166         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9167 
9168       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9169     }
9170 
9171     // Don't resolve overloads if the other type is overloadable.
9172     if (pty->getKind() == BuiltinType::Overload &&
9173         LHSExpr->getType()->isOverloadableType())
9174       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9175 
9176     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9177     if (!resolvedRHS.isUsable()) return ExprError();
9178     RHSExpr = resolvedRHS.take();
9179   }
9180 
9181   if (getLangOpts().CPlusPlus) {
9182     // If either expression is type-dependent, always build an
9183     // overloaded op.
9184     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9185       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9186 
9187     // Otherwise, build an overloaded op if either expression has an
9188     // overloadable type.
9189     if (LHSExpr->getType()->isOverloadableType() ||
9190         RHSExpr->getType()->isOverloadableType())
9191       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9192   }
9193 
9194   // Build a built-in binary operation.
9195   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9196 }
9197 
9198 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
9199                                       UnaryOperatorKind Opc,
9200                                       Expr *InputExpr) {
9201   ExprResult Input = Owned(InputExpr);
9202   ExprValueKind VK = VK_RValue;
9203   ExprObjectKind OK = OK_Ordinary;
9204   QualType resultType;
9205   switch (Opc) {
9206   case UO_PreInc:
9207   case UO_PreDec:
9208   case UO_PostInc:
9209   case UO_PostDec:
9210     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
9211                                                 Opc == UO_PreInc ||
9212                                                 Opc == UO_PostInc,
9213                                                 Opc == UO_PreInc ||
9214                                                 Opc == UO_PreDec);
9215     break;
9216   case UO_AddrOf:
9217     resultType = CheckAddressOfOperand(*this, Input, OpLoc);
9218     break;
9219   case UO_Deref: {
9220     Input = DefaultFunctionArrayLvalueConversion(Input.take());
9221     if (Input.isInvalid()) return ExprError();
9222     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
9223     break;
9224   }
9225   case UO_Plus:
9226   case UO_Minus:
9227     Input = UsualUnaryConversions(Input.take());
9228     if (Input.isInvalid()) return ExprError();
9229     resultType = Input.get()->getType();
9230     if (resultType->isDependentType())
9231       break;
9232     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9233         resultType->isVectorType())
9234       break;
9235     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
9236              resultType->isEnumeralType())
9237       break;
9238     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
9239              Opc == UO_Plus &&
9240              resultType->isPointerType())
9241       break;
9242 
9243     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9244       << resultType << Input.get()->getSourceRange());
9245 
9246   case UO_Not: // bitwise complement
9247     Input = UsualUnaryConversions(Input.take());
9248     if (Input.isInvalid())
9249       return ExprError();
9250     resultType = Input.get()->getType();
9251     if (resultType->isDependentType())
9252       break;
9253     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9254     if (resultType->isComplexType() || resultType->isComplexIntegerType())
9255       // C99 does not support '~' for complex conjugation.
9256       Diag(OpLoc, diag::ext_integer_complement_complex)
9257           << resultType << Input.get()->getSourceRange();
9258     else if (resultType->hasIntegerRepresentation())
9259       break;
9260     else if (resultType->isExtVectorType()) {
9261       if (Context.getLangOpts().OpenCL) {
9262         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
9263         // on vector float types.
9264         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9265         if (!T->isIntegerType())
9266           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9267                            << resultType << Input.get()->getSourceRange());
9268       }
9269       break;
9270     } else {
9271       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9272                        << resultType << Input.get()->getSourceRange());
9273     }
9274     break;
9275 
9276   case UO_LNot: // logical negation
9277     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
9278     Input = DefaultFunctionArrayLvalueConversion(Input.take());
9279     if (Input.isInvalid()) return ExprError();
9280     resultType = Input.get()->getType();
9281 
9282     // Though we still have to promote half FP to float...
9283     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
9284       Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
9285       resultType = Context.FloatTy;
9286     }
9287 
9288     if (resultType->isDependentType())
9289       break;
9290     if (resultType->isScalarType()) {
9291       // C99 6.5.3.3p1: ok, fallthrough;
9292       if (Context.getLangOpts().CPlusPlus) {
9293         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9294         // operand contextually converted to bool.
9295         Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9296                                   ScalarTypeToBooleanCastKind(resultType));
9297       } else if (Context.getLangOpts().OpenCL &&
9298                  Context.getLangOpts().OpenCLVersion < 120) {
9299         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9300         // operate on scalar float types.
9301         if (!resultType->isIntegerType())
9302           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9303                            << resultType << Input.get()->getSourceRange());
9304       }
9305     } else if (resultType->isExtVectorType()) {
9306       if (Context.getLangOpts().OpenCL &&
9307           Context.getLangOpts().OpenCLVersion < 120) {
9308         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9309         // operate on vector float types.
9310         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9311         if (!T->isIntegerType())
9312           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9313                            << resultType << Input.get()->getSourceRange());
9314       }
9315       // Vector logical not returns the signed variant of the operand type.
9316       resultType = GetSignedVectorType(resultType);
9317       break;
9318     } else {
9319       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9320         << resultType << Input.get()->getSourceRange());
9321     }
9322 
9323     // LNot always has type int. C99 6.5.3.3p5.
9324     // In C++, it's bool. C++ 5.3.1p8
9325     resultType = Context.getLogicalOperationType();
9326     break;
9327   case UO_Real:
9328   case UO_Imag:
9329     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
9330     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
9331     // complex l-values to ordinary l-values and all other values to r-values.
9332     if (Input.isInvalid()) return ExprError();
9333     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
9334       if (Input.get()->getValueKind() != VK_RValue &&
9335           Input.get()->getObjectKind() == OK_Ordinary)
9336         VK = Input.get()->getValueKind();
9337     } else if (!getLangOpts().CPlusPlus) {
9338       // In C, a volatile scalar is read by __imag. In C++, it is not.
9339       Input = DefaultLvalueConversion(Input.take());
9340     }
9341     break;
9342   case UO_Extension:
9343     resultType = Input.get()->getType();
9344     VK = Input.get()->getValueKind();
9345     OK = Input.get()->getObjectKind();
9346     break;
9347   }
9348   if (resultType.isNull() || Input.isInvalid())
9349     return ExprError();
9350 
9351   // Check for array bounds violations in the operand of the UnaryOperator,
9352   // except for the '*' and '&' operators that have to be handled specially
9353   // by CheckArrayAccess (as there are special cases like &array[arraysize]
9354   // that are explicitly defined as valid by the standard).
9355   if (Opc != UO_AddrOf && Opc != UO_Deref)
9356     CheckArrayAccess(Input.get());
9357 
9358   return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
9359                                            VK, OK, OpLoc));
9360 }
9361 
9362 /// \brief Determine whether the given expression is a qualified member
9363 /// access expression, of a form that could be turned into a pointer to member
9364 /// with the address-of operator.
9365 static bool isQualifiedMemberAccess(Expr *E) {
9366   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9367     if (!DRE->getQualifier())
9368       return false;
9369 
9370     ValueDecl *VD = DRE->getDecl();
9371     if (!VD->isCXXClassMember())
9372       return false;
9373 
9374     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9375       return true;
9376     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9377       return Method->isInstance();
9378 
9379     return false;
9380   }
9381 
9382   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9383     if (!ULE->getQualifier())
9384       return false;
9385 
9386     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9387                                            DEnd = ULE->decls_end();
9388          D != DEnd; ++D) {
9389       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9390         if (Method->isInstance())
9391           return true;
9392       } else {
9393         // Overload set does not contain methods.
9394         break;
9395       }
9396     }
9397 
9398     return false;
9399   }
9400 
9401   return false;
9402 }
9403 
9404 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
9405                               UnaryOperatorKind Opc, Expr *Input) {
9406   // First things first: handle placeholders so that the
9407   // overloaded-operator check considers the right type.
9408   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
9409     // Increment and decrement of pseudo-object references.
9410     if (pty->getKind() == BuiltinType::PseudoObject &&
9411         UnaryOperator::isIncrementDecrementOp(Opc))
9412       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
9413 
9414     // extension is always a builtin operator.
9415     if (Opc == UO_Extension)
9416       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9417 
9418     // & gets special logic for several kinds of placeholder.
9419     // The builtin code knows what to do.
9420     if (Opc == UO_AddrOf &&
9421         (pty->getKind() == BuiltinType::Overload ||
9422          pty->getKind() == BuiltinType::UnknownAny ||
9423          pty->getKind() == BuiltinType::BoundMember))
9424       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9425 
9426     // Anything else needs to be handled now.
9427     ExprResult Result = CheckPlaceholderExpr(Input);
9428     if (Result.isInvalid()) return ExprError();
9429     Input = Result.take();
9430   }
9431 
9432   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
9433       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
9434       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
9435     // Find all of the overloaded operators visible from this
9436     // point. We perform both an operator-name lookup from the local
9437     // scope and an argument-dependent lookup based on the types of
9438     // the arguments.
9439     UnresolvedSet<16> Functions;
9440     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
9441     if (S && OverOp != OO_None)
9442       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9443                                    Functions);
9444 
9445     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
9446   }
9447 
9448   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9449 }
9450 
9451 // Unary Operators.  'Tok' is the token for the operator.
9452 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
9453                               tok::TokenKind Op, Expr *Input) {
9454   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
9455 }
9456 
9457 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
9458 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
9459                                 LabelDecl *TheDecl) {
9460   TheDecl->setUsed();
9461   // Create the AST node.  The address of a label always has type 'void*'.
9462   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
9463                                        Context.getPointerType(Context.VoidTy)));
9464 }
9465 
9466 /// Given the last statement in a statement-expression, check whether
9467 /// the result is a producing expression (like a call to an
9468 /// ns_returns_retained function) and, if so, rebuild it to hoist the
9469 /// release out of the full-expression.  Otherwise, return null.
9470 /// Cannot fail.
9471 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
9472   // Should always be wrapped with one of these.
9473   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
9474   if (!cleanups) return 0;
9475 
9476   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
9477   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
9478     return 0;
9479 
9480   // Splice out the cast.  This shouldn't modify any interesting
9481   // features of the statement.
9482   Expr *producer = cast->getSubExpr();
9483   assert(producer->getType() == cast->getType());
9484   assert(producer->getValueKind() == cast->getValueKind());
9485   cleanups->setSubExpr(producer);
9486   return cleanups;
9487 }
9488 
9489 void Sema::ActOnStartStmtExpr() {
9490   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9491 }
9492 
9493 void Sema::ActOnStmtExprError() {
9494   // Note that function is also called by TreeTransform when leaving a
9495   // StmtExpr scope without rebuilding anything.
9496 
9497   DiscardCleanupsInEvaluationContext();
9498   PopExpressionEvaluationContext();
9499 }
9500 
9501 ExprResult
9502 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
9503                     SourceLocation RPLoc) { // "({..})"
9504   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9505   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9506 
9507   if (hasAnyUnrecoverableErrorsInThisFunction())
9508     DiscardCleanupsInEvaluationContext();
9509   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9510   PopExpressionEvaluationContext();
9511 
9512   bool isFileScope
9513     = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
9514   if (isFileScope)
9515     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
9516 
9517   // FIXME: there are a variety of strange constraints to enforce here, for
9518   // example, it is not possible to goto into a stmt expression apparently.
9519   // More semantic analysis is needed.
9520 
9521   // If there are sub stmts in the compound stmt, take the type of the last one
9522   // as the type of the stmtexpr.
9523   QualType Ty = Context.VoidTy;
9524   bool StmtExprMayBindToTemp = false;
9525   if (!Compound->body_empty()) {
9526     Stmt *LastStmt = Compound->body_back();
9527     LabelStmt *LastLabelStmt = 0;
9528     // If LastStmt is a label, skip down through into the body.
9529     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9530       LastLabelStmt = Label;
9531       LastStmt = Label->getSubStmt();
9532     }
9533 
9534     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
9535       // Do function/array conversion on the last expression, but not
9536       // lvalue-to-rvalue.  However, initialize an unqualified type.
9537       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9538       if (LastExpr.isInvalid())
9539         return ExprError();
9540       Ty = LastExpr.get()->getType().getUnqualifiedType();
9541 
9542       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9543         // In ARC, if the final expression ends in a consume, splice
9544         // the consume out and bind it later.  In the alternate case
9545         // (when dealing with a retainable type), the result
9546         // initialization will create a produce.  In both cases the
9547         // result will be +1, and we'll need to balance that out with
9548         // a bind.
9549         if (Expr *rebuiltLastStmt
9550               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9551           LastExpr = rebuiltLastStmt;
9552         } else {
9553           LastExpr = PerformCopyInitialization(
9554                             InitializedEntity::InitializeResult(LPLoc,
9555                                                                 Ty,
9556                                                                 false),
9557                                                    SourceLocation(),
9558                                                LastExpr);
9559         }
9560 
9561         if (LastExpr.isInvalid())
9562           return ExprError();
9563         if (LastExpr.get() != 0) {
9564           if (!LastLabelStmt)
9565             Compound->setLastStmt(LastExpr.take());
9566           else
9567             LastLabelStmt->setSubStmt(LastExpr.take());
9568           StmtExprMayBindToTemp = true;
9569         }
9570       }
9571     }
9572   }
9573 
9574   // FIXME: Check that expression type is complete/non-abstract; statement
9575   // expressions are not lvalues.
9576   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9577   if (StmtExprMayBindToTemp)
9578     return MaybeBindToTemporary(ResStmtExpr);
9579   return Owned(ResStmtExpr);
9580 }
9581 
9582 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
9583                                       TypeSourceInfo *TInfo,
9584                                       OffsetOfComponent *CompPtr,
9585                                       unsigned NumComponents,
9586                                       SourceLocation RParenLoc) {
9587   QualType ArgTy = TInfo->getType();
9588   bool Dependent = ArgTy->isDependentType();
9589   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
9590 
9591   // We must have at least one component that refers to the type, and the first
9592   // one is known to be a field designator.  Verify that the ArgTy represents
9593   // a struct/union/class.
9594   if (!Dependent && !ArgTy->isRecordType())
9595     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9596                        << ArgTy << TypeRange);
9597 
9598   // Type must be complete per C99 7.17p3 because a declaring a variable
9599   // with an incomplete type would be ill-formed.
9600   if (!Dependent
9601       && RequireCompleteType(BuiltinLoc, ArgTy,
9602                              diag::err_offsetof_incomplete_type, TypeRange))
9603     return ExprError();
9604 
9605   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9606   // GCC extension, diagnose them.
9607   // FIXME: This diagnostic isn't actually visible because the location is in
9608   // a system header!
9609   if (NumComponents != 1)
9610     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9611       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
9612 
9613   bool DidWarnAboutNonPOD = false;
9614   QualType CurrentType = ArgTy;
9615   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9616   SmallVector<OffsetOfNode, 4> Comps;
9617   SmallVector<Expr*, 4> Exprs;
9618   for (unsigned i = 0; i != NumComponents; ++i) {
9619     const OffsetOfComponent &OC = CompPtr[i];
9620     if (OC.isBrackets) {
9621       // Offset of an array sub-field.  TODO: Should we allow vector elements?
9622       if (!CurrentType->isDependentType()) {
9623         const ArrayType *AT = Context.getAsArrayType(CurrentType);
9624         if(!AT)
9625           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9626                            << CurrentType);
9627         CurrentType = AT->getElementType();
9628       } else
9629         CurrentType = Context.DependentTy;
9630 
9631       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9632       if (IdxRval.isInvalid())
9633         return ExprError();
9634       Expr *Idx = IdxRval.take();
9635 
9636       // The expression must be an integral expression.
9637       // FIXME: An integral constant expression?
9638       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9639           !Idx->getType()->isIntegerType())
9640         return ExprError(Diag(Idx->getLocStart(),
9641                               diag::err_typecheck_subscript_not_integer)
9642                          << Idx->getSourceRange());
9643 
9644       // Record this array index.
9645       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9646       Exprs.push_back(Idx);
9647       continue;
9648     }
9649 
9650     // Offset of a field.
9651     if (CurrentType->isDependentType()) {
9652       // We have the offset of a field, but we can't look into the dependent
9653       // type. Just record the identifier of the field.
9654       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9655       CurrentType = Context.DependentTy;
9656       continue;
9657     }
9658 
9659     // We need to have a complete type to look into.
9660     if (RequireCompleteType(OC.LocStart, CurrentType,
9661                             diag::err_offsetof_incomplete_type))
9662       return ExprError();
9663 
9664     // Look for the designated field.
9665     const RecordType *RC = CurrentType->getAs<RecordType>();
9666     if (!RC)
9667       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9668                        << CurrentType);
9669     RecordDecl *RD = RC->getDecl();
9670 
9671     // C++ [lib.support.types]p5:
9672     //   The macro offsetof accepts a restricted set of type arguments in this
9673     //   International Standard. type shall be a POD structure or a POD union
9674     //   (clause 9).
9675     // C++11 [support.types]p4:
9676     //   If type is not a standard-layout class (Clause 9), the results are
9677     //   undefined.
9678     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9679       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
9680       unsigned DiagID =
9681         LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type
9682                             : diag::warn_offsetof_non_pod_type;
9683 
9684       if (!IsSafe && !DidWarnAboutNonPOD &&
9685           DiagRuntimeBehavior(BuiltinLoc, 0,
9686                               PDiag(DiagID)
9687                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9688                               << CurrentType))
9689         DidWarnAboutNonPOD = true;
9690     }
9691 
9692     // Look for the field.
9693     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9694     LookupQualifiedName(R, RD);
9695     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
9696     IndirectFieldDecl *IndirectMemberDecl = 0;
9697     if (!MemberDecl) {
9698       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
9699         MemberDecl = IndirectMemberDecl->getAnonField();
9700     }
9701 
9702     if (!MemberDecl)
9703       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9704                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9705                                                               OC.LocEnd));
9706 
9707     // C99 7.17p3:
9708     //   (If the specified member is a bit-field, the behavior is undefined.)
9709     //
9710     // We diagnose this as an error.
9711     if (MemberDecl->isBitField()) {
9712       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9713         << MemberDecl->getDeclName()
9714         << SourceRange(BuiltinLoc, RParenLoc);
9715       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9716       return ExprError();
9717     }
9718 
9719     RecordDecl *Parent = MemberDecl->getParent();
9720     if (IndirectMemberDecl)
9721       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
9722 
9723     // If the member was found in a base class, introduce OffsetOfNodes for
9724     // the base class indirections.
9725     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9726                        /*DetectVirtual=*/false);
9727     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
9728       CXXBasePath &Path = Paths.front();
9729       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9730            B != BEnd; ++B)
9731         Comps.push_back(OffsetOfNode(B->Base));
9732     }
9733 
9734     if (IndirectMemberDecl) {
9735       for (IndirectFieldDecl::chain_iterator FI =
9736            IndirectMemberDecl->chain_begin(),
9737            FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9738         assert(isa<FieldDecl>(*FI));
9739         Comps.push_back(OffsetOfNode(OC.LocStart,
9740                                      cast<FieldDecl>(*FI), OC.LocEnd));
9741       }
9742     } else
9743       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
9744 
9745     CurrentType = MemberDecl->getType().getNonReferenceType();
9746   }
9747 
9748   return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9749                                     TInfo, Comps, Exprs, RParenLoc));
9750 }
9751 
9752 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
9753                                       SourceLocation BuiltinLoc,
9754                                       SourceLocation TypeLoc,
9755                                       ParsedType ParsedArgTy,
9756                                       OffsetOfComponent *CompPtr,
9757                                       unsigned NumComponents,
9758                                       SourceLocation RParenLoc) {
9759 
9760   TypeSourceInfo *ArgTInfo;
9761   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
9762   if (ArgTy.isNull())
9763     return ExprError();
9764 
9765   if (!ArgTInfo)
9766     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9767 
9768   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9769                               RParenLoc);
9770 }
9771 
9772 
9773 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
9774                                  Expr *CondExpr,
9775                                  Expr *LHSExpr, Expr *RHSExpr,
9776                                  SourceLocation RPLoc) {
9777   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9778 
9779   ExprValueKind VK = VK_RValue;
9780   ExprObjectKind OK = OK_Ordinary;
9781   QualType resType;
9782   bool ValueDependent = false;
9783   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
9784     resType = Context.DependentTy;
9785     ValueDependent = true;
9786   } else {
9787     // The conditional expression is required to be a constant expression.
9788     llvm::APSInt condEval(32);
9789     ExprResult CondICE
9790       = VerifyIntegerConstantExpression(CondExpr, &condEval,
9791           diag::err_typecheck_choose_expr_requires_constant, false);
9792     if (CondICE.isInvalid())
9793       return ExprError();
9794     CondExpr = CondICE.take();
9795 
9796     // If the condition is > zero, then the AST type is the same as the LSHExpr.
9797     Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9798 
9799     resType = ActiveExpr->getType();
9800     ValueDependent = ActiveExpr->isValueDependent();
9801     VK = ActiveExpr->getValueKind();
9802     OK = ActiveExpr->getObjectKind();
9803   }
9804 
9805   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
9806                                         resType, VK, OK, RPLoc,
9807                                         resType->isDependentType(),
9808                                         ValueDependent));
9809 }
9810 
9811 //===----------------------------------------------------------------------===//
9812 // Clang Extensions.
9813 //===----------------------------------------------------------------------===//
9814 
9815 /// ActOnBlockStart - This callback is invoked when a block literal is started.
9816 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
9817   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9818   PushBlockScope(CurScope, Block);
9819   CurContext->addDecl(Block);
9820   if (CurScope)
9821     PushDeclContext(CurScope, Block);
9822   else
9823     CurContext = Block;
9824 
9825   getCurBlock()->HasImplicitReturnType = true;
9826 
9827   // Enter a new evaluation context to insulate the block from any
9828   // cleanups from the enclosing full-expression.
9829   PushExpressionEvaluationContext(PotentiallyEvaluated);
9830 }
9831 
9832 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9833                                Scope *CurScope) {
9834   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
9835   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
9836   BlockScopeInfo *CurBlock = getCurBlock();
9837 
9838   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
9839   QualType T = Sig->getType();
9840 
9841   // FIXME: We should allow unexpanded parameter packs here, but that would,
9842   // in turn, make the block expression contain unexpanded parameter packs.
9843   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9844     // Drop the parameters.
9845     FunctionProtoType::ExtProtoInfo EPI;
9846     EPI.HasTrailingReturn = false;
9847     EPI.TypeQuals |= DeclSpec::TQ_const;
9848     T = Context.getFunctionType(Context.DependentTy, None, EPI);
9849     Sig = Context.getTrivialTypeSourceInfo(T);
9850   }
9851 
9852   // GetTypeForDeclarator always produces a function type for a block
9853   // literal signature.  Furthermore, it is always a FunctionProtoType
9854   // unless the function was written with a typedef.
9855   assert(T->isFunctionType() &&
9856          "GetTypeForDeclarator made a non-function block signature");
9857 
9858   // Look for an explicit signature in that function type.
9859   FunctionProtoTypeLoc ExplicitSignature;
9860 
9861   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9862   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
9863 
9864     // Check whether that explicit signature was synthesized by
9865     // GetTypeForDeclarator.  If so, don't save that as part of the
9866     // written signature.
9867     if (ExplicitSignature.getLocalRangeBegin() ==
9868         ExplicitSignature.getLocalRangeEnd()) {
9869       // This would be much cheaper if we stored TypeLocs instead of
9870       // TypeSourceInfos.
9871       TypeLoc Result = ExplicitSignature.getResultLoc();
9872       unsigned Size = Result.getFullDataSize();
9873       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9874       Sig->getTypeLoc().initializeFullCopy(Result, Size);
9875 
9876       ExplicitSignature = FunctionProtoTypeLoc();
9877     }
9878   }
9879 
9880   CurBlock->TheDecl->setSignatureAsWritten(Sig);
9881   CurBlock->FunctionType = T;
9882 
9883   const FunctionType *Fn = T->getAs<FunctionType>();
9884   QualType RetTy = Fn->getResultType();
9885   bool isVariadic =
9886     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9887 
9888   CurBlock->TheDecl->setIsVariadic(isVariadic);
9889 
9890   // Context.DependentTy is used as a placeholder for a missing block
9891   // return type.  TODO:  what should we do with declarators like:
9892   //   ^ * { ... }
9893   // If the answer is "apply template argument deduction"....
9894   if (RetTy != Context.DependentTy) {
9895     CurBlock->ReturnType = RetTy;
9896     CurBlock->TheDecl->setBlockMissingReturnType(false);
9897     CurBlock->HasImplicitReturnType = false;
9898   }
9899 
9900   // Push block parameters from the declarator if we had them.
9901   SmallVector<ParmVarDecl*, 8> Params;
9902   if (ExplicitSignature) {
9903     for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9904       ParmVarDecl *Param = ExplicitSignature.getArg(I);
9905       if (Param->getIdentifier() == 0 &&
9906           !Param->isImplicit() &&
9907           !Param->isInvalidDecl() &&
9908           !getLangOpts().CPlusPlus)
9909         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
9910       Params.push_back(Param);
9911     }
9912 
9913   // Fake up parameter variables if we have a typedef, like
9914   //   ^ fntype { ... }
9915   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9916     for (FunctionProtoType::arg_type_iterator
9917            I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9918       ParmVarDecl *Param =
9919         BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9920                                    ParamInfo.getLocStart(),
9921                                    *I);
9922       Params.push_back(Param);
9923     }
9924   }
9925 
9926   // Set the parameters on the block decl.
9927   if (!Params.empty()) {
9928     CurBlock->TheDecl->setParams(Params);
9929     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9930                              CurBlock->TheDecl->param_end(),
9931                              /*CheckParameterNames=*/false);
9932   }
9933 
9934   // Finally we can process decl attributes.
9935   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
9936 
9937   // Put the parameter variables in scope.  We can bail out immediately
9938   // if we don't have any.
9939   if (Params.empty())
9940     return;
9941 
9942   for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
9943          E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9944     (*AI)->setOwningFunction(CurBlock->TheDecl);
9945 
9946     // If this has an identifier, add it to the scope stack.
9947     if ((*AI)->getIdentifier()) {
9948       CheckShadow(CurBlock->TheScope, *AI);
9949 
9950       PushOnScopeChains(*AI, CurBlock->TheScope);
9951     }
9952   }
9953 }
9954 
9955 /// ActOnBlockError - If there is an error parsing a block, this callback
9956 /// is invoked to pop the information about the block from the action impl.
9957 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
9958   // Leave the expression-evaluation context.
9959   DiscardCleanupsInEvaluationContext();
9960   PopExpressionEvaluationContext();
9961 
9962   // Pop off CurBlock, handle nested blocks.
9963   PopDeclContext();
9964   PopFunctionScopeInfo();
9965 }
9966 
9967 /// ActOnBlockStmtExpr - This is called when the body of a block statement
9968 /// literal was successfully completed.  ^(int x){...}
9969 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
9970                                     Stmt *Body, Scope *CurScope) {
9971   // If blocks are disabled, emit an error.
9972   if (!LangOpts.Blocks)
9973     Diag(CaretLoc, diag::err_blocks_disable);
9974 
9975   // Leave the expression-evaluation context.
9976   if (hasAnyUnrecoverableErrorsInThisFunction())
9977     DiscardCleanupsInEvaluationContext();
9978   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9979   PopExpressionEvaluationContext();
9980 
9981   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
9982 
9983   if (BSI->HasImplicitReturnType)
9984     deduceClosureReturnType(*BSI);
9985 
9986   PopDeclContext();
9987 
9988   QualType RetTy = Context.VoidTy;
9989   if (!BSI->ReturnType.isNull())
9990     RetTy = BSI->ReturnType;
9991 
9992   bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
9993   QualType BlockTy;
9994 
9995   // Set the captured variables on the block.
9996   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9997   SmallVector<BlockDecl::Capture, 4> Captures;
9998   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9999     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
10000     if (Cap.isThisCapture())
10001       continue;
10002     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
10003                               Cap.isNested(), Cap.getInitExpr());
10004     Captures.push_back(NewCap);
10005   }
10006   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
10007                             BSI->CXXThisCaptureIndex != 0);
10008 
10009   // If the user wrote a function type in some form, try to use that.
10010   if (!BSI->FunctionType.isNull()) {
10011     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
10012 
10013     FunctionType::ExtInfo Ext = FTy->getExtInfo();
10014     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
10015 
10016     // Turn protoless block types into nullary block types.
10017     if (isa<FunctionNoProtoType>(FTy)) {
10018       FunctionProtoType::ExtProtoInfo EPI;
10019       EPI.ExtInfo = Ext;
10020       BlockTy = Context.getFunctionType(RetTy, None, EPI);
10021 
10022     // Otherwise, if we don't need to change anything about the function type,
10023     // preserve its sugar structure.
10024     } else if (FTy->getResultType() == RetTy &&
10025                (!NoReturn || FTy->getNoReturnAttr())) {
10026       BlockTy = BSI->FunctionType;
10027 
10028     // Otherwise, make the minimal modifications to the function type.
10029     } else {
10030       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
10031       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10032       EPI.TypeQuals = 0; // FIXME: silently?
10033       EPI.ExtInfo = Ext;
10034       BlockTy = Context.getFunctionType(RetTy, FPT->getArgTypes(), EPI);
10035     }
10036 
10037   // If we don't have a function type, just build one from nothing.
10038   } else {
10039     FunctionProtoType::ExtProtoInfo EPI;
10040     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
10041     BlockTy = Context.getFunctionType(RetTy, None, EPI);
10042   }
10043 
10044   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
10045                            BSI->TheDecl->param_end());
10046   BlockTy = Context.getBlockPointerType(BlockTy);
10047 
10048   // If needed, diagnose invalid gotos and switches in the block.
10049   if (getCurFunction()->NeedsScopeChecking() &&
10050       !hasAnyUnrecoverableErrorsInThisFunction() &&
10051       !PP.isCodeCompletionEnabled())
10052     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
10053 
10054   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
10055 
10056   // Try to apply the named return value optimization. We have to check again
10057   // if we can do this, though, because blocks keep return statements around
10058   // to deduce an implicit return type.
10059   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
10060       !BSI->TheDecl->isDependentContext())
10061     computeNRVO(Body, getCurBlock());
10062 
10063   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
10064   const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
10065   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
10066 
10067   // If the block isn't obviously global, i.e. it captures anything at
10068   // all, then we need to do a few things in the surrounding context:
10069   if (Result->getBlockDecl()->hasCaptures()) {
10070     // First, this expression has a new cleanup object.
10071     ExprCleanupObjects.push_back(Result->getBlockDecl());
10072     ExprNeedsCleanups = true;
10073 
10074     // It also gets a branch-protected scope if any of the captured
10075     // variables needs destruction.
10076     for (BlockDecl::capture_const_iterator
10077            ci = Result->getBlockDecl()->capture_begin(),
10078            ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
10079       const VarDecl *var = ci->getVariable();
10080       if (var->getType().isDestructedType() != QualType::DK_none) {
10081         getCurFunction()->setHasBranchProtectedScope();
10082         break;
10083       }
10084     }
10085   }
10086 
10087   return Owned(Result);
10088 }
10089 
10090 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
10091                                         Expr *E, ParsedType Ty,
10092                                         SourceLocation RPLoc) {
10093   TypeSourceInfo *TInfo;
10094   GetTypeFromParser(Ty, &TInfo);
10095   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
10096 }
10097 
10098 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
10099                                 Expr *E, TypeSourceInfo *TInfo,
10100                                 SourceLocation RPLoc) {
10101   Expr *OrigExpr = E;
10102 
10103   // Get the va_list type
10104   QualType VaListType = Context.getBuiltinVaListType();
10105   if (VaListType->isArrayType()) {
10106     // Deal with implicit array decay; for example, on x86-64,
10107     // va_list is an array, but it's supposed to decay to
10108     // a pointer for va_arg.
10109     VaListType = Context.getArrayDecayedType(VaListType);
10110     // Make sure the input expression also decays appropriately.
10111     ExprResult Result = UsualUnaryConversions(E);
10112     if (Result.isInvalid())
10113       return ExprError();
10114     E = Result.take();
10115   } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
10116     // If va_list is a record type and we are compiling in C++ mode,
10117     // check the argument using reference binding.
10118     InitializedEntity Entity
10119       = InitializedEntity::InitializeParameter(Context,
10120           Context.getLValueReferenceType(VaListType), false);
10121     ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
10122     if (Init.isInvalid())
10123       return ExprError();
10124     E = Init.takeAs<Expr>();
10125   } else {
10126     // Otherwise, the va_list argument must be an l-value because
10127     // it is modified by va_arg.
10128     if (!E->isTypeDependent() &&
10129         CheckForModifiableLvalue(E, BuiltinLoc, *this))
10130       return ExprError();
10131   }
10132 
10133   if (!E->isTypeDependent() &&
10134       !Context.hasSameType(VaListType, E->getType())) {
10135     return ExprError(Diag(E->getLocStart(),
10136                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
10137       << OrigExpr->getType() << E->getSourceRange());
10138   }
10139 
10140   if (!TInfo->getType()->isDependentType()) {
10141     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10142                             diag::err_second_parameter_to_va_arg_incomplete,
10143                             TInfo->getTypeLoc()))
10144       return ExprError();
10145 
10146     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10147                                TInfo->getType(),
10148                                diag::err_second_parameter_to_va_arg_abstract,
10149                                TInfo->getTypeLoc()))
10150       return ExprError();
10151 
10152     if (!TInfo->getType().isPODType(Context)) {
10153       Diag(TInfo->getTypeLoc().getBeginLoc(),
10154            TInfo->getType()->isObjCLifetimeType()
10155              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
10156              : diag::warn_second_parameter_to_va_arg_not_pod)
10157         << TInfo->getType()
10158         << TInfo->getTypeLoc().getSourceRange();
10159     }
10160 
10161     // Check for va_arg where arguments of the given type will be promoted
10162     // (i.e. this va_arg is guaranteed to have undefined behavior).
10163     QualType PromoteType;
10164     if (TInfo->getType()->isPromotableIntegerType()) {
10165       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
10166       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
10167         PromoteType = QualType();
10168     }
10169     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
10170       PromoteType = Context.DoubleTy;
10171     if (!PromoteType.isNull())
10172       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
10173                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
10174                           << TInfo->getType()
10175                           << PromoteType
10176                           << TInfo->getTypeLoc().getSourceRange());
10177   }
10178 
10179   QualType T = TInfo->getType().getNonLValueExprType(Context);
10180   return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
10181 }
10182 
10183 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
10184   // The type of __null will be int or long, depending on the size of
10185   // pointers on the target.
10186   QualType Ty;
10187   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
10188   if (pw == Context.getTargetInfo().getIntWidth())
10189     Ty = Context.IntTy;
10190   else if (pw == Context.getTargetInfo().getLongWidth())
10191     Ty = Context.LongTy;
10192   else if (pw == Context.getTargetInfo().getLongLongWidth())
10193     Ty = Context.LongLongTy;
10194   else {
10195     llvm_unreachable("I don't know size of pointer!");
10196   }
10197 
10198   return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
10199 }
10200 
10201 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
10202                                            Expr *SrcExpr, FixItHint &Hint,
10203                                            bool &IsNSString) {
10204   if (!SemaRef.getLangOpts().ObjC1)
10205     return;
10206 
10207   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10208   if (!PT)
10209     return;
10210 
10211   // Check if the destination is of type 'id'.
10212   if (!PT->isObjCIdType()) {
10213     // Check if the destination is the 'NSString' interface.
10214     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10215     if (!ID || !ID->getIdentifier()->isStr("NSString"))
10216       return;
10217     IsNSString = true;
10218   }
10219 
10220   // Ignore any parens, implicit casts (should only be
10221   // array-to-pointer decays), and not-so-opaque values.  The last is
10222   // important for making this trigger for property assignments.
10223   SrcExpr = SrcExpr->IgnoreParenImpCasts();
10224   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10225     if (OV->getSourceExpr())
10226       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10227 
10228   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
10229   if (!SL || !SL->isAscii())
10230     return;
10231 
10232   Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
10233 }
10234 
10235 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10236                                     SourceLocation Loc,
10237                                     QualType DstType, QualType SrcType,
10238                                     Expr *SrcExpr, AssignmentAction Action,
10239                                     bool *Complained) {
10240   if (Complained)
10241     *Complained = false;
10242 
10243   // Decode the result (notice that AST's are still created for extensions).
10244   bool CheckInferredResultType = false;
10245   bool isInvalid = false;
10246   unsigned DiagKind = 0;
10247   FixItHint Hint;
10248   ConversionFixItGenerator ConvHints;
10249   bool MayHaveConvFixit = false;
10250   bool MayHaveFunctionDiff = false;
10251   bool IsNSString = false;
10252 
10253   switch (ConvTy) {
10254   case Compatible:
10255       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10256       return false;
10257 
10258   case PointerToInt:
10259     DiagKind = diag::ext_typecheck_convert_pointer_int;
10260     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10261     MayHaveConvFixit = true;
10262     break;
10263   case IntToPointer:
10264     DiagKind = diag::ext_typecheck_convert_int_pointer;
10265     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10266     MayHaveConvFixit = true;
10267     break;
10268   case IncompatiblePointer:
10269     MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint, IsNSString);
10270     DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
10271     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10272       SrcType->isObjCObjectPointerType();
10273     if (Hint.isNull() && !CheckInferredResultType) {
10274       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10275     }
10276     else if (CheckInferredResultType) {
10277       SrcType = SrcType.getUnqualifiedType();
10278       DstType = DstType.getUnqualifiedType();
10279     }
10280     else if (IsNSString && !Hint.isNull())
10281       DiagKind = diag::warn_missing_atsign_prefix;
10282     MayHaveConvFixit = true;
10283     break;
10284   case IncompatiblePointerSign:
10285     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10286     break;
10287   case FunctionVoidPointer:
10288     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10289     break;
10290   case IncompatiblePointerDiscardsQualifiers: {
10291     // Perform array-to-pointer decay if necessary.
10292     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10293 
10294     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10295     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10296     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10297       DiagKind = diag::err_typecheck_incompatible_address_space;
10298       break;
10299 
10300 
10301     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10302       DiagKind = diag::err_typecheck_incompatible_ownership;
10303       break;
10304     }
10305 
10306     llvm_unreachable("unknown error case for discarding qualifiers!");
10307     // fallthrough
10308   }
10309   case CompatiblePointerDiscardsQualifiers:
10310     // If the qualifiers lost were because we were applying the
10311     // (deprecated) C++ conversion from a string literal to a char*
10312     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
10313     // Ideally, this check would be performed in
10314     // checkPointerTypesForAssignment. However, that would require a
10315     // bit of refactoring (so that the second argument is an
10316     // expression, rather than a type), which should be done as part
10317     // of a larger effort to fix checkPointerTypesForAssignment for
10318     // C++ semantics.
10319     if (getLangOpts().CPlusPlus &&
10320         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10321       return false;
10322     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10323     break;
10324   case IncompatibleNestedPointerQualifiers:
10325     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
10326     break;
10327   case IntToBlockPointer:
10328     DiagKind = diag::err_int_to_block_pointer;
10329     break;
10330   case IncompatibleBlockPointer:
10331     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
10332     break;
10333   case IncompatibleObjCQualifiedId:
10334     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
10335     // it can give a more specific diagnostic.
10336     DiagKind = diag::warn_incompatible_qualified_id;
10337     break;
10338   case IncompatibleVectors:
10339     DiagKind = diag::warn_incompatible_vectors;
10340     break;
10341   case IncompatibleObjCWeakRef:
10342     DiagKind = diag::err_arc_weak_unavailable_assign;
10343     break;
10344   case Incompatible:
10345     DiagKind = diag::err_typecheck_convert_incompatible;
10346     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10347     MayHaveConvFixit = true;
10348     isInvalid = true;
10349     MayHaveFunctionDiff = true;
10350     break;
10351   }
10352 
10353   QualType FirstType, SecondType;
10354   switch (Action) {
10355   case AA_Assigning:
10356   case AA_Initializing:
10357     // The destination type comes first.
10358     FirstType = DstType;
10359     SecondType = SrcType;
10360     break;
10361 
10362   case AA_Returning:
10363   case AA_Passing:
10364   case AA_Converting:
10365   case AA_Sending:
10366   case AA_Casting:
10367     // The source type comes first.
10368     FirstType = SrcType;
10369     SecondType = DstType;
10370     break;
10371   }
10372 
10373   PartialDiagnostic FDiag = PDiag(DiagKind);
10374   FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
10375 
10376   // If we can fix the conversion, suggest the FixIts.
10377   assert(ConvHints.isNull() || Hint.isNull());
10378   if (!ConvHints.isNull()) {
10379     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
10380          HE = ConvHints.Hints.end(); HI != HE; ++HI)
10381       FDiag << *HI;
10382   } else {
10383     FDiag << Hint;
10384   }
10385   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
10386 
10387   if (MayHaveFunctionDiff)
10388     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
10389 
10390   Diag(Loc, FDiag);
10391 
10392   if (SecondType == Context.OverloadTy)
10393     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
10394                               FirstType);
10395 
10396   if (CheckInferredResultType)
10397     EmitRelatedResultTypeNote(SrcExpr);
10398 
10399   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
10400     EmitRelatedResultTypeNoteForReturn(DstType);
10401 
10402   if (Complained)
10403     *Complained = true;
10404   return isInvalid;
10405 }
10406 
10407 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10408                                                  llvm::APSInt *Result) {
10409   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
10410   public:
10411     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10412       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
10413     }
10414   } Diagnoser;
10415 
10416   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
10417 }
10418 
10419 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10420                                                  llvm::APSInt *Result,
10421                                                  unsigned DiagID,
10422                                                  bool AllowFold) {
10423   class IDDiagnoser : public VerifyICEDiagnoser {
10424     unsigned DiagID;
10425 
10426   public:
10427     IDDiagnoser(unsigned DiagID)
10428       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
10429 
10430     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10431       S.Diag(Loc, DiagID) << SR;
10432     }
10433   } Diagnoser(DiagID);
10434 
10435   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
10436 }
10437 
10438 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
10439                                             SourceRange SR) {
10440   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
10441 }
10442 
10443 ExprResult
10444 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10445                                       VerifyICEDiagnoser &Diagnoser,
10446                                       bool AllowFold) {
10447   SourceLocation DiagLoc = E->getLocStart();
10448 
10449   if (getLangOpts().CPlusPlus11) {
10450     // C++11 [expr.const]p5:
10451     //   If an expression of literal class type is used in a context where an
10452     //   integral constant expression is required, then that class type shall
10453     //   have a single non-explicit conversion function to an integral or
10454     //   unscoped enumeration type
10455     ExprResult Converted;
10456     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
10457     public:
10458       CXX11ConvertDiagnoser(bool Silent)
10459           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
10460                                 Silent, true) {}
10461 
10462       virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10463                                                    QualType T) {
10464         return S.Diag(Loc, diag::err_ice_not_integral) << T;
10465       }
10466 
10467       virtual SemaDiagnosticBuilder diagnoseIncomplete(
10468           Sema &S, SourceLocation Loc, QualType T) {
10469         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
10470       }
10471 
10472       virtual SemaDiagnosticBuilder diagnoseExplicitConv(
10473           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
10474         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10475       }
10476 
10477       virtual SemaDiagnosticBuilder noteExplicitConv(
10478           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
10479         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10480                  << ConvTy->isEnumeralType() << ConvTy;
10481       }
10482 
10483       virtual SemaDiagnosticBuilder diagnoseAmbiguous(
10484           Sema &S, SourceLocation Loc, QualType T) {
10485         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10486       }
10487 
10488       virtual SemaDiagnosticBuilder noteAmbiguous(
10489           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
10490         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10491                  << ConvTy->isEnumeralType() << ConvTy;
10492       }
10493 
10494       virtual SemaDiagnosticBuilder diagnoseConversion(
10495           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
10496         llvm_unreachable("conversion functions are permitted");
10497       }
10498     } ConvertDiagnoser(Diagnoser.Suppress);
10499 
10500     Converted = PerformContextualImplicitConversion(DiagLoc, E,
10501                                                     ConvertDiagnoser);
10502     if (Converted.isInvalid())
10503       return Converted;
10504     E = Converted.take();
10505     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10506       return ExprError();
10507   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10508     // An ICE must be of integral or unscoped enumeration type.
10509     if (!Diagnoser.Suppress)
10510       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10511     return ExprError();
10512   }
10513 
10514   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10515   // in the non-ICE case.
10516   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
10517     if (Result)
10518       *Result = E->EvaluateKnownConstInt(Context);
10519     return Owned(E);
10520   }
10521 
10522   Expr::EvalResult EvalResult;
10523   SmallVector<PartialDiagnosticAt, 8> Notes;
10524   EvalResult.Diag = &Notes;
10525 
10526   // Try to evaluate the expression, and produce diagnostics explaining why it's
10527   // not a constant expression as a side-effect.
10528   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10529                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10530 
10531   // In C++11, we can rely on diagnostics being produced for any expression
10532   // which is not a constant expression. If no diagnostics were produced, then
10533   // this is a constant expression.
10534   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
10535     if (Result)
10536       *Result = EvalResult.Val.getInt();
10537     return Owned(E);
10538   }
10539 
10540   // If our only note is the usual "invalid subexpression" note, just point
10541   // the caret at its location rather than producing an essentially
10542   // redundant note.
10543   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10544         diag::note_invalid_subexpr_in_const_expr) {
10545     DiagLoc = Notes[0].first;
10546     Notes.clear();
10547   }
10548 
10549   if (!Folded || !AllowFold) {
10550     if (!Diagnoser.Suppress) {
10551       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10552       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10553         Diag(Notes[I].first, Notes[I].second);
10554     }
10555 
10556     return ExprError();
10557   }
10558 
10559   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
10560   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10561     Diag(Notes[I].first, Notes[I].second);
10562 
10563   if (Result)
10564     *Result = EvalResult.Val.getInt();
10565   return Owned(E);
10566 }
10567 
10568 namespace {
10569   // Handle the case where we conclude a expression which we speculatively
10570   // considered to be unevaluated is actually evaluated.
10571   class TransformToPE : public TreeTransform<TransformToPE> {
10572     typedef TreeTransform<TransformToPE> BaseTransform;
10573 
10574   public:
10575     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10576 
10577     // Make sure we redo semantic analysis
10578     bool AlwaysRebuild() { return true; }
10579 
10580     // Make sure we handle LabelStmts correctly.
10581     // FIXME: This does the right thing, but maybe we need a more general
10582     // fix to TreeTransform?
10583     StmtResult TransformLabelStmt(LabelStmt *S) {
10584       S->getDecl()->setStmt(0);
10585       return BaseTransform::TransformLabelStmt(S);
10586     }
10587 
10588     // We need to special-case DeclRefExprs referring to FieldDecls which
10589     // are not part of a member pointer formation; normal TreeTransforming
10590     // doesn't catch this case because of the way we represent them in the AST.
10591     // FIXME: This is a bit ugly; is it really the best way to handle this
10592     // case?
10593     //
10594     // Error on DeclRefExprs referring to FieldDecls.
10595     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10596       if (isa<FieldDecl>(E->getDecl()) &&
10597           !SemaRef.isUnevaluatedContext())
10598         return SemaRef.Diag(E->getLocation(),
10599                             diag::err_invalid_non_static_member_use)
10600             << E->getDecl() << E->getSourceRange();
10601 
10602       return BaseTransform::TransformDeclRefExpr(E);
10603     }
10604 
10605     // Exception: filter out member pointer formation
10606     ExprResult TransformUnaryOperator(UnaryOperator *E) {
10607       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10608         return E;
10609 
10610       return BaseTransform::TransformUnaryOperator(E);
10611     }
10612 
10613     ExprResult TransformLambdaExpr(LambdaExpr *E) {
10614       // Lambdas never need to be transformed.
10615       return E;
10616     }
10617   };
10618 }
10619 
10620 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
10621   assert(isUnevaluatedContext() &&
10622          "Should only transform unevaluated expressions");
10623   ExprEvalContexts.back().Context =
10624       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10625   if (isUnevaluatedContext())
10626     return E;
10627   return TransformToPE(*this).TransformExpr(E);
10628 }
10629 
10630 void
10631 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10632                                       Decl *LambdaContextDecl,
10633                                       bool IsDecltype) {
10634   ExprEvalContexts.push_back(
10635              ExpressionEvaluationContextRecord(NewContext,
10636                                                ExprCleanupObjects.size(),
10637                                                ExprNeedsCleanups,
10638                                                LambdaContextDecl,
10639                                                IsDecltype));
10640   ExprNeedsCleanups = false;
10641   if (!MaybeODRUseExprs.empty())
10642     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
10643 }
10644 
10645 void
10646 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10647                                       ReuseLambdaContextDecl_t,
10648                                       bool IsDecltype) {
10649   Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl;
10650   PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype);
10651 }
10652 
10653 void Sema::PopExpressionEvaluationContext() {
10654   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
10655 
10656   if (!Rec.Lambdas.empty()) {
10657     if (Rec.isUnevaluated()) {
10658       // C++11 [expr.prim.lambda]p2:
10659       //   A lambda-expression shall not appear in an unevaluated operand
10660       //   (Clause 5).
10661       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10662         Diag(Rec.Lambdas[I]->getLocStart(),
10663              diag::err_lambda_unevaluated_operand);
10664     } else {
10665       // Mark the capture expressions odr-used. This was deferred
10666       // during lambda expression creation.
10667       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10668         LambdaExpr *Lambda = Rec.Lambdas[I];
10669         for (LambdaExpr::capture_init_iterator
10670                   C = Lambda->capture_init_begin(),
10671                CEnd = Lambda->capture_init_end();
10672              C != CEnd; ++C) {
10673           MarkDeclarationsReferencedInExpr(*C);
10674         }
10675       }
10676     }
10677   }
10678 
10679   // When are coming out of an unevaluated context, clear out any
10680   // temporaries that we may have created as part of the evaluation of
10681   // the expression in that context: they aren't relevant because they
10682   // will never be constructed.
10683   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
10684     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10685                              ExprCleanupObjects.end());
10686     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
10687     CleanupVarDeclMarking();
10688     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
10689   // Otherwise, merge the contexts together.
10690   } else {
10691     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
10692     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10693                             Rec.SavedMaybeODRUseExprs.end());
10694   }
10695 
10696   // Pop the current expression evaluation context off the stack.
10697   ExprEvalContexts.pop_back();
10698 }
10699 
10700 void Sema::DiscardCleanupsInEvaluationContext() {
10701   ExprCleanupObjects.erase(
10702          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10703          ExprCleanupObjects.end());
10704   ExprNeedsCleanups = false;
10705   MaybeODRUseExprs.clear();
10706 }
10707 
10708 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10709   if (!E->getType()->isVariablyModifiedType())
10710     return E;
10711   return TransformToPotentiallyEvaluated(E);
10712 }
10713 
10714 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
10715   // Do not mark anything as "used" within a dependent context; wait for
10716   // an instantiation.
10717   if (SemaRef.CurContext->isDependentContext())
10718     return false;
10719 
10720   switch (SemaRef.ExprEvalContexts.back().Context) {
10721     case Sema::Unevaluated:
10722     case Sema::UnevaluatedAbstract:
10723       // We are in an expression that is not potentially evaluated; do nothing.
10724       // (Depending on how you read the standard, we actually do need to do
10725       // something here for null pointer constants, but the standard's
10726       // definition of a null pointer constant is completely crazy.)
10727       return false;
10728 
10729     case Sema::ConstantEvaluated:
10730     case Sema::PotentiallyEvaluated:
10731       // We are in a potentially evaluated expression (or a constant-expression
10732       // in C++03); we need to do implicit template instantiation, implicitly
10733       // define class members, and mark most declarations as used.
10734       return true;
10735 
10736     case Sema::PotentiallyEvaluatedIfUsed:
10737       // Referenced declarations will only be used if the construct in the
10738       // containing expression is used.
10739       return false;
10740   }
10741   llvm_unreachable("Invalid context");
10742 }
10743 
10744 /// \brief Mark a function referenced, and check whether it is odr-used
10745 /// (C++ [basic.def.odr]p2, C99 6.9p3)
10746 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10747   assert(Func && "No function?");
10748 
10749   Func->setReferenced();
10750 
10751   // C++11 [basic.def.odr]p3:
10752   //   A function whose name appears as a potentially-evaluated expression is
10753   //   odr-used if it is the unique lookup result or the selected member of a
10754   //   set of overloaded functions [...].
10755   //
10756   // We (incorrectly) mark overload resolution as an unevaluated context, so we
10757   // can just check that here. Skip the rest of this function if we've already
10758   // marked the function as used.
10759   if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
10760     // C++11 [temp.inst]p3:
10761     //   Unless a function template specialization has been explicitly
10762     //   instantiated or explicitly specialized, the function template
10763     //   specialization is implicitly instantiated when the specialization is
10764     //   referenced in a context that requires a function definition to exist.
10765     //
10766     // We consider constexpr function templates to be referenced in a context
10767     // that requires a definition to exist whenever they are referenced.
10768     //
10769     // FIXME: This instantiates constexpr functions too frequently. If this is
10770     // really an unevaluated context (and we're not just in the definition of a
10771     // function template or overload resolution or other cases which we
10772     // incorrectly consider to be unevaluated contexts), and we're not in a
10773     // subexpression which we actually need to evaluate (for instance, a
10774     // template argument, array bound or an expression in a braced-init-list),
10775     // we are not permitted to instantiate this constexpr function definition.
10776     //
10777     // FIXME: This also implicitly defines special members too frequently. They
10778     // are only supposed to be implicitly defined if they are odr-used, but they
10779     // are not odr-used from constant expressions in unevaluated contexts.
10780     // However, they cannot be referenced if they are deleted, and they are
10781     // deleted whenever the implicit definition of the special member would
10782     // fail.
10783     if (!Func->isConstexpr() || Func->getBody())
10784       return;
10785     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
10786     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
10787       return;
10788   }
10789 
10790   // Note that this declaration has been used.
10791   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
10792     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
10793       if (Constructor->isDefaultConstructor()) {
10794         if (Constructor->isTrivial())
10795           return;
10796         if (!Constructor->isUsed(false))
10797           DefineImplicitDefaultConstructor(Loc, Constructor);
10798       } else if (Constructor->isCopyConstructor()) {
10799         if (!Constructor->isUsed(false))
10800           DefineImplicitCopyConstructor(Loc, Constructor);
10801       } else if (Constructor->isMoveConstructor()) {
10802         if (!Constructor->isUsed(false))
10803           DefineImplicitMoveConstructor(Loc, Constructor);
10804       }
10805     } else if (Constructor->getInheritedConstructor()) {
10806       if (!Constructor->isUsed(false))
10807         DefineInheritingConstructor(Loc, Constructor);
10808     }
10809 
10810     MarkVTableUsed(Loc, Constructor->getParent());
10811   } else if (CXXDestructorDecl *Destructor =
10812                  dyn_cast<CXXDestructorDecl>(Func)) {
10813     if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10814         !Destructor->isUsed(false))
10815       DefineImplicitDestructor(Loc, Destructor);
10816     if (Destructor->isVirtual())
10817       MarkVTableUsed(Loc, Destructor->getParent());
10818   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
10819     if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10820         MethodDecl->isOverloadedOperator() &&
10821         MethodDecl->getOverloadedOperator() == OO_Equal) {
10822       if (!MethodDecl->isUsed(false)) {
10823         if (MethodDecl->isCopyAssignmentOperator())
10824           DefineImplicitCopyAssignment(Loc, MethodDecl);
10825         else
10826           DefineImplicitMoveAssignment(Loc, MethodDecl);
10827       }
10828     } else if (isa<CXXConversionDecl>(MethodDecl) &&
10829                MethodDecl->getParent()->isLambda()) {
10830       CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10831       if (Conversion->isLambdaToBlockPointerConversion())
10832         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10833       else
10834         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
10835     } else if (MethodDecl->isVirtual())
10836       MarkVTableUsed(Loc, MethodDecl->getParent());
10837   }
10838 
10839   // Recursive functions should be marked when used from another function.
10840   // FIXME: Is this really right?
10841   if (CurContext == Func) return;
10842 
10843   // Resolve the exception specification for any function which is
10844   // used: CodeGen will need it.
10845   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
10846   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10847     ResolveExceptionSpec(Loc, FPT);
10848 
10849   // Implicit instantiation of function templates and member functions of
10850   // class templates.
10851   if (Func->isImplicitlyInstantiable()) {
10852     bool AlreadyInstantiated = false;
10853     SourceLocation PointOfInstantiation = Loc;
10854     if (FunctionTemplateSpecializationInfo *SpecInfo
10855                               = Func->getTemplateSpecializationInfo()) {
10856       if (SpecInfo->getPointOfInstantiation().isInvalid())
10857         SpecInfo->setPointOfInstantiation(Loc);
10858       else if (SpecInfo->getTemplateSpecializationKind()
10859                  == TSK_ImplicitInstantiation) {
10860         AlreadyInstantiated = true;
10861         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10862       }
10863     } else if (MemberSpecializationInfo *MSInfo
10864                                 = Func->getMemberSpecializationInfo()) {
10865       if (MSInfo->getPointOfInstantiation().isInvalid())
10866         MSInfo->setPointOfInstantiation(Loc);
10867       else if (MSInfo->getTemplateSpecializationKind()
10868                  == TSK_ImplicitInstantiation) {
10869         AlreadyInstantiated = true;
10870         PointOfInstantiation = MSInfo->getPointOfInstantiation();
10871       }
10872     }
10873 
10874     if (!AlreadyInstantiated || Func->isConstexpr()) {
10875       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10876           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
10877         PendingLocalImplicitInstantiations.push_back(
10878             std::make_pair(Func, PointOfInstantiation));
10879       else if (Func->isConstexpr())
10880         // Do not defer instantiations of constexpr functions, to avoid the
10881         // expression evaluator needing to call back into Sema if it sees a
10882         // call to such a function.
10883         InstantiateFunctionDefinition(PointOfInstantiation, Func);
10884       else {
10885         PendingInstantiations.push_back(std::make_pair(Func,
10886                                                        PointOfInstantiation));
10887         // Notify the consumer that a function was implicitly instantiated.
10888         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10889       }
10890     }
10891   } else {
10892     // Walk redefinitions, as some of them may be instantiable.
10893     for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10894          e(Func->redecls_end()); i != e; ++i) {
10895       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10896         MarkFunctionReferenced(Loc, *i);
10897     }
10898   }
10899 
10900   // Keep track of used but undefined functions.
10901   if (!Func->isDefined()) {
10902     if (mightHaveNonExternalLinkage(Func))
10903       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
10904     else if (Func->getMostRecentDecl()->isInlined() &&
10905              (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
10906              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
10907       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
10908   }
10909 
10910   // Normally the must current decl is marked used while processing the use and
10911   // any subsequent decls are marked used by decl merging. This fails with
10912   // template instantiation since marking can happen at the end of the file
10913   // and, because of the two phase lookup, this function is called with at
10914   // decl in the middle of a decl chain. We loop to maintain the invariant
10915   // that once a decl is used, all decls after it are also used.
10916   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
10917     F->setUsed(true);
10918     if (F == Func)
10919       break;
10920   }
10921 }
10922 
10923 static void
10924 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10925                                    VarDecl *var, DeclContext *DC) {
10926   DeclContext *VarDC = var->getDeclContext();
10927 
10928   //  If the parameter still belongs to the translation unit, then
10929   //  we're actually just using one parameter in the declaration of
10930   //  the next.
10931   if (isa<ParmVarDecl>(var) &&
10932       isa<TranslationUnitDecl>(VarDC))
10933     return;
10934 
10935   // For C code, don't diagnose about capture if we're not actually in code
10936   // right now; it's impossible to write a non-constant expression outside of
10937   // function context, so we'll get other (more useful) diagnostics later.
10938   //
10939   // For C++, things get a bit more nasty... it would be nice to suppress this
10940   // diagnostic for certain cases like using a local variable in an array bound
10941   // for a member of a local class, but the correct predicate is not obvious.
10942   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
10943     return;
10944 
10945   if (isa<CXXMethodDecl>(VarDC) &&
10946       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10947     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10948       << var->getIdentifier();
10949   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10950     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10951       << var->getIdentifier() << fn->getDeclName();
10952   } else if (isa<BlockDecl>(VarDC)) {
10953     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10954       << var->getIdentifier();
10955   } else {
10956     // FIXME: Is there any other context where a local variable can be
10957     // declared?
10958     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10959       << var->getIdentifier();
10960   }
10961 
10962   S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10963     << var->getIdentifier();
10964 
10965   // FIXME: Add additional diagnostic info about class etc. which prevents
10966   // capture.
10967 }
10968 
10969 /// \brief Capture the given variable in the captured region.
10970 static ExprResult captureInCapturedRegion(Sema &S, CapturedRegionScopeInfo *RSI,
10971                                           VarDecl *Var, QualType FieldType,
10972                                           QualType DeclRefType,
10973                                           SourceLocation Loc,
10974                                           bool RefersToEnclosingLocal) {
10975   // The current implemention assumes that all variables are captured
10976   // by references. Since there is no capture by copy, no expression evaluation
10977   // will be needed.
10978   //
10979   RecordDecl *RD = RSI->TheRecordDecl;
10980 
10981   FieldDecl *Field
10982     = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, FieldType,
10983                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
10984                         0, false, ICIS_NoInit);
10985   Field->setImplicit(true);
10986   Field->setAccess(AS_private);
10987   RD->addDecl(Field);
10988 
10989   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10990                                           DeclRefType, VK_LValue, Loc);
10991   Var->setReferenced(true);
10992   Var->setUsed(true);
10993 
10994   return Ref;
10995 }
10996 
10997 /// \brief Capture the given variable in the given lambda expression.
10998 static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
10999                                   VarDecl *Var, QualType FieldType,
11000                                   QualType DeclRefType,
11001                                   SourceLocation Loc,
11002                                   bool RefersToEnclosingLocal) {
11003   CXXRecordDecl *Lambda = LSI->Lambda;
11004 
11005   // Build the non-static data member.
11006   FieldDecl *Field
11007     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
11008                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
11009                         0, false, ICIS_NoInit);
11010   Field->setImplicit(true);
11011   Field->setAccess(AS_private);
11012   Lambda->addDecl(Field);
11013 
11014   // C++11 [expr.prim.lambda]p21:
11015   //   When the lambda-expression is evaluated, the entities that
11016   //   are captured by copy are used to direct-initialize each
11017   //   corresponding non-static data member of the resulting closure
11018   //   object. (For array members, the array elements are
11019   //   direct-initialized in increasing subscript order.) These
11020   //   initializations are performed in the (unspecified) order in
11021   //   which the non-static data members are declared.
11022 
11023   // Introduce a new evaluation context for the initialization, so
11024   // that temporaries introduced as part of the capture are retained
11025   // to be re-"exported" from the lambda expression itself.
11026   EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
11027 
11028   // C++ [expr.prim.labda]p12:
11029   //   An entity captured by a lambda-expression is odr-used (3.2) in
11030   //   the scope containing the lambda-expression.
11031   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11032                                           DeclRefType, VK_LValue, Loc);
11033   Var->setReferenced(true);
11034   Var->setUsed(true);
11035 
11036   // When the field has array type, create index variables for each
11037   // dimension of the array. We use these index variables to subscript
11038   // the source array, and other clients (e.g., CodeGen) will perform
11039   // the necessary iteration with these index variables.
11040   SmallVector<VarDecl *, 4> IndexVariables;
11041   QualType BaseType = FieldType;
11042   QualType SizeType = S.Context.getSizeType();
11043   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
11044   while (const ConstantArrayType *Array
11045                         = S.Context.getAsConstantArrayType(BaseType)) {
11046     // Create the iteration variable for this array index.
11047     IdentifierInfo *IterationVarName = 0;
11048     {
11049       SmallString<8> Str;
11050       llvm::raw_svector_ostream OS(Str);
11051       OS << "__i" << IndexVariables.size();
11052       IterationVarName = &S.Context.Idents.get(OS.str());
11053     }
11054     VarDecl *IterationVar
11055       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11056                         IterationVarName, SizeType,
11057                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11058                         SC_None);
11059     IndexVariables.push_back(IterationVar);
11060     LSI->ArrayIndexVars.push_back(IterationVar);
11061 
11062     // Create a reference to the iteration variable.
11063     ExprResult IterationVarRef
11064       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
11065     assert(!IterationVarRef.isInvalid() &&
11066            "Reference to invented variable cannot fail!");
11067     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
11068     assert(!IterationVarRef.isInvalid() &&
11069            "Conversion of invented variable cannot fail!");
11070 
11071     // Subscript the array with this iteration variable.
11072     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
11073                              Ref, Loc, IterationVarRef.take(), Loc);
11074     if (Subscript.isInvalid()) {
11075       S.CleanupVarDeclMarking();
11076       S.DiscardCleanupsInEvaluationContext();
11077       return ExprError();
11078     }
11079 
11080     Ref = Subscript.take();
11081     BaseType = Array->getElementType();
11082   }
11083 
11084   // Construct the entity that we will be initializing. For an array, this
11085   // will be first element in the array, which may require several levels
11086   // of array-subscript entities.
11087   SmallVector<InitializedEntity, 4> Entities;
11088   Entities.reserve(1 + IndexVariables.size());
11089   Entities.push_back(
11090     InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
11091   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
11092     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
11093                                                             0,
11094                                                             Entities.back()));
11095 
11096   InitializationKind InitKind
11097     = InitializationKind::CreateDirect(Loc, Loc, Loc);
11098   InitializationSequence Init(S, Entities.back(), InitKind, Ref);
11099   ExprResult Result(true);
11100   if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
11101     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
11102 
11103   // If this initialization requires any cleanups (e.g., due to a
11104   // default argument to a copy constructor), note that for the
11105   // lambda.
11106   if (S.ExprNeedsCleanups)
11107     LSI->ExprNeedsCleanups = true;
11108 
11109   // Exit the expression evaluation context used for the capture.
11110   S.CleanupVarDeclMarking();
11111   S.DiscardCleanupsInEvaluationContext();
11112   return Result;
11113 }
11114 
11115 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
11116                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
11117                               bool BuildAndDiagnose,
11118                               QualType &CaptureType,
11119                               QualType &DeclRefType) {
11120   bool Nested = false;
11121 
11122   DeclContext *DC = CurContext;
11123   if (Var->getDeclContext() == DC) return true;
11124   if (!Var->hasLocalStorage()) return true;
11125 
11126   bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11127 
11128   // Walk up the stack to determine whether we can capture the variable,
11129   // performing the "simple" checks that don't depend on type. We stop when
11130   // we've either hit the declared scope of the variable or find an existing
11131   // capture of that variable.
11132   CaptureType = Var->getType();
11133   DeclRefType = CaptureType.getNonReferenceType();
11134   bool Explicit = (Kind != TryCapture_Implicit);
11135   unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
11136   do {
11137     // Only block literals, captured statements, and lambda expressions can
11138     // capture; other scopes don't work.
11139     DeclContext *ParentDC;
11140     if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC))
11141       ParentDC = DC->getParent();
11142     else if (isa<CXXMethodDecl>(DC) &&
11143              cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
11144              cast<CXXRecordDecl>(DC->getParent())->isLambda())
11145       ParentDC = DC->getParent()->getParent();
11146     else {
11147       if (BuildAndDiagnose)
11148         diagnoseUncapturableValueReference(*this, Loc, Var, DC);
11149       return true;
11150     }
11151 
11152     CapturingScopeInfo *CSI =
11153       cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
11154 
11155     // Check whether we've already captured it.
11156     if (CSI->isCaptured(Var)) {
11157       const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
11158 
11159       // If we found a capture, any subcaptures are nested.
11160       Nested = true;
11161 
11162       // Retrieve the capture type for this variable.
11163       CaptureType = Cap.getCaptureType();
11164 
11165       // Compute the type of an expression that refers to this variable.
11166       DeclRefType = CaptureType.getNonReferenceType();
11167 
11168       if (Cap.isCopyCapture() &&
11169           !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
11170         DeclRefType.addConst();
11171       break;
11172     }
11173 
11174     bool IsBlock = isa<BlockScopeInfo>(CSI);
11175     bool IsLambda = isa<LambdaScopeInfo>(CSI);
11176 
11177     // Lambdas are not allowed to capture unnamed variables
11178     // (e.g. anonymous unions).
11179     // FIXME: The C++11 rule don't actually state this explicitly, but I'm
11180     // assuming that's the intent.
11181     if (IsLambda && !Var->getDeclName()) {
11182       if (BuildAndDiagnose) {
11183         Diag(Loc, diag::err_lambda_capture_anonymous_var);
11184         Diag(Var->getLocation(), diag::note_declared_at);
11185       }
11186       return true;
11187     }
11188 
11189     // Prohibit variably-modified types; they're difficult to deal with.
11190     if (Var->getType()->isVariablyModifiedType()) {
11191       if (BuildAndDiagnose) {
11192         if (IsBlock)
11193           Diag(Loc, diag::err_ref_vm_type);
11194         else
11195           Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
11196         Diag(Var->getLocation(), diag::note_previous_decl)
11197           << Var->getDeclName();
11198       }
11199       return true;
11200     }
11201     // Prohibit structs with flexible array members too.
11202     // We cannot capture what is in the tail end of the struct.
11203     if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
11204       if (VTTy->getDecl()->hasFlexibleArrayMember()) {
11205         if (BuildAndDiagnose) {
11206           if (IsBlock)
11207             Diag(Loc, diag::err_ref_flexarray_type);
11208           else
11209             Diag(Loc, diag::err_lambda_capture_flexarray_type)
11210               << Var->getDeclName();
11211           Diag(Var->getLocation(), diag::note_previous_decl)
11212             << Var->getDeclName();
11213         }
11214         return true;
11215       }
11216     }
11217     // Lambdas and captured statements are not allowed to capture __block
11218     // variables; they don't support the expected semantics.
11219     if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
11220       if (BuildAndDiagnose) {
11221         Diag(Loc, diag::err_capture_block_variable)
11222           << Var->getDeclName() << !IsLambda;
11223         Diag(Var->getLocation(), diag::note_previous_decl)
11224           << Var->getDeclName();
11225       }
11226       return true;
11227     }
11228 
11229     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
11230       // No capture-default
11231       if (BuildAndDiagnose) {
11232         Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
11233         Diag(Var->getLocation(), diag::note_previous_decl)
11234           << Var->getDeclName();
11235         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
11236              diag::note_lambda_decl);
11237       }
11238       return true;
11239     }
11240 
11241     FunctionScopesIndex--;
11242     DC = ParentDC;
11243     Explicit = false;
11244   } while (!Var->getDeclContext()->Equals(DC));
11245 
11246   // Walk back down the scope stack, computing the type of the capture at
11247   // each step, checking type-specific requirements, and adding captures if
11248   // requested.
11249   for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
11250        ++I) {
11251     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
11252 
11253     // Compute the type of the capture and of a reference to the capture within
11254     // this scope.
11255     if (isa<BlockScopeInfo>(CSI)) {
11256       Expr *CopyExpr = 0;
11257       bool ByRef = false;
11258 
11259       // Blocks are not allowed to capture arrays.
11260       if (CaptureType->isArrayType()) {
11261         if (BuildAndDiagnose) {
11262           Diag(Loc, diag::err_ref_array_type);
11263           Diag(Var->getLocation(), diag::note_previous_decl)
11264           << Var->getDeclName();
11265         }
11266         return true;
11267       }
11268 
11269       // Forbid the block-capture of autoreleasing variables.
11270       if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11271         if (BuildAndDiagnose) {
11272           Diag(Loc, diag::err_arc_autoreleasing_capture)
11273             << /*block*/ 0;
11274           Diag(Var->getLocation(), diag::note_previous_decl)
11275             << Var->getDeclName();
11276         }
11277         return true;
11278       }
11279 
11280       if (HasBlocksAttr || CaptureType->isReferenceType()) {
11281         // Block capture by reference does not change the capture or
11282         // declaration reference types.
11283         ByRef = true;
11284       } else {
11285         // Block capture by copy introduces 'const'.
11286         CaptureType = CaptureType.getNonReferenceType().withConst();
11287         DeclRefType = CaptureType;
11288 
11289         if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
11290           if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11291             // The capture logic needs the destructor, so make sure we mark it.
11292             // Usually this is unnecessary because most local variables have
11293             // their destructors marked at declaration time, but parameters are
11294             // an exception because it's technically only the call site that
11295             // actually requires the destructor.
11296             if (isa<ParmVarDecl>(Var))
11297               FinalizeVarWithDestructor(Var, Record);
11298 
11299             // Enter a new evaluation context to insulate the copy
11300             // full-expression.
11301             EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11302 
11303             // According to the blocks spec, the capture of a variable from
11304             // the stack requires a const copy constructor.  This is not true
11305             // of the copy/move done to move a __block variable to the heap.
11306             Expr *DeclRef = new (Context) DeclRefExpr(Var, Nested,
11307                                                       DeclRefType.withConst(),
11308                                                       VK_LValue, Loc);
11309 
11310             ExprResult Result
11311               = PerformCopyInitialization(
11312                   InitializedEntity::InitializeBlock(Var->getLocation(),
11313                                                      CaptureType, false),
11314                   Loc, Owned(DeclRef));
11315 
11316             // Build a full-expression copy expression if initialization
11317             // succeeded and used a non-trivial constructor.  Recover from
11318             // errors by pretending that the copy isn't necessary.
11319             if (!Result.isInvalid() &&
11320                 !cast<CXXConstructExpr>(Result.get())->getConstructor()
11321                    ->isTrivial()) {
11322               Result = MaybeCreateExprWithCleanups(Result);
11323               CopyExpr = Result.take();
11324             }
11325           }
11326         }
11327       }
11328 
11329       // Actually capture the variable.
11330       if (BuildAndDiagnose)
11331         CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11332                         SourceLocation(), CaptureType, CopyExpr);
11333       Nested = true;
11334       continue;
11335     }
11336 
11337     if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
11338       // By default, capture variables by reference.
11339       bool ByRef = true;
11340       // Using an LValue reference type is consistent with Lambdas (see below).
11341       CaptureType = Context.getLValueReferenceType(DeclRefType);
11342 
11343       Expr *CopyExpr = 0;
11344       if (BuildAndDiagnose) {
11345         ExprResult Result = captureInCapturedRegion(*this, RSI, Var,
11346                                                     CaptureType, DeclRefType,
11347                                                     Loc, Nested);
11348         if (!Result.isInvalid())
11349           CopyExpr = Result.take();
11350       }
11351 
11352       // Actually capture the variable.
11353       if (BuildAndDiagnose)
11354         CSI->addCapture(Var, /*isBlock*/false, ByRef, Nested, Loc,
11355                         SourceLocation(), CaptureType, CopyExpr);
11356       Nested = true;
11357       continue;
11358     }
11359 
11360     LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
11361 
11362     // Determine whether we are capturing by reference or by value.
11363     bool ByRef = false;
11364     if (I == N - 1 && Kind != TryCapture_Implicit) {
11365       ByRef = (Kind == TryCapture_ExplicitByRef);
11366     } else {
11367       ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
11368     }
11369 
11370     // Compute the type of the field that will capture this variable.
11371     if (ByRef) {
11372       // C++11 [expr.prim.lambda]p15:
11373       //   An entity is captured by reference if it is implicitly or
11374       //   explicitly captured but not captured by copy. It is
11375       //   unspecified whether additional unnamed non-static data
11376       //   members are declared in the closure type for entities
11377       //   captured by reference.
11378       //
11379       // FIXME: It is not clear whether we want to build an lvalue reference
11380       // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
11381       // to do the former, while EDG does the latter. Core issue 1249 will
11382       // clarify, but for now we follow GCC because it's a more permissive and
11383       // easily defensible position.
11384       CaptureType = Context.getLValueReferenceType(DeclRefType);
11385     } else {
11386       // C++11 [expr.prim.lambda]p14:
11387       //   For each entity captured by copy, an unnamed non-static
11388       //   data member is declared in the closure type. The
11389       //   declaration order of these members is unspecified. The type
11390       //   of such a data member is the type of the corresponding
11391       //   captured entity if the entity is not a reference to an
11392       //   object, or the referenced type otherwise. [Note: If the
11393       //   captured entity is a reference to a function, the
11394       //   corresponding data member is also a reference to a
11395       //   function. - end note ]
11396       if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
11397         if (!RefType->getPointeeType()->isFunctionType())
11398           CaptureType = RefType->getPointeeType();
11399       }
11400 
11401       // Forbid the lambda copy-capture of autoreleasing variables.
11402       if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11403         if (BuildAndDiagnose) {
11404           Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
11405           Diag(Var->getLocation(), diag::note_previous_decl)
11406             << Var->getDeclName();
11407         }
11408         return true;
11409       }
11410     }
11411 
11412     // Capture this variable in the lambda.
11413     Expr *CopyExpr = 0;
11414     if (BuildAndDiagnose) {
11415       ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
11416                                           DeclRefType, Loc,
11417                                           Nested);
11418       if (!Result.isInvalid())
11419         CopyExpr = Result.take();
11420     }
11421 
11422     // Compute the type of a reference to this captured variable.
11423     if (ByRef)
11424       DeclRefType = CaptureType.getNonReferenceType();
11425     else {
11426       // C++ [expr.prim.lambda]p5:
11427       //   The closure type for a lambda-expression has a public inline
11428       //   function call operator [...]. This function call operator is
11429       //   declared const (9.3.1) if and only if the lambda-expression’s
11430       //   parameter-declaration-clause is not followed by mutable.
11431       DeclRefType = CaptureType.getNonReferenceType();
11432       if (!LSI->Mutable && !CaptureType->isReferenceType())
11433         DeclRefType.addConst();
11434     }
11435 
11436     // Add the capture.
11437     if (BuildAndDiagnose)
11438       CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
11439                       EllipsisLoc, CaptureType, CopyExpr);
11440     Nested = true;
11441   }
11442 
11443   return false;
11444 }
11445 
11446 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
11447                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
11448   QualType CaptureType;
11449   QualType DeclRefType;
11450   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
11451                             /*BuildAndDiagnose=*/true, CaptureType,
11452                             DeclRefType);
11453 }
11454 
11455 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
11456   QualType CaptureType;
11457   QualType DeclRefType;
11458 
11459   // Determine whether we can capture this variable.
11460   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
11461                          /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
11462     return QualType();
11463 
11464   return DeclRefType;
11465 }
11466 
11467 static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
11468                                SourceLocation Loc) {
11469   // Keep track of used but undefined variables.
11470   // FIXME: We shouldn't suppress this warning for static data members.
11471   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
11472       !Var->isExternallyVisible() &&
11473       !(Var->isStaticDataMember() && Var->hasInit())) {
11474     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
11475     if (old.isInvalid()) old = Loc;
11476   }
11477 
11478   SemaRef.tryCaptureVariable(Var, Loc);
11479 
11480   Var->setUsed(true);
11481 }
11482 
11483 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
11484   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
11485   // an object that satisfies the requirements for appearing in a
11486   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
11487   // is immediately applied."  This function handles the lvalue-to-rvalue
11488   // conversion part.
11489   MaybeODRUseExprs.erase(E->IgnoreParens());
11490 }
11491 
11492 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
11493   if (!Res.isUsable())
11494     return Res;
11495 
11496   // If a constant-expression is a reference to a variable where we delay
11497   // deciding whether it is an odr-use, just assume we will apply the
11498   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
11499   // (a non-type template argument), we have special handling anyway.
11500   UpdateMarkingForLValueToRValue(Res.get());
11501   return Res;
11502 }
11503 
11504 void Sema::CleanupVarDeclMarking() {
11505   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
11506                                         e = MaybeODRUseExprs.end();
11507        i != e; ++i) {
11508     VarDecl *Var;
11509     SourceLocation Loc;
11510     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
11511       Var = cast<VarDecl>(DRE->getDecl());
11512       Loc = DRE->getLocation();
11513     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
11514       Var = cast<VarDecl>(ME->getMemberDecl());
11515       Loc = ME->getMemberLoc();
11516     } else {
11517       llvm_unreachable("Unexpcted expression");
11518     }
11519 
11520     MarkVarDeclODRUsed(*this, Var, Loc);
11521   }
11522 
11523   MaybeODRUseExprs.clear();
11524 }
11525 
11526 // Mark a VarDecl referenced, and perform the necessary handling to compute
11527 // odr-uses.
11528 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
11529                                     VarDecl *Var, Expr *E) {
11530   Var->setReferenced();
11531 
11532   if (!IsPotentiallyEvaluatedContext(SemaRef))
11533     return;
11534 
11535   // Implicit instantiation of static data members of class templates.
11536   if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
11537     MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
11538     assert(MSInfo && "Missing member specialization information?");
11539     bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
11540     if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
11541         (!AlreadyInstantiated ||
11542          Var->isUsableInConstantExpressions(SemaRef.Context))) {
11543       if (!AlreadyInstantiated) {
11544         // This is a modification of an existing AST node. Notify listeners.
11545         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
11546           L->StaticDataMemberInstantiated(Var);
11547         MSInfo->setPointOfInstantiation(Loc);
11548       }
11549       SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
11550       if (Var->isUsableInConstantExpressions(SemaRef.Context))
11551         // Do not defer instantiations of variables which could be used in a
11552         // constant expression.
11553         SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
11554       else
11555         SemaRef.PendingInstantiations.push_back(
11556             std::make_pair(Var, PointOfInstantiation));
11557     }
11558   }
11559 
11560   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
11561   // the requirements for appearing in a constant expression (5.19) and, if
11562   // it is an object, the lvalue-to-rvalue conversion (4.1)
11563   // is immediately applied."  We check the first part here, and
11564   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
11565   // Note that we use the C++11 definition everywhere because nothing in
11566   // C++03 depends on whether we get the C++03 version correct. The second
11567   // part does not apply to references, since they are not objects.
11568   const VarDecl *DefVD;
11569   if (E && !isa<ParmVarDecl>(Var) &&
11570       Var->isUsableInConstantExpressions(SemaRef.Context) &&
11571       Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) {
11572     if (!Var->getType()->isReferenceType())
11573       SemaRef.MaybeODRUseExprs.insert(E);
11574   } else
11575     MarkVarDeclODRUsed(SemaRef, Var, Loc);
11576 }
11577 
11578 /// \brief Mark a variable referenced, and check whether it is odr-used
11579 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
11580 /// used directly for normal expressions referring to VarDecl.
11581 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
11582   DoMarkVarDeclReferenced(*this, Loc, Var, 0);
11583 }
11584 
11585 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
11586                                Decl *D, Expr *E, bool OdrUse) {
11587   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
11588     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
11589     return;
11590   }
11591 
11592   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
11593 
11594   // If this is a call to a method via a cast, also mark the method in the
11595   // derived class used in case codegen can devirtualize the call.
11596   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11597   if (!ME)
11598     return;
11599   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
11600   if (!MD)
11601     return;
11602   const Expr *Base = ME->getBase();
11603   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
11604   if (!MostDerivedClassDecl)
11605     return;
11606   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
11607   if (!DM || DM->isPure())
11608     return;
11609   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
11610 }
11611 
11612 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
11613 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
11614   // TODO: update this with DR# once a defect report is filed.
11615   // C++11 defect. The address of a pure member should not be an ODR use, even
11616   // if it's a qualified reference.
11617   bool OdrUse = true;
11618   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
11619     if (Method->isVirtual())
11620       OdrUse = false;
11621   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
11622 }
11623 
11624 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
11625 void Sema::MarkMemberReferenced(MemberExpr *E) {
11626   // C++11 [basic.def.odr]p2:
11627   //   A non-overloaded function whose name appears as a potentially-evaluated
11628   //   expression or a member of a set of candidate functions, if selected by
11629   //   overload resolution when referred to from a potentially-evaluated
11630   //   expression, is odr-used, unless it is a pure virtual function and its
11631   //   name is not explicitly qualified.
11632   bool OdrUse = true;
11633   if (!E->hasQualifier()) {
11634     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
11635       if (Method->isPure())
11636         OdrUse = false;
11637   }
11638   SourceLocation Loc = E->getMemberLoc().isValid() ?
11639                             E->getMemberLoc() : E->getLocStart();
11640   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
11641 }
11642 
11643 /// \brief Perform marking for a reference to an arbitrary declaration.  It
11644 /// marks the declaration referenced, and performs odr-use checking for functions
11645 /// and variables. This method should not be used when building an normal
11646 /// expression which refers to a variable.
11647 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
11648   if (OdrUse) {
11649     if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11650       MarkVariableReferenced(Loc, VD);
11651       return;
11652     }
11653     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
11654       MarkFunctionReferenced(Loc, FD);
11655       return;
11656     }
11657   }
11658   D->setReferenced();
11659 }
11660 
11661 namespace {
11662   // Mark all of the declarations referenced
11663   // FIXME: Not fully implemented yet! We need to have a better understanding
11664   // of when we're entering
11665   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11666     Sema &S;
11667     SourceLocation Loc;
11668 
11669   public:
11670     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
11671 
11672     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
11673 
11674     bool TraverseTemplateArgument(const TemplateArgument &Arg);
11675     bool TraverseRecordType(RecordType *T);
11676   };
11677 }
11678 
11679 bool MarkReferencedDecls::TraverseTemplateArgument(
11680   const TemplateArgument &Arg) {
11681   if (Arg.getKind() == TemplateArgument::Declaration) {
11682     if (Decl *D = Arg.getAsDecl())
11683       S.MarkAnyDeclReferenced(Loc, D, true);
11684   }
11685 
11686   return Inherited::TraverseTemplateArgument(Arg);
11687 }
11688 
11689 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
11690   if (ClassTemplateSpecializationDecl *Spec
11691                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11692     const TemplateArgumentList &Args = Spec->getTemplateArgs();
11693     return TraverseTemplateArguments(Args.data(), Args.size());
11694   }
11695 
11696   return true;
11697 }
11698 
11699 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11700   MarkReferencedDecls Marker(*this, Loc);
11701   Marker.TraverseType(Context.getCanonicalType(T));
11702 }
11703 
11704 namespace {
11705   /// \brief Helper class that marks all of the declarations referenced by
11706   /// potentially-evaluated subexpressions as "referenced".
11707   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11708     Sema &S;
11709     bool SkipLocalVariables;
11710 
11711   public:
11712     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11713 
11714     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11715       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
11716 
11717     void VisitDeclRefExpr(DeclRefExpr *E) {
11718       // If we were asked not to visit local variables, don't.
11719       if (SkipLocalVariables) {
11720         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11721           if (VD->hasLocalStorage())
11722             return;
11723       }
11724 
11725       S.MarkDeclRefReferenced(E);
11726     }
11727 
11728     void VisitMemberExpr(MemberExpr *E) {
11729       S.MarkMemberReferenced(E);
11730       Inherited::VisitMemberExpr(E);
11731     }
11732 
11733     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
11734       S.MarkFunctionReferenced(E->getLocStart(),
11735             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11736       Visit(E->getSubExpr());
11737     }
11738 
11739     void VisitCXXNewExpr(CXXNewExpr *E) {
11740       if (E->getOperatorNew())
11741         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
11742       if (E->getOperatorDelete())
11743         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11744       Inherited::VisitCXXNewExpr(E);
11745     }
11746 
11747     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11748       if (E->getOperatorDelete())
11749         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11750       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11751       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11752         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
11753         S.MarkFunctionReferenced(E->getLocStart(),
11754                                     S.LookupDestructor(Record));
11755       }
11756 
11757       Inherited::VisitCXXDeleteExpr(E);
11758     }
11759 
11760     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11761       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
11762       Inherited::VisitCXXConstructExpr(E);
11763     }
11764 
11765     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11766       Visit(E->getExpr());
11767     }
11768 
11769     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11770       Inherited::VisitImplicitCastExpr(E);
11771 
11772       if (E->getCastKind() == CK_LValueToRValue)
11773         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11774     }
11775   };
11776 }
11777 
11778 /// \brief Mark any declarations that appear within this expression or any
11779 /// potentially-evaluated subexpressions as "referenced".
11780 ///
11781 /// \param SkipLocalVariables If true, don't mark local variables as
11782 /// 'referenced'.
11783 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11784                                             bool SkipLocalVariables) {
11785   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
11786 }
11787 
11788 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
11789 /// of the program being compiled.
11790 ///
11791 /// This routine emits the given diagnostic when the code currently being
11792 /// type-checked is "potentially evaluated", meaning that there is a
11793 /// possibility that the code will actually be executable. Code in sizeof()
11794 /// expressions, code used only during overload resolution, etc., are not
11795 /// potentially evaluated. This routine will suppress such diagnostics or,
11796 /// in the absolutely nutty case of potentially potentially evaluated
11797 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
11798 /// later.
11799 ///
11800 /// This routine should be used for all diagnostics that describe the run-time
11801 /// behavior of a program, such as passing a non-POD value through an ellipsis.
11802 /// Failure to do so will likely result in spurious diagnostics or failures
11803 /// during overload resolution or within sizeof/alignof/typeof/typeid.
11804 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
11805                                const PartialDiagnostic &PD) {
11806   switch (ExprEvalContexts.back().Context) {
11807   case Unevaluated:
11808   case UnevaluatedAbstract:
11809     // The argument will never be evaluated, so don't complain.
11810     break;
11811 
11812   case ConstantEvaluated:
11813     // Relevant diagnostics should be produced by constant evaluation.
11814     break;
11815 
11816   case PotentiallyEvaluated:
11817   case PotentiallyEvaluatedIfUsed:
11818     if (Statement && getCurFunctionOrMethodDecl()) {
11819       FunctionScopes.back()->PossiblyUnreachableDiags.
11820         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
11821     }
11822     else
11823       Diag(Loc, PD);
11824 
11825     return true;
11826   }
11827 
11828   return false;
11829 }
11830 
11831 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11832                                CallExpr *CE, FunctionDecl *FD) {
11833   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11834     return false;
11835 
11836   // If we're inside a decltype's expression, don't check for a valid return
11837   // type or construct temporaries until we know whether this is the last call.
11838   if (ExprEvalContexts.back().IsDecltype) {
11839     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11840     return false;
11841   }
11842 
11843   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
11844     FunctionDecl *FD;
11845     CallExpr *CE;
11846 
11847   public:
11848     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11849       : FD(FD), CE(CE) { }
11850 
11851     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11852       if (!FD) {
11853         S.Diag(Loc, diag::err_call_incomplete_return)
11854           << T << CE->getSourceRange();
11855         return;
11856       }
11857 
11858       S.Diag(Loc, diag::err_call_function_incomplete_return)
11859         << CE->getSourceRange() << FD->getDeclName() << T;
11860       S.Diag(FD->getLocation(),
11861              diag::note_function_with_incomplete_return_type_declared_here)
11862         << FD->getDeclName();
11863     }
11864   } Diagnoser(FD, CE);
11865 
11866   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
11867     return true;
11868 
11869   return false;
11870 }
11871 
11872 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
11873 // will prevent this condition from triggering, which is what we want.
11874 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11875   SourceLocation Loc;
11876 
11877   unsigned diagnostic = diag::warn_condition_is_assignment;
11878   bool IsOrAssign = false;
11879 
11880   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
11881     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
11882       return;
11883 
11884     IsOrAssign = Op->getOpcode() == BO_OrAssign;
11885 
11886     // Greylist some idioms by putting them into a warning subcategory.
11887     if (ObjCMessageExpr *ME
11888           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11889       Selector Sel = ME->getSelector();
11890 
11891       // self = [<foo> init...]
11892       if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
11893         diagnostic = diag::warn_condition_is_idiomatic_assignment;
11894 
11895       // <foo> = [<bar> nextObject]
11896       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
11897         diagnostic = diag::warn_condition_is_idiomatic_assignment;
11898     }
11899 
11900     Loc = Op->getOperatorLoc();
11901   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
11902     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
11903       return;
11904 
11905     IsOrAssign = Op->getOperator() == OO_PipeEqual;
11906     Loc = Op->getOperatorLoc();
11907   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11908     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11909   else {
11910     // Not an assignment.
11911     return;
11912   }
11913 
11914   Diag(Loc, diagnostic) << E->getSourceRange();
11915 
11916   SourceLocation Open = E->getLocStart();
11917   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11918   Diag(Loc, diag::note_condition_assign_silence)
11919         << FixItHint::CreateInsertion(Open, "(")
11920         << FixItHint::CreateInsertion(Close, ")");
11921 
11922   if (IsOrAssign)
11923     Diag(Loc, diag::note_condition_or_assign_to_comparison)
11924       << FixItHint::CreateReplacement(Loc, "!=");
11925   else
11926     Diag(Loc, diag::note_condition_assign_to_comparison)
11927       << FixItHint::CreateReplacement(Loc, "==");
11928 }
11929 
11930 /// \brief Redundant parentheses over an equality comparison can indicate
11931 /// that the user intended an assignment used as condition.
11932 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
11933   // Don't warn if the parens came from a macro.
11934   SourceLocation parenLoc = ParenE->getLocStart();
11935   if (parenLoc.isInvalid() || parenLoc.isMacroID())
11936     return;
11937   // Don't warn for dependent expressions.
11938   if (ParenE->isTypeDependent())
11939     return;
11940 
11941   Expr *E = ParenE->IgnoreParens();
11942 
11943   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
11944     if (opE->getOpcode() == BO_EQ &&
11945         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11946                                                            == Expr::MLV_Valid) {
11947       SourceLocation Loc = opE->getOperatorLoc();
11948 
11949       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
11950       SourceRange ParenERange = ParenE->getSourceRange();
11951       Diag(Loc, diag::note_equality_comparison_silence)
11952         << FixItHint::CreateRemoval(ParenERange.getBegin())
11953         << FixItHint::CreateRemoval(ParenERange.getEnd());
11954       Diag(Loc, diag::note_equality_comparison_to_assign)
11955         << FixItHint::CreateReplacement(Loc, "=");
11956     }
11957 }
11958 
11959 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
11960   DiagnoseAssignmentAsCondition(E);
11961   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11962     DiagnoseEqualityWithExtraParens(parenE);
11963 
11964   ExprResult result = CheckPlaceholderExpr(E);
11965   if (result.isInvalid()) return ExprError();
11966   E = result.take();
11967 
11968   if (!E->isTypeDependent()) {
11969     if (getLangOpts().CPlusPlus)
11970       return CheckCXXBooleanCondition(E); // C++ 6.4p4
11971 
11972     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11973     if (ERes.isInvalid())
11974       return ExprError();
11975     E = ERes.take();
11976 
11977     QualType T = E->getType();
11978     if (!T->isScalarType()) { // C99 6.8.4.1p1
11979       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11980         << T << E->getSourceRange();
11981       return ExprError();
11982     }
11983   }
11984 
11985   return Owned(E);
11986 }
11987 
11988 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
11989                                        Expr *SubExpr) {
11990   if (!SubExpr)
11991     return ExprError();
11992 
11993   return CheckBooleanCondition(SubExpr, Loc);
11994 }
11995 
11996 namespace {
11997   /// A visitor for rebuilding a call to an __unknown_any expression
11998   /// to have an appropriate type.
11999   struct RebuildUnknownAnyFunction
12000     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
12001 
12002     Sema &S;
12003 
12004     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
12005 
12006     ExprResult VisitStmt(Stmt *S) {
12007       llvm_unreachable("unexpected statement!");
12008     }
12009 
12010     ExprResult VisitExpr(Expr *E) {
12011       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
12012         << E->getSourceRange();
12013       return ExprError();
12014     }
12015 
12016     /// Rebuild an expression which simply semantically wraps another
12017     /// expression which it shares the type and value kind of.
12018     template <class T> ExprResult rebuildSugarExpr(T *E) {
12019       ExprResult SubResult = Visit(E->getSubExpr());
12020       if (SubResult.isInvalid()) return ExprError();
12021 
12022       Expr *SubExpr = SubResult.take();
12023       E->setSubExpr(SubExpr);
12024       E->setType(SubExpr->getType());
12025       E->setValueKind(SubExpr->getValueKind());
12026       assert(E->getObjectKind() == OK_Ordinary);
12027       return E;
12028     }
12029 
12030     ExprResult VisitParenExpr(ParenExpr *E) {
12031       return rebuildSugarExpr(E);
12032     }
12033 
12034     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12035       return rebuildSugarExpr(E);
12036     }
12037 
12038     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12039       ExprResult SubResult = Visit(E->getSubExpr());
12040       if (SubResult.isInvalid()) return ExprError();
12041 
12042       Expr *SubExpr = SubResult.take();
12043       E->setSubExpr(SubExpr);
12044       E->setType(S.Context.getPointerType(SubExpr->getType()));
12045       assert(E->getValueKind() == VK_RValue);
12046       assert(E->getObjectKind() == OK_Ordinary);
12047       return E;
12048     }
12049 
12050     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
12051       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
12052 
12053       E->setType(VD->getType());
12054 
12055       assert(E->getValueKind() == VK_RValue);
12056       if (S.getLangOpts().CPlusPlus &&
12057           !(isa<CXXMethodDecl>(VD) &&
12058             cast<CXXMethodDecl>(VD)->isInstance()))
12059         E->setValueKind(VK_LValue);
12060 
12061       return E;
12062     }
12063 
12064     ExprResult VisitMemberExpr(MemberExpr *E) {
12065       return resolveDecl(E, E->getMemberDecl());
12066     }
12067 
12068     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12069       return resolveDecl(E, E->getDecl());
12070     }
12071   };
12072 }
12073 
12074 /// Given a function expression of unknown-any type, try to rebuild it
12075 /// to have a function type.
12076 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
12077   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
12078   if (Result.isInvalid()) return ExprError();
12079   return S.DefaultFunctionArrayConversion(Result.take());
12080 }
12081 
12082 namespace {
12083   /// A visitor for rebuilding an expression of type __unknown_anytype
12084   /// into one which resolves the type directly on the referring
12085   /// expression.  Strict preservation of the original source
12086   /// structure is not a goal.
12087   struct RebuildUnknownAnyExpr
12088     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
12089 
12090     Sema &S;
12091 
12092     /// The current destination type.
12093     QualType DestType;
12094 
12095     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
12096       : S(S), DestType(CastType) {}
12097 
12098     ExprResult VisitStmt(Stmt *S) {
12099       llvm_unreachable("unexpected statement!");
12100     }
12101 
12102     ExprResult VisitExpr(Expr *E) {
12103       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12104         << E->getSourceRange();
12105       return ExprError();
12106     }
12107 
12108     ExprResult VisitCallExpr(CallExpr *E);
12109     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
12110 
12111     /// Rebuild an expression which simply semantically wraps another
12112     /// expression which it shares the type and value kind of.
12113     template <class T> ExprResult rebuildSugarExpr(T *E) {
12114       ExprResult SubResult = Visit(E->getSubExpr());
12115       if (SubResult.isInvalid()) return ExprError();
12116       Expr *SubExpr = SubResult.take();
12117       E->setSubExpr(SubExpr);
12118       E->setType(SubExpr->getType());
12119       E->setValueKind(SubExpr->getValueKind());
12120       assert(E->getObjectKind() == OK_Ordinary);
12121       return E;
12122     }
12123 
12124     ExprResult VisitParenExpr(ParenExpr *E) {
12125       return rebuildSugarExpr(E);
12126     }
12127 
12128     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12129       return rebuildSugarExpr(E);
12130     }
12131 
12132     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12133       const PointerType *Ptr = DestType->getAs<PointerType>();
12134       if (!Ptr) {
12135         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
12136           << E->getSourceRange();
12137         return ExprError();
12138       }
12139       assert(E->getValueKind() == VK_RValue);
12140       assert(E->getObjectKind() == OK_Ordinary);
12141       E->setType(DestType);
12142 
12143       // Build the sub-expression as if it were an object of the pointee type.
12144       DestType = Ptr->getPointeeType();
12145       ExprResult SubResult = Visit(E->getSubExpr());
12146       if (SubResult.isInvalid()) return ExprError();
12147       E->setSubExpr(SubResult.take());
12148       return E;
12149     }
12150 
12151     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
12152 
12153     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
12154 
12155     ExprResult VisitMemberExpr(MemberExpr *E) {
12156       return resolveDecl(E, E->getMemberDecl());
12157     }
12158 
12159     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12160       return resolveDecl(E, E->getDecl());
12161     }
12162   };
12163 }
12164 
12165 /// Rebuilds a call expression which yielded __unknown_anytype.
12166 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
12167   Expr *CalleeExpr = E->getCallee();
12168 
12169   enum FnKind {
12170     FK_MemberFunction,
12171     FK_FunctionPointer,
12172     FK_BlockPointer
12173   };
12174 
12175   FnKind Kind;
12176   QualType CalleeType = CalleeExpr->getType();
12177   if (CalleeType == S.Context.BoundMemberTy) {
12178     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
12179     Kind = FK_MemberFunction;
12180     CalleeType = Expr::findBoundMemberType(CalleeExpr);
12181   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
12182     CalleeType = Ptr->getPointeeType();
12183     Kind = FK_FunctionPointer;
12184   } else {
12185     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
12186     Kind = FK_BlockPointer;
12187   }
12188   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
12189 
12190   // Verify that this is a legal result type of a function.
12191   if (DestType->isArrayType() || DestType->isFunctionType()) {
12192     unsigned diagID = diag::err_func_returning_array_function;
12193     if (Kind == FK_BlockPointer)
12194       diagID = diag::err_block_returning_array_function;
12195 
12196     S.Diag(E->getExprLoc(), diagID)
12197       << DestType->isFunctionType() << DestType;
12198     return ExprError();
12199   }
12200 
12201   // Otherwise, go ahead and set DestType as the call's result.
12202   E->setType(DestType.getNonLValueExprType(S.Context));
12203   E->setValueKind(Expr::getValueKindForType(DestType));
12204   assert(E->getObjectKind() == OK_Ordinary);
12205 
12206   // Rebuild the function type, replacing the result type with DestType.
12207   if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
12208     DestType = S.Context.getFunctionType(DestType, Proto->getArgTypes(),
12209                                          Proto->getExtProtoInfo());
12210   else
12211     DestType = S.Context.getFunctionNoProtoType(DestType,
12212                                                 FnType->getExtInfo());
12213 
12214   // Rebuild the appropriate pointer-to-function type.
12215   switch (Kind) {
12216   case FK_MemberFunction:
12217     // Nothing to do.
12218     break;
12219 
12220   case FK_FunctionPointer:
12221     DestType = S.Context.getPointerType(DestType);
12222     break;
12223 
12224   case FK_BlockPointer:
12225     DestType = S.Context.getBlockPointerType(DestType);
12226     break;
12227   }
12228 
12229   // Finally, we can recurse.
12230   ExprResult CalleeResult = Visit(CalleeExpr);
12231   if (!CalleeResult.isUsable()) return ExprError();
12232   E->setCallee(CalleeResult.take());
12233 
12234   // Bind a temporary if necessary.
12235   return S.MaybeBindToTemporary(E);
12236 }
12237 
12238 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
12239   // Verify that this is a legal result type of a call.
12240   if (DestType->isArrayType() || DestType->isFunctionType()) {
12241     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
12242       << DestType->isFunctionType() << DestType;
12243     return ExprError();
12244   }
12245 
12246   // Rewrite the method result type if available.
12247   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
12248     assert(Method->getResultType() == S.Context.UnknownAnyTy);
12249     Method->setResultType(DestType);
12250   }
12251 
12252   // Change the type of the message.
12253   E->setType(DestType.getNonReferenceType());
12254   E->setValueKind(Expr::getValueKindForType(DestType));
12255 
12256   return S.MaybeBindToTemporary(E);
12257 }
12258 
12259 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
12260   // The only case we should ever see here is a function-to-pointer decay.
12261   if (E->getCastKind() == CK_FunctionToPointerDecay) {
12262     assert(E->getValueKind() == VK_RValue);
12263     assert(E->getObjectKind() == OK_Ordinary);
12264 
12265     E->setType(DestType);
12266 
12267     // Rebuild the sub-expression as the pointee (function) type.
12268     DestType = DestType->castAs<PointerType>()->getPointeeType();
12269 
12270     ExprResult Result = Visit(E->getSubExpr());
12271     if (!Result.isUsable()) return ExprError();
12272 
12273     E->setSubExpr(Result.take());
12274     return S.Owned(E);
12275   } else if (E->getCastKind() == CK_LValueToRValue) {
12276     assert(E->getValueKind() == VK_RValue);
12277     assert(E->getObjectKind() == OK_Ordinary);
12278 
12279     assert(isa<BlockPointerType>(E->getType()));
12280 
12281     E->setType(DestType);
12282 
12283     // The sub-expression has to be a lvalue reference, so rebuild it as such.
12284     DestType = S.Context.getLValueReferenceType(DestType);
12285 
12286     ExprResult Result = Visit(E->getSubExpr());
12287     if (!Result.isUsable()) return ExprError();
12288 
12289     E->setSubExpr(Result.take());
12290     return S.Owned(E);
12291   } else {
12292     llvm_unreachable("Unhandled cast type!");
12293   }
12294 }
12295 
12296 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
12297   ExprValueKind ValueKind = VK_LValue;
12298   QualType Type = DestType;
12299 
12300   // We know how to make this work for certain kinds of decls:
12301 
12302   //  - functions
12303   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
12304     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
12305       DestType = Ptr->getPointeeType();
12306       ExprResult Result = resolveDecl(E, VD);
12307       if (Result.isInvalid()) return ExprError();
12308       return S.ImpCastExprToType(Result.take(), Type,
12309                                  CK_FunctionToPointerDecay, VK_RValue);
12310     }
12311 
12312     if (!Type->isFunctionType()) {
12313       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
12314         << VD << E->getSourceRange();
12315       return ExprError();
12316     }
12317 
12318     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
12319       if (MD->isInstance()) {
12320         ValueKind = VK_RValue;
12321         Type = S.Context.BoundMemberTy;
12322       }
12323 
12324     // Function references aren't l-values in C.
12325     if (!S.getLangOpts().CPlusPlus)
12326       ValueKind = VK_RValue;
12327 
12328   //  - variables
12329   } else if (isa<VarDecl>(VD)) {
12330     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
12331       Type = RefTy->getPointeeType();
12332     } else if (Type->isFunctionType()) {
12333       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
12334         << VD << E->getSourceRange();
12335       return ExprError();
12336     }
12337 
12338   //  - nothing else
12339   } else {
12340     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
12341       << VD << E->getSourceRange();
12342     return ExprError();
12343   }
12344 
12345   VD->setType(DestType);
12346   E->setType(Type);
12347   E->setValueKind(ValueKind);
12348   return S.Owned(E);
12349 }
12350 
12351 /// Check a cast of an unknown-any type.  We intentionally only
12352 /// trigger this for C-style casts.
12353 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
12354                                      Expr *CastExpr, CastKind &CastKind,
12355                                      ExprValueKind &VK, CXXCastPath &Path) {
12356   // Rewrite the casted expression from scratch.
12357   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
12358   if (!result.isUsable()) return ExprError();
12359 
12360   CastExpr = result.take();
12361   VK = CastExpr->getValueKind();
12362   CastKind = CK_NoOp;
12363 
12364   return CastExpr;
12365 }
12366 
12367 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
12368   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
12369 }
12370 
12371 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
12372                                     Expr *arg, QualType &paramType) {
12373   // If the syntactic form of the argument is not an explicit cast of
12374   // any sort, just do default argument promotion.
12375   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
12376   if (!castArg) {
12377     ExprResult result = DefaultArgumentPromotion(arg);
12378     if (result.isInvalid()) return ExprError();
12379     paramType = result.get()->getType();
12380     return result;
12381   }
12382 
12383   // Otherwise, use the type that was written in the explicit cast.
12384   assert(!arg->hasPlaceholderType());
12385   paramType = castArg->getTypeAsWritten();
12386 
12387   // Copy-initialize a parameter of that type.
12388   InitializedEntity entity =
12389     InitializedEntity::InitializeParameter(Context, paramType,
12390                                            /*consumed*/ false);
12391   return PerformCopyInitialization(entity, callLoc, Owned(arg));
12392 }
12393 
12394 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
12395   Expr *orig = E;
12396   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
12397   while (true) {
12398     E = E->IgnoreParenImpCasts();
12399     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
12400       E = call->getCallee();
12401       diagID = diag::err_uncasted_call_of_unknown_any;
12402     } else {
12403       break;
12404     }
12405   }
12406 
12407   SourceLocation loc;
12408   NamedDecl *d;
12409   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
12410     loc = ref->getLocation();
12411     d = ref->getDecl();
12412   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
12413     loc = mem->getMemberLoc();
12414     d = mem->getMemberDecl();
12415   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
12416     diagID = diag::err_uncasted_call_of_unknown_any;
12417     loc = msg->getSelectorStartLoc();
12418     d = msg->getMethodDecl();
12419     if (!d) {
12420       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
12421         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
12422         << orig->getSourceRange();
12423       return ExprError();
12424     }
12425   } else {
12426     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12427       << E->getSourceRange();
12428     return ExprError();
12429   }
12430 
12431   S.Diag(loc, diagID) << d << orig->getSourceRange();
12432 
12433   // Never recoverable.
12434   return ExprError();
12435 }
12436 
12437 /// Check for operands with placeholder types and complain if found.
12438 /// Returns true if there was an error and no recovery was possible.
12439 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
12440   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
12441   if (!placeholderType) return Owned(E);
12442 
12443   switch (placeholderType->getKind()) {
12444 
12445   // Overloaded expressions.
12446   case BuiltinType::Overload: {
12447     // Try to resolve a single function template specialization.
12448     // This is obligatory.
12449     ExprResult result = Owned(E);
12450     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
12451       return result;
12452 
12453     // If that failed, try to recover with a call.
12454     } else {
12455       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
12456                            /*complain*/ true);
12457       return result;
12458     }
12459   }
12460 
12461   // Bound member functions.
12462   case BuiltinType::BoundMember: {
12463     ExprResult result = Owned(E);
12464     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
12465                          /*complain*/ true);
12466     return result;
12467   }
12468 
12469   // ARC unbridged casts.
12470   case BuiltinType::ARCUnbridgedCast: {
12471     Expr *realCast = stripARCUnbridgedCast(E);
12472     diagnoseARCUnbridgedCast(realCast);
12473     return Owned(realCast);
12474   }
12475 
12476   // Expressions of unknown type.
12477   case BuiltinType::UnknownAny:
12478     return diagnoseUnknownAnyExpr(*this, E);
12479 
12480   // Pseudo-objects.
12481   case BuiltinType::PseudoObject:
12482     return checkPseudoObjectRValue(E);
12483 
12484   case BuiltinType::BuiltinFn:
12485     Diag(E->getLocStart(), diag::err_builtin_fn_use);
12486     return ExprError();
12487 
12488   // Everything else should be impossible.
12489 #define BUILTIN_TYPE(Id, SingletonId) \
12490   case BuiltinType::Id:
12491 #define PLACEHOLDER_TYPE(Id, SingletonId)
12492 #include "clang/AST/BuiltinTypes.def"
12493     break;
12494   }
12495 
12496   llvm_unreachable("invalid placeholder type!");
12497 }
12498 
12499 bool Sema::CheckCaseExpression(Expr *E) {
12500   if (E->isTypeDependent())
12501     return true;
12502   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
12503     return E->getType()->isIntegralOrEnumerationType();
12504   return false;
12505 }
12506 
12507 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
12508 ExprResult
12509 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
12510   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
12511          "Unknown Objective-C Boolean value!");
12512   QualType BoolT = Context.ObjCBuiltinBoolTy;
12513   if (!Context.getBOOLDecl()) {
12514     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
12515                         Sema::LookupOrdinaryName);
12516     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
12517       NamedDecl *ND = Result.getFoundDecl();
12518       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
12519         Context.setBOOLDecl(TD);
12520     }
12521   }
12522   if (Context.getBOOLDecl())
12523     BoolT = Context.getBOOLType();
12524   return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
12525                                         BoolT, OpLoc));
12526 }
12527