]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaExpr.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304149, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaExpr.cpp
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 "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.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/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/Support/ConvertUTF.h"
47 using namespace clang;
48 using namespace sema;
49
50 /// \brief Determine whether the use of this declaration is valid, without
51 /// emitting diagnostics.
52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
53   // See if this is an auto-typed variable whose initializer we are parsing.
54   if (ParsingInitForAutoVars.count(D))
55     return false;
56
57   // See if this is a deleted function.
58   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
59     if (FD->isDeleted())
60       return false;
61
62     // If the function has a deduced return type, and we can't deduce it,
63     // then we can't use it either.
64     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
65         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
66       return false;
67   }
68
69   // See if this function is unavailable.
70   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
71       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
72     return false;
73
74   return true;
75 }
76
77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
78   // Warn if this is used but marked unused.
79   if (const auto *A = D->getAttr<UnusedAttr>()) {
80     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
81     // should diagnose them.
82     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) {
83       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
84       if (DC && !DC->hasAttr<UnusedAttr>())
85         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
86     }
87   }
88 }
89
90 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
91   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
92   if (!OMD)
93     return false;
94   const ObjCInterfaceDecl *OID = OMD->getClassInterface();
95   if (!OID)
96     return false;
97
98   for (const ObjCCategoryDecl *Cat : OID->visible_categories())
99     if (ObjCMethodDecl *CatMeth =
100             Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
101       if (!CatMeth->hasAttr<AvailabilityAttr>())
102         return true;
103   return false;
104 }
105
106 AvailabilityResult
107 Sema::ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D, std::string *Message) {
108   AvailabilityResult Result = D->getAvailability(Message);
109
110   // For typedefs, if the typedef declaration appears available look
111   // to the underlying type to see if it is more restrictive.
112   while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
113     if (Result == AR_Available) {
114       if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
115         D = TT->getDecl();
116         Result = D->getAvailability(Message);
117         continue;
118       }
119     }
120     break;
121   }
122
123   // Forward class declarations get their attributes from their definition.
124   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
125     if (IDecl->getDefinition()) {
126       D = IDecl->getDefinition();
127       Result = D->getAvailability(Message);
128     }
129   }
130
131   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
132     if (Result == AR_Available) {
133       const DeclContext *DC = ECD->getDeclContext();
134       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
135         Result = TheEnumDecl->getAvailability(Message);
136     }
137
138   if (Result == AR_NotYetIntroduced) {
139     // Don't do this for enums, they can't be redeclared.
140     if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
141       return AR_Available;
142
143     bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
144     // Objective-C method declarations in categories are not modelled as
145     // redeclarations, so manually look for a redeclaration in a category
146     // if necessary.
147     if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
148       Warn = false;
149     // In general, D will point to the most recent redeclaration. However,
150     // for `@class A;` decls, this isn't true -- manually go through the
151     // redecl chain in that case.
152     if (Warn && isa<ObjCInterfaceDecl>(D))
153       for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
154            Redecl = Redecl->getPreviousDecl())
155         if (!Redecl->hasAttr<AvailabilityAttr>() ||
156             Redecl->getAttr<AvailabilityAttr>()->isInherited())
157           Warn = false;
158
159     return Warn ? AR_NotYetIntroduced : AR_Available;
160   }
161
162   return Result;
163 }
164
165 static void
166 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
167                            const ObjCInterfaceDecl *UnknownObjCClass,
168                            bool ObjCPropertyAccess) {
169   std::string Message;
170   // See if this declaration is unavailable, deprecated, or partial.
171   if (AvailabilityResult Result =
172           S.ShouldDiagnoseAvailabilityOfDecl(D, &Message)) {
173
174     if (Result == AR_NotYetIntroduced) {
175       if (S.getCurFunctionOrMethodDecl()) {
176         S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
177         return;
178       } else if (S.getCurBlock() || S.getCurLambda()) {
179         S.getCurFunction()->HasPotentialAvailabilityViolations = true;
180         return;
181       }
182     }
183
184     const ObjCPropertyDecl *ObjCPDecl = nullptr;
185     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
186       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
187         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
188         if (PDeclResult == Result)
189           ObjCPDecl = PD;
190       }
191     }
192
193     S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass,
194                               ObjCPDecl, ObjCPropertyAccess);
195   }
196 }
197
198 /// \brief Emit a note explaining that this function is deleted.
199 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
200   assert(Decl->isDeleted());
201
202   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
203
204   if (Method && Method->isDeleted() && Method->isDefaulted()) {
205     // If the method was explicitly defaulted, point at that declaration.
206     if (!Method->isImplicit())
207       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
208
209     // Try to diagnose why this special member function was implicitly
210     // deleted. This might fail, if that reason no longer applies.
211     CXXSpecialMember CSM = getSpecialMember(Method);
212     if (CSM != CXXInvalid)
213       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
214
215     return;
216   }
217
218   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
219   if (Ctor && Ctor->isInheritingConstructor())
220     return NoteDeletedInheritingConstructor(Ctor);
221
222   Diag(Decl->getLocation(), diag::note_availability_specified_here)
223     << Decl << true;
224 }
225
226 /// \brief Determine whether a FunctionDecl was ever declared with an
227 /// explicit storage class.
228 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
229   for (auto I : D->redecls()) {
230     if (I->getStorageClass() != SC_None)
231       return true;
232   }
233   return false;
234 }
235
236 /// \brief Check whether we're in an extern inline function and referring to a
237 /// variable or function with internal linkage (C11 6.7.4p3).
238 ///
239 /// This is only a warning because we used to silently accept this code, but
240 /// in many cases it will not behave correctly. This is not enabled in C++ mode
241 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
242 /// and so while there may still be user mistakes, most of the time we can't
243 /// prove that there are errors.
244 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
245                                                       const NamedDecl *D,
246                                                       SourceLocation Loc) {
247   // This is disabled under C++; there are too many ways for this to fire in
248   // contexts where the warning is a false positive, or where it is technically
249   // correct but benign.
250   if (S.getLangOpts().CPlusPlus)
251     return;
252
253   // Check if this is an inlined function or method.
254   FunctionDecl *Current = S.getCurFunctionDecl();
255   if (!Current)
256     return;
257   if (!Current->isInlined())
258     return;
259   if (!Current->isExternallyVisible())
260     return;
261
262   // Check if the decl has internal linkage.
263   if (D->getFormalLinkage() != InternalLinkage)
264     return;
265
266   // Downgrade from ExtWarn to Extension if
267   //  (1) the supposedly external inline function is in the main file,
268   //      and probably won't be included anywhere else.
269   //  (2) the thing we're referencing is a pure function.
270   //  (3) the thing we're referencing is another inline function.
271   // This last can give us false negatives, but it's better than warning on
272   // wrappers for simple C library functions.
273   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
274   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
275   if (!DowngradeWarning && UsedFn)
276     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
277
278   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
279                                : diag::ext_internal_in_extern_inline)
280     << /*IsVar=*/!UsedFn << D;
281
282   S.MaybeSuggestAddingStaticToDecl(Current);
283
284   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
285       << D;
286 }
287
288 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
289   const FunctionDecl *First = Cur->getFirstDecl();
290
291   // Suggest "static" on the function, if possible.
292   if (!hasAnyExplicitStorageClass(First)) {
293     SourceLocation DeclBegin = First->getSourceRange().getBegin();
294     Diag(DeclBegin, diag::note_convert_inline_to_static)
295       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
296   }
297 }
298
299 /// \brief Determine whether the use of this declaration is valid, and
300 /// emit any corresponding diagnostics.
301 ///
302 /// This routine diagnoses various problems with referencing
303 /// declarations that can occur when using a declaration. For example,
304 /// it might warn if a deprecated or unavailable declaration is being
305 /// used, or produce an error (and return true) if a C++0x deleted
306 /// function is being used.
307 ///
308 /// \returns true if there was an error (this declaration cannot be
309 /// referenced), false otherwise.
310 ///
311 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
312                              const ObjCInterfaceDecl *UnknownObjCClass,
313                              bool ObjCPropertyAccess) {
314   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
315     // If there were any diagnostics suppressed by template argument deduction,
316     // emit them now.
317     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
318     if (Pos != SuppressedDiagnostics.end()) {
319       for (const PartialDiagnosticAt &Suppressed : Pos->second)
320         Diag(Suppressed.first, Suppressed.second);
321
322       // Clear out the list of suppressed diagnostics, so that we don't emit
323       // them again for this specialization. However, we don't obsolete this
324       // entry from the table, because we want to avoid ever emitting these
325       // diagnostics again.
326       Pos->second.clear();
327     }
328
329     // C++ [basic.start.main]p3:
330     //   The function 'main' shall not be used within a program.
331     if (cast<FunctionDecl>(D)->isMain())
332       Diag(Loc, diag::ext_main_used);
333   }
334
335   // See if this is an auto-typed variable whose initializer we are parsing.
336   if (ParsingInitForAutoVars.count(D)) {
337     if (isa<BindingDecl>(D)) {
338       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
339         << D->getDeclName();
340     } else {
341       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
342         << D->getDeclName() << cast<VarDecl>(D)->getType();
343     }
344     return true;
345   }
346
347   // See if this is a deleted function.
348   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
349     if (FD->isDeleted()) {
350       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
351       if (Ctor && Ctor->isInheritingConstructor())
352         Diag(Loc, diag::err_deleted_inherited_ctor_use)
353             << Ctor->getParent()
354             << Ctor->getInheritedConstructor().getConstructor()->getParent();
355       else 
356         Diag(Loc, diag::err_deleted_function_use);
357       NoteDeletedFunction(FD);
358       return true;
359     }
360
361     // If the function has a deduced return type, and we can't deduce it,
362     // then we can't use it either.
363     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
364         DeduceReturnType(FD, Loc))
365       return true;
366
367     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
368       return true;
369   }
370
371   auto getReferencedObjCProp = [](const NamedDecl *D) ->
372                                       const ObjCPropertyDecl * {
373     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
374       return MD->findPropertyDecl();
375     return nullptr;
376   };
377   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
378     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
379       return true;
380   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
381       return true;
382   }
383
384   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
385   // Only the variables omp_in and omp_out are allowed in the combiner.
386   // Only the variables omp_priv and omp_orig are allowed in the
387   // initializer-clause.
388   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
389   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
390       isa<VarDecl>(D)) {
391     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
392         << getCurFunction()->HasOMPDeclareReductionCombiner;
393     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
394     return true;
395   }
396
397   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
398                              ObjCPropertyAccess);
399
400   DiagnoseUnusedOfDecl(*this, D, Loc);
401
402   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
403
404   return false;
405 }
406
407 /// \brief Retrieve the message suffix that should be added to a
408 /// diagnostic complaining about the given function being deleted or
409 /// unavailable.
410 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
411   std::string Message;
412   if (FD->getAvailability(&Message))
413     return ": " + Message;
414
415   return std::string();
416 }
417
418 /// DiagnoseSentinelCalls - This routine checks whether a call or
419 /// message-send is to a declaration with the sentinel attribute, and
420 /// if so, it checks that the requirements of the sentinel are
421 /// satisfied.
422 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
423                                  ArrayRef<Expr *> Args) {
424   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
425   if (!attr)
426     return;
427
428   // The number of formal parameters of the declaration.
429   unsigned numFormalParams;
430
431   // The kind of declaration.  This is also an index into a %select in
432   // the diagnostic.
433   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
434
435   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
436     numFormalParams = MD->param_size();
437     calleeType = CT_Method;
438   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
439     numFormalParams = FD->param_size();
440     calleeType = CT_Function;
441   } else if (isa<VarDecl>(D)) {
442     QualType type = cast<ValueDecl>(D)->getType();
443     const FunctionType *fn = nullptr;
444     if (const PointerType *ptr = type->getAs<PointerType>()) {
445       fn = ptr->getPointeeType()->getAs<FunctionType>();
446       if (!fn) return;
447       calleeType = CT_Function;
448     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
449       fn = ptr->getPointeeType()->castAs<FunctionType>();
450       calleeType = CT_Block;
451     } else {
452       return;
453     }
454
455     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
456       numFormalParams = proto->getNumParams();
457     } else {
458       numFormalParams = 0;
459     }
460   } else {
461     return;
462   }
463
464   // "nullPos" is the number of formal parameters at the end which
465   // effectively count as part of the variadic arguments.  This is
466   // useful if you would prefer to not have *any* formal parameters,
467   // but the language forces you to have at least one.
468   unsigned nullPos = attr->getNullPos();
469   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
470   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
471
472   // The number of arguments which should follow the sentinel.
473   unsigned numArgsAfterSentinel = attr->getSentinel();
474
475   // If there aren't enough arguments for all the formal parameters,
476   // the sentinel, and the args after the sentinel, complain.
477   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
478     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
479     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
480     return;
481   }
482
483   // Otherwise, find the sentinel expression.
484   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
485   if (!sentinelExpr) return;
486   if (sentinelExpr->isValueDependent()) return;
487   if (Context.isSentinelNullExpr(sentinelExpr)) return;
488
489   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
490   // or 'NULL' if those are actually defined in the context.  Only use
491   // 'nil' for ObjC methods, where it's much more likely that the
492   // variadic arguments form a list of object pointers.
493   SourceLocation MissingNilLoc
494     = getLocForEndOfToken(sentinelExpr->getLocEnd());
495   std::string NullValue;
496   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
497     NullValue = "nil";
498   else if (getLangOpts().CPlusPlus11)
499     NullValue = "nullptr";
500   else if (PP.isMacroDefined("NULL"))
501     NullValue = "NULL";
502   else
503     NullValue = "(void*) 0";
504
505   if (MissingNilLoc.isInvalid())
506     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
507   else
508     Diag(MissingNilLoc, diag::warn_missing_sentinel) 
509       << int(calleeType)
510       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
511   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
512 }
513
514 SourceRange Sema::getExprRange(Expr *E) const {
515   return E ? E->getSourceRange() : SourceRange();
516 }
517
518 //===----------------------------------------------------------------------===//
519 //  Standard Promotions and Conversions
520 //===----------------------------------------------------------------------===//
521
522 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
523 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
524   // Handle any placeholder expressions which made it here.
525   if (E->getType()->isPlaceholderType()) {
526     ExprResult result = CheckPlaceholderExpr(E);
527     if (result.isInvalid()) return ExprError();
528     E = result.get();
529   }
530   
531   QualType Ty = E->getType();
532   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
533
534   if (Ty->isFunctionType()) {
535     // If we are here, we are not calling a function but taking
536     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
537     if (getLangOpts().OpenCL) {
538       if (Diagnose)
539         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
540       return ExprError();
541     }
542
543     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
544       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
545         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
546           return ExprError();
547
548     E = ImpCastExprToType(E, Context.getPointerType(Ty),
549                           CK_FunctionToPointerDecay).get();
550   } else if (Ty->isArrayType()) {
551     // In C90 mode, arrays only promote to pointers if the array expression is
552     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
553     // type 'array of type' is converted to an expression that has type 'pointer
554     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
555     // that has type 'array of type' ...".  The relevant change is "an lvalue"
556     // (C90) to "an expression" (C99).
557     //
558     // C++ 4.2p1:
559     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
560     // T" can be converted to an rvalue of type "pointer to T".
561     //
562     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
563       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
564                             CK_ArrayToPointerDecay).get();
565   }
566   return E;
567 }
568
569 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
570   // Check to see if we are dereferencing a null pointer.  If so,
571   // and if not volatile-qualified, this is undefined behavior that the
572   // optimizer will delete, so warn about it.  People sometimes try to use this
573   // to get a deterministic trap and are surprised by clang's behavior.  This
574   // only handles the pattern "*null", which is a very syntactic check.
575   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
576     if (UO->getOpcode() == UO_Deref &&
577         UO->getSubExpr()->IgnoreParenCasts()->
578           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
579         !UO->getType().isVolatileQualified()) {
580     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
581                           S.PDiag(diag::warn_indirection_through_null)
582                             << UO->getSubExpr()->getSourceRange());
583     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
584                         S.PDiag(diag::note_indirection_through_null));
585   }
586 }
587
588 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
589                                     SourceLocation AssignLoc,
590                                     const Expr* RHS) {
591   const ObjCIvarDecl *IV = OIRE->getDecl();
592   if (!IV)
593     return;
594   
595   DeclarationName MemberName = IV->getDeclName();
596   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
597   if (!Member || !Member->isStr("isa"))
598     return;
599   
600   const Expr *Base = OIRE->getBase();
601   QualType BaseType = Base->getType();
602   if (OIRE->isArrow())
603     BaseType = BaseType->getPointeeType();
604   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
605     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
606       ObjCInterfaceDecl *ClassDeclared = nullptr;
607       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
608       if (!ClassDeclared->getSuperClass()
609           && (*ClassDeclared->ivar_begin()) == IV) {
610         if (RHS) {
611           NamedDecl *ObjectSetClass =
612             S.LookupSingleName(S.TUScope,
613                                &S.Context.Idents.get("object_setClass"),
614                                SourceLocation(), S.LookupOrdinaryName);
615           if (ObjectSetClass) {
616             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
617             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
618             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
619             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
620                                                      AssignLoc), ",") <<
621             FixItHint::CreateInsertion(RHSLocEnd, ")");
622           }
623           else
624             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
625         } else {
626           NamedDecl *ObjectGetClass =
627             S.LookupSingleName(S.TUScope,
628                                &S.Context.Idents.get("object_getClass"),
629                                SourceLocation(), S.LookupOrdinaryName);
630           if (ObjectGetClass)
631             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
632             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
633             FixItHint::CreateReplacement(
634                                          SourceRange(OIRE->getOpLoc(),
635                                                      OIRE->getLocEnd()), ")");
636           else
637             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
638         }
639         S.Diag(IV->getLocation(), diag::note_ivar_decl);
640       }
641     }
642 }
643
644 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
645   // Handle any placeholder expressions which made it here.
646   if (E->getType()->isPlaceholderType()) {
647     ExprResult result = CheckPlaceholderExpr(E);
648     if (result.isInvalid()) return ExprError();
649     E = result.get();
650   }
651   
652   // C++ [conv.lval]p1:
653   //   A glvalue of a non-function, non-array type T can be
654   //   converted to a prvalue.
655   if (!E->isGLValue()) return E;
656
657   QualType T = E->getType();
658   assert(!T.isNull() && "r-value conversion on typeless expression?");
659
660   // We don't want to throw lvalue-to-rvalue casts on top of
661   // expressions of certain types in C++.
662   if (getLangOpts().CPlusPlus &&
663       (E->getType() == Context.OverloadTy ||
664        T->isDependentType() ||
665        T->isRecordType()))
666     return E;
667
668   // The C standard is actually really unclear on this point, and
669   // DR106 tells us what the result should be but not why.  It's
670   // generally best to say that void types just doesn't undergo
671   // lvalue-to-rvalue at all.  Note that expressions of unqualified
672   // 'void' type are never l-values, but qualified void can be.
673   if (T->isVoidType())
674     return E;
675
676   // OpenCL usually rejects direct accesses to values of 'half' type.
677   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
678       T->isHalfType()) {
679     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
680       << 0 << T;
681     return ExprError();
682   }
683
684   CheckForNullPointerDereference(*this, E);
685   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
686     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
687                                      &Context.Idents.get("object_getClass"),
688                                      SourceLocation(), LookupOrdinaryName);
689     if (ObjectGetClass)
690       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
691         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
692         FixItHint::CreateReplacement(
693                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
694     else
695       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
696   }
697   else if (const ObjCIvarRefExpr *OIRE =
698             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
699     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
700
701   // C++ [conv.lval]p1:
702   //   [...] If T is a non-class type, the type of the prvalue is the
703   //   cv-unqualified version of T. Otherwise, the type of the
704   //   rvalue is T.
705   //
706   // C99 6.3.2.1p2:
707   //   If the lvalue has qualified type, the value has the unqualified
708   //   version of the type of the lvalue; otherwise, the value has the
709   //   type of the lvalue.
710   if (T.hasQualifiers())
711     T = T.getUnqualifiedType();
712
713   // Under the MS ABI, lock down the inheritance model now.
714   if (T->isMemberPointerType() &&
715       Context.getTargetInfo().getCXXABI().isMicrosoft())
716     (void)isCompleteType(E->getExprLoc(), T);
717
718   UpdateMarkingForLValueToRValue(E);
719   
720   // Loading a __weak object implicitly retains the value, so we need a cleanup to 
721   // balance that.
722   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
723     Cleanup.setExprNeedsCleanups(true);
724
725   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
726                                             nullptr, VK_RValue);
727
728   // C11 6.3.2.1p2:
729   //   ... if the lvalue has atomic type, the value has the non-atomic version 
730   //   of the type of the lvalue ...
731   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
732     T = Atomic->getValueType().getUnqualifiedType();
733     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
734                                    nullptr, VK_RValue);
735   }
736   
737   return Res;
738 }
739
740 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
741   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
742   if (Res.isInvalid())
743     return ExprError();
744   Res = DefaultLvalueConversion(Res.get());
745   if (Res.isInvalid())
746     return ExprError();
747   return Res;
748 }
749
750 /// CallExprUnaryConversions - a special case of an unary conversion
751 /// performed on a function designator of a call expression.
752 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
753   QualType Ty = E->getType();
754   ExprResult Res = E;
755   // Only do implicit cast for a function type, but not for a pointer
756   // to function type.
757   if (Ty->isFunctionType()) {
758     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
759                             CK_FunctionToPointerDecay).get();
760     if (Res.isInvalid())
761       return ExprError();
762   }
763   Res = DefaultLvalueConversion(Res.get());
764   if (Res.isInvalid())
765     return ExprError();
766   return Res.get();
767 }
768
769 /// UsualUnaryConversions - Performs various conversions that are common to most
770 /// operators (C99 6.3). The conversions of array and function types are
771 /// sometimes suppressed. For example, the array->pointer conversion doesn't
772 /// apply if the array is an argument to the sizeof or address (&) operators.
773 /// In these instances, this routine should *not* be called.
774 ExprResult Sema::UsualUnaryConversions(Expr *E) {
775   // First, convert to an r-value.
776   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
777   if (Res.isInvalid())
778     return ExprError();
779   E = Res.get();
780
781   QualType Ty = E->getType();
782   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
783
784   // Half FP have to be promoted to float unless it is natively supported
785   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
786     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
787
788   // Try to perform integral promotions if the object has a theoretically
789   // promotable type.
790   if (Ty->isIntegralOrUnscopedEnumerationType()) {
791     // C99 6.3.1.1p2:
792     //
793     //   The following may be used in an expression wherever an int or
794     //   unsigned int may be used:
795     //     - an object or expression with an integer type whose integer
796     //       conversion rank is less than or equal to the rank of int
797     //       and unsigned int.
798     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
799     //
800     //   If an int can represent all values of the original type, the
801     //   value is converted to an int; otherwise, it is converted to an
802     //   unsigned int. These are called the integer promotions. All
803     //   other types are unchanged by the integer promotions.
804
805     QualType PTy = Context.isPromotableBitField(E);
806     if (!PTy.isNull()) {
807       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
808       return E;
809     }
810     if (Ty->isPromotableIntegerType()) {
811       QualType PT = Context.getPromotedIntegerType(Ty);
812       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
813       return E;
814     }
815   }
816   return E;
817 }
818
819 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
820 /// do not have a prototype. Arguments that have type float or __fp16
821 /// are promoted to double. All other argument types are converted by
822 /// UsualUnaryConversions().
823 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
824   QualType Ty = E->getType();
825   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
826
827   ExprResult Res = UsualUnaryConversions(E);
828   if (Res.isInvalid())
829     return ExprError();
830   E = Res.get();
831
832   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
833   // double.
834   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
835   if (BTy && (BTy->getKind() == BuiltinType::Half ||
836               BTy->getKind() == BuiltinType::Float)) {
837     if (getLangOpts().OpenCL &&
838         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
839         if (BTy->getKind() == BuiltinType::Half) {
840             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
841         }
842     } else {
843       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
844     }
845   }
846
847   // C++ performs lvalue-to-rvalue conversion as a default argument
848   // promotion, even on class types, but note:
849   //   C++11 [conv.lval]p2:
850   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
851   //     operand or a subexpression thereof the value contained in the
852   //     referenced object is not accessed. Otherwise, if the glvalue
853   //     has a class type, the conversion copy-initializes a temporary
854   //     of type T from the glvalue and the result of the conversion
855   //     is a prvalue for the temporary.
856   // FIXME: add some way to gate this entire thing for correctness in
857   // potentially potentially evaluated contexts.
858   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
859     ExprResult Temp = PerformCopyInitialization(
860                        InitializedEntity::InitializeTemporary(E->getType()),
861                                                 E->getExprLoc(), E);
862     if (Temp.isInvalid())
863       return ExprError();
864     E = Temp.get();
865   }
866
867   return E;
868 }
869
870 /// Determine the degree of POD-ness for an expression.
871 /// Incomplete types are considered POD, since this check can be performed
872 /// when we're in an unevaluated context.
873 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
874   if (Ty->isIncompleteType()) {
875     // C++11 [expr.call]p7:
876     //   After these conversions, if the argument does not have arithmetic,
877     //   enumeration, pointer, pointer to member, or class type, the program
878     //   is ill-formed.
879     //
880     // Since we've already performed array-to-pointer and function-to-pointer
881     // decay, the only such type in C++ is cv void. This also handles
882     // initializer lists as variadic arguments.
883     if (Ty->isVoidType())
884       return VAK_Invalid;
885
886     if (Ty->isObjCObjectType())
887       return VAK_Invalid;
888     return VAK_Valid;
889   }
890
891   if (Ty.isCXX98PODType(Context))
892     return VAK_Valid;
893
894   // C++11 [expr.call]p7:
895   //   Passing a potentially-evaluated argument of class type (Clause 9)
896   //   having a non-trivial copy constructor, a non-trivial move constructor,
897   //   or a non-trivial destructor, with no corresponding parameter,
898   //   is conditionally-supported with implementation-defined semantics.
899   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
900     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
901       if (!Record->hasNonTrivialCopyConstructor() &&
902           !Record->hasNonTrivialMoveConstructor() &&
903           !Record->hasNonTrivialDestructor())
904         return VAK_ValidInCXX11;
905
906   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
907     return VAK_Valid;
908
909   if (Ty->isObjCObjectType())
910     return VAK_Invalid;
911
912   if (getLangOpts().MSVCCompat)
913     return VAK_MSVCUndefined;
914
915   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
916   // permitted to reject them. We should consider doing so.
917   return VAK_Undefined;
918 }
919
920 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
921   // Don't allow one to pass an Objective-C interface to a vararg.
922   const QualType &Ty = E->getType();
923   VarArgKind VAK = isValidVarArgType(Ty);
924
925   // Complain about passing non-POD types through varargs.
926   switch (VAK) {
927   case VAK_ValidInCXX11:
928     DiagRuntimeBehavior(
929         E->getLocStart(), nullptr,
930         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
931           << Ty << CT);
932     // Fall through.
933   case VAK_Valid:
934     if (Ty->isRecordType()) {
935       // This is unlikely to be what the user intended. If the class has a
936       // 'c_str' member function, the user probably meant to call that.
937       DiagRuntimeBehavior(E->getLocStart(), nullptr,
938                           PDiag(diag::warn_pass_class_arg_to_vararg)
939                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
940     }
941     break;
942
943   case VAK_Undefined:
944   case VAK_MSVCUndefined:
945     DiagRuntimeBehavior(
946         E->getLocStart(), nullptr,
947         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
948           << getLangOpts().CPlusPlus11 << Ty << CT);
949     break;
950
951   case VAK_Invalid:
952     if (Ty->isObjCObjectType())
953       DiagRuntimeBehavior(
954           E->getLocStart(), nullptr,
955           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
956             << Ty << CT);
957     else
958       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
959         << isa<InitListExpr>(E) << Ty << CT;
960     break;
961   }
962 }
963
964 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
965 /// will create a trap if the resulting type is not a POD type.
966 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
967                                                   FunctionDecl *FDecl) {
968   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
969     // Strip the unbridged-cast placeholder expression off, if applicable.
970     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
971         (CT == VariadicMethod ||
972          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
973       E = stripARCUnbridgedCast(E);
974
975     // Otherwise, do normal placeholder checking.
976     } else {
977       ExprResult ExprRes = CheckPlaceholderExpr(E);
978       if (ExprRes.isInvalid())
979         return ExprError();
980       E = ExprRes.get();
981     }
982   }
983   
984   ExprResult ExprRes = DefaultArgumentPromotion(E);
985   if (ExprRes.isInvalid())
986     return ExprError();
987   E = ExprRes.get();
988
989   // Diagnostics regarding non-POD argument types are
990   // emitted along with format string checking in Sema::CheckFunctionCall().
991   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
992     // Turn this into a trap.
993     CXXScopeSpec SS;
994     SourceLocation TemplateKWLoc;
995     UnqualifiedId Name;
996     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
997                        E->getLocStart());
998     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
999                                           Name, true, false);
1000     if (TrapFn.isInvalid())
1001       return ExprError();
1002
1003     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
1004                                     E->getLocStart(), None,
1005                                     E->getLocEnd());
1006     if (Call.isInvalid())
1007       return ExprError();
1008
1009     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
1010                                   Call.get(), E);
1011     if (Comma.isInvalid())
1012       return ExprError();
1013     return Comma.get();
1014   }
1015
1016   if (!getLangOpts().CPlusPlus &&
1017       RequireCompleteType(E->getExprLoc(), E->getType(),
1018                           diag::err_call_incomplete_argument))
1019     return ExprError();
1020
1021   return E;
1022 }
1023
1024 /// \brief Converts an integer to complex float type.  Helper function of
1025 /// UsualArithmeticConversions()
1026 ///
1027 /// \return false if the integer expression is an integer type and is
1028 /// successfully converted to the complex type.
1029 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1030                                                   ExprResult &ComplexExpr,
1031                                                   QualType IntTy,
1032                                                   QualType ComplexTy,
1033                                                   bool SkipCast) {
1034   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1035   if (SkipCast) return false;
1036   if (IntTy->isIntegerType()) {
1037     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1038     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1039     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1040                                   CK_FloatingRealToComplex);
1041   } else {
1042     assert(IntTy->isComplexIntegerType());
1043     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1044                                   CK_IntegralComplexToFloatingComplex);
1045   }
1046   return false;
1047 }
1048
1049 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1050 /// UsualArithmeticConversions()
1051 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1052                                              ExprResult &RHS, QualType LHSType,
1053                                              QualType RHSType,
1054                                              bool IsCompAssign) {
1055   // if we have an integer operand, the result is the complex type.
1056   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1057                                              /*skipCast*/false))
1058     return LHSType;
1059   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1060                                              /*skipCast*/IsCompAssign))
1061     return RHSType;
1062
1063   // This handles complex/complex, complex/float, or float/complex.
1064   // When both operands are complex, the shorter operand is converted to the
1065   // type of the longer, and that is the type of the result. This corresponds
1066   // to what is done when combining two real floating-point operands.
1067   // The fun begins when size promotion occur across type domains.
1068   // From H&S 6.3.4: When one operand is complex and the other is a real
1069   // floating-point type, the less precise type is converted, within it's
1070   // real or complex domain, to the precision of the other type. For example,
1071   // when combining a "long double" with a "double _Complex", the
1072   // "double _Complex" is promoted to "long double _Complex".
1073
1074   // Compute the rank of the two types, regardless of whether they are complex.
1075   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1076
1077   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1078   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1079   QualType LHSElementType =
1080       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1081   QualType RHSElementType =
1082       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1083
1084   QualType ResultType = S.Context.getComplexType(LHSElementType);
1085   if (Order < 0) {
1086     // Promote the precision of the LHS if not an assignment.
1087     ResultType = S.Context.getComplexType(RHSElementType);
1088     if (!IsCompAssign) {
1089       if (LHSComplexType)
1090         LHS =
1091             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1092       else
1093         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1094     }
1095   } else if (Order > 0) {
1096     // Promote the precision of the RHS.
1097     if (RHSComplexType)
1098       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1099     else
1100       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1101   }
1102   return ResultType;
1103 }
1104
1105 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1106 /// of UsualArithmeticConversions()
1107 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1108                                            ExprResult &IntExpr,
1109                                            QualType FloatTy, QualType IntTy,
1110                                            bool ConvertFloat, bool ConvertInt) {
1111   if (IntTy->isIntegerType()) {
1112     if (ConvertInt)
1113       // Convert intExpr to the lhs floating point type.
1114       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1115                                     CK_IntegralToFloating);
1116     return FloatTy;
1117   }
1118      
1119   // Convert both sides to the appropriate complex float.
1120   assert(IntTy->isComplexIntegerType());
1121   QualType result = S.Context.getComplexType(FloatTy);
1122
1123   // _Complex int -> _Complex float
1124   if (ConvertInt)
1125     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1126                                   CK_IntegralComplexToFloatingComplex);
1127
1128   // float -> _Complex float
1129   if (ConvertFloat)
1130     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1131                                     CK_FloatingRealToComplex);
1132
1133   return result;
1134 }
1135
1136 /// \brief Handle arithmethic conversion with floating point types.  Helper
1137 /// function of UsualArithmeticConversions()
1138 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1139                                       ExprResult &RHS, QualType LHSType,
1140                                       QualType RHSType, bool IsCompAssign) {
1141   bool LHSFloat = LHSType->isRealFloatingType();
1142   bool RHSFloat = RHSType->isRealFloatingType();
1143
1144   // If we have two real floating types, convert the smaller operand
1145   // to the bigger result.
1146   if (LHSFloat && RHSFloat) {
1147     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1148     if (order > 0) {
1149       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1150       return LHSType;
1151     }
1152
1153     assert(order < 0 && "illegal float comparison");
1154     if (!IsCompAssign)
1155       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1156     return RHSType;
1157   }
1158
1159   if (LHSFloat) {
1160     // Half FP has to be promoted to float unless it is natively supported
1161     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1162       LHSType = S.Context.FloatTy;
1163
1164     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1165                                       /*convertFloat=*/!IsCompAssign,
1166                                       /*convertInt=*/ true);
1167   }
1168   assert(RHSFloat);
1169   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1170                                     /*convertInt=*/ true,
1171                                     /*convertFloat=*/!IsCompAssign);
1172 }
1173
1174 /// \brief Diagnose attempts to convert between __float128 and long double if
1175 /// there is no support for such conversion. Helper function of
1176 /// UsualArithmeticConversions().
1177 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1178                                       QualType RHSType) {
1179   /*  No issue converting if at least one of the types is not a floating point
1180       type or the two types have the same rank.
1181   */
1182   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1183       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1184     return false;
1185
1186   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1187          "The remaining types must be floating point types.");
1188
1189   auto *LHSComplex = LHSType->getAs<ComplexType>();
1190   auto *RHSComplex = RHSType->getAs<ComplexType>();
1191
1192   QualType LHSElemType = LHSComplex ?
1193     LHSComplex->getElementType() : LHSType;
1194   QualType RHSElemType = RHSComplex ?
1195     RHSComplex->getElementType() : RHSType;
1196
1197   // No issue if the two types have the same representation
1198   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1199       &S.Context.getFloatTypeSemantics(RHSElemType))
1200     return false;
1201
1202   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1203                                 RHSElemType == S.Context.LongDoubleTy);
1204   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1205                             RHSElemType == S.Context.Float128Ty);
1206
1207   /* We've handled the situation where __float128 and long double have the same
1208      representation. The only other allowable conversion is if long double is
1209      really just double.
1210   */
1211   return Float128AndLongDouble &&
1212     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1213      &llvm::APFloat::IEEEdouble());
1214 }
1215
1216 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1217
1218 namespace {
1219 /// These helper callbacks are placed in an anonymous namespace to
1220 /// permit their use as function template parameters.
1221 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1222   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1223 }
1224
1225 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1226   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1227                              CK_IntegralComplexCast);
1228 }
1229 }
1230
1231 /// \brief Handle integer arithmetic conversions.  Helper function of
1232 /// UsualArithmeticConversions()
1233 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1234 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1235                                         ExprResult &RHS, QualType LHSType,
1236                                         QualType RHSType, bool IsCompAssign) {
1237   // The rules for this case are in C99 6.3.1.8
1238   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1239   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1240   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1241   if (LHSSigned == RHSSigned) {
1242     // Same signedness; use the higher-ranked type
1243     if (order >= 0) {
1244       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1245       return LHSType;
1246     } else if (!IsCompAssign)
1247       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1248     return RHSType;
1249   } else if (order != (LHSSigned ? 1 : -1)) {
1250     // The unsigned type has greater than or equal rank to the
1251     // signed type, so use the unsigned type
1252     if (RHSSigned) {
1253       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1254       return LHSType;
1255     } else if (!IsCompAssign)
1256       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1257     return RHSType;
1258   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1259     // The two types are different widths; if we are here, that
1260     // means the signed type is larger than the unsigned type, so
1261     // use the signed type.
1262     if (LHSSigned) {
1263       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1264       return LHSType;
1265     } else if (!IsCompAssign)
1266       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1267     return RHSType;
1268   } else {
1269     // The signed type is higher-ranked than the unsigned type,
1270     // but isn't actually any bigger (like unsigned int and long
1271     // on most 32-bit systems).  Use the unsigned type corresponding
1272     // to the signed type.
1273     QualType result =
1274       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1275     RHS = (*doRHSCast)(S, RHS.get(), result);
1276     if (!IsCompAssign)
1277       LHS = (*doLHSCast)(S, LHS.get(), result);
1278     return result;
1279   }
1280 }
1281
1282 /// \brief Handle conversions with GCC complex int extension.  Helper function
1283 /// of UsualArithmeticConversions()
1284 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1285                                            ExprResult &RHS, QualType LHSType,
1286                                            QualType RHSType,
1287                                            bool IsCompAssign) {
1288   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1289   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1290
1291   if (LHSComplexInt && RHSComplexInt) {
1292     QualType LHSEltType = LHSComplexInt->getElementType();
1293     QualType RHSEltType = RHSComplexInt->getElementType();
1294     QualType ScalarType =
1295       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1296         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1297
1298     return S.Context.getComplexType(ScalarType);
1299   }
1300
1301   if (LHSComplexInt) {
1302     QualType LHSEltType = LHSComplexInt->getElementType();
1303     QualType ScalarType =
1304       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1305         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1306     QualType ComplexType = S.Context.getComplexType(ScalarType);
1307     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1308                               CK_IntegralRealToComplex);
1309  
1310     return ComplexType;
1311   }
1312
1313   assert(RHSComplexInt);
1314
1315   QualType RHSEltType = RHSComplexInt->getElementType();
1316   QualType ScalarType =
1317     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1318       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1319   QualType ComplexType = S.Context.getComplexType(ScalarType);
1320   
1321   if (!IsCompAssign)
1322     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1323                               CK_IntegralRealToComplex);
1324   return ComplexType;
1325 }
1326
1327 /// UsualArithmeticConversions - Performs various conversions that are common to
1328 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1329 /// routine returns the first non-arithmetic type found. The client is
1330 /// responsible for emitting appropriate error diagnostics.
1331 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1332                                           bool IsCompAssign) {
1333   if (!IsCompAssign) {
1334     LHS = UsualUnaryConversions(LHS.get());
1335     if (LHS.isInvalid())
1336       return QualType();
1337   }
1338
1339   RHS = UsualUnaryConversions(RHS.get());
1340   if (RHS.isInvalid())
1341     return QualType();
1342
1343   // For conversion purposes, we ignore any qualifiers.
1344   // For example, "const float" and "float" are equivalent.
1345   QualType LHSType =
1346     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1347   QualType RHSType =
1348     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1349
1350   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1351   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1352     LHSType = AtomicLHS->getValueType();
1353
1354   // If both types are identical, no conversion is needed.
1355   if (LHSType == RHSType)
1356     return LHSType;
1357
1358   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1359   // The caller can deal with this (e.g. pointer + int).
1360   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1361     return QualType();
1362
1363   // Apply unary and bitfield promotions to the LHS's type.
1364   QualType LHSUnpromotedType = LHSType;
1365   if (LHSType->isPromotableIntegerType())
1366     LHSType = Context.getPromotedIntegerType(LHSType);
1367   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1368   if (!LHSBitfieldPromoteTy.isNull())
1369     LHSType = LHSBitfieldPromoteTy;
1370   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1371     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1372
1373   // If both types are identical, no conversion is needed.
1374   if (LHSType == RHSType)
1375     return LHSType;
1376
1377   // At this point, we have two different arithmetic types.
1378
1379   // Diagnose attempts to convert between __float128 and long double where
1380   // such conversions currently can't be handled.
1381   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1382     return QualType();
1383
1384   // Handle complex types first (C99 6.3.1.8p1).
1385   if (LHSType->isComplexType() || RHSType->isComplexType())
1386     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1387                                         IsCompAssign);
1388
1389   // Now handle "real" floating types (i.e. float, double, long double).
1390   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1391     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1392                                  IsCompAssign);
1393
1394   // Handle GCC complex int extension.
1395   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1396     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1397                                       IsCompAssign);
1398
1399   // Finally, we have two differing integer types.
1400   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1401            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1402 }
1403
1404
1405 //===----------------------------------------------------------------------===//
1406 //  Semantic Analysis for various Expression Types
1407 //===----------------------------------------------------------------------===//
1408
1409
1410 ExprResult
1411 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1412                                 SourceLocation DefaultLoc,
1413                                 SourceLocation RParenLoc,
1414                                 Expr *ControllingExpr,
1415                                 ArrayRef<ParsedType> ArgTypes,
1416                                 ArrayRef<Expr *> ArgExprs) {
1417   unsigned NumAssocs = ArgTypes.size();
1418   assert(NumAssocs == ArgExprs.size());
1419
1420   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1421   for (unsigned i = 0; i < NumAssocs; ++i) {
1422     if (ArgTypes[i])
1423       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1424     else
1425       Types[i] = nullptr;
1426   }
1427
1428   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1429                                              ControllingExpr,
1430                                              llvm::makeArrayRef(Types, NumAssocs),
1431                                              ArgExprs);
1432   delete [] Types;
1433   return ER;
1434 }
1435
1436 ExprResult
1437 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1438                                  SourceLocation DefaultLoc,
1439                                  SourceLocation RParenLoc,
1440                                  Expr *ControllingExpr,
1441                                  ArrayRef<TypeSourceInfo *> Types,
1442                                  ArrayRef<Expr *> Exprs) {
1443   unsigned NumAssocs = Types.size();
1444   assert(NumAssocs == Exprs.size());
1445
1446   // Decay and strip qualifiers for the controlling expression type, and handle
1447   // placeholder type replacement. See committee discussion from WG14 DR423.
1448   {
1449     EnterExpressionEvaluationContext Unevaluated(
1450         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1451     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1452     if (R.isInvalid())
1453       return ExprError();
1454     ControllingExpr = R.get();
1455   }
1456
1457   // The controlling expression is an unevaluated operand, so side effects are
1458   // likely unintended.
1459   if (!inTemplateInstantiation() &&
1460       ControllingExpr->HasSideEffects(Context, false))
1461     Diag(ControllingExpr->getExprLoc(),
1462          diag::warn_side_effects_unevaluated_context);
1463
1464   bool TypeErrorFound = false,
1465        IsResultDependent = ControllingExpr->isTypeDependent(),
1466        ContainsUnexpandedParameterPack
1467          = ControllingExpr->containsUnexpandedParameterPack();
1468
1469   for (unsigned i = 0; i < NumAssocs; ++i) {
1470     if (Exprs[i]->containsUnexpandedParameterPack())
1471       ContainsUnexpandedParameterPack = true;
1472
1473     if (Types[i]) {
1474       if (Types[i]->getType()->containsUnexpandedParameterPack())
1475         ContainsUnexpandedParameterPack = true;
1476
1477       if (Types[i]->getType()->isDependentType()) {
1478         IsResultDependent = true;
1479       } else {
1480         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1481         // complete object type other than a variably modified type."
1482         unsigned D = 0;
1483         if (Types[i]->getType()->isIncompleteType())
1484           D = diag::err_assoc_type_incomplete;
1485         else if (!Types[i]->getType()->isObjectType())
1486           D = diag::err_assoc_type_nonobject;
1487         else if (Types[i]->getType()->isVariablyModifiedType())
1488           D = diag::err_assoc_type_variably_modified;
1489
1490         if (D != 0) {
1491           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1492             << Types[i]->getTypeLoc().getSourceRange()
1493             << Types[i]->getType();
1494           TypeErrorFound = true;
1495         }
1496
1497         // C11 6.5.1.1p2 "No two generic associations in the same generic
1498         // selection shall specify compatible types."
1499         for (unsigned j = i+1; j < NumAssocs; ++j)
1500           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1501               Context.typesAreCompatible(Types[i]->getType(),
1502                                          Types[j]->getType())) {
1503             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1504                  diag::err_assoc_compatible_types)
1505               << Types[j]->getTypeLoc().getSourceRange()
1506               << Types[j]->getType()
1507               << Types[i]->getType();
1508             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1509                  diag::note_compat_assoc)
1510               << Types[i]->getTypeLoc().getSourceRange()
1511               << Types[i]->getType();
1512             TypeErrorFound = true;
1513           }
1514       }
1515     }
1516   }
1517   if (TypeErrorFound)
1518     return ExprError();
1519
1520   // If we determined that the generic selection is result-dependent, don't
1521   // try to compute the result expression.
1522   if (IsResultDependent)
1523     return new (Context) GenericSelectionExpr(
1524         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1525         ContainsUnexpandedParameterPack);
1526
1527   SmallVector<unsigned, 1> CompatIndices;
1528   unsigned DefaultIndex = -1U;
1529   for (unsigned i = 0; i < NumAssocs; ++i) {
1530     if (!Types[i])
1531       DefaultIndex = i;
1532     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1533                                         Types[i]->getType()))
1534       CompatIndices.push_back(i);
1535   }
1536
1537   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1538   // type compatible with at most one of the types named in its generic
1539   // association list."
1540   if (CompatIndices.size() > 1) {
1541     // We strip parens here because the controlling expression is typically
1542     // parenthesized in macro definitions.
1543     ControllingExpr = ControllingExpr->IgnoreParens();
1544     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1545       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1546       << (unsigned) CompatIndices.size();
1547     for (unsigned I : CompatIndices) {
1548       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1549            diag::note_compat_assoc)
1550         << Types[I]->getTypeLoc().getSourceRange()
1551         << Types[I]->getType();
1552     }
1553     return ExprError();
1554   }
1555
1556   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1557   // its controlling expression shall have type compatible with exactly one of
1558   // the types named in its generic association list."
1559   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1560     // We strip parens here because the controlling expression is typically
1561     // parenthesized in macro definitions.
1562     ControllingExpr = ControllingExpr->IgnoreParens();
1563     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1564       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1565     return ExprError();
1566   }
1567
1568   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1569   // type name that is compatible with the type of the controlling expression,
1570   // then the result expression of the generic selection is the expression
1571   // in that generic association. Otherwise, the result expression of the
1572   // generic selection is the expression in the default generic association."
1573   unsigned ResultIndex =
1574     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1575
1576   return new (Context) GenericSelectionExpr(
1577       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1578       ContainsUnexpandedParameterPack, ResultIndex);
1579 }
1580
1581 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1582 /// location of the token and the offset of the ud-suffix within it.
1583 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1584                                      unsigned Offset) {
1585   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1586                                         S.getLangOpts());
1587 }
1588
1589 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1590 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1591 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1592                                                  IdentifierInfo *UDSuffix,
1593                                                  SourceLocation UDSuffixLoc,
1594                                                  ArrayRef<Expr*> Args,
1595                                                  SourceLocation LitEndLoc) {
1596   assert(Args.size() <= 2 && "too many arguments for literal operator");
1597
1598   QualType ArgTy[2];
1599   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1600     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1601     if (ArgTy[ArgIdx]->isArrayType())
1602       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1603   }
1604
1605   DeclarationName OpName =
1606     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1607   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1608   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1609
1610   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1611   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1612                               /*AllowRaw*/false, /*AllowTemplate*/false,
1613                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1614     return ExprError();
1615
1616   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1617 }
1618
1619 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1620 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1621 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1622 /// multiple tokens.  However, the common case is that StringToks points to one
1623 /// string.
1624 ///
1625 ExprResult
1626 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1627   assert(!StringToks.empty() && "Must have at least one string!");
1628
1629   StringLiteralParser Literal(StringToks, PP);
1630   if (Literal.hadError)
1631     return ExprError();
1632
1633   SmallVector<SourceLocation, 4> StringTokLocs;
1634   for (const Token &Tok : StringToks)
1635     StringTokLocs.push_back(Tok.getLocation());
1636
1637   QualType CharTy = Context.CharTy;
1638   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1639   if (Literal.isWide()) {
1640     CharTy = Context.getWideCharType();
1641     Kind = StringLiteral::Wide;
1642   } else if (Literal.isUTF8()) {
1643     Kind = StringLiteral::UTF8;
1644   } else if (Literal.isUTF16()) {
1645     CharTy = Context.Char16Ty;
1646     Kind = StringLiteral::UTF16;
1647   } else if (Literal.isUTF32()) {
1648     CharTy = Context.Char32Ty;
1649     Kind = StringLiteral::UTF32;
1650   } else if (Literal.isPascal()) {
1651     CharTy = Context.UnsignedCharTy;
1652   }
1653
1654   QualType CharTyConst = CharTy;
1655   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1656   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1657     CharTyConst.addConst();
1658
1659   // Get an array type for the string, according to C99 6.4.5.  This includes
1660   // the nul terminator character as well as the string length for pascal
1661   // strings.
1662   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1663                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1664                                  ArrayType::Normal, 0);
1665
1666   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1667   if (getLangOpts().OpenCL) {
1668     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1669   }
1670
1671   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1672   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1673                                              Kind, Literal.Pascal, StrTy,
1674                                              &StringTokLocs[0],
1675                                              StringTokLocs.size());
1676   if (Literal.getUDSuffix().empty())
1677     return Lit;
1678
1679   // We're building a user-defined literal.
1680   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1681   SourceLocation UDSuffixLoc =
1682     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1683                    Literal.getUDSuffixOffset());
1684
1685   // Make sure we're allowed user-defined literals here.
1686   if (!UDLScope)
1687     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1688
1689   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1690   //   operator "" X (str, len)
1691   QualType SizeType = Context.getSizeType();
1692
1693   DeclarationName OpName =
1694     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1695   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1696   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1697
1698   QualType ArgTy[] = {
1699     Context.getArrayDecayedType(StrTy), SizeType
1700   };
1701
1702   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1703   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1704                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1705                                 /*AllowStringTemplate*/true)) {
1706
1707   case LOLR_Cooked: {
1708     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1709     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1710                                                     StringTokLocs[0]);
1711     Expr *Args[] = { Lit, LenArg };
1712
1713     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1714   }
1715
1716   case LOLR_StringTemplate: {
1717     TemplateArgumentListInfo ExplicitArgs;
1718
1719     unsigned CharBits = Context.getIntWidth(CharTy);
1720     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1721     llvm::APSInt Value(CharBits, CharIsUnsigned);
1722
1723     TemplateArgument TypeArg(CharTy);
1724     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1725     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1726
1727     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1728       Value = Lit->getCodeUnit(I);
1729       TemplateArgument Arg(Context, Value, CharTy);
1730       TemplateArgumentLocInfo ArgInfo;
1731       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1732     }
1733     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1734                                     &ExplicitArgs);
1735   }
1736   case LOLR_Raw:
1737   case LOLR_Template:
1738     llvm_unreachable("unexpected literal operator lookup result");
1739   case LOLR_Error:
1740     return ExprError();
1741   }
1742   llvm_unreachable("unexpected literal operator lookup result");
1743 }
1744
1745 ExprResult
1746 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1747                        SourceLocation Loc,
1748                        const CXXScopeSpec *SS) {
1749   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1750   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1751 }
1752
1753 /// BuildDeclRefExpr - Build an expression that references a
1754 /// declaration that does not require a closure capture.
1755 ExprResult
1756 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1757                        const DeclarationNameInfo &NameInfo,
1758                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1759                        const TemplateArgumentListInfo *TemplateArgs) {
1760   bool RefersToCapturedVariable =
1761       isa<VarDecl>(D) &&
1762       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1763
1764   DeclRefExpr *E;
1765   if (isa<VarTemplateSpecializationDecl>(D)) {
1766     VarTemplateSpecializationDecl *VarSpec =
1767         cast<VarTemplateSpecializationDecl>(D);
1768
1769     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1770                                         : NestedNameSpecifierLoc(),
1771                             VarSpec->getTemplateKeywordLoc(), D,
1772                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1773                             FoundD, TemplateArgs);
1774   } else {
1775     assert(!TemplateArgs && "No template arguments for non-variable"
1776                             " template specialization references");
1777     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1778                                         : NestedNameSpecifierLoc(),
1779                             SourceLocation(), D, RefersToCapturedVariable,
1780                             NameInfo, Ty, VK, FoundD);
1781   }
1782
1783   MarkDeclRefReferenced(E);
1784
1785   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1786       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1787       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1788       recordUseOfEvaluatedWeak(E);
1789
1790   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1791   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1792     FD = IFD->getAnonField();
1793   if (FD) {
1794     UnusedPrivateFields.remove(FD);
1795     // Just in case we're building an illegal pointer-to-member.
1796     if (FD->isBitField())
1797       E->setObjectKind(OK_BitField);
1798   }
1799
1800   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1801   // designates a bit-field.
1802   if (auto *BD = dyn_cast<BindingDecl>(D))
1803     if (auto *BE = BD->getBinding())
1804       E->setObjectKind(BE->getObjectKind());
1805
1806   return E;
1807 }
1808
1809 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1810 /// possibly a list of template arguments.
1811 ///
1812 /// If this produces template arguments, it is permitted to call
1813 /// DecomposeTemplateName.
1814 ///
1815 /// This actually loses a lot of source location information for
1816 /// non-standard name kinds; we should consider preserving that in
1817 /// some way.
1818 void
1819 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1820                              TemplateArgumentListInfo &Buffer,
1821                              DeclarationNameInfo &NameInfo,
1822                              const TemplateArgumentListInfo *&TemplateArgs) {
1823   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1824     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1825     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1826
1827     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1828                                        Id.TemplateId->NumArgs);
1829     translateTemplateArguments(TemplateArgsPtr, Buffer);
1830
1831     TemplateName TName = Id.TemplateId->Template.get();
1832     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1833     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1834     TemplateArgs = &Buffer;
1835   } else {
1836     NameInfo = GetNameFromUnqualifiedId(Id);
1837     TemplateArgs = nullptr;
1838   }
1839 }
1840
1841 static void emitEmptyLookupTypoDiagnostic(
1842     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1843     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1844     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1845   DeclContext *Ctx =
1846       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1847   if (!TC) {
1848     // Emit a special diagnostic for failed member lookups.
1849     // FIXME: computing the declaration context might fail here (?)
1850     if (Ctx)
1851       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1852                                                  << SS.getRange();
1853     else
1854       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1855     return;
1856   }
1857
1858   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1859   bool DroppedSpecifier =
1860       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1861   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1862                         ? diag::note_implicit_param_decl
1863                         : diag::note_previous_decl;
1864   if (!Ctx)
1865     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1866                          SemaRef.PDiag(NoteID));
1867   else
1868     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1869                                  << Typo << Ctx << DroppedSpecifier
1870                                  << SS.getRange(),
1871                          SemaRef.PDiag(NoteID));
1872 }
1873
1874 /// Diagnose an empty lookup.
1875 ///
1876 /// \return false if new lookup candidates were found
1877 bool
1878 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1879                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1880                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1881                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1882   DeclarationName Name = R.getLookupName();
1883
1884   unsigned diagnostic = diag::err_undeclared_var_use;
1885   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1886   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1887       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1888       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1889     diagnostic = diag::err_undeclared_use;
1890     diagnostic_suggest = diag::err_undeclared_use_suggest;
1891   }
1892
1893   // If the original lookup was an unqualified lookup, fake an
1894   // unqualified lookup.  This is useful when (for example) the
1895   // original lookup would not have found something because it was a
1896   // dependent name.
1897   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1898   while (DC) {
1899     if (isa<CXXRecordDecl>(DC)) {
1900       LookupQualifiedName(R, DC);
1901
1902       if (!R.empty()) {
1903         // Don't give errors about ambiguities in this lookup.
1904         R.suppressDiagnostics();
1905
1906         // During a default argument instantiation the CurContext points
1907         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1908         // function parameter list, hence add an explicit check.
1909         bool isDefaultArgument =
1910             !CodeSynthesisContexts.empty() &&
1911             CodeSynthesisContexts.back().Kind ==
1912                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1913         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1914         bool isInstance = CurMethod &&
1915                           CurMethod->isInstance() &&
1916                           DC == CurMethod->getParent() && !isDefaultArgument;
1917
1918         // Give a code modification hint to insert 'this->'.
1919         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1920         // Actually quite difficult!
1921         if (getLangOpts().MSVCCompat)
1922           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1923         if (isInstance) {
1924           Diag(R.getNameLoc(), diagnostic) << Name
1925             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1926           CheckCXXThisCapture(R.getNameLoc());
1927         } else {
1928           Diag(R.getNameLoc(), diagnostic) << Name;
1929         }
1930
1931         // Do we really want to note all of these?
1932         for (NamedDecl *D : R)
1933           Diag(D->getLocation(), diag::note_dependent_var_use);
1934
1935         // Return true if we are inside a default argument instantiation
1936         // and the found name refers to an instance member function, otherwise
1937         // the function calling DiagnoseEmptyLookup will try to create an
1938         // implicit member call and this is wrong for default argument.
1939         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1940           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1941           return true;
1942         }
1943
1944         // Tell the callee to try to recover.
1945         return false;
1946       }
1947
1948       R.clear();
1949     }
1950
1951     // In Microsoft mode, if we are performing lookup from within a friend
1952     // function definition declared at class scope then we must set
1953     // DC to the lexical parent to be able to search into the parent
1954     // class.
1955     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1956         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1957         DC->getLexicalParent()->isRecord())
1958       DC = DC->getLexicalParent();
1959     else
1960       DC = DC->getParent();
1961   }
1962
1963   // We didn't find anything, so try to correct for a typo.
1964   TypoCorrection Corrected;
1965   if (S && Out) {
1966     SourceLocation TypoLoc = R.getNameLoc();
1967     assert(!ExplicitTemplateArgs &&
1968            "Diagnosing an empty lookup with explicit template args!");
1969     *Out = CorrectTypoDelayed(
1970         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1971         [=](const TypoCorrection &TC) {
1972           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1973                                         diagnostic, diagnostic_suggest);
1974         },
1975         nullptr, CTK_ErrorRecovery);
1976     if (*Out)
1977       return true;
1978   } else if (S && (Corrected =
1979                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1980                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1981     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1982     bool DroppedSpecifier =
1983         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1984     R.setLookupName(Corrected.getCorrection());
1985
1986     bool AcceptableWithRecovery = false;
1987     bool AcceptableWithoutRecovery = false;
1988     NamedDecl *ND = Corrected.getFoundDecl();
1989     if (ND) {
1990       if (Corrected.isOverloaded()) {
1991         OverloadCandidateSet OCS(R.getNameLoc(),
1992                                  OverloadCandidateSet::CSK_Normal);
1993         OverloadCandidateSet::iterator Best;
1994         for (NamedDecl *CD : Corrected) {
1995           if (FunctionTemplateDecl *FTD =
1996                    dyn_cast<FunctionTemplateDecl>(CD))
1997             AddTemplateOverloadCandidate(
1998                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1999                 Args, OCS);
2000           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2001             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2002               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2003                                    Args, OCS);
2004         }
2005         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2006         case OR_Success:
2007           ND = Best->FoundDecl;
2008           Corrected.setCorrectionDecl(ND);
2009           break;
2010         default:
2011           // FIXME: Arbitrarily pick the first declaration for the note.
2012           Corrected.setCorrectionDecl(ND);
2013           break;
2014         }
2015       }
2016       R.addDecl(ND);
2017       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2018         CXXRecordDecl *Record = nullptr;
2019         if (Corrected.getCorrectionSpecifier()) {
2020           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2021           Record = Ty->getAsCXXRecordDecl();
2022         }
2023         if (!Record)
2024           Record = cast<CXXRecordDecl>(
2025               ND->getDeclContext()->getRedeclContext());
2026         R.setNamingClass(Record);
2027       }
2028
2029       auto *UnderlyingND = ND->getUnderlyingDecl();
2030       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2031                                isa<FunctionTemplateDecl>(UnderlyingND);
2032       // FIXME: If we ended up with a typo for a type name or
2033       // Objective-C class name, we're in trouble because the parser
2034       // is in the wrong place to recover. Suggest the typo
2035       // correction, but don't make it a fix-it since we're not going
2036       // to recover well anyway.
2037       AcceptableWithoutRecovery =
2038           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2039     } else {
2040       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2041       // because we aren't able to recover.
2042       AcceptableWithoutRecovery = true;
2043     }
2044
2045     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2046       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2047                             ? diag::note_implicit_param_decl
2048                             : diag::note_previous_decl;
2049       if (SS.isEmpty())
2050         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2051                      PDiag(NoteID), AcceptableWithRecovery);
2052       else
2053         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2054                                   << Name << computeDeclContext(SS, false)
2055                                   << DroppedSpecifier << SS.getRange(),
2056                      PDiag(NoteID), AcceptableWithRecovery);
2057
2058       // Tell the callee whether to try to recover.
2059       return !AcceptableWithRecovery;
2060     }
2061   }
2062   R.clear();
2063
2064   // Emit a special diagnostic for failed member lookups.
2065   // FIXME: computing the declaration context might fail here (?)
2066   if (!SS.isEmpty()) {
2067     Diag(R.getNameLoc(), diag::err_no_member)
2068       << Name << computeDeclContext(SS, false)
2069       << SS.getRange();
2070     return true;
2071   }
2072
2073   // Give up, we can't recover.
2074   Diag(R.getNameLoc(), diagnostic) << Name;
2075   return true;
2076 }
2077
2078 /// In Microsoft mode, if we are inside a template class whose parent class has
2079 /// dependent base classes, and we can't resolve an unqualified identifier, then
2080 /// assume the identifier is a member of a dependent base class.  We can only
2081 /// recover successfully in static methods, instance methods, and other contexts
2082 /// where 'this' is available.  This doesn't precisely match MSVC's
2083 /// instantiation model, but it's close enough.
2084 static Expr *
2085 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2086                                DeclarationNameInfo &NameInfo,
2087                                SourceLocation TemplateKWLoc,
2088                                const TemplateArgumentListInfo *TemplateArgs) {
2089   // Only try to recover from lookup into dependent bases in static methods or
2090   // contexts where 'this' is available.
2091   QualType ThisType = S.getCurrentThisType();
2092   const CXXRecordDecl *RD = nullptr;
2093   if (!ThisType.isNull())
2094     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2095   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2096     RD = MD->getParent();
2097   if (!RD || !RD->hasAnyDependentBases())
2098     return nullptr;
2099
2100   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2101   // is available, suggest inserting 'this->' as a fixit.
2102   SourceLocation Loc = NameInfo.getLoc();
2103   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2104   DB << NameInfo.getName() << RD;
2105
2106   if (!ThisType.isNull()) {
2107     DB << FixItHint::CreateInsertion(Loc, "this->");
2108     return CXXDependentScopeMemberExpr::Create(
2109         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2110         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2111         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2112   }
2113
2114   // Synthesize a fake NNS that points to the derived class.  This will
2115   // perform name lookup during template instantiation.
2116   CXXScopeSpec SS;
2117   auto *NNS =
2118       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2119   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2120   return DependentScopeDeclRefExpr::Create(
2121       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2122       TemplateArgs);
2123 }
2124
2125 ExprResult
2126 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2127                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2128                         bool HasTrailingLParen, bool IsAddressOfOperand,
2129                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2130                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2131   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2132          "cannot be direct & operand and have a trailing lparen");
2133   if (SS.isInvalid())
2134     return ExprError();
2135
2136   TemplateArgumentListInfo TemplateArgsBuffer;
2137
2138   // Decompose the UnqualifiedId into the following data.
2139   DeclarationNameInfo NameInfo;
2140   const TemplateArgumentListInfo *TemplateArgs;
2141   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2142
2143   DeclarationName Name = NameInfo.getName();
2144   IdentifierInfo *II = Name.getAsIdentifierInfo();
2145   SourceLocation NameLoc = NameInfo.getLoc();
2146
2147   if (II && II->isEditorPlaceholder()) {
2148     // FIXME: When typed placeholders are supported we can create a typed
2149     // placeholder expression node.
2150     return ExprError();
2151   }
2152
2153   // C++ [temp.dep.expr]p3:
2154   //   An id-expression is type-dependent if it contains:
2155   //     -- an identifier that was declared with a dependent type,
2156   //        (note: handled after lookup)
2157   //     -- a template-id that is dependent,
2158   //        (note: handled in BuildTemplateIdExpr)
2159   //     -- a conversion-function-id that specifies a dependent type,
2160   //     -- a nested-name-specifier that contains a class-name that
2161   //        names a dependent type.
2162   // Determine whether this is a member of an unknown specialization;
2163   // we need to handle these differently.
2164   bool DependentID = false;
2165   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2166       Name.getCXXNameType()->isDependentType()) {
2167     DependentID = true;
2168   } else if (SS.isSet()) {
2169     if (DeclContext *DC = computeDeclContext(SS, false)) {
2170       if (RequireCompleteDeclContext(SS, DC))
2171         return ExprError();
2172     } else {
2173       DependentID = true;
2174     }
2175   }
2176
2177   if (DependentID)
2178     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2179                                       IsAddressOfOperand, TemplateArgs);
2180
2181   // Perform the required lookup.
2182   LookupResult R(*this, NameInfo, 
2183                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 
2184                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2185   if (TemplateArgs) {
2186     // Lookup the template name again to correctly establish the context in
2187     // which it was found. This is really unfortunate as we already did the
2188     // lookup to determine that it was a template name in the first place. If
2189     // this becomes a performance hit, we can work harder to preserve those
2190     // results until we get here but it's likely not worth it.
2191     bool MemberOfUnknownSpecialization;
2192     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2193                        MemberOfUnknownSpecialization);
2194     
2195     if (MemberOfUnknownSpecialization ||
2196         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2197       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2198                                         IsAddressOfOperand, TemplateArgs);
2199   } else {
2200     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2201     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2202
2203     // If the result might be in a dependent base class, this is a dependent 
2204     // id-expression.
2205     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2206       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2207                                         IsAddressOfOperand, TemplateArgs);
2208
2209     // If this reference is in an Objective-C method, then we need to do
2210     // some special Objective-C lookup, too.
2211     if (IvarLookupFollowUp) {
2212       ExprResult E(LookupInObjCMethod(R, S, II, true));
2213       if (E.isInvalid())
2214         return ExprError();
2215
2216       if (Expr *Ex = E.getAs<Expr>())
2217         return Ex;
2218     }
2219   }
2220
2221   if (R.isAmbiguous())
2222     return ExprError();
2223
2224   // This could be an implicitly declared function reference (legal in C90,
2225   // extension in C99, forbidden in C++).
2226   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2227     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2228     if (D) R.addDecl(D);
2229   }
2230
2231   // Determine whether this name might be a candidate for
2232   // argument-dependent lookup.
2233   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2234
2235   if (R.empty() && !ADL) {
2236     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2237       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2238                                                    TemplateKWLoc, TemplateArgs))
2239         return E;
2240     }
2241
2242     // Don't diagnose an empty lookup for inline assembly.
2243     if (IsInlineAsmIdentifier)
2244       return ExprError();
2245
2246     // If this name wasn't predeclared and if this is not a function
2247     // call, diagnose the problem.
2248     TypoExpr *TE = nullptr;
2249     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2250         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2251     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2252     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2253            "Typo correction callback misconfigured");
2254     if (CCC) {
2255       // Make sure the callback knows what the typo being diagnosed is.
2256       CCC->setTypoName(II);
2257       if (SS.isValid())
2258         CCC->setTypoNNS(SS.getScopeRep());
2259     }
2260     if (DiagnoseEmptyLookup(S, SS, R,
2261                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2262                             nullptr, None, &TE)) {
2263       if (TE && KeywordReplacement) {
2264         auto &State = getTypoExprState(TE);
2265         auto BestTC = State.Consumer->getNextCorrection();
2266         if (BestTC.isKeyword()) {
2267           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2268           if (State.DiagHandler)
2269             State.DiagHandler(BestTC);
2270           KeywordReplacement->startToken();
2271           KeywordReplacement->setKind(II->getTokenID());
2272           KeywordReplacement->setIdentifierInfo(II);
2273           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2274           // Clean up the state associated with the TypoExpr, since it has
2275           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2276           clearDelayedTypo(TE);
2277           // Signal that a correction to a keyword was performed by returning a
2278           // valid-but-null ExprResult.
2279           return (Expr*)nullptr;
2280         }
2281         State.Consumer->resetCorrectionStream();
2282       }
2283       return TE ? TE : ExprError();
2284     }
2285
2286     assert(!R.empty() &&
2287            "DiagnoseEmptyLookup returned false but added no results");
2288
2289     // If we found an Objective-C instance variable, let
2290     // LookupInObjCMethod build the appropriate expression to
2291     // reference the ivar.
2292     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2293       R.clear();
2294       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2295       // In a hopelessly buggy code, Objective-C instance variable
2296       // lookup fails and no expression will be built to reference it.
2297       if (!E.isInvalid() && !E.get())
2298         return ExprError();
2299       return E;
2300     }
2301   }
2302
2303   // This is guaranteed from this point on.
2304   assert(!R.empty() || ADL);
2305
2306   // Check whether this might be a C++ implicit instance member access.
2307   // C++ [class.mfct.non-static]p3:
2308   //   When an id-expression that is not part of a class member access
2309   //   syntax and not used to form a pointer to member is used in the
2310   //   body of a non-static member function of class X, if name lookup
2311   //   resolves the name in the id-expression to a non-static non-type
2312   //   member of some class C, the id-expression is transformed into a
2313   //   class member access expression using (*this) as the
2314   //   postfix-expression to the left of the . operator.
2315   //
2316   // But we don't actually need to do this for '&' operands if R
2317   // resolved to a function or overloaded function set, because the
2318   // expression is ill-formed if it actually works out to be a
2319   // non-static member function:
2320   //
2321   // C++ [expr.ref]p4:
2322   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2323   //   [t]he expression can be used only as the left-hand operand of a
2324   //   member function call.
2325   //
2326   // There are other safeguards against such uses, but it's important
2327   // to get this right here so that we don't end up making a
2328   // spuriously dependent expression if we're inside a dependent
2329   // instance method.
2330   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2331     bool MightBeImplicitMember;
2332     if (!IsAddressOfOperand)
2333       MightBeImplicitMember = true;
2334     else if (!SS.isEmpty())
2335       MightBeImplicitMember = false;
2336     else if (R.isOverloadedResult())
2337       MightBeImplicitMember = false;
2338     else if (R.isUnresolvableResult())
2339       MightBeImplicitMember = true;
2340     else
2341       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2342                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2343                               isa<MSPropertyDecl>(R.getFoundDecl());
2344
2345     if (MightBeImplicitMember)
2346       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2347                                              R, TemplateArgs, S);
2348   }
2349
2350   if (TemplateArgs || TemplateKWLoc.isValid()) {
2351
2352     // In C++1y, if this is a variable template id, then check it
2353     // in BuildTemplateIdExpr().
2354     // The single lookup result must be a variable template declaration.
2355     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2356         Id.TemplateId->Kind == TNK_Var_template) {
2357       assert(R.getAsSingle<VarTemplateDecl>() &&
2358              "There should only be one declaration found.");
2359     }
2360
2361     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2362   }
2363
2364   return BuildDeclarationNameExpr(SS, R, ADL);
2365 }
2366
2367 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2368 /// declaration name, generally during template instantiation.
2369 /// There's a large number of things which don't need to be done along
2370 /// this path.
2371 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2372     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2373     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2374   DeclContext *DC = computeDeclContext(SS, false);
2375   if (!DC)
2376     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2377                                      NameInfo, /*TemplateArgs=*/nullptr);
2378
2379   if (RequireCompleteDeclContext(SS, DC))
2380     return ExprError();
2381
2382   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2383   LookupQualifiedName(R, DC);
2384
2385   if (R.isAmbiguous())
2386     return ExprError();
2387
2388   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2389     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2390                                      NameInfo, /*TemplateArgs=*/nullptr);
2391
2392   if (R.empty()) {
2393     Diag(NameInfo.getLoc(), diag::err_no_member)
2394       << NameInfo.getName() << DC << SS.getRange();
2395     return ExprError();
2396   }
2397
2398   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2399     // Diagnose a missing typename if this resolved unambiguously to a type in
2400     // a dependent context.  If we can recover with a type, downgrade this to
2401     // a warning in Microsoft compatibility mode.
2402     unsigned DiagID = diag::err_typename_missing;
2403     if (RecoveryTSI && getLangOpts().MSVCCompat)
2404       DiagID = diag::ext_typename_missing;
2405     SourceLocation Loc = SS.getBeginLoc();
2406     auto D = Diag(Loc, DiagID);
2407     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2408       << SourceRange(Loc, NameInfo.getEndLoc());
2409
2410     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2411     // context.
2412     if (!RecoveryTSI)
2413       return ExprError();
2414
2415     // Only issue the fixit if we're prepared to recover.
2416     D << FixItHint::CreateInsertion(Loc, "typename ");
2417
2418     // Recover by pretending this was an elaborated type.
2419     QualType Ty = Context.getTypeDeclType(TD);
2420     TypeLocBuilder TLB;
2421     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2422
2423     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2424     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2425     QTL.setElaboratedKeywordLoc(SourceLocation());
2426     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2427
2428     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2429
2430     return ExprEmpty();
2431   }
2432
2433   // Defend against this resolving to an implicit member access. We usually
2434   // won't get here if this might be a legitimate a class member (we end up in
2435   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2436   // a pointer-to-member or in an unevaluated context in C++11.
2437   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2438     return BuildPossibleImplicitMemberExpr(SS,
2439                                            /*TemplateKWLoc=*/SourceLocation(),
2440                                            R, /*TemplateArgs=*/nullptr, S);
2441
2442   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2443 }
2444
2445 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2446 /// detected that we're currently inside an ObjC method.  Perform some
2447 /// additional lookup.
2448 ///
2449 /// Ideally, most of this would be done by lookup, but there's
2450 /// actually quite a lot of extra work involved.
2451 ///
2452 /// Returns a null sentinel to indicate trivial success.
2453 ExprResult
2454 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2455                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2456   SourceLocation Loc = Lookup.getNameLoc();
2457   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2458   
2459   // Check for error condition which is already reported.
2460   if (!CurMethod)
2461     return ExprError();
2462
2463   // There are two cases to handle here.  1) scoped lookup could have failed,
2464   // in which case we should look for an ivar.  2) scoped lookup could have
2465   // found a decl, but that decl is outside the current instance method (i.e.
2466   // a global variable).  In these two cases, we do a lookup for an ivar with
2467   // this name, if the lookup sucedes, we replace it our current decl.
2468
2469   // If we're in a class method, we don't normally want to look for
2470   // ivars.  But if we don't find anything else, and there's an
2471   // ivar, that's an error.
2472   bool IsClassMethod = CurMethod->isClassMethod();
2473
2474   bool LookForIvars;
2475   if (Lookup.empty())
2476     LookForIvars = true;
2477   else if (IsClassMethod)
2478     LookForIvars = false;
2479   else
2480     LookForIvars = (Lookup.isSingleResult() &&
2481                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2482   ObjCInterfaceDecl *IFace = nullptr;
2483   if (LookForIvars) {
2484     IFace = CurMethod->getClassInterface();
2485     ObjCInterfaceDecl *ClassDeclared;
2486     ObjCIvarDecl *IV = nullptr;
2487     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2488       // Diagnose using an ivar in a class method.
2489       if (IsClassMethod)
2490         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2491                          << IV->getDeclName());
2492
2493       // If we're referencing an invalid decl, just return this as a silent
2494       // error node.  The error diagnostic was already emitted on the decl.
2495       if (IV->isInvalidDecl())
2496         return ExprError();
2497
2498       // Check if referencing a field with __attribute__((deprecated)).
2499       if (DiagnoseUseOfDecl(IV, Loc))
2500         return ExprError();
2501
2502       // Diagnose the use of an ivar outside of the declaring class.
2503       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2504           !declaresSameEntity(ClassDeclared, IFace) &&
2505           !getLangOpts().DebuggerSupport)
2506         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2507
2508       // FIXME: This should use a new expr for a direct reference, don't
2509       // turn this into Self->ivar, just return a BareIVarExpr or something.
2510       IdentifierInfo &II = Context.Idents.get("self");
2511       UnqualifiedId SelfName;
2512       SelfName.setIdentifier(&II, SourceLocation());
2513       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2514       CXXScopeSpec SelfScopeSpec;
2515       SourceLocation TemplateKWLoc;
2516       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2517                                               SelfName, false, false);
2518       if (SelfExpr.isInvalid())
2519         return ExprError();
2520
2521       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2522       if (SelfExpr.isInvalid())
2523         return ExprError();
2524
2525       MarkAnyDeclReferenced(Loc, IV, true);
2526
2527       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2528       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2529           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2530         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2531
2532       ObjCIvarRefExpr *Result = new (Context)
2533           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2534                           IV->getLocation(), SelfExpr.get(), true, true);
2535
2536       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2537         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2538           recordUseOfEvaluatedWeak(Result);
2539       }
2540       if (getLangOpts().ObjCAutoRefCount) {
2541         if (CurContext->isClosure())
2542           Diag(Loc, diag::warn_implicitly_retains_self)
2543             << FixItHint::CreateInsertion(Loc, "self->");
2544       }
2545       
2546       return Result;
2547     }
2548   } else if (CurMethod->isInstanceMethod()) {
2549     // We should warn if a local variable hides an ivar.
2550     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2551       ObjCInterfaceDecl *ClassDeclared;
2552       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2553         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2554             declaresSameEntity(IFace, ClassDeclared))
2555           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2556       }
2557     }
2558   } else if (Lookup.isSingleResult() &&
2559              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2560     // If accessing a stand-alone ivar in a class method, this is an error.
2561     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2562       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2563                        << IV->getDeclName());
2564   }
2565
2566   if (Lookup.empty() && II && AllowBuiltinCreation) {
2567     // FIXME. Consolidate this with similar code in LookupName.
2568     if (unsigned BuiltinID = II->getBuiltinID()) {
2569       if (!(getLangOpts().CPlusPlus &&
2570             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2571         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2572                                            S, Lookup.isForRedeclaration(),
2573                                            Lookup.getNameLoc());
2574         if (D) Lookup.addDecl(D);
2575       }
2576     }
2577   }
2578   // Sentinel value saying that we didn't do anything special.
2579   return ExprResult((Expr *)nullptr);
2580 }
2581
2582 /// \brief Cast a base object to a member's actual type.
2583 ///
2584 /// Logically this happens in three phases:
2585 ///
2586 /// * First we cast from the base type to the naming class.
2587 ///   The naming class is the class into which we were looking
2588 ///   when we found the member;  it's the qualifier type if a
2589 ///   qualifier was provided, and otherwise it's the base type.
2590 ///
2591 /// * Next we cast from the naming class to the declaring class.
2592 ///   If the member we found was brought into a class's scope by
2593 ///   a using declaration, this is that class;  otherwise it's
2594 ///   the class declaring the member.
2595 ///
2596 /// * Finally we cast from the declaring class to the "true"
2597 ///   declaring class of the member.  This conversion does not
2598 ///   obey access control.
2599 ExprResult
2600 Sema::PerformObjectMemberConversion(Expr *From,
2601                                     NestedNameSpecifier *Qualifier,
2602                                     NamedDecl *FoundDecl,
2603                                     NamedDecl *Member) {
2604   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2605   if (!RD)
2606     return From;
2607
2608   QualType DestRecordType;
2609   QualType DestType;
2610   QualType FromRecordType;
2611   QualType FromType = From->getType();
2612   bool PointerConversions = false;
2613   if (isa<FieldDecl>(Member)) {
2614     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2615
2616     if (FromType->getAs<PointerType>()) {
2617       DestType = Context.getPointerType(DestRecordType);
2618       FromRecordType = FromType->getPointeeType();
2619       PointerConversions = true;
2620     } else {
2621       DestType = DestRecordType;
2622       FromRecordType = FromType;
2623     }
2624   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2625     if (Method->isStatic())
2626       return From;
2627
2628     DestType = Method->getThisType(Context);
2629     DestRecordType = DestType->getPointeeType();
2630
2631     if (FromType->getAs<PointerType>()) {
2632       FromRecordType = FromType->getPointeeType();
2633       PointerConversions = true;
2634     } else {
2635       FromRecordType = FromType;
2636       DestType = DestRecordType;
2637     }
2638   } else {
2639     // No conversion necessary.
2640     return From;
2641   }
2642
2643   if (DestType->isDependentType() || FromType->isDependentType())
2644     return From;
2645
2646   // If the unqualified types are the same, no conversion is necessary.
2647   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2648     return From;
2649
2650   SourceRange FromRange = From->getSourceRange();
2651   SourceLocation FromLoc = FromRange.getBegin();
2652
2653   ExprValueKind VK = From->getValueKind();
2654
2655   // C++ [class.member.lookup]p8:
2656   //   [...] Ambiguities can often be resolved by qualifying a name with its
2657   //   class name.
2658   //
2659   // If the member was a qualified name and the qualified referred to a
2660   // specific base subobject type, we'll cast to that intermediate type
2661   // first and then to the object in which the member is declared. That allows
2662   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2663   //
2664   //   class Base { public: int x; };
2665   //   class Derived1 : public Base { };
2666   //   class Derived2 : public Base { };
2667   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2668   //
2669   //   void VeryDerived::f() {
2670   //     x = 17; // error: ambiguous base subobjects
2671   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2672   //   }
2673   if (Qualifier && Qualifier->getAsType()) {
2674     QualType QType = QualType(Qualifier->getAsType(), 0);
2675     assert(QType->isRecordType() && "lookup done with non-record type");
2676
2677     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2678
2679     // In C++98, the qualifier type doesn't actually have to be a base
2680     // type of the object type, in which case we just ignore it.
2681     // Otherwise build the appropriate casts.
2682     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2683       CXXCastPath BasePath;
2684       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2685                                        FromLoc, FromRange, &BasePath))
2686         return ExprError();
2687
2688       if (PointerConversions)
2689         QType = Context.getPointerType(QType);
2690       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2691                                VK, &BasePath).get();
2692
2693       FromType = QType;
2694       FromRecordType = QRecordType;
2695
2696       // If the qualifier type was the same as the destination type,
2697       // we're done.
2698       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2699         return From;
2700     }
2701   }
2702
2703   bool IgnoreAccess = false;
2704
2705   // If we actually found the member through a using declaration, cast
2706   // down to the using declaration's type.
2707   //
2708   // Pointer equality is fine here because only one declaration of a
2709   // class ever has member declarations.
2710   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2711     assert(isa<UsingShadowDecl>(FoundDecl));
2712     QualType URecordType = Context.getTypeDeclType(
2713                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2714
2715     // We only need to do this if the naming-class to declaring-class
2716     // conversion is non-trivial.
2717     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2718       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2719       CXXCastPath BasePath;
2720       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2721                                        FromLoc, FromRange, &BasePath))
2722         return ExprError();
2723
2724       QualType UType = URecordType;
2725       if (PointerConversions)
2726         UType = Context.getPointerType(UType);
2727       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2728                                VK, &BasePath).get();
2729       FromType = UType;
2730       FromRecordType = URecordType;
2731     }
2732
2733     // We don't do access control for the conversion from the
2734     // declaring class to the true declaring class.
2735     IgnoreAccess = true;
2736   }
2737
2738   CXXCastPath BasePath;
2739   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2740                                    FromLoc, FromRange, &BasePath,
2741                                    IgnoreAccess))
2742     return ExprError();
2743
2744   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2745                            VK, &BasePath);
2746 }
2747
2748 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2749                                       const LookupResult &R,
2750                                       bool HasTrailingLParen) {
2751   // Only when used directly as the postfix-expression of a call.
2752   if (!HasTrailingLParen)
2753     return false;
2754
2755   // Never if a scope specifier was provided.
2756   if (SS.isSet())
2757     return false;
2758
2759   // Only in C++ or ObjC++.
2760   if (!getLangOpts().CPlusPlus)
2761     return false;
2762
2763   // Turn off ADL when we find certain kinds of declarations during
2764   // normal lookup:
2765   for (NamedDecl *D : R) {
2766     // C++0x [basic.lookup.argdep]p3:
2767     //     -- a declaration of a class member
2768     // Since using decls preserve this property, we check this on the
2769     // original decl.
2770     if (D->isCXXClassMember())
2771       return false;
2772
2773     // C++0x [basic.lookup.argdep]p3:
2774     //     -- a block-scope function declaration that is not a
2775     //        using-declaration
2776     // NOTE: we also trigger this for function templates (in fact, we
2777     // don't check the decl type at all, since all other decl types
2778     // turn off ADL anyway).
2779     if (isa<UsingShadowDecl>(D))
2780       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2781     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2782       return false;
2783
2784     // C++0x [basic.lookup.argdep]p3:
2785     //     -- a declaration that is neither a function or a function
2786     //        template
2787     // And also for builtin functions.
2788     if (isa<FunctionDecl>(D)) {
2789       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2790
2791       // But also builtin functions.
2792       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2793         return false;
2794     } else if (!isa<FunctionTemplateDecl>(D))
2795       return false;
2796   }
2797
2798   return true;
2799 }
2800
2801
2802 /// Diagnoses obvious problems with the use of the given declaration
2803 /// as an expression.  This is only actually called for lookups that
2804 /// were not overloaded, and it doesn't promise that the declaration
2805 /// will in fact be used.
2806 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2807   if (D->isInvalidDecl())
2808     return true;
2809
2810   if (isa<TypedefNameDecl>(D)) {
2811     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2812     return true;
2813   }
2814
2815   if (isa<ObjCInterfaceDecl>(D)) {
2816     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2817     return true;
2818   }
2819
2820   if (isa<NamespaceDecl>(D)) {
2821     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2822     return true;
2823   }
2824
2825   return false;
2826 }
2827
2828 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2829                                           LookupResult &R, bool NeedsADL,
2830                                           bool AcceptInvalidDecl) {
2831   // If this is a single, fully-resolved result and we don't need ADL,
2832   // just build an ordinary singleton decl ref.
2833   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2834     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2835                                     R.getRepresentativeDecl(), nullptr,
2836                                     AcceptInvalidDecl);
2837
2838   // We only need to check the declaration if there's exactly one
2839   // result, because in the overloaded case the results can only be
2840   // functions and function templates.
2841   if (R.isSingleResult() &&
2842       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2843     return ExprError();
2844
2845   // Otherwise, just build an unresolved lookup expression.  Suppress
2846   // any lookup-related diagnostics; we'll hash these out later, when
2847   // we've picked a target.
2848   R.suppressDiagnostics();
2849
2850   UnresolvedLookupExpr *ULE
2851     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2852                                    SS.getWithLocInContext(Context),
2853                                    R.getLookupNameInfo(),
2854                                    NeedsADL, R.isOverloadedResult(),
2855                                    R.begin(), R.end());
2856
2857   return ULE;
2858 }
2859
2860 static void
2861 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2862                                    ValueDecl *var, DeclContext *DC);
2863
2864 /// \brief Complete semantic analysis for a reference to the given declaration.
2865 ExprResult Sema::BuildDeclarationNameExpr(
2866     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2867     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2868     bool AcceptInvalidDecl) {
2869   assert(D && "Cannot refer to a NULL declaration");
2870   assert(!isa<FunctionTemplateDecl>(D) &&
2871          "Cannot refer unambiguously to a function template");
2872
2873   SourceLocation Loc = NameInfo.getLoc();
2874   if (CheckDeclInExpr(*this, Loc, D))
2875     return ExprError();
2876
2877   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2878     // Specifically diagnose references to class templates that are missing
2879     // a template argument list.
2880     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2881                                            << Template << SS.getRange();
2882     Diag(Template->getLocation(), diag::note_template_decl_here);
2883     return ExprError();
2884   }
2885
2886   // Make sure that we're referring to a value.
2887   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2888   if (!VD) {
2889     Diag(Loc, diag::err_ref_non_value)
2890       << D << SS.getRange();
2891     Diag(D->getLocation(), diag::note_declared_at);
2892     return ExprError();
2893   }
2894
2895   // Check whether this declaration can be used. Note that we suppress
2896   // this check when we're going to perform argument-dependent lookup
2897   // on this function name, because this might not be the function
2898   // that overload resolution actually selects.
2899   if (DiagnoseUseOfDecl(VD, Loc))
2900     return ExprError();
2901
2902   // Only create DeclRefExpr's for valid Decl's.
2903   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2904     return ExprError();
2905
2906   // Handle members of anonymous structs and unions.  If we got here,
2907   // and the reference is to a class member indirect field, then this
2908   // must be the subject of a pointer-to-member expression.
2909   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2910     if (!indirectField->isCXXClassMember())
2911       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2912                                                       indirectField);
2913
2914   {
2915     QualType type = VD->getType();
2916     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2917       // C++ [except.spec]p17:
2918       //   An exception-specification is considered to be needed when:
2919       //   - in an expression, the function is the unique lookup result or
2920       //     the selected member of a set of overloaded functions.
2921       ResolveExceptionSpec(Loc, FPT);
2922       type = VD->getType();
2923     }
2924     ExprValueKind valueKind = VK_RValue;
2925
2926     switch (D->getKind()) {
2927     // Ignore all the non-ValueDecl kinds.
2928 #define ABSTRACT_DECL(kind)
2929 #define VALUE(type, base)
2930 #define DECL(type, base) \
2931     case Decl::type:
2932 #include "clang/AST/DeclNodes.inc"
2933       llvm_unreachable("invalid value decl kind");
2934
2935     // These shouldn't make it here.
2936     case Decl::ObjCAtDefsField:
2937     case Decl::ObjCIvar:
2938       llvm_unreachable("forming non-member reference to ivar?");
2939
2940     // Enum constants are always r-values and never references.
2941     // Unresolved using declarations are dependent.
2942     case Decl::EnumConstant:
2943     case Decl::UnresolvedUsingValue:
2944     case Decl::OMPDeclareReduction:
2945       valueKind = VK_RValue;
2946       break;
2947
2948     // Fields and indirect fields that got here must be for
2949     // pointer-to-member expressions; we just call them l-values for
2950     // internal consistency, because this subexpression doesn't really
2951     // exist in the high-level semantics.
2952     case Decl::Field:
2953     case Decl::IndirectField:
2954       assert(getLangOpts().CPlusPlus &&
2955              "building reference to field in C?");
2956
2957       // These can't have reference type in well-formed programs, but
2958       // for internal consistency we do this anyway.
2959       type = type.getNonReferenceType();
2960       valueKind = VK_LValue;
2961       break;
2962
2963     // Non-type template parameters are either l-values or r-values
2964     // depending on the type.
2965     case Decl::NonTypeTemplateParm: {
2966       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2967         type = reftype->getPointeeType();
2968         valueKind = VK_LValue; // even if the parameter is an r-value reference
2969         break;
2970       }
2971
2972       // For non-references, we need to strip qualifiers just in case
2973       // the template parameter was declared as 'const int' or whatever.
2974       valueKind = VK_RValue;
2975       type = type.getUnqualifiedType();
2976       break;
2977     }
2978
2979     case Decl::Var:
2980     case Decl::VarTemplateSpecialization:
2981     case Decl::VarTemplatePartialSpecialization:
2982     case Decl::Decomposition:
2983     case Decl::OMPCapturedExpr:
2984       // In C, "extern void blah;" is valid and is an r-value.
2985       if (!getLangOpts().CPlusPlus &&
2986           !type.hasQualifiers() &&
2987           type->isVoidType()) {
2988         valueKind = VK_RValue;
2989         break;
2990       }
2991       // fallthrough
2992
2993     case Decl::ImplicitParam:
2994     case Decl::ParmVar: {
2995       // These are always l-values.
2996       valueKind = VK_LValue;
2997       type = type.getNonReferenceType();
2998
2999       // FIXME: Does the addition of const really only apply in
3000       // potentially-evaluated contexts? Since the variable isn't actually
3001       // captured in an unevaluated context, it seems that the answer is no.
3002       if (!isUnevaluatedContext()) {
3003         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3004         if (!CapturedType.isNull())
3005           type = CapturedType;
3006       }
3007       
3008       break;
3009     }
3010
3011     case Decl::Binding: {
3012       // These are always lvalues.
3013       valueKind = VK_LValue;
3014       type = type.getNonReferenceType();
3015       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3016       // decides how that's supposed to work.
3017       auto *BD = cast<BindingDecl>(VD);
3018       if (BD->getDeclContext()->isFunctionOrMethod() &&
3019           BD->getDeclContext() != CurContext)
3020         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3021       break;
3022     }
3023         
3024     case Decl::Function: {
3025       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3026         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3027           type = Context.BuiltinFnTy;
3028           valueKind = VK_RValue;
3029           break;
3030         }
3031       }
3032
3033       const FunctionType *fty = type->castAs<FunctionType>();
3034
3035       // If we're referring to a function with an __unknown_anytype
3036       // result type, make the entire expression __unknown_anytype.
3037       if (fty->getReturnType() == Context.UnknownAnyTy) {
3038         type = Context.UnknownAnyTy;
3039         valueKind = VK_RValue;
3040         break;
3041       }
3042
3043       // Functions are l-values in C++.
3044       if (getLangOpts().CPlusPlus) {
3045         valueKind = VK_LValue;
3046         break;
3047       }
3048       
3049       // C99 DR 316 says that, if a function type comes from a
3050       // function definition (without a prototype), that type is only
3051       // used for checking compatibility. Therefore, when referencing
3052       // the function, we pretend that we don't have the full function
3053       // type.
3054       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3055           isa<FunctionProtoType>(fty))
3056         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3057                                               fty->getExtInfo());
3058
3059       // Functions are r-values in C.
3060       valueKind = VK_RValue;
3061       break;
3062     }
3063
3064     case Decl::CXXDeductionGuide:
3065       llvm_unreachable("building reference to deduction guide");
3066
3067     case Decl::MSProperty:
3068       valueKind = VK_LValue;
3069       break;
3070
3071     case Decl::CXXMethod:
3072       // If we're referring to a method with an __unknown_anytype
3073       // result type, make the entire expression __unknown_anytype.
3074       // This should only be possible with a type written directly.
3075       if (const FunctionProtoType *proto
3076             = dyn_cast<FunctionProtoType>(VD->getType()))
3077         if (proto->getReturnType() == Context.UnknownAnyTy) {
3078           type = Context.UnknownAnyTy;
3079           valueKind = VK_RValue;
3080           break;
3081         }
3082
3083       // C++ methods are l-values if static, r-values if non-static.
3084       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3085         valueKind = VK_LValue;
3086         break;
3087       }
3088       // fallthrough
3089
3090     case Decl::CXXConversion:
3091     case Decl::CXXDestructor:
3092     case Decl::CXXConstructor:
3093       valueKind = VK_RValue;
3094       break;
3095     }
3096
3097     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3098                             TemplateArgs);
3099   }
3100 }
3101
3102 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3103                                     SmallString<32> &Target) {
3104   Target.resize(CharByteWidth * (Source.size() + 1));
3105   char *ResultPtr = &Target[0];
3106   const llvm::UTF8 *ErrorPtr;
3107   bool success =
3108       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3109   (void)success;
3110   assert(success);
3111   Target.resize(ResultPtr - &Target[0]);
3112 }
3113
3114 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3115                                      PredefinedExpr::IdentType IT) {
3116   // Pick the current block, lambda, captured statement or function.
3117   Decl *currentDecl = nullptr;
3118   if (const BlockScopeInfo *BSI = getCurBlock())
3119     currentDecl = BSI->TheDecl;
3120   else if (const LambdaScopeInfo *LSI = getCurLambda())
3121     currentDecl = LSI->CallOperator;
3122   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3123     currentDecl = CSI->TheCapturedDecl;
3124   else
3125     currentDecl = getCurFunctionOrMethodDecl();
3126
3127   if (!currentDecl) {
3128     Diag(Loc, diag::ext_predef_outside_function);
3129     currentDecl = Context.getTranslationUnitDecl();
3130   }
3131
3132   QualType ResTy;
3133   StringLiteral *SL = nullptr;
3134   if (cast<DeclContext>(currentDecl)->isDependentContext())
3135     ResTy = Context.DependentTy;
3136   else {
3137     // Pre-defined identifiers are of type char[x], where x is the length of
3138     // the string.
3139     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3140     unsigned Length = Str.length();
3141
3142     llvm::APInt LengthI(32, Length + 1);
3143     if (IT == PredefinedExpr::LFunction) {
3144       ResTy = Context.WideCharTy.withConst();
3145       SmallString<32> RawChars;
3146       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3147                               Str, RawChars);
3148       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3149                                            /*IndexTypeQuals*/ 0);
3150       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3151                                  /*Pascal*/ false, ResTy, Loc);
3152     } else {
3153       ResTy = Context.CharTy.withConst();
3154       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3155                                            /*IndexTypeQuals*/ 0);
3156       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3157                                  /*Pascal*/ false, ResTy, Loc);
3158     }
3159   }
3160
3161   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3162 }
3163
3164 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3165   PredefinedExpr::IdentType IT;
3166
3167   switch (Kind) {
3168   default: llvm_unreachable("Unknown simple primary expr!");
3169   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3170   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3171   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3172   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3173   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3174   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3175   }
3176
3177   return BuildPredefinedExpr(Loc, IT);
3178 }
3179
3180 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3181   SmallString<16> CharBuffer;
3182   bool Invalid = false;
3183   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3184   if (Invalid)
3185     return ExprError();
3186
3187   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3188                             PP, Tok.getKind());
3189   if (Literal.hadError())
3190     return ExprError();
3191
3192   QualType Ty;
3193   if (Literal.isWide())
3194     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3195   else if (Literal.isUTF16())
3196     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3197   else if (Literal.isUTF32())
3198     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3199   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3200     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3201   else
3202     Ty = Context.CharTy;  // 'x' -> char in C++
3203
3204   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3205   if (Literal.isWide())
3206     Kind = CharacterLiteral::Wide;
3207   else if (Literal.isUTF16())
3208     Kind = CharacterLiteral::UTF16;
3209   else if (Literal.isUTF32())
3210     Kind = CharacterLiteral::UTF32;
3211   else if (Literal.isUTF8())
3212     Kind = CharacterLiteral::UTF8;
3213
3214   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3215                                              Tok.getLocation());
3216
3217   if (Literal.getUDSuffix().empty())
3218     return Lit;
3219
3220   // We're building a user-defined literal.
3221   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3222   SourceLocation UDSuffixLoc =
3223     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3224
3225   // Make sure we're allowed user-defined literals here.
3226   if (!UDLScope)
3227     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3228
3229   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3230   //   operator "" X (ch)
3231   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3232                                         Lit, Tok.getLocation());
3233 }
3234
3235 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3236   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3237   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3238                                 Context.IntTy, Loc);
3239 }
3240
3241 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3242                                   QualType Ty, SourceLocation Loc) {
3243   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3244
3245   using llvm::APFloat;
3246   APFloat Val(Format);
3247
3248   APFloat::opStatus result = Literal.GetFloatValue(Val);
3249
3250   // Overflow is always an error, but underflow is only an error if
3251   // we underflowed to zero (APFloat reports denormals as underflow).
3252   if ((result & APFloat::opOverflow) ||
3253       ((result & APFloat::opUnderflow) && Val.isZero())) {
3254     unsigned diagnostic;
3255     SmallString<20> buffer;
3256     if (result & APFloat::opOverflow) {
3257       diagnostic = diag::warn_float_overflow;
3258       APFloat::getLargest(Format).toString(buffer);
3259     } else {
3260       diagnostic = diag::warn_float_underflow;
3261       APFloat::getSmallest(Format).toString(buffer);
3262     }
3263
3264     S.Diag(Loc, diagnostic)
3265       << Ty
3266       << StringRef(buffer.data(), buffer.size());
3267   }
3268
3269   bool isExact = (result == APFloat::opOK);
3270   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3271 }
3272
3273 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3274   assert(E && "Invalid expression");
3275
3276   if (E->isValueDependent())
3277     return false;
3278
3279   QualType QT = E->getType();
3280   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3281     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3282     return true;
3283   }
3284
3285   llvm::APSInt ValueAPS;
3286   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3287
3288   if (R.isInvalid())
3289     return true;
3290
3291   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3292   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3293     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3294         << ValueAPS.toString(10) << ValueIsPositive;
3295     return true;
3296   }
3297
3298   return false;
3299 }
3300
3301 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3302   // Fast path for a single digit (which is quite common).  A single digit
3303   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3304   if (Tok.getLength() == 1) {
3305     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3306     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3307   }
3308
3309   SmallString<128> SpellingBuffer;
3310   // NumericLiteralParser wants to overread by one character.  Add padding to
3311   // the buffer in case the token is copied to the buffer.  If getSpelling()
3312   // returns a StringRef to the memory buffer, it should have a null char at
3313   // the EOF, so it is also safe.
3314   SpellingBuffer.resize(Tok.getLength() + 1);
3315
3316   // Get the spelling of the token, which eliminates trigraphs, etc.
3317   bool Invalid = false;
3318   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3319   if (Invalid)
3320     return ExprError();
3321
3322   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3323   if (Literal.hadError)
3324     return ExprError();
3325
3326   if (Literal.hasUDSuffix()) {
3327     // We're building a user-defined literal.
3328     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3329     SourceLocation UDSuffixLoc =
3330       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3331
3332     // Make sure we're allowed user-defined literals here.
3333     if (!UDLScope)
3334       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3335
3336     QualType CookedTy;
3337     if (Literal.isFloatingLiteral()) {
3338       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3339       // long double, the literal is treated as a call of the form
3340       //   operator "" X (f L)
3341       CookedTy = Context.LongDoubleTy;
3342     } else {
3343       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3344       // unsigned long long, the literal is treated as a call of the form
3345       //   operator "" X (n ULL)
3346       CookedTy = Context.UnsignedLongLongTy;
3347     }
3348
3349     DeclarationName OpName =
3350       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3351     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3352     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3353
3354     SourceLocation TokLoc = Tok.getLocation();
3355
3356     // Perform literal operator lookup to determine if we're building a raw
3357     // literal or a cooked one.
3358     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3359     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3360                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3361                                   /*AllowStringTemplate*/false)) {
3362     case LOLR_Error:
3363       return ExprError();
3364
3365     case LOLR_Cooked: {
3366       Expr *Lit;
3367       if (Literal.isFloatingLiteral()) {
3368         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3369       } else {
3370         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3371         if (Literal.GetIntegerValue(ResultVal))
3372           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3373               << /* Unsigned */ 1;
3374         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3375                                      Tok.getLocation());
3376       }
3377       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3378     }
3379
3380     case LOLR_Raw: {
3381       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3382       // literal is treated as a call of the form
3383       //   operator "" X ("n")
3384       unsigned Length = Literal.getUDSuffixOffset();
3385       QualType StrTy = Context.getConstantArrayType(
3386           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3387           ArrayType::Normal, 0);
3388       Expr *Lit = StringLiteral::Create(
3389           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3390           /*Pascal*/false, StrTy, &TokLoc, 1);
3391       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3392     }
3393
3394     case LOLR_Template: {
3395       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3396       // template), L is treated as a call fo the form
3397       //   operator "" X <'c1', 'c2', ... 'ck'>()
3398       // where n is the source character sequence c1 c2 ... ck.
3399       TemplateArgumentListInfo ExplicitArgs;
3400       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3401       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3402       llvm::APSInt Value(CharBits, CharIsUnsigned);
3403       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3404         Value = TokSpelling[I];
3405         TemplateArgument Arg(Context, Value, Context.CharTy);
3406         TemplateArgumentLocInfo ArgInfo;
3407         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3408       }
3409       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3410                                       &ExplicitArgs);
3411     }
3412     case LOLR_StringTemplate:
3413       llvm_unreachable("unexpected literal operator lookup result");
3414     }
3415   }
3416
3417   Expr *Res;
3418
3419   if (Literal.isFloatingLiteral()) {
3420     QualType Ty;
3421     if (Literal.isHalf){
3422       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3423         Ty = Context.HalfTy;
3424       else {
3425         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3426         return ExprError();
3427       }
3428     } else if (Literal.isFloat)
3429       Ty = Context.FloatTy;
3430     else if (Literal.isLong)
3431       Ty = Context.LongDoubleTy;
3432     else if (Literal.isFloat128)
3433       Ty = Context.Float128Ty;
3434     else
3435       Ty = Context.DoubleTy;
3436
3437     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3438
3439     if (Ty == Context.DoubleTy) {
3440       if (getLangOpts().SinglePrecisionConstants) {
3441         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3442         if (BTy->getKind() != BuiltinType::Float) {
3443           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3444         }
3445       } else if (getLangOpts().OpenCL &&
3446                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3447         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3448         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3449         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3450       }
3451     }
3452   } else if (!Literal.isIntegerLiteral()) {
3453     return ExprError();
3454   } else {
3455     QualType Ty;
3456
3457     // 'long long' is a C99 or C++11 feature.
3458     if (!getLangOpts().C99 && Literal.isLongLong) {
3459       if (getLangOpts().CPlusPlus)
3460         Diag(Tok.getLocation(),
3461              getLangOpts().CPlusPlus11 ?
3462              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3463       else
3464         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3465     }
3466
3467     // Get the value in the widest-possible width.
3468     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3469     llvm::APInt ResultVal(MaxWidth, 0);
3470
3471     if (Literal.GetIntegerValue(ResultVal)) {
3472       // If this value didn't fit into uintmax_t, error and force to ull.
3473       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3474           << /* Unsigned */ 1;
3475       Ty = Context.UnsignedLongLongTy;
3476       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3477              "long long is not intmax_t?");
3478     } else {
3479       // If this value fits into a ULL, try to figure out what else it fits into
3480       // according to the rules of C99 6.4.4.1p5.
3481
3482       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3483       // be an unsigned int.
3484       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3485
3486       // Check from smallest to largest, picking the smallest type we can.
3487       unsigned Width = 0;
3488
3489       // Microsoft specific integer suffixes are explicitly sized.
3490       if (Literal.MicrosoftInteger) {
3491         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3492           Width = 8;
3493           Ty = Context.CharTy;
3494         } else {
3495           Width = Literal.MicrosoftInteger;
3496           Ty = Context.getIntTypeForBitwidth(Width,
3497                                              /*Signed=*/!Literal.isUnsigned);
3498         }
3499       }
3500
3501       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3502         // Are int/unsigned possibilities?
3503         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3504
3505         // Does it fit in a unsigned int?
3506         if (ResultVal.isIntN(IntSize)) {
3507           // Does it fit in a signed int?
3508           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3509             Ty = Context.IntTy;
3510           else if (AllowUnsigned)
3511             Ty = Context.UnsignedIntTy;
3512           Width = IntSize;
3513         }
3514       }
3515
3516       // Are long/unsigned long possibilities?
3517       if (Ty.isNull() && !Literal.isLongLong) {
3518         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3519
3520         // Does it fit in a unsigned long?
3521         if (ResultVal.isIntN(LongSize)) {
3522           // Does it fit in a signed long?
3523           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3524             Ty = Context.LongTy;
3525           else if (AllowUnsigned)
3526             Ty = Context.UnsignedLongTy;
3527           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3528           // is compatible.
3529           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3530             const unsigned LongLongSize =
3531                 Context.getTargetInfo().getLongLongWidth();
3532             Diag(Tok.getLocation(),
3533                  getLangOpts().CPlusPlus
3534                      ? Literal.isLong
3535                            ? diag::warn_old_implicitly_unsigned_long_cxx
3536                            : /*C++98 UB*/ diag::
3537                                  ext_old_implicitly_unsigned_long_cxx
3538                      : diag::warn_old_implicitly_unsigned_long)
3539                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3540                                             : /*will be ill-formed*/ 1);
3541             Ty = Context.UnsignedLongTy;
3542           }
3543           Width = LongSize;
3544         }
3545       }
3546
3547       // Check long long if needed.
3548       if (Ty.isNull()) {
3549         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3550
3551         // Does it fit in a unsigned long long?
3552         if (ResultVal.isIntN(LongLongSize)) {
3553           // Does it fit in a signed long long?
3554           // To be compatible with MSVC, hex integer literals ending with the
3555           // LL or i64 suffix are always signed in Microsoft mode.
3556           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3557               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3558             Ty = Context.LongLongTy;
3559           else if (AllowUnsigned)
3560             Ty = Context.UnsignedLongLongTy;
3561           Width = LongLongSize;
3562         }
3563       }
3564
3565       // If we still couldn't decide a type, we probably have something that
3566       // does not fit in a signed long long, but has no U suffix.
3567       if (Ty.isNull()) {
3568         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3569         Ty = Context.UnsignedLongLongTy;
3570         Width = Context.getTargetInfo().getLongLongWidth();
3571       }
3572
3573       if (ResultVal.getBitWidth() != Width)
3574         ResultVal = ResultVal.trunc(Width);
3575     }
3576     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3577   }
3578
3579   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3580   if (Literal.isImaginary)
3581     Res = new (Context) ImaginaryLiteral(Res,
3582                                         Context.getComplexType(Res->getType()));
3583
3584   return Res;
3585 }
3586
3587 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3588   assert(E && "ActOnParenExpr() missing expr");
3589   return new (Context) ParenExpr(L, R, E);
3590 }
3591
3592 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3593                                          SourceLocation Loc,
3594                                          SourceRange ArgRange) {
3595   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3596   // scalar or vector data type argument..."
3597   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3598   // type (C99 6.2.5p18) or void.
3599   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3600     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3601       << T << ArgRange;
3602     return true;
3603   }
3604
3605   assert((T->isVoidType() || !T->isIncompleteType()) &&
3606          "Scalar types should always be complete");
3607   return false;
3608 }
3609
3610 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3611                                            SourceLocation Loc,
3612                                            SourceRange ArgRange,
3613                                            UnaryExprOrTypeTrait TraitKind) {
3614   // Invalid types must be hard errors for SFINAE in C++.
3615   if (S.LangOpts.CPlusPlus)
3616     return true;
3617
3618   // C99 6.5.3.4p1:
3619   if (T->isFunctionType() &&
3620       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3621     // sizeof(function)/alignof(function) is allowed as an extension.
3622     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3623       << TraitKind << ArgRange;
3624     return false;
3625   }
3626
3627   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3628   // this is an error (OpenCL v1.1 s6.3.k)
3629   if (T->isVoidType()) {
3630     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3631                                         : diag::ext_sizeof_alignof_void_type;
3632     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3633     return false;
3634   }
3635
3636   return true;
3637 }
3638
3639 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3640                                              SourceLocation Loc,
3641                                              SourceRange ArgRange,
3642                                              UnaryExprOrTypeTrait TraitKind) {
3643   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3644   // runtime doesn't allow it.
3645   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3646     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3647       << T << (TraitKind == UETT_SizeOf)
3648       << ArgRange;
3649     return true;
3650   }
3651
3652   return false;
3653 }
3654
3655 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3656 /// pointer type is equal to T) and emit a warning if it is.
3657 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3658                                      Expr *E) {
3659   // Don't warn if the operation changed the type.
3660   if (T != E->getType())
3661     return;
3662
3663   // Now look for array decays.
3664   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3665   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3666     return;
3667
3668   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3669                                              << ICE->getType()
3670                                              << ICE->getSubExpr()->getType();
3671 }
3672
3673 /// \brief Check the constraints on expression operands to unary type expression
3674 /// and type traits.
3675 ///
3676 /// Completes any types necessary and validates the constraints on the operand
3677 /// expression. The logic mostly mirrors the type-based overload, but may modify
3678 /// the expression as it completes the type for that expression through template
3679 /// instantiation, etc.
3680 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3681                                             UnaryExprOrTypeTrait ExprKind) {
3682   QualType ExprTy = E->getType();
3683   assert(!ExprTy->isReferenceType());
3684
3685   if (ExprKind == UETT_VecStep)
3686     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3687                                         E->getSourceRange());
3688
3689   // Whitelist some types as extensions
3690   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3691                                       E->getSourceRange(), ExprKind))
3692     return false;
3693
3694   // 'alignof' applied to an expression only requires the base element type of
3695   // the expression to be complete. 'sizeof' requires the expression's type to
3696   // be complete (and will attempt to complete it if it's an array of unknown
3697   // bound).
3698   if (ExprKind == UETT_AlignOf) {
3699     if (RequireCompleteType(E->getExprLoc(),
3700                             Context.getBaseElementType(E->getType()),
3701                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3702                             E->getSourceRange()))
3703       return true;
3704   } else {
3705     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3706                                 ExprKind, E->getSourceRange()))
3707       return true;
3708   }
3709
3710   // Completing the expression's type may have changed it.
3711   ExprTy = E->getType();
3712   assert(!ExprTy->isReferenceType());
3713
3714   if (ExprTy->isFunctionType()) {
3715     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3716       << ExprKind << E->getSourceRange();
3717     return true;
3718   }
3719
3720   // The operand for sizeof and alignof is in an unevaluated expression context,
3721   // so side effects could result in unintended consequences.
3722   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3723       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3724     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3725
3726   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3727                                        E->getSourceRange(), ExprKind))
3728     return true;
3729
3730   if (ExprKind == UETT_SizeOf) {
3731     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3732       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3733         QualType OType = PVD->getOriginalType();
3734         QualType Type = PVD->getType();
3735         if (Type->isPointerType() && OType->isArrayType()) {
3736           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3737             << Type << OType;
3738           Diag(PVD->getLocation(), diag::note_declared_at);
3739         }
3740       }
3741     }
3742
3743     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3744     // decays into a pointer and returns an unintended result. This is most
3745     // likely a typo for "sizeof(array) op x".
3746     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3747       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3748                                BO->getLHS());
3749       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3750                                BO->getRHS());
3751     }
3752   }
3753
3754   return false;
3755 }
3756
3757 /// \brief Check the constraints on operands to unary expression and type
3758 /// traits.
3759 ///
3760 /// This will complete any types necessary, and validate the various constraints
3761 /// on those operands.
3762 ///
3763 /// The UsualUnaryConversions() function is *not* called by this routine.
3764 /// C99 6.3.2.1p[2-4] all state:
3765 ///   Except when it is the operand of the sizeof operator ...
3766 ///
3767 /// C++ [expr.sizeof]p4
3768 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3769 ///   standard conversions are not applied to the operand of sizeof.
3770 ///
3771 /// This policy is followed for all of the unary trait expressions.
3772 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3773                                             SourceLocation OpLoc,
3774                                             SourceRange ExprRange,
3775                                             UnaryExprOrTypeTrait ExprKind) {
3776   if (ExprType->isDependentType())
3777     return false;
3778
3779   // C++ [expr.sizeof]p2:
3780   //     When applied to a reference or a reference type, the result
3781   //     is the size of the referenced type.
3782   // C++11 [expr.alignof]p3:
3783   //     When alignof is applied to a reference type, the result
3784   //     shall be the alignment of the referenced type.
3785   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3786     ExprType = Ref->getPointeeType();
3787
3788   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3789   //   When alignof or _Alignof is applied to an array type, the result
3790   //   is the alignment of the element type.
3791   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3792     ExprType = Context.getBaseElementType(ExprType);
3793
3794   if (ExprKind == UETT_VecStep)
3795     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3796
3797   // Whitelist some types as extensions
3798   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3799                                       ExprKind))
3800     return false;
3801
3802   if (RequireCompleteType(OpLoc, ExprType,
3803                           diag::err_sizeof_alignof_incomplete_type,
3804                           ExprKind, ExprRange))
3805     return true;
3806
3807   if (ExprType->isFunctionType()) {
3808     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3809       << ExprKind << ExprRange;
3810     return true;
3811   }
3812
3813   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3814                                        ExprKind))
3815     return true;
3816
3817   return false;
3818 }
3819
3820 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3821   E = E->IgnoreParens();
3822
3823   // Cannot know anything else if the expression is dependent.
3824   if (E->isTypeDependent())
3825     return false;
3826
3827   if (E->getObjectKind() == OK_BitField) {
3828     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3829        << 1 << E->getSourceRange();
3830     return true;
3831   }
3832
3833   ValueDecl *D = nullptr;
3834   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3835     D = DRE->getDecl();
3836   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3837     D = ME->getMemberDecl();
3838   }
3839
3840   // If it's a field, require the containing struct to have a
3841   // complete definition so that we can compute the layout.
3842   //
3843   // This can happen in C++11 onwards, either by naming the member
3844   // in a way that is not transformed into a member access expression
3845   // (in an unevaluated operand, for instance), or by naming the member
3846   // in a trailing-return-type.
3847   //
3848   // For the record, since __alignof__ on expressions is a GCC
3849   // extension, GCC seems to permit this but always gives the
3850   // nonsensical answer 0.
3851   //
3852   // We don't really need the layout here --- we could instead just
3853   // directly check for all the appropriate alignment-lowing
3854   // attributes --- but that would require duplicating a lot of
3855   // logic that just isn't worth duplicating for such a marginal
3856   // use-case.
3857   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3858     // Fast path this check, since we at least know the record has a
3859     // definition if we can find a member of it.
3860     if (!FD->getParent()->isCompleteDefinition()) {
3861       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3862         << E->getSourceRange();
3863       return true;
3864     }
3865
3866     // Otherwise, if it's a field, and the field doesn't have
3867     // reference type, then it must have a complete type (or be a
3868     // flexible array member, which we explicitly want to
3869     // white-list anyway), which makes the following checks trivial.
3870     if (!FD->getType()->isReferenceType())
3871       return false;
3872   }
3873
3874   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3875 }
3876
3877 bool Sema::CheckVecStepExpr(Expr *E) {
3878   E = E->IgnoreParens();
3879
3880   // Cannot know anything else if the expression is dependent.
3881   if (E->isTypeDependent())
3882     return false;
3883
3884   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3885 }
3886
3887 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3888                                         CapturingScopeInfo *CSI) {
3889   assert(T->isVariablyModifiedType());
3890   assert(CSI != nullptr);
3891
3892   // We're going to walk down into the type and look for VLA expressions.
3893   do {
3894     const Type *Ty = T.getTypePtr();
3895     switch (Ty->getTypeClass()) {
3896 #define TYPE(Class, Base)
3897 #define ABSTRACT_TYPE(Class, Base)
3898 #define NON_CANONICAL_TYPE(Class, Base)
3899 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3900 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3901 #include "clang/AST/TypeNodes.def"
3902       T = QualType();
3903       break;
3904     // These types are never variably-modified.
3905     case Type::Builtin:
3906     case Type::Complex:
3907     case Type::Vector:
3908     case Type::ExtVector:
3909     case Type::Record:
3910     case Type::Enum:
3911     case Type::Elaborated:
3912     case Type::TemplateSpecialization:
3913     case Type::ObjCObject:
3914     case Type::ObjCInterface:
3915     case Type::ObjCObjectPointer:
3916     case Type::ObjCTypeParam:
3917     case Type::Pipe:
3918       llvm_unreachable("type class is never variably-modified!");
3919     case Type::Adjusted:
3920       T = cast<AdjustedType>(Ty)->getOriginalType();
3921       break;
3922     case Type::Decayed:
3923       T = cast<DecayedType>(Ty)->getPointeeType();
3924       break;
3925     case Type::Pointer:
3926       T = cast<PointerType>(Ty)->getPointeeType();
3927       break;
3928     case Type::BlockPointer:
3929       T = cast<BlockPointerType>(Ty)->getPointeeType();
3930       break;
3931     case Type::LValueReference:
3932     case Type::RValueReference:
3933       T = cast<ReferenceType>(Ty)->getPointeeType();
3934       break;
3935     case Type::MemberPointer:
3936       T = cast<MemberPointerType>(Ty)->getPointeeType();
3937       break;
3938     case Type::ConstantArray:
3939     case Type::IncompleteArray:
3940       // Losing element qualification here is fine.
3941       T = cast<ArrayType>(Ty)->getElementType();
3942       break;
3943     case Type::VariableArray: {
3944       // Losing element qualification here is fine.
3945       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3946
3947       // Unknown size indication requires no size computation.
3948       // Otherwise, evaluate and record it.
3949       if (auto Size = VAT->getSizeExpr()) {
3950         if (!CSI->isVLATypeCaptured(VAT)) {
3951           RecordDecl *CapRecord = nullptr;
3952           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3953             CapRecord = LSI->Lambda;
3954           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3955             CapRecord = CRSI->TheRecordDecl;
3956           }
3957           if (CapRecord) {
3958             auto ExprLoc = Size->getExprLoc();
3959             auto SizeType = Context.getSizeType();
3960             // Build the non-static data member.
3961             auto Field =
3962                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3963                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3964                                   /*BW*/ nullptr, /*Mutable*/ false,
3965                                   /*InitStyle*/ ICIS_NoInit);
3966             Field->setImplicit(true);
3967             Field->setAccess(AS_private);
3968             Field->setCapturedVLAType(VAT);
3969             CapRecord->addDecl(Field);
3970
3971             CSI->addVLATypeCapture(ExprLoc, SizeType);
3972           }
3973         }
3974       }
3975       T = VAT->getElementType();
3976       break;
3977     }
3978     case Type::FunctionProto:
3979     case Type::FunctionNoProto:
3980       T = cast<FunctionType>(Ty)->getReturnType();
3981       break;
3982     case Type::Paren:
3983     case Type::TypeOf:
3984     case Type::UnaryTransform:
3985     case Type::Attributed:
3986     case Type::SubstTemplateTypeParm:
3987     case Type::PackExpansion:
3988       // Keep walking after single level desugaring.
3989       T = T.getSingleStepDesugaredType(Context);
3990       break;
3991     case Type::Typedef:
3992       T = cast<TypedefType>(Ty)->desugar();
3993       break;
3994     case Type::Decltype:
3995       T = cast<DecltypeType>(Ty)->desugar();
3996       break;
3997     case Type::Auto:
3998     case Type::DeducedTemplateSpecialization:
3999       T = cast<DeducedType>(Ty)->getDeducedType();
4000       break;
4001     case Type::TypeOfExpr:
4002       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4003       break;
4004     case Type::Atomic:
4005       T = cast<AtomicType>(Ty)->getValueType();
4006       break;
4007     }
4008   } while (!T.isNull() && T->isVariablyModifiedType());
4009 }
4010
4011 /// \brief Build a sizeof or alignof expression given a type operand.
4012 ExprResult
4013 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4014                                      SourceLocation OpLoc,
4015                                      UnaryExprOrTypeTrait ExprKind,
4016                                      SourceRange R) {
4017   if (!TInfo)
4018     return ExprError();
4019
4020   QualType T = TInfo->getType();
4021
4022   if (!T->isDependentType() &&
4023       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4024     return ExprError();
4025
4026   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4027     if (auto *TT = T->getAs<TypedefType>()) {
4028       for (auto I = FunctionScopes.rbegin(),
4029                 E = std::prev(FunctionScopes.rend());
4030            I != E; ++I) {
4031         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4032         if (CSI == nullptr)
4033           break;
4034         DeclContext *DC = nullptr;
4035         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4036           DC = LSI->CallOperator;
4037         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4038           DC = CRSI->TheCapturedDecl;
4039         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4040           DC = BSI->TheDecl;
4041         if (DC) {
4042           if (DC->containsDecl(TT->getDecl()))
4043             break;
4044           captureVariablyModifiedType(Context, T, CSI);
4045         }
4046       }
4047     }
4048   }
4049
4050   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4051   return new (Context) UnaryExprOrTypeTraitExpr(
4052       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4053 }
4054
4055 /// \brief Build a sizeof or alignof expression given an expression
4056 /// operand.
4057 ExprResult
4058 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4059                                      UnaryExprOrTypeTrait ExprKind) {
4060   ExprResult PE = CheckPlaceholderExpr(E);
4061   if (PE.isInvalid()) 
4062     return ExprError();
4063
4064   E = PE.get();
4065   
4066   // Verify that the operand is valid.
4067   bool isInvalid = false;
4068   if (E->isTypeDependent()) {
4069     // Delay type-checking for type-dependent expressions.
4070   } else if (ExprKind == UETT_AlignOf) {
4071     isInvalid = CheckAlignOfExpr(*this, E);
4072   } else if (ExprKind == UETT_VecStep) {
4073     isInvalid = CheckVecStepExpr(E);
4074   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4075       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4076       isInvalid = true;
4077   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4078     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4079     isInvalid = true;
4080   } else {
4081     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4082   }
4083
4084   if (isInvalid)
4085     return ExprError();
4086
4087   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4088     PE = TransformToPotentiallyEvaluated(E);
4089     if (PE.isInvalid()) return ExprError();
4090     E = PE.get();
4091   }
4092
4093   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4094   return new (Context) UnaryExprOrTypeTraitExpr(
4095       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4096 }
4097
4098 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4099 /// expr and the same for @c alignof and @c __alignof
4100 /// Note that the ArgRange is invalid if isType is false.
4101 ExprResult
4102 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4103                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4104                                     void *TyOrEx, SourceRange ArgRange) {
4105   // If error parsing type, ignore.
4106   if (!TyOrEx) return ExprError();
4107
4108   if (IsType) {
4109     TypeSourceInfo *TInfo;
4110     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4111     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4112   }
4113
4114   Expr *ArgEx = (Expr *)TyOrEx;
4115   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4116   return Result;
4117 }
4118
4119 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4120                                      bool IsReal) {
4121   if (V.get()->isTypeDependent())
4122     return S.Context.DependentTy;
4123
4124   // _Real and _Imag are only l-values for normal l-values.
4125   if (V.get()->getObjectKind() != OK_Ordinary) {
4126     V = S.DefaultLvalueConversion(V.get());
4127     if (V.isInvalid())
4128       return QualType();
4129   }
4130
4131   // These operators return the element type of a complex type.
4132   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4133     return CT->getElementType();
4134
4135   // Otherwise they pass through real integer and floating point types here.
4136   if (V.get()->getType()->isArithmeticType())
4137     return V.get()->getType();
4138
4139   // Test for placeholders.
4140   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4141   if (PR.isInvalid()) return QualType();
4142   if (PR.get() != V.get()) {
4143     V = PR;
4144     return CheckRealImagOperand(S, V, Loc, IsReal);
4145   }
4146
4147   // Reject anything else.
4148   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4149     << (IsReal ? "__real" : "__imag");
4150   return QualType();
4151 }
4152
4153
4154
4155 ExprResult
4156 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4157                           tok::TokenKind Kind, Expr *Input) {
4158   UnaryOperatorKind Opc;
4159   switch (Kind) {
4160   default: llvm_unreachable("Unknown unary op!");
4161   case tok::plusplus:   Opc = UO_PostInc; break;
4162   case tok::minusminus: Opc = UO_PostDec; break;
4163   }
4164
4165   // Since this might is a postfix expression, get rid of ParenListExprs.
4166   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4167   if (Result.isInvalid()) return ExprError();
4168   Input = Result.get();
4169
4170   return BuildUnaryOp(S, OpLoc, Opc, Input);
4171 }
4172
4173 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4174 ///
4175 /// \return true on error
4176 static bool checkArithmeticOnObjCPointer(Sema &S,
4177                                          SourceLocation opLoc,
4178                                          Expr *op) {
4179   assert(op->getType()->isObjCObjectPointerType());
4180   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4181       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4182     return false;
4183
4184   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4185     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4186     << op->getSourceRange();
4187   return true;
4188 }
4189
4190 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4191   auto *BaseNoParens = Base->IgnoreParens();
4192   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4193     return MSProp->getPropertyDecl()->getType()->isArrayType();
4194   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4195 }
4196
4197 ExprResult
4198 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4199                               Expr *idx, SourceLocation rbLoc) {
4200   if (base && !base->getType().isNull() &&
4201       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4202     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4203                                     /*Length=*/nullptr, rbLoc);
4204
4205   // Since this might be a postfix expression, get rid of ParenListExprs.
4206   if (isa<ParenListExpr>(base)) {
4207     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4208     if (result.isInvalid()) return ExprError();
4209     base = result.get();
4210   }
4211
4212   // Handle any non-overload placeholder types in the base and index
4213   // expressions.  We can't handle overloads here because the other
4214   // operand might be an overloadable type, in which case the overload
4215   // resolution for the operator overload should get the first crack
4216   // at the overload.
4217   bool IsMSPropertySubscript = false;
4218   if (base->getType()->isNonOverloadPlaceholderType()) {
4219     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4220     if (!IsMSPropertySubscript) {
4221       ExprResult result = CheckPlaceholderExpr(base);
4222       if (result.isInvalid())
4223         return ExprError();
4224       base = result.get();
4225     }
4226   }
4227   if (idx->getType()->isNonOverloadPlaceholderType()) {
4228     ExprResult result = CheckPlaceholderExpr(idx);
4229     if (result.isInvalid()) return ExprError();
4230     idx = result.get();
4231   }
4232
4233   // Build an unanalyzed expression if either operand is type-dependent.
4234   if (getLangOpts().CPlusPlus &&
4235       (base->isTypeDependent() || idx->isTypeDependent())) {
4236     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4237                                             VK_LValue, OK_Ordinary, rbLoc);
4238   }
4239
4240   // MSDN, property (C++)
4241   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4242   // This attribute can also be used in the declaration of an empty array in a
4243   // class or structure definition. For example:
4244   // __declspec(property(get=GetX, put=PutX)) int x[];
4245   // The above statement indicates that x[] can be used with one or more array
4246   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4247   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4248   if (IsMSPropertySubscript) {
4249     // Build MS property subscript expression if base is MS property reference
4250     // or MS property subscript.
4251     return new (Context) MSPropertySubscriptExpr(
4252         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4253   }
4254
4255   // Use C++ overloaded-operator rules if either operand has record
4256   // type.  The spec says to do this if either type is *overloadable*,
4257   // but enum types can't declare subscript operators or conversion
4258   // operators, so there's nothing interesting for overload resolution
4259   // to do if there aren't any record types involved.
4260   //
4261   // ObjC pointers have their own subscripting logic that is not tied
4262   // to overload resolution and so should not take this path.
4263   if (getLangOpts().CPlusPlus &&
4264       (base->getType()->isRecordType() ||
4265        (!base->getType()->isObjCObjectPointerType() &&
4266         idx->getType()->isRecordType()))) {
4267     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4268   }
4269
4270   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4271 }
4272
4273 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4274                                           Expr *LowerBound,
4275                                           SourceLocation ColonLoc, Expr *Length,
4276                                           SourceLocation RBLoc) {
4277   if (Base->getType()->isPlaceholderType() &&
4278       !Base->getType()->isSpecificPlaceholderType(
4279           BuiltinType::OMPArraySection)) {
4280     ExprResult Result = CheckPlaceholderExpr(Base);
4281     if (Result.isInvalid())
4282       return ExprError();
4283     Base = Result.get();
4284   }
4285   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4286     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4287     if (Result.isInvalid())
4288       return ExprError();
4289     Result = DefaultLvalueConversion(Result.get());
4290     if (Result.isInvalid())
4291       return ExprError();
4292     LowerBound = Result.get();
4293   }
4294   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4295     ExprResult Result = CheckPlaceholderExpr(Length);
4296     if (Result.isInvalid())
4297       return ExprError();
4298     Result = DefaultLvalueConversion(Result.get());
4299     if (Result.isInvalid())
4300       return ExprError();
4301     Length = Result.get();
4302   }
4303
4304   // Build an unanalyzed expression if either operand is type-dependent.
4305   if (Base->isTypeDependent() ||
4306       (LowerBound &&
4307        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4308       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4309     return new (Context)
4310         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4311                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4312   }
4313
4314   // Perform default conversions.
4315   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4316   QualType ResultTy;
4317   if (OriginalTy->isAnyPointerType()) {
4318     ResultTy = OriginalTy->getPointeeType();
4319   } else if (OriginalTy->isArrayType()) {
4320     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4321   } else {
4322     return ExprError(
4323         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4324         << Base->getSourceRange());
4325   }
4326   // C99 6.5.2.1p1
4327   if (LowerBound) {
4328     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4329                                                       LowerBound);
4330     if (Res.isInvalid())
4331       return ExprError(Diag(LowerBound->getExprLoc(),
4332                             diag::err_omp_typecheck_section_not_integer)
4333                        << 0 << LowerBound->getSourceRange());
4334     LowerBound = Res.get();
4335
4336     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4337         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4338       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4339           << 0 << LowerBound->getSourceRange();
4340   }
4341   if (Length) {
4342     auto Res =
4343         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4344     if (Res.isInvalid())
4345       return ExprError(Diag(Length->getExprLoc(),
4346                             diag::err_omp_typecheck_section_not_integer)
4347                        << 1 << Length->getSourceRange());
4348     Length = Res.get();
4349
4350     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4351         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4352       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4353           << 1 << Length->getSourceRange();
4354   }
4355
4356   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4357   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4358   // type. Note that functions are not objects, and that (in C99 parlance)
4359   // incomplete types are not object types.
4360   if (ResultTy->isFunctionType()) {
4361     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4362         << ResultTy << Base->getSourceRange();
4363     return ExprError();
4364   }
4365
4366   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4367                           diag::err_omp_section_incomplete_type, Base))
4368     return ExprError();
4369
4370   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4371     llvm::APSInt LowerBoundValue;
4372     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4373       // OpenMP 4.5, [2.4 Array Sections]
4374       // The array section must be a subset of the original array.
4375       if (LowerBoundValue.isNegative()) {
4376         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4377             << LowerBound->getSourceRange();
4378         return ExprError();
4379       }
4380     }
4381   }
4382
4383   if (Length) {
4384     llvm::APSInt LengthValue;
4385     if (Length->EvaluateAsInt(LengthValue, Context)) {
4386       // OpenMP 4.5, [2.4 Array Sections]
4387       // The length must evaluate to non-negative integers.
4388       if (LengthValue.isNegative()) {
4389         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4390             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4391             << Length->getSourceRange();
4392         return ExprError();
4393       }
4394     }
4395   } else if (ColonLoc.isValid() &&
4396              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4397                                       !OriginalTy->isVariableArrayType()))) {
4398     // OpenMP 4.5, [2.4 Array Sections]
4399     // When the size of the array dimension is not known, the length must be
4400     // specified explicitly.
4401     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4402         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4403     return ExprError();
4404   }
4405
4406   if (!Base->getType()->isSpecificPlaceholderType(
4407           BuiltinType::OMPArraySection)) {
4408     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4409     if (Result.isInvalid())
4410       return ExprError();
4411     Base = Result.get();
4412   }
4413   return new (Context)
4414       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4415                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4416 }
4417
4418 ExprResult
4419 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4420                                       Expr *Idx, SourceLocation RLoc) {
4421   Expr *LHSExp = Base;
4422   Expr *RHSExp = Idx;
4423
4424   ExprValueKind VK = VK_LValue;
4425   ExprObjectKind OK = OK_Ordinary;
4426
4427   // Per C++ core issue 1213, the result is an xvalue if either operand is
4428   // a non-lvalue array, and an lvalue otherwise.
4429   if (getLangOpts().CPlusPlus11 &&
4430       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4431        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4432     VK = VK_XValue;
4433
4434   // Perform default conversions.
4435   if (!LHSExp->getType()->getAs<VectorType>()) {
4436     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4437     if (Result.isInvalid())
4438       return ExprError();
4439     LHSExp = Result.get();
4440   }
4441   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4442   if (Result.isInvalid())
4443     return ExprError();
4444   RHSExp = Result.get();
4445
4446   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4447
4448   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4449   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4450   // in the subscript position. As a result, we need to derive the array base
4451   // and index from the expression types.
4452   Expr *BaseExpr, *IndexExpr;
4453   QualType ResultType;
4454   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4455     BaseExpr = LHSExp;
4456     IndexExpr = RHSExp;
4457     ResultType = Context.DependentTy;
4458   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4459     BaseExpr = LHSExp;
4460     IndexExpr = RHSExp;
4461     ResultType = PTy->getPointeeType();
4462   } else if (const ObjCObjectPointerType *PTy =
4463                LHSTy->getAs<ObjCObjectPointerType>()) {
4464     BaseExpr = LHSExp;
4465     IndexExpr = RHSExp;
4466
4467     // Use custom logic if this should be the pseudo-object subscript
4468     // expression.
4469     if (!LangOpts.isSubscriptPointerArithmetic())
4470       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4471                                           nullptr);
4472
4473     ResultType = PTy->getPointeeType();
4474   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4475      // Handle the uncommon case of "123[Ptr]".
4476     BaseExpr = RHSExp;
4477     IndexExpr = LHSExp;
4478     ResultType = PTy->getPointeeType();
4479   } else if (const ObjCObjectPointerType *PTy =
4480                RHSTy->getAs<ObjCObjectPointerType>()) {
4481      // Handle the uncommon case of "123[Ptr]".
4482     BaseExpr = RHSExp;
4483     IndexExpr = LHSExp;
4484     ResultType = PTy->getPointeeType();
4485     if (!LangOpts.isSubscriptPointerArithmetic()) {
4486       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4487         << ResultType << BaseExpr->getSourceRange();
4488       return ExprError();
4489     }
4490   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4491     BaseExpr = LHSExp;    // vectors: V[123]
4492     IndexExpr = RHSExp;
4493     VK = LHSExp->getValueKind();
4494     if (VK != VK_RValue)
4495       OK = OK_VectorComponent;
4496
4497     // FIXME: need to deal with const...
4498     ResultType = VTy->getElementType();
4499   } else if (LHSTy->isArrayType()) {
4500     // If we see an array that wasn't promoted by
4501     // DefaultFunctionArrayLvalueConversion, it must be an array that
4502     // wasn't promoted because of the C90 rule that doesn't
4503     // allow promoting non-lvalue arrays.  Warn, then
4504     // force the promotion here.
4505     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4506         LHSExp->getSourceRange();
4507     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4508                                CK_ArrayToPointerDecay).get();
4509     LHSTy = LHSExp->getType();
4510
4511     BaseExpr = LHSExp;
4512     IndexExpr = RHSExp;
4513     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4514   } else if (RHSTy->isArrayType()) {
4515     // Same as previous, except for 123[f().a] case
4516     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4517         RHSExp->getSourceRange();
4518     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4519                                CK_ArrayToPointerDecay).get();
4520     RHSTy = RHSExp->getType();
4521
4522     BaseExpr = RHSExp;
4523     IndexExpr = LHSExp;
4524     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4525   } else {
4526     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4527        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4528   }
4529   // C99 6.5.2.1p1
4530   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4531     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4532                      << IndexExpr->getSourceRange());
4533
4534   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4535        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4536          && !IndexExpr->isTypeDependent())
4537     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4538
4539   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4540   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4541   // type. Note that Functions are not objects, and that (in C99 parlance)
4542   // incomplete types are not object types.
4543   if (ResultType->isFunctionType()) {
4544     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4545       << ResultType << BaseExpr->getSourceRange();
4546     return ExprError();
4547   }
4548
4549   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4550     // GNU extension: subscripting on pointer to void
4551     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4552       << BaseExpr->getSourceRange();
4553
4554     // C forbids expressions of unqualified void type from being l-values.
4555     // See IsCForbiddenLValueType.
4556     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4557   } else if (!ResultType->isDependentType() &&
4558       RequireCompleteType(LLoc, ResultType,
4559                           diag::err_subscript_incomplete_type, BaseExpr))
4560     return ExprError();
4561
4562   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4563          !ResultType.isCForbiddenLValueType());
4564
4565   return new (Context)
4566       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4567 }
4568
4569 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4570                                   ParmVarDecl *Param) {
4571   if (Param->hasUnparsedDefaultArg()) {
4572     Diag(CallLoc,
4573          diag::err_use_of_default_argument_to_function_declared_later) <<
4574       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4575     Diag(UnparsedDefaultArgLocs[Param],
4576          diag::note_default_argument_declared_here);
4577     return true;
4578   }
4579   
4580   if (Param->hasUninstantiatedDefaultArg()) {
4581     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4582
4583     EnterExpressionEvaluationContext EvalContext(
4584         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4585
4586     // Instantiate the expression.
4587     MultiLevelTemplateArgumentList MutiLevelArgList
4588       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4589
4590     InstantiatingTemplate Inst(*this, CallLoc, Param,
4591                                MutiLevelArgList.getInnermost());
4592     if (Inst.isInvalid())
4593       return true;
4594     if (Inst.isAlreadyInstantiating()) {
4595       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4596       Param->setInvalidDecl();
4597       return true;
4598     }
4599
4600     ExprResult Result;
4601     {
4602       // C++ [dcl.fct.default]p5:
4603       //   The names in the [default argument] expression are bound, and
4604       //   the semantic constraints are checked, at the point where the
4605       //   default argument expression appears.
4606       ContextRAII SavedContext(*this, FD);
4607       LocalInstantiationScope Local(*this);
4608       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4609                                 /*DirectInit*/false);
4610     }
4611     if (Result.isInvalid())
4612       return true;
4613
4614     // Check the expression as an initializer for the parameter.
4615     InitializedEntity Entity
4616       = InitializedEntity::InitializeParameter(Context, Param);
4617     InitializationKind Kind
4618       = InitializationKind::CreateCopy(Param->getLocation(),
4619              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4620     Expr *ResultE = Result.getAs<Expr>();
4621
4622     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4623     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4624     if (Result.isInvalid())
4625       return true;
4626
4627     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4628                                  Param->getOuterLocStart());
4629     if (Result.isInvalid())
4630       return true;
4631
4632     // Remember the instantiated default argument.
4633     Param->setDefaultArg(Result.getAs<Expr>());
4634     if (ASTMutationListener *L = getASTMutationListener()) {
4635       L->DefaultArgumentInstantiated(Param);
4636     }
4637   }
4638
4639   // If the default argument expression is not set yet, we are building it now.
4640   if (!Param->hasInit()) {
4641     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4642     Param->setInvalidDecl();
4643     return true;
4644   }
4645
4646   // If the default expression creates temporaries, we need to
4647   // push them to the current stack of expression temporaries so they'll
4648   // be properly destroyed.
4649   // FIXME: We should really be rebuilding the default argument with new
4650   // bound temporaries; see the comment in PR5810.
4651   // We don't need to do that with block decls, though, because
4652   // blocks in default argument expression can never capture anything.
4653   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4654     // Set the "needs cleanups" bit regardless of whether there are
4655     // any explicit objects.
4656     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4657
4658     // Append all the objects to the cleanup list.  Right now, this
4659     // should always be a no-op, because blocks in default argument
4660     // expressions should never be able to capture anything.
4661     assert(!Init->getNumObjects() &&
4662            "default argument expression has capturing blocks?");
4663   }
4664
4665   // We already type-checked the argument, so we know it works. 
4666   // Just mark all of the declarations in this potentially-evaluated expression
4667   // as being "referenced".
4668   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4669                                    /*SkipLocalVariables=*/true);
4670   return false;
4671 }
4672
4673 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4674                                         FunctionDecl *FD, ParmVarDecl *Param) {
4675   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4676     return ExprError();
4677   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4678 }
4679
4680 Sema::VariadicCallType
4681 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4682                           Expr *Fn) {
4683   if (Proto && Proto->isVariadic()) {
4684     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4685       return VariadicConstructor;
4686     else if (Fn && Fn->getType()->isBlockPointerType())
4687       return VariadicBlock;
4688     else if (FDecl) {
4689       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4690         if (Method->isInstance())
4691           return VariadicMethod;
4692     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4693       return VariadicMethod;
4694     return VariadicFunction;
4695   }
4696   return VariadicDoesNotApply;
4697 }
4698
4699 namespace {
4700 class FunctionCallCCC : public FunctionCallFilterCCC {
4701 public:
4702   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4703                   unsigned NumArgs, MemberExpr *ME)
4704       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4705         FunctionName(FuncName) {}
4706
4707   bool ValidateCandidate(const TypoCorrection &candidate) override {
4708     if (!candidate.getCorrectionSpecifier() ||
4709         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4710       return false;
4711     }
4712
4713     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4714   }
4715
4716 private:
4717   const IdentifierInfo *const FunctionName;
4718 };
4719 }
4720
4721 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4722                                                FunctionDecl *FDecl,
4723                                                ArrayRef<Expr *> Args) {
4724   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4725   DeclarationName FuncName = FDecl->getDeclName();
4726   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4727
4728   if (TypoCorrection Corrected = S.CorrectTypo(
4729           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4730           S.getScopeForContext(S.CurContext), nullptr,
4731           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4732                                              Args.size(), ME),
4733           Sema::CTK_ErrorRecovery)) {
4734     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4735       if (Corrected.isOverloaded()) {
4736         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4737         OverloadCandidateSet::iterator Best;
4738         for (NamedDecl *CD : Corrected) {
4739           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4740             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4741                                    OCS);
4742         }
4743         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4744         case OR_Success:
4745           ND = Best->FoundDecl;
4746           Corrected.setCorrectionDecl(ND);
4747           break;
4748         default:
4749           break;
4750         }
4751       }
4752       ND = ND->getUnderlyingDecl();
4753       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4754         return Corrected;
4755     }
4756   }
4757   return TypoCorrection();
4758 }
4759
4760 /// ConvertArgumentsForCall - Converts the arguments specified in
4761 /// Args/NumArgs to the parameter types of the function FDecl with
4762 /// function prototype Proto. Call is the call expression itself, and
4763 /// Fn is the function expression. For a C++ member function, this
4764 /// routine does not attempt to convert the object argument. Returns
4765 /// true if the call is ill-formed.
4766 bool
4767 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4768                               FunctionDecl *FDecl,
4769                               const FunctionProtoType *Proto,
4770                               ArrayRef<Expr *> Args,
4771                               SourceLocation RParenLoc,
4772                               bool IsExecConfig) {
4773   // Bail out early if calling a builtin with custom typechecking.
4774   if (FDecl)
4775     if (unsigned ID = FDecl->getBuiltinID())
4776       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4777         return false;
4778
4779   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4780   // assignment, to the types of the corresponding parameter, ...
4781   unsigned NumParams = Proto->getNumParams();
4782   bool Invalid = false;
4783   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4784   unsigned FnKind = Fn->getType()->isBlockPointerType()
4785                        ? 1 /* block */
4786                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4787                                        : 0 /* function */);
4788
4789   // If too few arguments are available (and we don't have default
4790   // arguments for the remaining parameters), don't make the call.
4791   if (Args.size() < NumParams) {
4792     if (Args.size() < MinArgs) {
4793       TypoCorrection TC;
4794       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4795         unsigned diag_id =
4796             MinArgs == NumParams && !Proto->isVariadic()
4797                 ? diag::err_typecheck_call_too_few_args_suggest
4798                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4799         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4800                                         << static_cast<unsigned>(Args.size())
4801                                         << TC.getCorrectionRange());
4802       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4803         Diag(RParenLoc,
4804              MinArgs == NumParams && !Proto->isVariadic()
4805                  ? diag::err_typecheck_call_too_few_args_one
4806                  : diag::err_typecheck_call_too_few_args_at_least_one)
4807             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4808       else
4809         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4810                             ? diag::err_typecheck_call_too_few_args
4811                             : diag::err_typecheck_call_too_few_args_at_least)
4812             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4813             << Fn->getSourceRange();
4814
4815       // Emit the location of the prototype.
4816       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4817         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4818           << FDecl;
4819
4820       return true;
4821     }
4822     Call->setNumArgs(Context, NumParams);
4823   }
4824
4825   // If too many are passed and not variadic, error on the extras and drop
4826   // them.
4827   if (Args.size() > NumParams) {
4828     if (!Proto->isVariadic()) {
4829       TypoCorrection TC;
4830       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4831         unsigned diag_id =
4832             MinArgs == NumParams && !Proto->isVariadic()
4833                 ? diag::err_typecheck_call_too_many_args_suggest
4834                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4835         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4836                                         << static_cast<unsigned>(Args.size())
4837                                         << TC.getCorrectionRange());
4838       } else if (NumParams == 1 && FDecl &&
4839                  FDecl->getParamDecl(0)->getDeclName())
4840         Diag(Args[NumParams]->getLocStart(),
4841              MinArgs == NumParams
4842                  ? diag::err_typecheck_call_too_many_args_one
4843                  : diag::err_typecheck_call_too_many_args_at_most_one)
4844             << FnKind << FDecl->getParamDecl(0)
4845             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4846             << SourceRange(Args[NumParams]->getLocStart(),
4847                            Args.back()->getLocEnd());
4848       else
4849         Diag(Args[NumParams]->getLocStart(),
4850              MinArgs == NumParams
4851                  ? diag::err_typecheck_call_too_many_args
4852                  : diag::err_typecheck_call_too_many_args_at_most)
4853             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4854             << Fn->getSourceRange()
4855             << SourceRange(Args[NumParams]->getLocStart(),
4856                            Args.back()->getLocEnd());
4857
4858       // Emit the location of the prototype.
4859       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4860         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4861           << FDecl;
4862       
4863       // This deletes the extra arguments.
4864       Call->setNumArgs(Context, NumParams);
4865       return true;
4866     }
4867   }
4868   SmallVector<Expr *, 8> AllArgs;
4869   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4870   
4871   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4872                                    Proto, 0, Args, AllArgs, CallType);
4873   if (Invalid)
4874     return true;
4875   unsigned TotalNumArgs = AllArgs.size();
4876   for (unsigned i = 0; i < TotalNumArgs; ++i)
4877     Call->setArg(i, AllArgs[i]);
4878
4879   return false;
4880 }
4881
4882 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4883                                   const FunctionProtoType *Proto,
4884                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4885                                   SmallVectorImpl<Expr *> &AllArgs,
4886                                   VariadicCallType CallType, bool AllowExplicit,
4887                                   bool IsListInitialization) {
4888   unsigned NumParams = Proto->getNumParams();
4889   bool Invalid = false;
4890   size_t ArgIx = 0;
4891   // Continue to check argument types (even if we have too few/many args).
4892   for (unsigned i = FirstParam; i < NumParams; i++) {
4893     QualType ProtoArgType = Proto->getParamType(i);
4894
4895     Expr *Arg;
4896     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4897     if (ArgIx < Args.size()) {
4898       Arg = Args[ArgIx++];
4899
4900       if (RequireCompleteType(Arg->getLocStart(),
4901                               ProtoArgType,
4902                               diag::err_call_incomplete_argument, Arg))
4903         return true;
4904
4905       // Strip the unbridged-cast placeholder expression off, if applicable.
4906       bool CFAudited = false;
4907       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4908           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4909           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4910         Arg = stripARCUnbridgedCast(Arg);
4911       else if (getLangOpts().ObjCAutoRefCount &&
4912                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4913                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4914         CFAudited = true;
4915
4916       InitializedEntity Entity =
4917           Param ? InitializedEntity::InitializeParameter(Context, Param,
4918                                                          ProtoArgType)
4919                 : InitializedEntity::InitializeParameter(
4920                       Context, ProtoArgType, Proto->isParamConsumed(i));
4921
4922       // Remember that parameter belongs to a CF audited API.
4923       if (CFAudited)
4924         Entity.setParameterCFAudited();
4925
4926       ExprResult ArgE = PerformCopyInitialization(
4927           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4928       if (ArgE.isInvalid())
4929         return true;
4930
4931       Arg = ArgE.getAs<Expr>();
4932     } else {
4933       assert(Param && "can't use default arguments without a known callee");
4934
4935       ExprResult ArgExpr =
4936         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4937       if (ArgExpr.isInvalid())
4938         return true;
4939
4940       Arg = ArgExpr.getAs<Expr>();
4941     }
4942
4943     // Check for array bounds violations for each argument to the call. This
4944     // check only triggers warnings when the argument isn't a more complex Expr
4945     // with its own checking, such as a BinaryOperator.
4946     CheckArrayAccess(Arg);
4947
4948     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4949     CheckStaticArrayArgument(CallLoc, Param, Arg);
4950
4951     AllArgs.push_back(Arg);
4952   }
4953
4954   // If this is a variadic call, handle args passed through "...".
4955   if (CallType != VariadicDoesNotApply) {
4956     // Assume that extern "C" functions with variadic arguments that
4957     // return __unknown_anytype aren't *really* variadic.
4958     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4959         FDecl->isExternC()) {
4960       for (Expr *A : Args.slice(ArgIx)) {
4961         QualType paramType; // ignored
4962         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4963         Invalid |= arg.isInvalid();
4964         AllArgs.push_back(arg.get());
4965       }
4966
4967     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4968     } else {
4969       for (Expr *A : Args.slice(ArgIx)) {
4970         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4971         Invalid |= Arg.isInvalid();
4972         AllArgs.push_back(Arg.get());
4973       }
4974     }
4975
4976     // Check for array bounds violations.
4977     for (Expr *A : Args.slice(ArgIx))
4978       CheckArrayAccess(A);
4979   }
4980   return Invalid;
4981 }
4982
4983 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4984   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4985   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4986     TL = DTL.getOriginalLoc();
4987   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4988     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4989       << ATL.getLocalSourceRange();
4990 }
4991
4992 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4993 /// array parameter, check that it is non-null, and that if it is formed by
4994 /// array-to-pointer decay, the underlying array is sufficiently large.
4995 ///
4996 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4997 /// array type derivation, then for each call to the function, the value of the
4998 /// corresponding actual argument shall provide access to the first element of
4999 /// an array with at least as many elements as specified by the size expression.
5000 void
5001 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5002                                ParmVarDecl *Param,
5003                                const Expr *ArgExpr) {
5004   // Static array parameters are not supported in C++.
5005   if (!Param || getLangOpts().CPlusPlus)
5006     return;
5007
5008   QualType OrigTy = Param->getOriginalType();
5009
5010   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5011   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5012     return;
5013
5014   if (ArgExpr->isNullPointerConstant(Context,
5015                                      Expr::NPC_NeverValueDependent)) {
5016     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5017     DiagnoseCalleeStaticArrayParam(*this, Param);
5018     return;
5019   }
5020
5021   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5022   if (!CAT)
5023     return;
5024
5025   const ConstantArrayType *ArgCAT =
5026     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5027   if (!ArgCAT)
5028     return;
5029
5030   if (ArgCAT->getSize().ult(CAT->getSize())) {
5031     Diag(CallLoc, diag::warn_static_array_too_small)
5032       << ArgExpr->getSourceRange()
5033       << (unsigned) ArgCAT->getSize().getZExtValue()
5034       << (unsigned) CAT->getSize().getZExtValue();
5035     DiagnoseCalleeStaticArrayParam(*this, Param);
5036   }
5037 }
5038
5039 /// Given a function expression of unknown-any type, try to rebuild it
5040 /// to have a function type.
5041 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5042
5043 /// Is the given type a placeholder that we need to lower out
5044 /// immediately during argument processing?
5045 static bool isPlaceholderToRemoveAsArg(QualType type) {
5046   // Placeholders are never sugared.
5047   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5048   if (!placeholder) return false;
5049
5050   switch (placeholder->getKind()) {
5051   // Ignore all the non-placeholder types.
5052 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5053   case BuiltinType::Id:
5054 #include "clang/Basic/OpenCLImageTypes.def"
5055 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5056 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5057 #include "clang/AST/BuiltinTypes.def"
5058     return false;
5059
5060   // We cannot lower out overload sets; they might validly be resolved
5061   // by the call machinery.
5062   case BuiltinType::Overload:
5063     return false;
5064
5065   // Unbridged casts in ARC can be handled in some call positions and
5066   // should be left in place.
5067   case BuiltinType::ARCUnbridgedCast:
5068     return false;
5069
5070   // Pseudo-objects should be converted as soon as possible.
5071   case BuiltinType::PseudoObject:
5072     return true;
5073
5074   // The debugger mode could theoretically but currently does not try
5075   // to resolve unknown-typed arguments based on known parameter types.
5076   case BuiltinType::UnknownAny:
5077     return true;
5078
5079   // These are always invalid as call arguments and should be reported.
5080   case BuiltinType::BoundMember:
5081   case BuiltinType::BuiltinFn:
5082   case BuiltinType::OMPArraySection:
5083     return true;
5084
5085   }
5086   llvm_unreachable("bad builtin type kind");
5087 }
5088
5089 /// Check an argument list for placeholders that we won't try to
5090 /// handle later.
5091 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5092   // Apply this processing to all the arguments at once instead of
5093   // dying at the first failure.
5094   bool hasInvalid = false;
5095   for (size_t i = 0, e = args.size(); i != e; i++) {
5096     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5097       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5098       if (result.isInvalid()) hasInvalid = true;
5099       else args[i] = result.get();
5100     } else if (hasInvalid) {
5101       (void)S.CorrectDelayedTyposInExpr(args[i]);
5102     }
5103   }
5104   return hasInvalid;
5105 }
5106
5107 /// If a builtin function has a pointer argument with no explicit address
5108 /// space, then it should be able to accept a pointer to any address
5109 /// space as input.  In order to do this, we need to replace the
5110 /// standard builtin declaration with one that uses the same address space
5111 /// as the call.
5112 ///
5113 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5114 ///                  it does not contain any pointer arguments without
5115 ///                  an address space qualifer.  Otherwise the rewritten
5116 ///                  FunctionDecl is returned.
5117 /// TODO: Handle pointer return types.
5118 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5119                                                 const FunctionDecl *FDecl,
5120                                                 MultiExprArg ArgExprs) {
5121
5122   QualType DeclType = FDecl->getType();
5123   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5124
5125   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5126       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5127     return nullptr;
5128
5129   bool NeedsNewDecl = false;
5130   unsigned i = 0;
5131   SmallVector<QualType, 8> OverloadParams;
5132
5133   for (QualType ParamType : FT->param_types()) {
5134
5135     // Convert array arguments to pointer to simplify type lookup.
5136     ExprResult ArgRes =
5137         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5138     if (ArgRes.isInvalid())
5139       return nullptr;
5140     Expr *Arg = ArgRes.get();
5141     QualType ArgType = Arg->getType();
5142     if (!ParamType->isPointerType() ||
5143         ParamType.getQualifiers().hasAddressSpace() ||
5144         !ArgType->isPointerType() ||
5145         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5146       OverloadParams.push_back(ParamType);
5147       continue;
5148     }
5149
5150     NeedsNewDecl = true;
5151     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5152
5153     QualType PointeeType = ParamType->getPointeeType();
5154     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5155     OverloadParams.push_back(Context.getPointerType(PointeeType));
5156   }
5157
5158   if (!NeedsNewDecl)
5159     return nullptr;
5160
5161   FunctionProtoType::ExtProtoInfo EPI;
5162   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5163                                                 OverloadParams, EPI);
5164   DeclContext *Parent = Context.getTranslationUnitDecl();
5165   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5166                                                     FDecl->getLocation(),
5167                                                     FDecl->getLocation(),
5168                                                     FDecl->getIdentifier(),
5169                                                     OverloadTy,
5170                                                     /*TInfo=*/nullptr,
5171                                                     SC_Extern, false,
5172                                                     /*hasPrototype=*/true);
5173   SmallVector<ParmVarDecl*, 16> Params;
5174   FT = cast<FunctionProtoType>(OverloadTy);
5175   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5176     QualType ParamType = FT->getParamType(i);
5177     ParmVarDecl *Parm =
5178         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5179                                 SourceLocation(), nullptr, ParamType,
5180                                 /*TInfo=*/nullptr, SC_None, nullptr);
5181     Parm->setScopeInfo(0, i);
5182     Params.push_back(Parm);
5183   }
5184   OverloadDecl->setParams(Params);
5185   return OverloadDecl;
5186 }
5187
5188 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5189                                     FunctionDecl *Callee,
5190                                     MultiExprArg ArgExprs) {
5191   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5192   // similar attributes) really don't like it when functions are called with an
5193   // invalid number of args.
5194   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5195                          /*PartialOverloading=*/false) &&
5196       !Callee->isVariadic())
5197     return;
5198   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5199     return;
5200
5201   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5202     S.Diag(Fn->getLocStart(),
5203            isa<CXXMethodDecl>(Callee)
5204                ? diag::err_ovl_no_viable_member_function_in_call
5205                : diag::err_ovl_no_viable_function_in_call)
5206         << Callee << Callee->getSourceRange();
5207     S.Diag(Callee->getLocation(),
5208            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5209         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5210     return;
5211   }
5212 }
5213
5214 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5215 /// This provides the location of the left/right parens and a list of comma
5216 /// locations.
5217 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5218                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5219                                Expr *ExecConfig, bool IsExecConfig) {
5220   // Since this might be a postfix expression, get rid of ParenListExprs.
5221   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5222   if (Result.isInvalid()) return ExprError();
5223   Fn = Result.get();
5224
5225   if (checkArgsForPlaceholders(*this, ArgExprs))
5226     return ExprError();
5227
5228   if (getLangOpts().CPlusPlus) {
5229     // If this is a pseudo-destructor expression, build the call immediately.
5230     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5231       if (!ArgExprs.empty()) {
5232         // Pseudo-destructor calls should not have any arguments.
5233         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5234             << FixItHint::CreateRemoval(
5235                    SourceRange(ArgExprs.front()->getLocStart(),
5236                                ArgExprs.back()->getLocEnd()));
5237       }
5238
5239       return new (Context)
5240           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5241     }
5242     if (Fn->getType() == Context.PseudoObjectTy) {
5243       ExprResult result = CheckPlaceholderExpr(Fn);
5244       if (result.isInvalid()) return ExprError();
5245       Fn = result.get();
5246     }
5247
5248     // Determine whether this is a dependent call inside a C++ template,
5249     // in which case we won't do any semantic analysis now.
5250     bool Dependent = false;
5251     if (Fn->isTypeDependent())
5252       Dependent = true;
5253     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5254       Dependent = true;
5255
5256     if (Dependent) {
5257       if (ExecConfig) {
5258         return new (Context) CUDAKernelCallExpr(
5259             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5260             Context.DependentTy, VK_RValue, RParenLoc);
5261       } else {
5262         return new (Context) CallExpr(
5263             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5264       }
5265     }
5266
5267     // Determine whether this is a call to an object (C++ [over.call.object]).
5268     if (Fn->getType()->isRecordType())
5269       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5270                                           RParenLoc);
5271
5272     if (Fn->getType() == Context.UnknownAnyTy) {
5273       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5274       if (result.isInvalid()) return ExprError();
5275       Fn = result.get();
5276     }
5277
5278     if (Fn->getType() == Context.BoundMemberTy) {
5279       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5280                                        RParenLoc);
5281     }
5282   }
5283
5284   // Check for overloaded calls.  This can happen even in C due to extensions.
5285   if (Fn->getType() == Context.OverloadTy) {
5286     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5287
5288     // We aren't supposed to apply this logic if there's an '&' involved.
5289     if (!find.HasFormOfMemberPointer) {
5290       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5291         return new (Context) CallExpr(
5292             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5293       OverloadExpr *ovl = find.Expression;
5294       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5295         return BuildOverloadedCallExpr(
5296             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5297             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5298       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5299                                        RParenLoc);
5300     }
5301   }
5302
5303   // If we're directly calling a function, get the appropriate declaration.
5304   if (Fn->getType() == Context.UnknownAnyTy) {
5305     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5306     if (result.isInvalid()) return ExprError();
5307     Fn = result.get();
5308   }
5309
5310   Expr *NakedFn = Fn->IgnoreParens();
5311
5312   bool CallingNDeclIndirectly = false;
5313   NamedDecl *NDecl = nullptr;
5314   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5315     if (UnOp->getOpcode() == UO_AddrOf) {
5316       CallingNDeclIndirectly = true;
5317       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5318     }
5319   }
5320
5321   if (isa<DeclRefExpr>(NakedFn)) {
5322     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5323
5324     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5325     if (FDecl && FDecl->getBuiltinID()) {
5326       // Rewrite the function decl for this builtin by replacing parameters
5327       // with no explicit address space with the address space of the arguments
5328       // in ArgExprs.
5329       if ((FDecl =
5330                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5331         NDecl = FDecl;
5332         Fn = DeclRefExpr::Create(
5333             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5334             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5335       }
5336     }
5337   } else if (isa<MemberExpr>(NakedFn))
5338     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5339
5340   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5341     if (CallingNDeclIndirectly &&
5342         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5343                                            Fn->getLocStart()))
5344       return ExprError();
5345
5346     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5347       return ExprError();
5348
5349     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5350   }
5351
5352   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5353                                ExecConfig, IsExecConfig);
5354 }
5355
5356 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5357 ///
5358 /// __builtin_astype( value, dst type )
5359 ///
5360 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5361                                  SourceLocation BuiltinLoc,
5362                                  SourceLocation RParenLoc) {
5363   ExprValueKind VK = VK_RValue;
5364   ExprObjectKind OK = OK_Ordinary;
5365   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5366   QualType SrcTy = E->getType();
5367   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5368     return ExprError(Diag(BuiltinLoc,
5369                           diag::err_invalid_astype_of_different_size)
5370                      << DstTy
5371                      << SrcTy
5372                      << E->getSourceRange());
5373   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5374 }
5375
5376 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5377 /// provided arguments.
5378 ///
5379 /// __builtin_convertvector( value, dst type )
5380 ///
5381 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5382                                         SourceLocation BuiltinLoc,
5383                                         SourceLocation RParenLoc) {
5384   TypeSourceInfo *TInfo;
5385   GetTypeFromParser(ParsedDestTy, &TInfo);
5386   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5387 }
5388
5389 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5390 /// i.e. an expression not of \p OverloadTy.  The expression should
5391 /// unary-convert to an expression of function-pointer or
5392 /// block-pointer type.
5393 ///
5394 /// \param NDecl the declaration being called, if available
5395 ExprResult
5396 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5397                             SourceLocation LParenLoc,
5398                             ArrayRef<Expr *> Args,
5399                             SourceLocation RParenLoc,
5400                             Expr *Config, bool IsExecConfig) {
5401   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5402   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5403
5404   // Functions with 'interrupt' attribute cannot be called directly.
5405   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5406     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5407     return ExprError();
5408   }
5409
5410   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5411   // so there's some risk when calling out to non-interrupt handler functions
5412   // that the callee might not preserve them. This is easy to diagnose here,
5413   // but can be very challenging to debug.
5414   if (auto *Caller = getCurFunctionDecl())
5415     if (Caller->hasAttr<ARMInterruptAttr>()) {
5416       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5417       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5418         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5419     }
5420
5421   // Promote the function operand.
5422   // We special-case function promotion here because we only allow promoting
5423   // builtin functions to function pointers in the callee of a call.
5424   ExprResult Result;
5425   if (BuiltinID &&
5426       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5427     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5428                                CK_BuiltinFnToFnPtr).get();
5429   } else {
5430     Result = CallExprUnaryConversions(Fn);
5431   }
5432   if (Result.isInvalid())
5433     return ExprError();
5434   Fn = Result.get();
5435
5436   // Make the call expr early, before semantic checks.  This guarantees cleanup
5437   // of arguments and function on error.
5438   CallExpr *TheCall;
5439   if (Config)
5440     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5441                                                cast<CallExpr>(Config), Args,
5442                                                Context.BoolTy, VK_RValue,
5443                                                RParenLoc);
5444   else
5445     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5446                                      VK_RValue, RParenLoc);
5447
5448   if (!getLangOpts().CPlusPlus) {
5449     // C cannot always handle TypoExpr nodes in builtin calls and direct
5450     // function calls as their argument checking don't necessarily handle
5451     // dependent types properly, so make sure any TypoExprs have been
5452     // dealt with.
5453     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5454     if (!Result.isUsable()) return ExprError();
5455     TheCall = dyn_cast<CallExpr>(Result.get());
5456     if (!TheCall) return Result;
5457     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5458   }
5459
5460   // Bail out early if calling a builtin with custom typechecking.
5461   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5462     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5463
5464  retry:
5465   const FunctionType *FuncT;
5466   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5467     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5468     // have type pointer to function".
5469     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5470     if (!FuncT)
5471       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5472                          << Fn->getType() << Fn->getSourceRange());
5473   } else if (const BlockPointerType *BPT =
5474                Fn->getType()->getAs<BlockPointerType>()) {
5475     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5476   } else {
5477     // Handle calls to expressions of unknown-any type.
5478     if (Fn->getType() == Context.UnknownAnyTy) {
5479       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5480       if (rewrite.isInvalid()) return ExprError();
5481       Fn = rewrite.get();
5482       TheCall->setCallee(Fn);
5483       goto retry;
5484     }
5485
5486     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5487       << Fn->getType() << Fn->getSourceRange());
5488   }
5489
5490   if (getLangOpts().CUDA) {
5491     if (Config) {
5492       // CUDA: Kernel calls must be to global functions
5493       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5494         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5495             << FDecl->getName() << Fn->getSourceRange());
5496
5497       // CUDA: Kernel function must have 'void' return type
5498       if (!FuncT->getReturnType()->isVoidType())
5499         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5500             << Fn->getType() << Fn->getSourceRange());
5501     } else {
5502       // CUDA: Calls to global functions must be configured
5503       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5504         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5505             << FDecl->getName() << Fn->getSourceRange());
5506     }
5507   }
5508
5509   // Check for a valid return type
5510   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5511                           FDecl))
5512     return ExprError();
5513
5514   // We know the result type of the call, set it.
5515   TheCall->setType(FuncT->getCallResultType(Context));
5516   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5517
5518   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5519   if (Proto) {
5520     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5521                                 IsExecConfig))
5522       return ExprError();
5523   } else {
5524     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5525
5526     if (FDecl) {
5527       // Check if we have too few/too many template arguments, based
5528       // on our knowledge of the function definition.
5529       const FunctionDecl *Def = nullptr;
5530       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5531         Proto = Def->getType()->getAs<FunctionProtoType>();
5532        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5533           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5534           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5535       }
5536       
5537       // If the function we're calling isn't a function prototype, but we have
5538       // a function prototype from a prior declaratiom, use that prototype.
5539       if (!FDecl->hasPrototype())
5540         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5541     }
5542
5543     // Promote the arguments (C99 6.5.2.2p6).
5544     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5545       Expr *Arg = Args[i];
5546
5547       if (Proto && i < Proto->getNumParams()) {
5548         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5549             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5550         ExprResult ArgE =
5551             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5552         if (ArgE.isInvalid())
5553           return true;
5554         
5555         Arg = ArgE.getAs<Expr>();
5556
5557       } else {
5558         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5559
5560         if (ArgE.isInvalid())
5561           return true;
5562
5563         Arg = ArgE.getAs<Expr>();
5564       }
5565       
5566       if (RequireCompleteType(Arg->getLocStart(),
5567                               Arg->getType(),
5568                               diag::err_call_incomplete_argument, Arg))
5569         return ExprError();
5570
5571       TheCall->setArg(i, Arg);
5572     }
5573   }
5574
5575   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5576     if (!Method->isStatic())
5577       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5578         << Fn->getSourceRange());
5579
5580   // Check for sentinels
5581   if (NDecl)
5582     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5583
5584   // Do special checking on direct calls to functions.
5585   if (FDecl) {
5586     if (CheckFunctionCall(FDecl, TheCall, Proto))
5587       return ExprError();
5588
5589     if (BuiltinID)
5590       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5591   } else if (NDecl) {
5592     if (CheckPointerCall(NDecl, TheCall, Proto))
5593       return ExprError();
5594   } else {
5595     if (CheckOtherCall(TheCall, Proto))
5596       return ExprError();
5597   }
5598
5599   return MaybeBindToTemporary(TheCall);
5600 }
5601
5602 ExprResult
5603 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5604                            SourceLocation RParenLoc, Expr *InitExpr) {
5605   assert(Ty && "ActOnCompoundLiteral(): missing type");
5606   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5607
5608   TypeSourceInfo *TInfo;
5609   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5610   if (!TInfo)
5611     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5612
5613   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5614 }
5615
5616 ExprResult
5617 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5618                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5619   QualType literalType = TInfo->getType();
5620
5621   if (literalType->isArrayType()) {
5622     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5623           diag::err_illegal_decl_array_incomplete_type,
5624           SourceRange(LParenLoc,
5625                       LiteralExpr->getSourceRange().getEnd())))
5626       return ExprError();
5627     if (literalType->isVariableArrayType())
5628       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5629         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5630   } else if (!literalType->isDependentType() &&
5631              RequireCompleteType(LParenLoc, literalType,
5632                diag::err_typecheck_decl_incomplete_type,
5633                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5634     return ExprError();
5635
5636   InitializedEntity Entity
5637     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5638   InitializationKind Kind
5639     = InitializationKind::CreateCStyleCast(LParenLoc, 
5640                                            SourceRange(LParenLoc, RParenLoc),
5641                                            /*InitList=*/true);
5642   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5643   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5644                                       &literalType);
5645   if (Result.isInvalid())
5646     return ExprError();
5647   LiteralExpr = Result.get();
5648
5649   bool isFileScope = !CurContext->isFunctionOrMethod();
5650   if (isFileScope &&
5651       !LiteralExpr->isTypeDependent() &&
5652       !LiteralExpr->isValueDependent() &&
5653       !literalType->isDependentType()) { // 6.5.2.5p3
5654     if (CheckForConstantInitializer(LiteralExpr, literalType))
5655       return ExprError();
5656   }
5657
5658   // In C, compound literals are l-values for some reason.
5659   // For GCC compatibility, in C++, file-scope array compound literals with
5660   // constant initializers are also l-values, and compound literals are
5661   // otherwise prvalues.
5662   //
5663   // (GCC also treats C++ list-initialized file-scope array prvalues with
5664   // constant initializers as l-values, but that's non-conforming, so we don't
5665   // follow it there.)
5666   //
5667   // FIXME: It would be better to handle the lvalue cases as materializing and
5668   // lifetime-extending a temporary object, but our materialized temporaries
5669   // representation only supports lifetime extension from a variable, not "out
5670   // of thin air".
5671   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5672   // is bound to the result of applying array-to-pointer decay to the compound
5673   // literal.
5674   // FIXME: GCC supports compound literals of reference type, which should
5675   // obviously have a value kind derived from the kind of reference involved.
5676   ExprValueKind VK =
5677       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5678           ? VK_RValue
5679           : VK_LValue;
5680
5681   return MaybeBindToTemporary(
5682       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5683                                         VK, LiteralExpr, isFileScope));
5684 }
5685
5686 ExprResult
5687 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5688                     SourceLocation RBraceLoc) {
5689   // Immediately handle non-overload placeholders.  Overloads can be
5690   // resolved contextually, but everything else here can't.
5691   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5692     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5693       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5694
5695       // Ignore failures; dropping the entire initializer list because
5696       // of one failure would be terrible for indexing/etc.
5697       if (result.isInvalid()) continue;
5698
5699       InitArgList[I] = result.get();
5700     }
5701   }
5702
5703   // Semantic analysis for initializers is done by ActOnDeclarator() and
5704   // CheckInitializer() - it requires knowledge of the object being intialized.
5705
5706   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5707                                                RBraceLoc);
5708   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5709   return E;
5710 }
5711
5712 /// Do an explicit extend of the given block pointer if we're in ARC.
5713 void Sema::maybeExtendBlockObject(ExprResult &E) {
5714   assert(E.get()->getType()->isBlockPointerType());
5715   assert(E.get()->isRValue());
5716
5717   // Only do this in an r-value context.
5718   if (!getLangOpts().ObjCAutoRefCount) return;
5719
5720   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5721                                CK_ARCExtendBlockObject, E.get(),
5722                                /*base path*/ nullptr, VK_RValue);
5723   Cleanup.setExprNeedsCleanups(true);
5724 }
5725
5726 /// Prepare a conversion of the given expression to an ObjC object
5727 /// pointer type.
5728 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5729   QualType type = E.get()->getType();
5730   if (type->isObjCObjectPointerType()) {
5731     return CK_BitCast;
5732   } else if (type->isBlockPointerType()) {
5733     maybeExtendBlockObject(E);
5734     return CK_BlockPointerToObjCPointerCast;
5735   } else {
5736     assert(type->isPointerType());
5737     return CK_CPointerToObjCPointerCast;
5738   }
5739 }
5740
5741 /// Prepares for a scalar cast, performing all the necessary stages
5742 /// except the final cast and returning the kind required.
5743 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5744   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5745   // Also, callers should have filtered out the invalid cases with
5746   // pointers.  Everything else should be possible.
5747
5748   QualType SrcTy = Src.get()->getType();
5749   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5750     return CK_NoOp;
5751
5752   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5753   case Type::STK_MemberPointer:
5754     llvm_unreachable("member pointer type in C");
5755
5756   case Type::STK_CPointer:
5757   case Type::STK_BlockPointer:
5758   case Type::STK_ObjCObjectPointer:
5759     switch (DestTy->getScalarTypeKind()) {
5760     case Type::STK_CPointer: {
5761       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5762       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5763       if (SrcAS != DestAS)
5764         return CK_AddressSpaceConversion;
5765       return CK_BitCast;
5766     }
5767     case Type::STK_BlockPointer:
5768       return (SrcKind == Type::STK_BlockPointer
5769                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5770     case Type::STK_ObjCObjectPointer:
5771       if (SrcKind == Type::STK_ObjCObjectPointer)
5772         return CK_BitCast;
5773       if (SrcKind == Type::STK_CPointer)
5774         return CK_CPointerToObjCPointerCast;
5775       maybeExtendBlockObject(Src);
5776       return CK_BlockPointerToObjCPointerCast;
5777     case Type::STK_Bool:
5778       return CK_PointerToBoolean;
5779     case Type::STK_Integral:
5780       return CK_PointerToIntegral;
5781     case Type::STK_Floating:
5782     case Type::STK_FloatingComplex:
5783     case Type::STK_IntegralComplex:
5784     case Type::STK_MemberPointer:
5785       llvm_unreachable("illegal cast from pointer");
5786     }
5787     llvm_unreachable("Should have returned before this");
5788
5789   case Type::STK_Bool: // casting from bool is like casting from an integer
5790   case Type::STK_Integral:
5791     switch (DestTy->getScalarTypeKind()) {
5792     case Type::STK_CPointer:
5793     case Type::STK_ObjCObjectPointer:
5794     case Type::STK_BlockPointer:
5795       if (Src.get()->isNullPointerConstant(Context,
5796                                            Expr::NPC_ValueDependentIsNull))
5797         return CK_NullToPointer;
5798       return CK_IntegralToPointer;
5799     case Type::STK_Bool:
5800       return CK_IntegralToBoolean;
5801     case Type::STK_Integral:
5802       return CK_IntegralCast;
5803     case Type::STK_Floating:
5804       return CK_IntegralToFloating;
5805     case Type::STK_IntegralComplex:
5806       Src = ImpCastExprToType(Src.get(),
5807                       DestTy->castAs<ComplexType>()->getElementType(),
5808                       CK_IntegralCast);
5809       return CK_IntegralRealToComplex;
5810     case Type::STK_FloatingComplex:
5811       Src = ImpCastExprToType(Src.get(),
5812                       DestTy->castAs<ComplexType>()->getElementType(),
5813                       CK_IntegralToFloating);
5814       return CK_FloatingRealToComplex;
5815     case Type::STK_MemberPointer:
5816       llvm_unreachable("member pointer type in C");
5817     }
5818     llvm_unreachable("Should have returned before this");
5819
5820   case Type::STK_Floating:
5821     switch (DestTy->getScalarTypeKind()) {
5822     case Type::STK_Floating:
5823       return CK_FloatingCast;
5824     case Type::STK_Bool:
5825       return CK_FloatingToBoolean;
5826     case Type::STK_Integral:
5827       return CK_FloatingToIntegral;
5828     case Type::STK_FloatingComplex:
5829       Src = ImpCastExprToType(Src.get(),
5830                               DestTy->castAs<ComplexType>()->getElementType(),
5831                               CK_FloatingCast);
5832       return CK_FloatingRealToComplex;
5833     case Type::STK_IntegralComplex:
5834       Src = ImpCastExprToType(Src.get(),
5835                               DestTy->castAs<ComplexType>()->getElementType(),
5836                               CK_FloatingToIntegral);
5837       return CK_IntegralRealToComplex;
5838     case Type::STK_CPointer:
5839     case Type::STK_ObjCObjectPointer:
5840     case Type::STK_BlockPointer:
5841       llvm_unreachable("valid float->pointer cast?");
5842     case Type::STK_MemberPointer:
5843       llvm_unreachable("member pointer type in C");
5844     }
5845     llvm_unreachable("Should have returned before this");
5846
5847   case Type::STK_FloatingComplex:
5848     switch (DestTy->getScalarTypeKind()) {
5849     case Type::STK_FloatingComplex:
5850       return CK_FloatingComplexCast;
5851     case Type::STK_IntegralComplex:
5852       return CK_FloatingComplexToIntegralComplex;
5853     case Type::STK_Floating: {
5854       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5855       if (Context.hasSameType(ET, DestTy))
5856         return CK_FloatingComplexToReal;
5857       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5858       return CK_FloatingCast;
5859     }
5860     case Type::STK_Bool:
5861       return CK_FloatingComplexToBoolean;
5862     case Type::STK_Integral:
5863       Src = ImpCastExprToType(Src.get(),
5864                               SrcTy->castAs<ComplexType>()->getElementType(),
5865                               CK_FloatingComplexToReal);
5866       return CK_FloatingToIntegral;
5867     case Type::STK_CPointer:
5868     case Type::STK_ObjCObjectPointer:
5869     case Type::STK_BlockPointer:
5870       llvm_unreachable("valid complex float->pointer cast?");
5871     case Type::STK_MemberPointer:
5872       llvm_unreachable("member pointer type in C");
5873     }
5874     llvm_unreachable("Should have returned before this");
5875
5876   case Type::STK_IntegralComplex:
5877     switch (DestTy->getScalarTypeKind()) {
5878     case Type::STK_FloatingComplex:
5879       return CK_IntegralComplexToFloatingComplex;
5880     case Type::STK_IntegralComplex:
5881       return CK_IntegralComplexCast;
5882     case Type::STK_Integral: {
5883       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5884       if (Context.hasSameType(ET, DestTy))
5885         return CK_IntegralComplexToReal;
5886       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5887       return CK_IntegralCast;
5888     }
5889     case Type::STK_Bool:
5890       return CK_IntegralComplexToBoolean;
5891     case Type::STK_Floating:
5892       Src = ImpCastExprToType(Src.get(),
5893                               SrcTy->castAs<ComplexType>()->getElementType(),
5894                               CK_IntegralComplexToReal);
5895       return CK_IntegralToFloating;
5896     case Type::STK_CPointer:
5897     case Type::STK_ObjCObjectPointer:
5898     case Type::STK_BlockPointer:
5899       llvm_unreachable("valid complex int->pointer cast?");
5900     case Type::STK_MemberPointer:
5901       llvm_unreachable("member pointer type in C");
5902     }
5903     llvm_unreachable("Should have returned before this");
5904   }
5905
5906   llvm_unreachable("Unhandled scalar cast");
5907 }
5908
5909 static bool breakDownVectorType(QualType type, uint64_t &len,
5910                                 QualType &eltType) {
5911   // Vectors are simple.
5912   if (const VectorType *vecType = type->getAs<VectorType>()) {
5913     len = vecType->getNumElements();
5914     eltType = vecType->getElementType();
5915     assert(eltType->isScalarType());
5916     return true;
5917   }
5918   
5919   // We allow lax conversion to and from non-vector types, but only if
5920   // they're real types (i.e. non-complex, non-pointer scalar types).
5921   if (!type->isRealType()) return false;
5922   
5923   len = 1;
5924   eltType = type;
5925   return true;
5926 }
5927
5928 /// Are the two types lax-compatible vector types?  That is, given
5929 /// that one of them is a vector, do they have equal storage sizes,
5930 /// where the storage size is the number of elements times the element
5931 /// size?
5932 ///
5933 /// This will also return false if either of the types is neither a
5934 /// vector nor a real type.
5935 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5936   assert(destTy->isVectorType() || srcTy->isVectorType());
5937   
5938   // Disallow lax conversions between scalars and ExtVectors (these
5939   // conversions are allowed for other vector types because common headers
5940   // depend on them).  Most scalar OP ExtVector cases are handled by the
5941   // splat path anyway, which does what we want (convert, not bitcast).
5942   // What this rules out for ExtVectors is crazy things like char4*float.
5943   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5944   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5945
5946   uint64_t srcLen, destLen;
5947   QualType srcEltTy, destEltTy;
5948   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5949   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5950   
5951   // ASTContext::getTypeSize will return the size rounded up to a
5952   // power of 2, so instead of using that, we need to use the raw
5953   // element size multiplied by the element count.
5954   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5955   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5956   
5957   return (srcLen * srcEltSize == destLen * destEltSize);
5958 }
5959
5960 /// Is this a legal conversion between two types, one of which is
5961 /// known to be a vector type?
5962 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5963   assert(destTy->isVectorType() || srcTy->isVectorType());
5964   
5965   if (!Context.getLangOpts().LaxVectorConversions)
5966     return false;
5967   return areLaxCompatibleVectorTypes(srcTy, destTy);
5968 }
5969
5970 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5971                            CastKind &Kind) {
5972   assert(VectorTy->isVectorType() && "Not a vector type!");
5973
5974   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5975     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5976       return Diag(R.getBegin(),
5977                   Ty->isVectorType() ?
5978                   diag::err_invalid_conversion_between_vectors :
5979                   diag::err_invalid_conversion_between_vector_and_integer)
5980         << VectorTy << Ty << R;
5981   } else
5982     return Diag(R.getBegin(),
5983                 diag::err_invalid_conversion_between_vector_and_scalar)
5984       << VectorTy << Ty << R;
5985
5986   Kind = CK_BitCast;
5987   return false;
5988 }
5989
5990 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5991   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5992
5993   if (DestElemTy == SplattedExpr->getType())
5994     return SplattedExpr;
5995
5996   assert(DestElemTy->isFloatingType() ||
5997          DestElemTy->isIntegralOrEnumerationType());
5998
5999   CastKind CK;
6000   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6001     // OpenCL requires that we convert `true` boolean expressions to -1, but
6002     // only when splatting vectors.
6003     if (DestElemTy->isFloatingType()) {
6004       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6005       // in two steps: boolean to signed integral, then to floating.
6006       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6007                                                  CK_BooleanToSignedIntegral);
6008       SplattedExpr = CastExprRes.get();
6009       CK = CK_IntegralToFloating;
6010     } else {
6011       CK = CK_BooleanToSignedIntegral;
6012     }
6013   } else {
6014     ExprResult CastExprRes = SplattedExpr;
6015     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6016     if (CastExprRes.isInvalid())
6017       return ExprError();
6018     SplattedExpr = CastExprRes.get();
6019   }
6020   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6021 }
6022
6023 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6024                                     Expr *CastExpr, CastKind &Kind) {
6025   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6026
6027   QualType SrcTy = CastExpr->getType();
6028
6029   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6030   // an ExtVectorType.
6031   // In OpenCL, casts between vectors of different types are not allowed.
6032   // (See OpenCL 6.2).
6033   if (SrcTy->isVectorType()) {
6034     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
6035         || (getLangOpts().OpenCL &&
6036             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
6037       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6038         << DestTy << SrcTy << R;
6039       return ExprError();
6040     }
6041     Kind = CK_BitCast;
6042     return CastExpr;
6043   }
6044
6045   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6046   // conversion will take place first from scalar to elt type, and then
6047   // splat from elt type to vector.
6048   if (SrcTy->isPointerType())
6049     return Diag(R.getBegin(),
6050                 diag::err_invalid_conversion_between_vector_and_scalar)
6051       << DestTy << SrcTy << R;
6052
6053   Kind = CK_VectorSplat;
6054   return prepareVectorSplat(DestTy, CastExpr);
6055 }
6056
6057 ExprResult
6058 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6059                     Declarator &D, ParsedType &Ty,
6060                     SourceLocation RParenLoc, Expr *CastExpr) {
6061   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6062          "ActOnCastExpr(): missing type or expr");
6063
6064   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6065   if (D.isInvalidType())
6066     return ExprError();
6067
6068   if (getLangOpts().CPlusPlus) {
6069     // Check that there are no default arguments (C++ only).
6070     CheckExtraCXXDefaultArguments(D);
6071   } else {
6072     // Make sure any TypoExprs have been dealt with.
6073     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6074     if (!Res.isUsable())
6075       return ExprError();
6076     CastExpr = Res.get();
6077   }
6078
6079   checkUnusedDeclAttributes(D);
6080
6081   QualType castType = castTInfo->getType();
6082   Ty = CreateParsedType(castType, castTInfo);
6083
6084   bool isVectorLiteral = false;
6085
6086   // Check for an altivec or OpenCL literal,
6087   // i.e. all the elements are integer constants.
6088   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6089   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6090   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6091        && castType->isVectorType() && (PE || PLE)) {
6092     if (PLE && PLE->getNumExprs() == 0) {
6093       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6094       return ExprError();
6095     }
6096     if (PE || PLE->getNumExprs() == 1) {
6097       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6098       if (!E->getType()->isVectorType())
6099         isVectorLiteral = true;
6100     }
6101     else
6102       isVectorLiteral = true;
6103   }
6104
6105   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6106   // then handle it as such.
6107   if (isVectorLiteral)
6108     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6109
6110   // If the Expr being casted is a ParenListExpr, handle it specially.
6111   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6112   // sequence of BinOp comma operators.
6113   if (isa<ParenListExpr>(CastExpr)) {
6114     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6115     if (Result.isInvalid()) return ExprError();
6116     CastExpr = Result.get();
6117   }
6118
6119   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6120       !getSourceManager().isInSystemMacro(LParenLoc))
6121     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6122   
6123   CheckTollFreeBridgeCast(castType, CastExpr);
6124   
6125   CheckObjCBridgeRelatedCast(castType, CastExpr);
6126
6127   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6128
6129   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6130 }
6131
6132 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6133                                     SourceLocation RParenLoc, Expr *E,
6134                                     TypeSourceInfo *TInfo) {
6135   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6136          "Expected paren or paren list expression");
6137
6138   Expr **exprs;
6139   unsigned numExprs;
6140   Expr *subExpr;
6141   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6142   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6143     LiteralLParenLoc = PE->getLParenLoc();
6144     LiteralRParenLoc = PE->getRParenLoc();
6145     exprs = PE->getExprs();
6146     numExprs = PE->getNumExprs();
6147   } else { // isa<ParenExpr> by assertion at function entrance
6148     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6149     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6150     subExpr = cast<ParenExpr>(E)->getSubExpr();
6151     exprs = &subExpr;
6152     numExprs = 1;
6153   }
6154
6155   QualType Ty = TInfo->getType();
6156   assert(Ty->isVectorType() && "Expected vector type");
6157
6158   SmallVector<Expr *, 8> initExprs;
6159   const VectorType *VTy = Ty->getAs<VectorType>();
6160   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6161   
6162   // '(...)' form of vector initialization in AltiVec: the number of
6163   // initializers must be one or must match the size of the vector.
6164   // If a single value is specified in the initializer then it will be
6165   // replicated to all the components of the vector
6166   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6167     // The number of initializers must be one or must match the size of the
6168     // vector. If a single value is specified in the initializer then it will
6169     // be replicated to all the components of the vector
6170     if (numExprs == 1) {
6171       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6172       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6173       if (Literal.isInvalid())
6174         return ExprError();
6175       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6176                                   PrepareScalarCast(Literal, ElemTy));
6177       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6178     }
6179     else if (numExprs < numElems) {
6180       Diag(E->getExprLoc(),
6181            diag::err_incorrect_number_of_vector_initializers);
6182       return ExprError();
6183     }
6184     else
6185       initExprs.append(exprs, exprs + numExprs);
6186   }
6187   else {
6188     // For OpenCL, when the number of initializers is a single value,
6189     // it will be replicated to all components of the vector.
6190     if (getLangOpts().OpenCL &&
6191         VTy->getVectorKind() == VectorType::GenericVector &&
6192         numExprs == 1) {
6193         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6194         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6195         if (Literal.isInvalid())
6196           return ExprError();
6197         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6198                                     PrepareScalarCast(Literal, ElemTy));
6199         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6200     }
6201     
6202     initExprs.append(exprs, exprs + numExprs);
6203   }
6204   // FIXME: This means that pretty-printing the final AST will produce curly
6205   // braces instead of the original commas.
6206   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6207                                                    initExprs, LiteralRParenLoc);
6208   initE->setType(Ty);
6209   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6210 }
6211
6212 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6213 /// the ParenListExpr into a sequence of comma binary operators.
6214 ExprResult
6215 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6216   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6217   if (!E)
6218     return OrigExpr;
6219
6220   ExprResult Result(E->getExpr(0));
6221
6222   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6223     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6224                         E->getExpr(i));
6225
6226   if (Result.isInvalid()) return ExprError();
6227
6228   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6229 }
6230
6231 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6232                                     SourceLocation R,
6233                                     MultiExprArg Val) {
6234   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6235   return expr;
6236 }
6237
6238 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6239 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6240 /// emitted.
6241 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6242                                       SourceLocation QuestionLoc) {
6243   Expr *NullExpr = LHSExpr;
6244   Expr *NonPointerExpr = RHSExpr;
6245   Expr::NullPointerConstantKind NullKind =
6246       NullExpr->isNullPointerConstant(Context,
6247                                       Expr::NPC_ValueDependentIsNotNull);
6248
6249   if (NullKind == Expr::NPCK_NotNull) {
6250     NullExpr = RHSExpr;
6251     NonPointerExpr = LHSExpr;
6252     NullKind =
6253         NullExpr->isNullPointerConstant(Context,
6254                                         Expr::NPC_ValueDependentIsNotNull);
6255   }
6256
6257   if (NullKind == Expr::NPCK_NotNull)
6258     return false;
6259
6260   if (NullKind == Expr::NPCK_ZeroExpression)
6261     return false;
6262
6263   if (NullKind == Expr::NPCK_ZeroLiteral) {
6264     // In this case, check to make sure that we got here from a "NULL"
6265     // string in the source code.
6266     NullExpr = NullExpr->IgnoreParenImpCasts();
6267     SourceLocation loc = NullExpr->getExprLoc();
6268     if (!findMacroSpelling(loc, "NULL"))
6269       return false;
6270   }
6271
6272   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6273   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6274       << NonPointerExpr->getType() << DiagType
6275       << NonPointerExpr->getSourceRange();
6276   return true;
6277 }
6278
6279 /// \brief Return false if the condition expression is valid, true otherwise.
6280 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6281   QualType CondTy = Cond->getType();
6282
6283   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6284   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6285     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6286       << CondTy << Cond->getSourceRange();
6287     return true;
6288   }
6289
6290   // C99 6.5.15p2
6291   if (CondTy->isScalarType()) return false;
6292
6293   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6294     << CondTy << Cond->getSourceRange();
6295   return true;
6296 }
6297
6298 /// \brief Handle when one or both operands are void type.
6299 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6300                                          ExprResult &RHS) {
6301     Expr *LHSExpr = LHS.get();
6302     Expr *RHSExpr = RHS.get();
6303
6304     if (!LHSExpr->getType()->isVoidType())
6305       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6306         << RHSExpr->getSourceRange();
6307     if (!RHSExpr->getType()->isVoidType())
6308       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6309         << LHSExpr->getSourceRange();
6310     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6311     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6312     return S.Context.VoidTy;
6313 }
6314
6315 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6316 /// true otherwise.
6317 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6318                                         QualType PointerTy) {
6319   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6320       !NullExpr.get()->isNullPointerConstant(S.Context,
6321                                             Expr::NPC_ValueDependentIsNull))
6322     return true;
6323
6324   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6325   return false;
6326 }
6327
6328 /// \brief Checks compatibility between two pointers and return the resulting
6329 /// type.
6330 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6331                                                      ExprResult &RHS,
6332                                                      SourceLocation Loc) {
6333   QualType LHSTy = LHS.get()->getType();
6334   QualType RHSTy = RHS.get()->getType();
6335
6336   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6337     // Two identical pointers types are always compatible.
6338     return LHSTy;
6339   }
6340
6341   QualType lhptee, rhptee;
6342
6343   // Get the pointee types.
6344   bool IsBlockPointer = false;
6345   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6346     lhptee = LHSBTy->getPointeeType();
6347     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6348     IsBlockPointer = true;
6349   } else {
6350     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6351     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6352   }
6353
6354   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6355   // differently qualified versions of compatible types, the result type is
6356   // a pointer to an appropriately qualified version of the composite
6357   // type.
6358
6359   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6360   // clause doesn't make sense for our extensions. E.g. address space 2 should
6361   // be incompatible with address space 3: they may live on different devices or
6362   // anything.
6363   Qualifiers lhQual = lhptee.getQualifiers();
6364   Qualifiers rhQual = rhptee.getQualifiers();
6365
6366   unsigned ResultAddrSpace = 0;
6367   unsigned LAddrSpace = lhQual.getAddressSpace();
6368   unsigned RAddrSpace = rhQual.getAddressSpace();
6369   if (S.getLangOpts().OpenCL) {
6370     // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6371     // spaces is disallowed.
6372     if (lhQual.isAddressSpaceSupersetOf(rhQual))
6373       ResultAddrSpace = LAddrSpace;
6374     else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6375       ResultAddrSpace = RAddrSpace;
6376     else {
6377       S.Diag(Loc,
6378              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6379           << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6380           << RHS.get()->getSourceRange();
6381       return QualType();
6382     }
6383   }
6384
6385   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6386   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6387   lhQual.removeCVRQualifiers();
6388   rhQual.removeCVRQualifiers();
6389
6390   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6391   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6392   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6393   // qual types are compatible iff
6394   //  * corresponded types are compatible
6395   //  * CVR qualifiers are equal
6396   //  * address spaces are equal
6397   // Thus for conditional operator we merge CVR and address space unqualified
6398   // pointees and if there is a composite type we return a pointer to it with
6399   // merged qualifiers.
6400   if (S.getLangOpts().OpenCL) {
6401     LHSCastKind = LAddrSpace == ResultAddrSpace
6402                       ? CK_BitCast
6403                       : CK_AddressSpaceConversion;
6404     RHSCastKind = RAddrSpace == ResultAddrSpace
6405                       ? CK_BitCast
6406                       : CK_AddressSpaceConversion;
6407     lhQual.removeAddressSpace();
6408     rhQual.removeAddressSpace();
6409   }
6410
6411   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6412   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6413
6414   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6415
6416   if (CompositeTy.isNull()) {
6417     // In this situation, we assume void* type. No especially good
6418     // reason, but this is what gcc does, and we do have to pick
6419     // to get a consistent AST.
6420     QualType incompatTy;
6421     incompatTy = S.Context.getPointerType(
6422         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6423     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6424     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6425     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6426     // for casts between types with incompatible address space qualifiers.
6427     // For the following code the compiler produces casts between global and
6428     // local address spaces of the corresponded innermost pointees:
6429     // local int *global *a;
6430     // global int *global *b;
6431     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6432     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6433         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6434         << RHS.get()->getSourceRange();
6435     return incompatTy;
6436   }
6437
6438   // The pointer types are compatible.
6439   // In case of OpenCL ResultTy should have the address space qualifier
6440   // which is a superset of address spaces of both the 2nd and the 3rd
6441   // operands of the conditional operator.
6442   QualType ResultTy = [&, ResultAddrSpace]() {
6443     if (S.getLangOpts().OpenCL) {
6444       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6445       CompositeQuals.setAddressSpace(ResultAddrSpace);
6446       return S.Context
6447           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6448           .withCVRQualifiers(MergedCVRQual);
6449     }
6450     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6451   }();
6452   if (IsBlockPointer)
6453     ResultTy = S.Context.getBlockPointerType(ResultTy);
6454   else
6455     ResultTy = S.Context.getPointerType(ResultTy);
6456
6457   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6458   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6459   return ResultTy;
6460 }
6461
6462 /// \brief Return the resulting type when the operands are both block pointers.
6463 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6464                                                           ExprResult &LHS,
6465                                                           ExprResult &RHS,
6466                                                           SourceLocation Loc) {
6467   QualType LHSTy = LHS.get()->getType();
6468   QualType RHSTy = RHS.get()->getType();
6469
6470   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6471     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6472       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6473       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6474       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6475       return destType;
6476     }
6477     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6478       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6479       << RHS.get()->getSourceRange();
6480     return QualType();
6481   }
6482
6483   // We have 2 block pointer types.
6484   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6485 }
6486
6487 /// \brief Return the resulting type when the operands are both pointers.
6488 static QualType
6489 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6490                                             ExprResult &RHS,
6491                                             SourceLocation Loc) {
6492   // get the pointer types
6493   QualType LHSTy = LHS.get()->getType();
6494   QualType RHSTy = RHS.get()->getType();
6495
6496   // get the "pointed to" types
6497   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6498   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6499
6500   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6501   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6502     // Figure out necessary qualifiers (C99 6.5.15p6)
6503     QualType destPointee
6504       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6505     QualType destType = S.Context.getPointerType(destPointee);
6506     // Add qualifiers if necessary.
6507     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6508     // Promote to void*.
6509     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6510     return destType;
6511   }
6512   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6513     QualType destPointee
6514       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6515     QualType destType = S.Context.getPointerType(destPointee);
6516     // Add qualifiers if necessary.
6517     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6518     // Promote to void*.
6519     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6520     return destType;
6521   }
6522
6523   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6524 }
6525
6526 /// \brief Return false if the first expression is not an integer and the second
6527 /// expression is not a pointer, true otherwise.
6528 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6529                                         Expr* PointerExpr, SourceLocation Loc,
6530                                         bool IsIntFirstExpr) {
6531   if (!PointerExpr->getType()->isPointerType() ||
6532       !Int.get()->getType()->isIntegerType())
6533     return false;
6534
6535   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6536   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6537
6538   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6539     << Expr1->getType() << Expr2->getType()
6540     << Expr1->getSourceRange() << Expr2->getSourceRange();
6541   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6542                             CK_IntegralToPointer);
6543   return true;
6544 }
6545
6546 /// \brief Simple conversion between integer and floating point types.
6547 ///
6548 /// Used when handling the OpenCL conditional operator where the
6549 /// condition is a vector while the other operands are scalar.
6550 ///
6551 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6552 /// types are either integer or floating type. Between the two
6553 /// operands, the type with the higher rank is defined as the "result
6554 /// type". The other operand needs to be promoted to the same type. No
6555 /// other type promotion is allowed. We cannot use
6556 /// UsualArithmeticConversions() for this purpose, since it always
6557 /// promotes promotable types.
6558 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6559                                             ExprResult &RHS,
6560                                             SourceLocation QuestionLoc) {
6561   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6562   if (LHS.isInvalid())
6563     return QualType();
6564   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6565   if (RHS.isInvalid())
6566     return QualType();
6567
6568   // For conversion purposes, we ignore any qualifiers.
6569   // For example, "const float" and "float" are equivalent.
6570   QualType LHSType =
6571     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6572   QualType RHSType =
6573     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6574
6575   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6576     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6577       << LHSType << LHS.get()->getSourceRange();
6578     return QualType();
6579   }
6580
6581   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6582     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6583       << RHSType << RHS.get()->getSourceRange();
6584     return QualType();
6585   }
6586
6587   // If both types are identical, no conversion is needed.
6588   if (LHSType == RHSType)
6589     return LHSType;
6590
6591   // Now handle "real" floating types (i.e. float, double, long double).
6592   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6593     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6594                                  /*IsCompAssign = */ false);
6595
6596   // Finally, we have two differing integer types.
6597   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6598   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6599 }
6600
6601 /// \brief Convert scalar operands to a vector that matches the
6602 ///        condition in length.
6603 ///
6604 /// Used when handling the OpenCL conditional operator where the
6605 /// condition is a vector while the other operands are scalar.
6606 ///
6607 /// We first compute the "result type" for the scalar operands
6608 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6609 /// into a vector of that type where the length matches the condition
6610 /// vector type. s6.11.6 requires that the element types of the result
6611 /// and the condition must have the same number of bits.
6612 static QualType
6613 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6614                               QualType CondTy, SourceLocation QuestionLoc) {
6615   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6616   if (ResTy.isNull()) return QualType();
6617
6618   const VectorType *CV = CondTy->getAs<VectorType>();
6619   assert(CV);
6620
6621   // Determine the vector result type
6622   unsigned NumElements = CV->getNumElements();
6623   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6624
6625   // Ensure that all types have the same number of bits
6626   if (S.Context.getTypeSize(CV->getElementType())
6627       != S.Context.getTypeSize(ResTy)) {
6628     // Since VectorTy is created internally, it does not pretty print
6629     // with an OpenCL name. Instead, we just print a description.
6630     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6631     SmallString<64> Str;
6632     llvm::raw_svector_ostream OS(Str);
6633     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6634     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6635       << CondTy << OS.str();
6636     return QualType();
6637   }
6638
6639   // Convert operands to the vector result type
6640   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6641   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6642
6643   return VectorTy;
6644 }
6645
6646 /// \brief Return false if this is a valid OpenCL condition vector
6647 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6648                                        SourceLocation QuestionLoc) {
6649   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6650   // integral type.
6651   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6652   assert(CondTy);
6653   QualType EleTy = CondTy->getElementType();
6654   if (EleTy->isIntegerType()) return false;
6655
6656   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6657     << Cond->getType() << Cond->getSourceRange();
6658   return true;
6659 }
6660
6661 /// \brief Return false if the vector condition type and the vector
6662 ///        result type are compatible.
6663 ///
6664 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6665 /// number of elements, and their element types have the same number
6666 /// of bits.
6667 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6668                               SourceLocation QuestionLoc) {
6669   const VectorType *CV = CondTy->getAs<VectorType>();
6670   const VectorType *RV = VecResTy->getAs<VectorType>();
6671   assert(CV && RV);
6672
6673   if (CV->getNumElements() != RV->getNumElements()) {
6674     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6675       << CondTy << VecResTy;
6676     return true;
6677   }
6678
6679   QualType CVE = CV->getElementType();
6680   QualType RVE = RV->getElementType();
6681
6682   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6683     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6684       << CondTy << VecResTy;
6685     return true;
6686   }
6687
6688   return false;
6689 }
6690
6691 /// \brief Return the resulting type for the conditional operator in
6692 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6693 ///        s6.3.i) when the condition is a vector type.
6694 static QualType
6695 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6696                              ExprResult &LHS, ExprResult &RHS,
6697                              SourceLocation QuestionLoc) {
6698   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 
6699   if (Cond.isInvalid())
6700     return QualType();
6701   QualType CondTy = Cond.get()->getType();
6702
6703   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6704     return QualType();
6705
6706   // If either operand is a vector then find the vector type of the
6707   // result as specified in OpenCL v1.1 s6.3.i.
6708   if (LHS.get()->getType()->isVectorType() ||
6709       RHS.get()->getType()->isVectorType()) {
6710     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6711                                               /*isCompAssign*/false,
6712                                               /*AllowBothBool*/true,
6713                                               /*AllowBoolConversions*/false);
6714     if (VecResTy.isNull()) return QualType();
6715     // The result type must match the condition type as specified in
6716     // OpenCL v1.1 s6.11.6.
6717     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6718       return QualType();
6719     return VecResTy;
6720   }
6721
6722   // Both operands are scalar.
6723   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6724 }
6725
6726 /// \brief Return true if the Expr is block type
6727 static bool checkBlockType(Sema &S, const Expr *E) {
6728   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6729     QualType Ty = CE->getCallee()->getType();
6730     if (Ty->isBlockPointerType()) {
6731       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6732       return true;
6733     }
6734   }
6735   return false;
6736 }
6737
6738 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6739 /// In that case, LHS = cond.
6740 /// C99 6.5.15
6741 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6742                                         ExprResult &RHS, ExprValueKind &VK,
6743                                         ExprObjectKind &OK,
6744                                         SourceLocation QuestionLoc) {
6745
6746   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6747   if (!LHSResult.isUsable()) return QualType();
6748   LHS = LHSResult;
6749
6750   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6751   if (!RHSResult.isUsable()) return QualType();
6752   RHS = RHSResult;
6753
6754   // C++ is sufficiently different to merit its own checker.
6755   if (getLangOpts().CPlusPlus)
6756     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6757
6758   VK = VK_RValue;
6759   OK = OK_Ordinary;
6760
6761   // The OpenCL operator with a vector condition is sufficiently
6762   // different to merit its own checker.
6763   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6764     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6765
6766   // First, check the condition.
6767   Cond = UsualUnaryConversions(Cond.get());
6768   if (Cond.isInvalid())
6769     return QualType();
6770   if (checkCondition(*this, Cond.get(), QuestionLoc))
6771     return QualType();
6772
6773   // Now check the two expressions.
6774   if (LHS.get()->getType()->isVectorType() ||
6775       RHS.get()->getType()->isVectorType())
6776     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6777                                /*AllowBothBool*/true,
6778                                /*AllowBoolConversions*/false);
6779
6780   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6781   if (LHS.isInvalid() || RHS.isInvalid())
6782     return QualType();
6783
6784   QualType LHSTy = LHS.get()->getType();
6785   QualType RHSTy = RHS.get()->getType();
6786
6787   // Diagnose attempts to convert between __float128 and long double where
6788   // such conversions currently can't be handled.
6789   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6790     Diag(QuestionLoc,
6791          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6792       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6793     return QualType();
6794   }
6795
6796   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6797   // selection operator (?:).
6798   if (getLangOpts().OpenCL &&
6799       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6800     return QualType();
6801   }
6802
6803   // If both operands have arithmetic type, do the usual arithmetic conversions
6804   // to find a common type: C99 6.5.15p3,5.
6805   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6806     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6807     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6808
6809     return ResTy;
6810   }
6811
6812   // If both operands are the same structure or union type, the result is that
6813   // type.
6814   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6815     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6816       if (LHSRT->getDecl() == RHSRT->getDecl())
6817         // "If both the operands have structure or union type, the result has
6818         // that type."  This implies that CV qualifiers are dropped.
6819         return LHSTy.getUnqualifiedType();
6820     // FIXME: Type of conditional expression must be complete in C mode.
6821   }
6822
6823   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6824   // The following || allows only one side to be void (a GCC-ism).
6825   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6826     return checkConditionalVoidType(*this, LHS, RHS);
6827   }
6828
6829   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6830   // the type of the other operand."
6831   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6832   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6833
6834   // All objective-c pointer type analysis is done here.
6835   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6836                                                         QuestionLoc);
6837   if (LHS.isInvalid() || RHS.isInvalid())
6838     return QualType();
6839   if (!compositeType.isNull())
6840     return compositeType;
6841
6842
6843   // Handle block pointer types.
6844   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6845     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6846                                                      QuestionLoc);
6847
6848   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6849   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6850     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6851                                                        QuestionLoc);
6852
6853   // GCC compatibility: soften pointer/integer mismatch.  Note that
6854   // null pointers have been filtered out by this point.
6855   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6856       /*isIntFirstExpr=*/true))
6857     return RHSTy;
6858   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6859       /*isIntFirstExpr=*/false))
6860     return LHSTy;
6861
6862   // Emit a better diagnostic if one of the expressions is a null pointer
6863   // constant and the other is not a pointer type. In this case, the user most
6864   // likely forgot to take the address of the other expression.
6865   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6866     return QualType();
6867
6868   // Otherwise, the operands are not compatible.
6869   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6870     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6871     << RHS.get()->getSourceRange();
6872   return QualType();
6873 }
6874
6875 /// FindCompositeObjCPointerType - Helper method to find composite type of
6876 /// two objective-c pointer types of the two input expressions.
6877 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6878                                             SourceLocation QuestionLoc) {
6879   QualType LHSTy = LHS.get()->getType();
6880   QualType RHSTy = RHS.get()->getType();
6881
6882   // Handle things like Class and struct objc_class*.  Here we case the result
6883   // to the pseudo-builtin, because that will be implicitly cast back to the
6884   // redefinition type if an attempt is made to access its fields.
6885   if (LHSTy->isObjCClassType() &&
6886       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6887     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6888     return LHSTy;
6889   }
6890   if (RHSTy->isObjCClassType() &&
6891       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6892     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6893     return RHSTy;
6894   }
6895   // And the same for struct objc_object* / id
6896   if (LHSTy->isObjCIdType() &&
6897       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6898     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6899     return LHSTy;
6900   }
6901   if (RHSTy->isObjCIdType() &&
6902       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6903     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6904     return RHSTy;
6905   }
6906   // And the same for struct objc_selector* / SEL
6907   if (Context.isObjCSelType(LHSTy) &&
6908       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6909     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6910     return LHSTy;
6911   }
6912   if (Context.isObjCSelType(RHSTy) &&
6913       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6914     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6915     return RHSTy;
6916   }
6917   // Check constraints for Objective-C object pointers types.
6918   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6919
6920     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6921       // Two identical object pointer types are always compatible.
6922       return LHSTy;
6923     }
6924     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6925     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6926     QualType compositeType = LHSTy;
6927
6928     // If both operands are interfaces and either operand can be
6929     // assigned to the other, use that type as the composite
6930     // type. This allows
6931     //   xxx ? (A*) a : (B*) b
6932     // where B is a subclass of A.
6933     //
6934     // Additionally, as for assignment, if either type is 'id'
6935     // allow silent coercion. Finally, if the types are
6936     // incompatible then make sure to use 'id' as the composite
6937     // type so the result is acceptable for sending messages to.
6938
6939     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6940     // It could return the composite type.
6941     if (!(compositeType =
6942           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6943       // Nothing more to do.
6944     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6945       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6946     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6947       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6948     } else if ((LHSTy->isObjCQualifiedIdType() ||
6949                 RHSTy->isObjCQualifiedIdType()) &&
6950                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6951       // Need to handle "id<xx>" explicitly.
6952       // GCC allows qualified id and any Objective-C type to devolve to
6953       // id. Currently localizing to here until clear this should be
6954       // part of ObjCQualifiedIdTypesAreCompatible.
6955       compositeType = Context.getObjCIdType();
6956     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6957       compositeType = Context.getObjCIdType();
6958     } else {
6959       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6960       << LHSTy << RHSTy
6961       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6962       QualType incompatTy = Context.getObjCIdType();
6963       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6964       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6965       return incompatTy;
6966     }
6967     // The object pointer types are compatible.
6968     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6969     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6970     return compositeType;
6971   }
6972   // Check Objective-C object pointer types and 'void *'
6973   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6974     if (getLangOpts().ObjCAutoRefCount) {
6975       // ARC forbids the implicit conversion of object pointers to 'void *',
6976       // so these types are not compatible.
6977       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6978           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6979       LHS = RHS = true;
6980       return QualType();
6981     }
6982     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6983     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6984     QualType destPointee
6985     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6986     QualType destType = Context.getPointerType(destPointee);
6987     // Add qualifiers if necessary.
6988     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6989     // Promote to void*.
6990     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6991     return destType;
6992   }
6993   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6994     if (getLangOpts().ObjCAutoRefCount) {
6995       // ARC forbids the implicit conversion of object pointers to 'void *',
6996       // so these types are not compatible.
6997       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6998           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6999       LHS = RHS = true;
7000       return QualType();
7001     }
7002     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7003     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7004     QualType destPointee
7005     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7006     QualType destType = Context.getPointerType(destPointee);
7007     // Add qualifiers if necessary.
7008     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7009     // Promote to void*.
7010     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7011     return destType;
7012   }
7013   return QualType();
7014 }
7015
7016 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7017 /// ParenRange in parentheses.
7018 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7019                                const PartialDiagnostic &Note,
7020                                SourceRange ParenRange) {
7021   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7022   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7023       EndLoc.isValid()) {
7024     Self.Diag(Loc, Note)
7025       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7026       << FixItHint::CreateInsertion(EndLoc, ")");
7027   } else {
7028     // We can't display the parentheses, so just show the bare note.
7029     Self.Diag(Loc, Note) << ParenRange;
7030   }
7031 }
7032
7033 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7034   return BinaryOperator::isAdditiveOp(Opc) ||
7035          BinaryOperator::isMultiplicativeOp(Opc) ||
7036          BinaryOperator::isShiftOp(Opc);
7037 }
7038
7039 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7040 /// expression, either using a built-in or overloaded operator,
7041 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7042 /// expression.
7043 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7044                                    Expr **RHSExprs) {
7045   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7046   E = E->IgnoreImpCasts();
7047   E = E->IgnoreConversionOperator();
7048   E = E->IgnoreImpCasts();
7049
7050   // Built-in binary operator.
7051   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7052     if (IsArithmeticOp(OP->getOpcode())) {
7053       *Opcode = OP->getOpcode();
7054       *RHSExprs = OP->getRHS();
7055       return true;
7056     }
7057   }
7058
7059   // Overloaded operator.
7060   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7061     if (Call->getNumArgs() != 2)
7062       return false;
7063
7064     // Make sure this is really a binary operator that is safe to pass into
7065     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7066     OverloadedOperatorKind OO = Call->getOperator();
7067     if (OO < OO_Plus || OO > OO_Arrow ||
7068         OO == OO_PlusPlus || OO == OO_MinusMinus)
7069       return false;
7070
7071     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7072     if (IsArithmeticOp(OpKind)) {
7073       *Opcode = OpKind;
7074       *RHSExprs = Call->getArg(1);
7075       return true;
7076     }
7077   }
7078
7079   return false;
7080 }
7081
7082 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7083 /// or is a logical expression such as (x==y) which has int type, but is
7084 /// commonly interpreted as boolean.
7085 static bool ExprLooksBoolean(Expr *E) {
7086   E = E->IgnoreParenImpCasts();
7087
7088   if (E->getType()->isBooleanType())
7089     return true;
7090   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7091     return OP->isComparisonOp() || OP->isLogicalOp();
7092   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7093     return OP->getOpcode() == UO_LNot;
7094   if (E->getType()->isPointerType())
7095     return true;
7096
7097   return false;
7098 }
7099
7100 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7101 /// and binary operator are mixed in a way that suggests the programmer assumed
7102 /// the conditional operator has higher precedence, for example:
7103 /// "int x = a + someBinaryCondition ? 1 : 2".
7104 static void DiagnoseConditionalPrecedence(Sema &Self,
7105                                           SourceLocation OpLoc,
7106                                           Expr *Condition,
7107                                           Expr *LHSExpr,
7108                                           Expr *RHSExpr) {
7109   BinaryOperatorKind CondOpcode;
7110   Expr *CondRHS;
7111
7112   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7113     return;
7114   if (!ExprLooksBoolean(CondRHS))
7115     return;
7116
7117   // The condition is an arithmetic binary expression, with a right-
7118   // hand side that looks boolean, so warn.
7119
7120   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7121       << Condition->getSourceRange()
7122       << BinaryOperator::getOpcodeStr(CondOpcode);
7123
7124   SuggestParentheses(Self, OpLoc,
7125     Self.PDiag(diag::note_precedence_silence)
7126       << BinaryOperator::getOpcodeStr(CondOpcode),
7127     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7128
7129   SuggestParentheses(Self, OpLoc,
7130     Self.PDiag(diag::note_precedence_conditional_first),
7131     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7132 }
7133
7134 /// Compute the nullability of a conditional expression.
7135 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7136                                               QualType LHSTy, QualType RHSTy,
7137                                               ASTContext &Ctx) {
7138   if (!ResTy->isAnyPointerType())
7139     return ResTy;
7140
7141   auto GetNullability = [&Ctx](QualType Ty) {
7142     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7143     if (Kind)
7144       return *Kind;
7145     return NullabilityKind::Unspecified;
7146   };
7147
7148   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7149   NullabilityKind MergedKind;
7150
7151   // Compute nullability of a binary conditional expression.
7152   if (IsBin) {
7153     if (LHSKind == NullabilityKind::NonNull)
7154       MergedKind = NullabilityKind::NonNull;
7155     else
7156       MergedKind = RHSKind;
7157   // Compute nullability of a normal conditional expression.
7158   } else {
7159     if (LHSKind == NullabilityKind::Nullable ||
7160         RHSKind == NullabilityKind::Nullable)
7161       MergedKind = NullabilityKind::Nullable;
7162     else if (LHSKind == NullabilityKind::NonNull)
7163       MergedKind = RHSKind;
7164     else if (RHSKind == NullabilityKind::NonNull)
7165       MergedKind = LHSKind;
7166     else
7167       MergedKind = NullabilityKind::Unspecified;
7168   }
7169
7170   // Return if ResTy already has the correct nullability.
7171   if (GetNullability(ResTy) == MergedKind)
7172     return ResTy;
7173
7174   // Strip all nullability from ResTy.
7175   while (ResTy->getNullability(Ctx))
7176     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7177
7178   // Create a new AttributedType with the new nullability kind.
7179   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7180   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7181 }
7182
7183 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7184 /// in the case of a the GNU conditional expr extension.
7185 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7186                                     SourceLocation ColonLoc,
7187                                     Expr *CondExpr, Expr *LHSExpr,
7188                                     Expr *RHSExpr) {
7189   if (!getLangOpts().CPlusPlus) {
7190     // C cannot handle TypoExpr nodes in the condition because it
7191     // doesn't handle dependent types properly, so make sure any TypoExprs have
7192     // been dealt with before checking the operands.
7193     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7194     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7195     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7196
7197     if (!CondResult.isUsable())
7198       return ExprError();
7199
7200     if (LHSExpr) {
7201       if (!LHSResult.isUsable())
7202         return ExprError();
7203     }
7204
7205     if (!RHSResult.isUsable())
7206       return ExprError();
7207
7208     CondExpr = CondResult.get();
7209     LHSExpr = LHSResult.get();
7210     RHSExpr = RHSResult.get();
7211   }
7212
7213   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7214   // was the condition.
7215   OpaqueValueExpr *opaqueValue = nullptr;
7216   Expr *commonExpr = nullptr;
7217   if (!LHSExpr) {
7218     commonExpr = CondExpr;
7219     // Lower out placeholder types first.  This is important so that we don't
7220     // try to capture a placeholder. This happens in few cases in C++; such
7221     // as Objective-C++'s dictionary subscripting syntax.
7222     if (commonExpr->hasPlaceholderType()) {
7223       ExprResult result = CheckPlaceholderExpr(commonExpr);
7224       if (!result.isUsable()) return ExprError();
7225       commonExpr = result.get();
7226     }
7227     // We usually want to apply unary conversions *before* saving, except
7228     // in the special case of a C++ l-value conditional.
7229     if (!(getLangOpts().CPlusPlus
7230           && !commonExpr->isTypeDependent()
7231           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7232           && commonExpr->isGLValue()
7233           && commonExpr->isOrdinaryOrBitFieldObject()
7234           && RHSExpr->isOrdinaryOrBitFieldObject()
7235           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7236       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7237       if (commonRes.isInvalid())
7238         return ExprError();
7239       commonExpr = commonRes.get();
7240     }
7241
7242     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7243                                                 commonExpr->getType(),
7244                                                 commonExpr->getValueKind(),
7245                                                 commonExpr->getObjectKind(),
7246                                                 commonExpr);
7247     LHSExpr = CondExpr = opaqueValue;
7248   }
7249
7250   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7251   ExprValueKind VK = VK_RValue;
7252   ExprObjectKind OK = OK_Ordinary;
7253   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7254   QualType result = CheckConditionalOperands(Cond, LHS, RHS, 
7255                                              VK, OK, QuestionLoc);
7256   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7257       RHS.isInvalid())
7258     return ExprError();
7259
7260   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7261                                 RHS.get());
7262
7263   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7264
7265   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7266                                          Context);
7267
7268   if (!commonExpr)
7269     return new (Context)
7270         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7271                             RHS.get(), result, VK, OK);
7272
7273   return new (Context) BinaryConditionalOperator(
7274       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7275       ColonLoc, result, VK, OK);
7276 }
7277
7278 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7279 // being closely modeled after the C99 spec:-). The odd characteristic of this
7280 // routine is it effectively iqnores the qualifiers on the top level pointee.
7281 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7282 // FIXME: add a couple examples in this comment.
7283 static Sema::AssignConvertType
7284 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7285   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7286   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7287
7288   // get the "pointed to" type (ignoring qualifiers at the top level)
7289   const Type *lhptee, *rhptee;
7290   Qualifiers lhq, rhq;
7291   std::tie(lhptee, lhq) =
7292       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7293   std::tie(rhptee, rhq) =
7294       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7295
7296   Sema::AssignConvertType ConvTy = Sema::Compatible;
7297
7298   // C99 6.5.16.1p1: This following citation is common to constraints
7299   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7300   // qualifiers of the type *pointed to* by the right;
7301
7302   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7303   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7304       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7305     // Ignore lifetime for further calculation.
7306     lhq.removeObjCLifetime();
7307     rhq.removeObjCLifetime();
7308   }
7309
7310   if (!lhq.compatiblyIncludes(rhq)) {
7311     // Treat address-space mismatches as fatal.  TODO: address subspaces
7312     if (!lhq.isAddressSpaceSupersetOf(rhq))
7313       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7314
7315     // It's okay to add or remove GC or lifetime qualifiers when converting to
7316     // and from void*.
7317     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7318                         .compatiblyIncludes(
7319                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7320              && (lhptee->isVoidType() || rhptee->isVoidType()))
7321       ; // keep old
7322
7323     // Treat lifetime mismatches as fatal.
7324     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7325       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7326     
7327     // For GCC/MS compatibility, other qualifier mismatches are treated
7328     // as still compatible in C.
7329     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7330   }
7331
7332   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7333   // incomplete type and the other is a pointer to a qualified or unqualified
7334   // version of void...
7335   if (lhptee->isVoidType()) {
7336     if (rhptee->isIncompleteOrObjectType())
7337       return ConvTy;
7338
7339     // As an extension, we allow cast to/from void* to function pointer.
7340     assert(rhptee->isFunctionType());
7341     return Sema::FunctionVoidPointer;
7342   }
7343
7344   if (rhptee->isVoidType()) {
7345     if (lhptee->isIncompleteOrObjectType())
7346       return ConvTy;
7347
7348     // As an extension, we allow cast to/from void* to function pointer.
7349     assert(lhptee->isFunctionType());
7350     return Sema::FunctionVoidPointer;
7351   }
7352
7353   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7354   // unqualified versions of compatible types, ...
7355   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7356   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7357     // Check if the pointee types are compatible ignoring the sign.
7358     // We explicitly check for char so that we catch "char" vs
7359     // "unsigned char" on systems where "char" is unsigned.
7360     if (lhptee->isCharType())
7361       ltrans = S.Context.UnsignedCharTy;
7362     else if (lhptee->hasSignedIntegerRepresentation())
7363       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7364
7365     if (rhptee->isCharType())
7366       rtrans = S.Context.UnsignedCharTy;
7367     else if (rhptee->hasSignedIntegerRepresentation())
7368       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7369
7370     if (ltrans == rtrans) {
7371       // Types are compatible ignoring the sign. Qualifier incompatibility
7372       // takes priority over sign incompatibility because the sign
7373       // warning can be disabled.
7374       if (ConvTy != Sema::Compatible)
7375         return ConvTy;
7376
7377       return Sema::IncompatiblePointerSign;
7378     }
7379
7380     // If we are a multi-level pointer, it's possible that our issue is simply
7381     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7382     // the eventual target type is the same and the pointers have the same
7383     // level of indirection, this must be the issue.
7384     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7385       do {
7386         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7387         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7388       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7389
7390       if (lhptee == rhptee)
7391         return Sema::IncompatibleNestedPointerQualifiers;
7392     }
7393
7394     // General pointer incompatibility takes priority over qualifiers.
7395     return Sema::IncompatiblePointer;
7396   }
7397   if (!S.getLangOpts().CPlusPlus &&
7398       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7399     return Sema::IncompatiblePointer;
7400   return ConvTy;
7401 }
7402
7403 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7404 /// block pointer types are compatible or whether a block and normal pointer
7405 /// are compatible. It is more restrict than comparing two function pointer
7406 // types.
7407 static Sema::AssignConvertType
7408 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7409                                     QualType RHSType) {
7410   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7411   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7412
7413   QualType lhptee, rhptee;
7414
7415   // get the "pointed to" type (ignoring qualifiers at the top level)
7416   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7417   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7418
7419   // In C++, the types have to match exactly.
7420   if (S.getLangOpts().CPlusPlus)
7421     return Sema::IncompatibleBlockPointer;
7422
7423   Sema::AssignConvertType ConvTy = Sema::Compatible;
7424
7425   // For blocks we enforce that qualifiers are identical.
7426   Qualifiers LQuals = lhptee.getLocalQualifiers();
7427   Qualifiers RQuals = rhptee.getLocalQualifiers();
7428   if (S.getLangOpts().OpenCL) {
7429     LQuals.removeAddressSpace();
7430     RQuals.removeAddressSpace();
7431   }
7432   if (LQuals != RQuals)
7433     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7434
7435   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7436   // assignment.
7437   // The current behavior is similar to C++ lambdas. A block might be
7438   // assigned to a variable iff its return type and parameters are compatible
7439   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7440   // an assignment. Presumably it should behave in way that a function pointer
7441   // assignment does in C, so for each parameter and return type:
7442   //  * CVR and address space of LHS should be a superset of CVR and address
7443   //  space of RHS.
7444   //  * unqualified types should be compatible.
7445   if (S.getLangOpts().OpenCL) {
7446     if (!S.Context.typesAreBlockPointerCompatible(
7447             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7448             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7449       return Sema::IncompatibleBlockPointer;
7450   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7451     return Sema::IncompatibleBlockPointer;
7452
7453   return ConvTy;
7454 }
7455
7456 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7457 /// for assignment compatibility.
7458 static Sema::AssignConvertType
7459 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7460                                    QualType RHSType) {
7461   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7462   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7463
7464   if (LHSType->isObjCBuiltinType()) {
7465     // Class is not compatible with ObjC object pointers.
7466     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7467         !RHSType->isObjCQualifiedClassType())
7468       return Sema::IncompatiblePointer;
7469     return Sema::Compatible;
7470   }
7471   if (RHSType->isObjCBuiltinType()) {
7472     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7473         !LHSType->isObjCQualifiedClassType())
7474       return Sema::IncompatiblePointer;
7475     return Sema::Compatible;
7476   }
7477   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7478   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7479
7480   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7481       // make an exception for id<P>
7482       !LHSType->isObjCQualifiedIdType())
7483     return Sema::CompatiblePointerDiscardsQualifiers;
7484
7485   if (S.Context.typesAreCompatible(LHSType, RHSType))
7486     return Sema::Compatible;
7487   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7488     return Sema::IncompatibleObjCQualifiedId;
7489   return Sema::IncompatiblePointer;
7490 }
7491
7492 Sema::AssignConvertType
7493 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7494                                  QualType LHSType, QualType RHSType) {
7495   // Fake up an opaque expression.  We don't actually care about what
7496   // cast operations are required, so if CheckAssignmentConstraints
7497   // adds casts to this they'll be wasted, but fortunately that doesn't
7498   // usually happen on valid code.
7499   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7500   ExprResult RHSPtr = &RHSExpr;
7501   CastKind K = CK_Invalid;
7502
7503   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7504 }
7505
7506 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7507 /// has code to accommodate several GCC extensions when type checking
7508 /// pointers. Here are some objectionable examples that GCC considers warnings:
7509 ///
7510 ///  int a, *pint;
7511 ///  short *pshort;
7512 ///  struct foo *pfoo;
7513 ///
7514 ///  pint = pshort; // warning: assignment from incompatible pointer type
7515 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7516 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7517 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7518 ///
7519 /// As a result, the code for dealing with pointers is more complex than the
7520 /// C99 spec dictates.
7521 ///
7522 /// Sets 'Kind' for any result kind except Incompatible.
7523 Sema::AssignConvertType
7524 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7525                                  CastKind &Kind, bool ConvertRHS) {
7526   QualType RHSType = RHS.get()->getType();
7527   QualType OrigLHSType = LHSType;
7528
7529   // Get canonical types.  We're not formatting these types, just comparing
7530   // them.
7531   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7532   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7533
7534   // Common case: no conversion required.
7535   if (LHSType == RHSType) {
7536     Kind = CK_NoOp;
7537     return Compatible;
7538   }
7539
7540   // If we have an atomic type, try a non-atomic assignment, then just add an
7541   // atomic qualification step.
7542   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7543     Sema::AssignConvertType result =
7544       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7545     if (result != Compatible)
7546       return result;
7547     if (Kind != CK_NoOp && ConvertRHS)
7548       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7549     Kind = CK_NonAtomicToAtomic;
7550     return Compatible;
7551   }
7552
7553   // If the left-hand side is a reference type, then we are in a
7554   // (rare!) case where we've allowed the use of references in C,
7555   // e.g., as a parameter type in a built-in function. In this case,
7556   // just make sure that the type referenced is compatible with the
7557   // right-hand side type. The caller is responsible for adjusting
7558   // LHSType so that the resulting expression does not have reference
7559   // type.
7560   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7561     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7562       Kind = CK_LValueBitCast;
7563       return Compatible;
7564     }
7565     return Incompatible;
7566   }
7567
7568   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7569   // to the same ExtVector type.
7570   if (LHSType->isExtVectorType()) {
7571     if (RHSType->isExtVectorType())
7572       return Incompatible;
7573     if (RHSType->isArithmeticType()) {
7574       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7575       if (ConvertRHS)
7576         RHS = prepareVectorSplat(LHSType, RHS.get());
7577       Kind = CK_VectorSplat;
7578       return Compatible;
7579     }
7580   }
7581
7582   // Conversions to or from vector type.
7583   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7584     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7585       // Allow assignments of an AltiVec vector type to an equivalent GCC
7586       // vector type and vice versa
7587       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7588         Kind = CK_BitCast;
7589         return Compatible;
7590       }
7591
7592       // If we are allowing lax vector conversions, and LHS and RHS are both
7593       // vectors, the total size only needs to be the same. This is a bitcast;
7594       // no bits are changed but the result type is different.
7595       if (isLaxVectorConversion(RHSType, LHSType)) {
7596         Kind = CK_BitCast;
7597         return IncompatibleVectors;
7598       }
7599     }
7600
7601     // When the RHS comes from another lax conversion (e.g. binops between
7602     // scalars and vectors) the result is canonicalized as a vector. When the
7603     // LHS is also a vector, the lax is allowed by the condition above. Handle
7604     // the case where LHS is a scalar.
7605     if (LHSType->isScalarType()) {
7606       const VectorType *VecType = RHSType->getAs<VectorType>();
7607       if (VecType && VecType->getNumElements() == 1 &&
7608           isLaxVectorConversion(RHSType, LHSType)) {
7609         ExprResult *VecExpr = &RHS;
7610         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7611         Kind = CK_BitCast;
7612         return Compatible;
7613       }
7614     }
7615
7616     return Incompatible;
7617   }
7618
7619   // Diagnose attempts to convert between __float128 and long double where
7620   // such conversions currently can't be handled.
7621   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7622     return Incompatible;
7623
7624   // Arithmetic conversions.
7625   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7626       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7627     if (ConvertRHS)
7628       Kind = PrepareScalarCast(RHS, LHSType);
7629     return Compatible;
7630   }
7631
7632   // Conversions to normal pointers.
7633   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7634     // U* -> T*
7635     if (isa<PointerType>(RHSType)) {
7636       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7637       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7638       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7639       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7640     }
7641
7642     // int -> T*
7643     if (RHSType->isIntegerType()) {
7644       Kind = CK_IntegralToPointer; // FIXME: null?
7645       return IntToPointer;
7646     }
7647
7648     // C pointers are not compatible with ObjC object pointers,
7649     // with two exceptions:
7650     if (isa<ObjCObjectPointerType>(RHSType)) {
7651       //  - conversions to void*
7652       if (LHSPointer->getPointeeType()->isVoidType()) {
7653         Kind = CK_BitCast;
7654         return Compatible;
7655       }
7656
7657       //  - conversions from 'Class' to the redefinition type
7658       if (RHSType->isObjCClassType() &&
7659           Context.hasSameType(LHSType, 
7660                               Context.getObjCClassRedefinitionType())) {
7661         Kind = CK_BitCast;
7662         return Compatible;
7663       }
7664
7665       Kind = CK_BitCast;
7666       return IncompatiblePointer;
7667     }
7668
7669     // U^ -> void*
7670     if (RHSType->getAs<BlockPointerType>()) {
7671       if (LHSPointer->getPointeeType()->isVoidType()) {
7672         unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7673         unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7674                                   ->getPointeeType()
7675                                   .getAddressSpace();
7676         Kind =
7677             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7678         return Compatible;
7679       }
7680     }
7681
7682     return Incompatible;
7683   }
7684
7685   // Conversions to block pointers.
7686   if (isa<BlockPointerType>(LHSType)) {
7687     // U^ -> T^
7688     if (RHSType->isBlockPointerType()) {
7689       unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>()
7690                                 ->getPointeeType()
7691                                 .getAddressSpace();
7692       unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7693                                 ->getPointeeType()
7694                                 .getAddressSpace();
7695       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7696       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7697     }
7698
7699     // int or null -> T^
7700     if (RHSType->isIntegerType()) {
7701       Kind = CK_IntegralToPointer; // FIXME: null
7702       return IntToBlockPointer;
7703     }
7704
7705     // id -> T^
7706     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7707       Kind = CK_AnyPointerToBlockPointerCast;
7708       return Compatible;
7709     }
7710
7711     // void* -> T^
7712     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7713       if (RHSPT->getPointeeType()->isVoidType()) {
7714         Kind = CK_AnyPointerToBlockPointerCast;
7715         return Compatible;
7716       }
7717
7718     return Incompatible;
7719   }
7720
7721   // Conversions to Objective-C pointers.
7722   if (isa<ObjCObjectPointerType>(LHSType)) {
7723     // A* -> B*
7724     if (RHSType->isObjCObjectPointerType()) {
7725       Kind = CK_BitCast;
7726       Sema::AssignConvertType result = 
7727         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7728       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7729           result == Compatible && 
7730           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7731         result = IncompatibleObjCWeakRef;
7732       return result;
7733     }
7734
7735     // int or null -> A*
7736     if (RHSType->isIntegerType()) {
7737       Kind = CK_IntegralToPointer; // FIXME: null
7738       return IntToPointer;
7739     }
7740
7741     // In general, C pointers are not compatible with ObjC object pointers,
7742     // with two exceptions:
7743     if (isa<PointerType>(RHSType)) {
7744       Kind = CK_CPointerToObjCPointerCast;
7745
7746       //  - conversions from 'void*'
7747       if (RHSType->isVoidPointerType()) {
7748         return Compatible;
7749       }
7750
7751       //  - conversions to 'Class' from its redefinition type
7752       if (LHSType->isObjCClassType() &&
7753           Context.hasSameType(RHSType, 
7754                               Context.getObjCClassRedefinitionType())) {
7755         return Compatible;
7756       }
7757
7758       return IncompatiblePointer;
7759     }
7760
7761     // Only under strict condition T^ is compatible with an Objective-C pointer.
7762     if (RHSType->isBlockPointerType() && 
7763         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7764       if (ConvertRHS)
7765         maybeExtendBlockObject(RHS);
7766       Kind = CK_BlockPointerToObjCPointerCast;
7767       return Compatible;
7768     }
7769
7770     return Incompatible;
7771   }
7772
7773   // Conversions from pointers that are not covered by the above.
7774   if (isa<PointerType>(RHSType)) {
7775     // T* -> _Bool
7776     if (LHSType == Context.BoolTy) {
7777       Kind = CK_PointerToBoolean;
7778       return Compatible;
7779     }
7780
7781     // T* -> int
7782     if (LHSType->isIntegerType()) {
7783       Kind = CK_PointerToIntegral;
7784       return PointerToInt;
7785     }
7786
7787     return Incompatible;
7788   }
7789
7790   // Conversions from Objective-C pointers that are not covered by the above.
7791   if (isa<ObjCObjectPointerType>(RHSType)) {
7792     // T* -> _Bool
7793     if (LHSType == Context.BoolTy) {
7794       Kind = CK_PointerToBoolean;
7795       return Compatible;
7796     }
7797
7798     // T* -> int
7799     if (LHSType->isIntegerType()) {
7800       Kind = CK_PointerToIntegral;
7801       return PointerToInt;
7802     }
7803
7804     return Incompatible;
7805   }
7806
7807   // struct A -> struct B
7808   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7809     if (Context.typesAreCompatible(LHSType, RHSType)) {
7810       Kind = CK_NoOp;
7811       return Compatible;
7812     }
7813   }
7814
7815   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7816     Kind = CK_IntToOCLSampler;
7817     return Compatible;
7818   }
7819
7820   return Incompatible;
7821 }
7822
7823 /// \brief Constructs a transparent union from an expression that is
7824 /// used to initialize the transparent union.
7825 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7826                                       ExprResult &EResult, QualType UnionType,
7827                                       FieldDecl *Field) {
7828   // Build an initializer list that designates the appropriate member
7829   // of the transparent union.
7830   Expr *E = EResult.get();
7831   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7832                                                    E, SourceLocation());
7833   Initializer->setType(UnionType);
7834   Initializer->setInitializedFieldInUnion(Field);
7835
7836   // Build a compound literal constructing a value of the transparent
7837   // union type from this initializer list.
7838   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7839   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7840                                         VK_RValue, Initializer, false);
7841 }
7842
7843 Sema::AssignConvertType
7844 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7845                                                ExprResult &RHS) {
7846   QualType RHSType = RHS.get()->getType();
7847
7848   // If the ArgType is a Union type, we want to handle a potential
7849   // transparent_union GCC extension.
7850   const RecordType *UT = ArgType->getAsUnionType();
7851   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7852     return Incompatible;
7853
7854   // The field to initialize within the transparent union.
7855   RecordDecl *UD = UT->getDecl();
7856   FieldDecl *InitField = nullptr;
7857   // It's compatible if the expression matches any of the fields.
7858   for (auto *it : UD->fields()) {
7859     if (it->getType()->isPointerType()) {
7860       // If the transparent union contains a pointer type, we allow:
7861       // 1) void pointer
7862       // 2) null pointer constant
7863       if (RHSType->isPointerType())
7864         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7865           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7866           InitField = it;
7867           break;
7868         }
7869
7870       if (RHS.get()->isNullPointerConstant(Context,
7871                                            Expr::NPC_ValueDependentIsNull)) {
7872         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7873                                 CK_NullToPointer);
7874         InitField = it;
7875         break;
7876       }
7877     }
7878
7879     CastKind Kind = CK_Invalid;
7880     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7881           == Compatible) {
7882       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7883       InitField = it;
7884       break;
7885     }
7886   }
7887
7888   if (!InitField)
7889     return Incompatible;
7890
7891   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7892   return Compatible;
7893 }
7894
7895 Sema::AssignConvertType
7896 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7897                                        bool Diagnose,
7898                                        bool DiagnoseCFAudited,
7899                                        bool ConvertRHS) {
7900   // We need to be able to tell the caller whether we diagnosed a problem, if
7901   // they ask us to issue diagnostics.
7902   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7903
7904   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7905   // we can't avoid *all* modifications at the moment, so we need some somewhere
7906   // to put the updated value.
7907   ExprResult LocalRHS = CallerRHS;
7908   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7909
7910   if (getLangOpts().CPlusPlus) {
7911     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7912       // C++ 5.17p3: If the left operand is not of class type, the
7913       // expression is implicitly converted (C++ 4) to the
7914       // cv-unqualified type of the left operand.
7915       QualType RHSType = RHS.get()->getType();
7916       if (Diagnose) {
7917         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7918                                         AA_Assigning);
7919       } else {
7920         ImplicitConversionSequence ICS =
7921             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7922                                   /*SuppressUserConversions=*/false,
7923                                   /*AllowExplicit=*/false,
7924                                   /*InOverloadResolution=*/false,
7925                                   /*CStyle=*/false,
7926                                   /*AllowObjCWritebackConversion=*/false);
7927         if (ICS.isFailure())
7928           return Incompatible;
7929         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7930                                         ICS, AA_Assigning);
7931       }
7932       if (RHS.isInvalid())
7933         return Incompatible;
7934       Sema::AssignConvertType result = Compatible;
7935       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7936           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7937         result = IncompatibleObjCWeakRef;
7938       return result;
7939     }
7940
7941     // FIXME: Currently, we fall through and treat C++ classes like C
7942     // structures.
7943     // FIXME: We also fall through for atomics; not sure what should
7944     // happen there, though.
7945   } else if (RHS.get()->getType() == Context.OverloadTy) {
7946     // As a set of extensions to C, we support overloading on functions. These
7947     // functions need to be resolved here.
7948     DeclAccessPair DAP;
7949     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7950             RHS.get(), LHSType, /*Complain=*/false, DAP))
7951       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7952     else
7953       return Incompatible;
7954   }
7955
7956   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7957   // a null pointer constant.
7958   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7959        LHSType->isBlockPointerType()) &&
7960       RHS.get()->isNullPointerConstant(Context,
7961                                        Expr::NPC_ValueDependentIsNull)) {
7962     if (Diagnose || ConvertRHS) {
7963       CastKind Kind;
7964       CXXCastPath Path;
7965       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7966                              /*IgnoreBaseAccess=*/false, Diagnose);
7967       if (ConvertRHS)
7968         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7969     }
7970     return Compatible;
7971   }
7972
7973   // This check seems unnatural, however it is necessary to ensure the proper
7974   // conversion of functions/arrays. If the conversion were done for all
7975   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7976   // expressions that suppress this implicit conversion (&, sizeof).
7977   //
7978   // Suppress this for references: C++ 8.5.3p5.
7979   if (!LHSType->isReferenceType()) {
7980     // FIXME: We potentially allocate here even if ConvertRHS is false.
7981     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7982     if (RHS.isInvalid())
7983       return Incompatible;
7984   }
7985
7986   Expr *PRE = RHS.get()->IgnoreParenCasts();
7987   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7988     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7989     if (PDecl && !PDecl->hasDefinition()) {
7990       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7991       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7992     }
7993   }
7994   
7995   CastKind Kind = CK_Invalid;
7996   Sema::AssignConvertType result =
7997     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7998
7999   // C99 6.5.16.1p2: The value of the right operand is converted to the
8000   // type of the assignment expression.
8001   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8002   // so that we can use references in built-in functions even in C.
8003   // The getNonReferenceType() call makes sure that the resulting expression
8004   // does not have reference type.
8005   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8006     QualType Ty = LHSType.getNonLValueExprType(Context);
8007     Expr *E = RHS.get();
8008
8009     // Check for various Objective-C errors. If we are not reporting
8010     // diagnostics and just checking for errors, e.g., during overload
8011     // resolution, return Incompatible to indicate the failure.
8012     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8013         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8014                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8015       if (!Diagnose)
8016         return Incompatible;
8017     }
8018     if (getLangOpts().ObjC1 &&
8019         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
8020                                            E->getType(), E, Diagnose) ||
8021          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8022       if (!Diagnose)
8023         return Incompatible;
8024       // Replace the expression with a corrected version and continue so we
8025       // can find further errors.
8026       RHS = E;
8027       return Compatible;
8028     }
8029     
8030     if (ConvertRHS)
8031       RHS = ImpCastExprToType(E, Ty, Kind);
8032   }
8033   return result;
8034 }
8035
8036 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8037                                ExprResult &RHS) {
8038   Diag(Loc, diag::err_typecheck_invalid_operands)
8039     << LHS.get()->getType() << RHS.get()->getType()
8040     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8041   return QualType();
8042 }
8043
8044 // Diagnose cases where a scalar was implicitly converted to a vector and
8045 // diagnose the underlying types. Otherwise, diagnose the error
8046 // as invalid vector logical operands for non-C++ cases.
8047 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8048                                             ExprResult &RHS) {
8049   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8050   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8051
8052   bool LHSNatVec = LHSType->isVectorType();
8053   bool RHSNatVec = RHSType->isVectorType();
8054
8055   if (!(LHSNatVec && RHSNatVec)) {
8056     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8057     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8058     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8059         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8060         << Vector->getSourceRange();
8061     return QualType();
8062   }
8063
8064   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8065       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8066       << RHS.get()->getSourceRange();
8067
8068   return QualType();
8069 }
8070
8071 /// Try to convert a value of non-vector type to a vector type by converting
8072 /// the type to the element type of the vector and then performing a splat.
8073 /// If the language is OpenCL, we only use conversions that promote scalar
8074 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8075 /// for float->int.
8076 ///
8077 /// \param scalar - if non-null, actually perform the conversions
8078 /// \return true if the operation fails (but without diagnosing the failure)
8079 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8080                                      QualType scalarTy,
8081                                      QualType vectorEltTy,
8082                                      QualType vectorTy) {
8083   // The conversion to apply to the scalar before splatting it,
8084   // if necessary.
8085   CastKind scalarCast = CK_Invalid;
8086   
8087   if (vectorEltTy->isIntegralType(S.Context)) {
8088     if (!scalarTy->isIntegralType(S.Context))
8089       return true;
8090     if (S.getLangOpts().OpenCL &&
8091         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
8092       return true;
8093     scalarCast = CK_IntegralCast;
8094   } else if (vectorEltTy->isRealFloatingType()) {
8095     if (scalarTy->isRealFloatingType()) {
8096       if (S.getLangOpts().OpenCL &&
8097           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
8098         return true;
8099       scalarCast = CK_FloatingCast;
8100     }
8101     else if (scalarTy->isIntegralType(S.Context))
8102       scalarCast = CK_IntegralToFloating;
8103     else
8104       return true;
8105   } else {
8106     return true;
8107   }
8108
8109   // Adjust scalar if desired.
8110   if (scalar) {
8111     if (scalarCast != CK_Invalid)
8112       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8113     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8114   }
8115   return false;
8116 }
8117
8118 /// Test if a (constant) integer Int can be casted to another integer type
8119 /// IntTy without losing precision.
8120 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8121                                       QualType OtherIntTy) {
8122   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8123
8124   // Reject cases where the value of the Int is unknown as that would
8125   // possibly cause truncation, but accept cases where the scalar can be
8126   // demoted without loss of precision.
8127   llvm::APSInt Result;
8128   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8129   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8130   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8131   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8132
8133   if (CstInt) {
8134     // If the scalar is constant and is of a higher order and has more active
8135     // bits that the vector element type, reject it.
8136     unsigned NumBits = IntSigned
8137                            ? (Result.isNegative() ? Result.getMinSignedBits()
8138                                                   : Result.getActiveBits())
8139                            : Result.getActiveBits();
8140     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8141       return true;
8142
8143     // If the signedness of the scalar type and the vector element type
8144     // differs and the number of bits is greater than that of the vector
8145     // element reject it.
8146     return (IntSigned != OtherIntSigned &&
8147             NumBits > S.Context.getIntWidth(OtherIntTy));
8148   }
8149
8150   // Reject cases where the value of the scalar is not constant and it's
8151   // order is greater than that of the vector element type.
8152   return (Order < 0);
8153 }
8154
8155 /// Test if a (constant) integer Int can be casted to floating point type
8156 /// FloatTy without losing precision.
8157 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8158                                      QualType FloatTy) {
8159   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8160
8161   // Determine if the integer constant can be expressed as a floating point
8162   // number of the appropiate type.
8163   llvm::APSInt Result;
8164   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8165   uint64_t Bits = 0;
8166   if (CstInt) {
8167     // Reject constants that would be truncated if they were converted to
8168     // the floating point type. Test by simple to/from conversion.
8169     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8170     //        could be avoided if there was a convertFromAPInt method
8171     //        which could signal back if implicit truncation occurred.
8172     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8173     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8174                            llvm::APFloat::rmTowardZero);
8175     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8176                              !IntTy->hasSignedIntegerRepresentation());
8177     bool Ignored = false;
8178     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8179                            &Ignored);
8180     if (Result != ConvertBack)
8181       return true;
8182   } else {
8183     // Reject types that cannot be fully encoded into the mantissa of
8184     // the float.
8185     Bits = S.Context.getTypeSize(IntTy);
8186     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8187         S.Context.getFloatTypeSemantics(FloatTy));
8188     if (Bits > FloatPrec)
8189       return true;
8190   }
8191
8192   return false;
8193 }
8194
8195 /// Attempt to convert and splat Scalar into a vector whose types matches
8196 /// Vector following GCC conversion rules. The rule is that implicit
8197 /// conversion can occur when Scalar can be casted to match Vector's element
8198 /// type without causing truncation of Scalar.
8199 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8200                                         ExprResult *Vector) {
8201   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8202   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8203   const VectorType *VT = VectorTy->getAs<VectorType>();
8204
8205   assert(!isa<ExtVectorType>(VT) &&
8206          "ExtVectorTypes should not be handled here!");
8207
8208   QualType VectorEltTy = VT->getElementType();
8209
8210   // Reject cases where the vector element type or the scalar element type are
8211   // not integral or floating point types.
8212   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8213     return true;
8214
8215   // The conversion to apply to the scalar before splatting it,
8216   // if necessary.
8217   CastKind ScalarCast = CK_NoOp;
8218
8219   // Accept cases where the vector elements are integers and the scalar is
8220   // an integer.
8221   // FIXME: Notionally if the scalar was a floating point value with a precise
8222   //        integral representation, we could cast it to an appropriate integer
8223   //        type and then perform the rest of the checks here. GCC will perform
8224   //        this conversion in some cases as determined by the input language.
8225   //        We should accept it on a language independent basis.
8226   if (VectorEltTy->isIntegralType(S.Context) &&
8227       ScalarTy->isIntegralType(S.Context) &&
8228       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8229
8230     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8231       return true;
8232
8233     ScalarCast = CK_IntegralCast;
8234   } else if (VectorEltTy->isRealFloatingType()) {
8235     if (ScalarTy->isRealFloatingType()) {
8236
8237       // Reject cases where the scalar type is not a constant and has a higher
8238       // Order than the vector element type.
8239       llvm::APFloat Result(0.0);
8240       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8241       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8242       if (!CstScalar && Order < 0)
8243         return true;
8244
8245       // If the scalar cannot be safely casted to the vector element type,
8246       // reject it.
8247       if (CstScalar) {
8248         bool Truncated = false;
8249         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8250                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8251         if (Truncated)
8252           return true;
8253       }
8254
8255       ScalarCast = CK_FloatingCast;
8256     } else if (ScalarTy->isIntegralType(S.Context)) {
8257       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8258         return true;
8259
8260       ScalarCast = CK_IntegralToFloating;
8261     } else
8262       return true;
8263   }
8264
8265   // Adjust scalar if desired.
8266   if (Scalar) {
8267     if (ScalarCast != CK_NoOp)
8268       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8269     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8270   }
8271   return false;
8272 }
8273
8274 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8275                                    SourceLocation Loc, bool IsCompAssign,
8276                                    bool AllowBothBool,
8277                                    bool AllowBoolConversions) {
8278   if (!IsCompAssign) {
8279     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8280     if (LHS.isInvalid())
8281       return QualType();
8282   }
8283   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8284   if (RHS.isInvalid())
8285     return QualType();
8286
8287   // For conversion purposes, we ignore any qualifiers.
8288   // For example, "const float" and "float" are equivalent.
8289   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8290   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8291
8292   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8293   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8294   assert(LHSVecType || RHSVecType);
8295
8296   // AltiVec-style "vector bool op vector bool" combinations are allowed
8297   // for some operators but not others.
8298   if (!AllowBothBool &&
8299       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8300       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8301     return InvalidOperands(Loc, LHS, RHS);
8302
8303   // If the vector types are identical, return.
8304   if (Context.hasSameType(LHSType, RHSType))
8305     return LHSType;
8306
8307   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8308   if (LHSVecType && RHSVecType &&
8309       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8310     if (isa<ExtVectorType>(LHSVecType)) {
8311       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8312       return LHSType;
8313     }
8314
8315     if (!IsCompAssign)
8316       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8317     return RHSType;
8318   }
8319
8320   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8321   // can be mixed, with the result being the non-bool type.  The non-bool
8322   // operand must have integer element type.
8323   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8324       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8325       (Context.getTypeSize(LHSVecType->getElementType()) ==
8326        Context.getTypeSize(RHSVecType->getElementType()))) {
8327     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8328         LHSVecType->getElementType()->isIntegerType() &&
8329         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8330       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8331       return LHSType;
8332     }
8333     if (!IsCompAssign &&
8334         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8335         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8336         RHSVecType->getElementType()->isIntegerType()) {
8337       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8338       return RHSType;
8339     }
8340   }
8341
8342   // If there's a vector type and a scalar, try to convert the scalar to
8343   // the vector element type and splat.
8344   if (!RHSVecType) {
8345     if (isa<ExtVectorType>(LHSVecType)) {
8346       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8347                                     LHSVecType->getElementType(), LHSType))
8348         return LHSType;
8349     } else {
8350       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8351         return LHSType;
8352     }
8353   }
8354   if (!LHSVecType) {
8355     if (isa<ExtVectorType>(RHSVecType)) {
8356       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8357                                     LHSType, RHSVecType->getElementType(),
8358                                     RHSType))
8359         return RHSType;
8360     } else {
8361       if (LHS.get()->getValueKind() == VK_LValue ||
8362           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8363         return RHSType;
8364     }
8365   }
8366
8367   // FIXME: The code below also handles conversion between vectors and
8368   // non-scalars, we should break this down into fine grained specific checks
8369   // and emit proper diagnostics.
8370   QualType VecType = LHSVecType ? LHSType : RHSType;
8371   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8372   QualType OtherType = LHSVecType ? RHSType : LHSType;
8373   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8374   if (isLaxVectorConversion(OtherType, VecType)) {
8375     // If we're allowing lax vector conversions, only the total (data) size
8376     // needs to be the same. For non compound assignment, if one of the types is
8377     // scalar, the result is always the vector type.
8378     if (!IsCompAssign) {
8379       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8380       return VecType;
8381     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8382     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8383     // type. Note that this is already done by non-compound assignments in
8384     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8385     // <1 x T> -> T. The result is also a vector type.
8386     } else if (OtherType->isExtVectorType() ||
8387                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8388       ExprResult *RHSExpr = &RHS;
8389       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8390       return VecType;
8391     }
8392   }
8393
8394   // Okay, the expression is invalid.
8395
8396   // If there's a non-vector, non-real operand, diagnose that.
8397   if ((!RHSVecType && !RHSType->isRealType()) ||
8398       (!LHSVecType && !LHSType->isRealType())) {
8399     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8400       << LHSType << RHSType
8401       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8402     return QualType();
8403   }
8404
8405   // OpenCL V1.1 6.2.6.p1:
8406   // If the operands are of more than one vector type, then an error shall
8407   // occur. Implicit conversions between vector types are not permitted, per
8408   // section 6.2.1.
8409   if (getLangOpts().OpenCL &&
8410       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8411       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8412     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8413                                                            << RHSType;
8414     return QualType();
8415   }
8416
8417
8418   // If there is a vector type that is not a ExtVector and a scalar, we reach
8419   // this point if scalar could not be converted to the vector's element type
8420   // without truncation.
8421   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8422       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8423     QualType Scalar = LHSVecType ? RHSType : LHSType;
8424     QualType Vector = LHSVecType ? LHSType : RHSType;
8425     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8426     Diag(Loc,
8427          diag::err_typecheck_vector_not_convertable_implict_truncation)
8428         << ScalarOrVector << Scalar << Vector;
8429
8430     return QualType();
8431   }
8432
8433   // Otherwise, use the generic diagnostic.
8434   Diag(Loc, diag::err_typecheck_vector_not_convertable)
8435     << LHSType << RHSType
8436     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8437   return QualType();
8438 }
8439
8440 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8441 // expression.  These are mainly cases where the null pointer is used as an
8442 // integer instead of a pointer.
8443 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8444                                 SourceLocation Loc, bool IsCompare) {
8445   // The canonical way to check for a GNU null is with isNullPointerConstant,
8446   // but we use a bit of a hack here for speed; this is a relatively
8447   // hot path, and isNullPointerConstant is slow.
8448   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8449   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8450
8451   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8452
8453   // Avoid analyzing cases where the result will either be invalid (and
8454   // diagnosed as such) or entirely valid and not something to warn about.
8455   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8456       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8457     return;
8458
8459   // Comparison operations would not make sense with a null pointer no matter
8460   // what the other expression is.
8461   if (!IsCompare) {
8462     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8463         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8464         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8465     return;
8466   }
8467
8468   // The rest of the operations only make sense with a null pointer
8469   // if the other expression is a pointer.
8470   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8471       NonNullType->canDecayToPointerType())
8472     return;
8473
8474   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8475       << LHSNull /* LHS is NULL */ << NonNullType
8476       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8477 }
8478
8479 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8480                                                ExprResult &RHS,
8481                                                SourceLocation Loc, bool IsDiv) {
8482   // Check for division/remainder by zero.
8483   llvm::APSInt RHSValue;
8484   if (!RHS.get()->isValueDependent() &&
8485       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8486     S.DiagRuntimeBehavior(Loc, RHS.get(),
8487                           S.PDiag(diag::warn_remainder_division_by_zero)
8488                             << IsDiv << RHS.get()->getSourceRange());
8489 }
8490
8491 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8492                                            SourceLocation Loc,
8493                                            bool IsCompAssign, bool IsDiv) {
8494   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8495
8496   if (LHS.get()->getType()->isVectorType() ||
8497       RHS.get()->getType()->isVectorType())
8498     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8499                                /*AllowBothBool*/getLangOpts().AltiVec,
8500                                /*AllowBoolConversions*/false);
8501
8502   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8503   if (LHS.isInvalid() || RHS.isInvalid())
8504     return QualType();
8505
8506
8507   if (compType.isNull() || !compType->isArithmeticType())
8508     return InvalidOperands(Loc, LHS, RHS);
8509   if (IsDiv)
8510     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8511   return compType;
8512 }
8513
8514 QualType Sema::CheckRemainderOperands(
8515   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8516   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8517
8518   if (LHS.get()->getType()->isVectorType() ||
8519       RHS.get()->getType()->isVectorType()) {
8520     if (LHS.get()->getType()->hasIntegerRepresentation() && 
8521         RHS.get()->getType()->hasIntegerRepresentation())
8522       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8523                                  /*AllowBothBool*/getLangOpts().AltiVec,
8524                                  /*AllowBoolConversions*/false);
8525     return InvalidOperands(Loc, LHS, RHS);
8526   }
8527
8528   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8529   if (LHS.isInvalid() || RHS.isInvalid())
8530     return QualType();
8531
8532   if (compType.isNull() || !compType->isIntegerType())
8533     return InvalidOperands(Loc, LHS, RHS);
8534   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8535   return compType;
8536 }
8537
8538 /// \brief Diagnose invalid arithmetic on two void pointers.
8539 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8540                                                 Expr *LHSExpr, Expr *RHSExpr) {
8541   S.Diag(Loc, S.getLangOpts().CPlusPlus
8542                 ? diag::err_typecheck_pointer_arith_void_type
8543                 : diag::ext_gnu_void_ptr)
8544     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8545                             << RHSExpr->getSourceRange();
8546 }
8547
8548 /// \brief Diagnose invalid arithmetic on a void pointer.
8549 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8550                                             Expr *Pointer) {
8551   S.Diag(Loc, S.getLangOpts().CPlusPlus
8552                 ? diag::err_typecheck_pointer_arith_void_type
8553                 : diag::ext_gnu_void_ptr)
8554     << 0 /* one pointer */ << Pointer->getSourceRange();
8555 }
8556
8557 /// \brief Diagnose invalid arithmetic on two function pointers.
8558 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8559                                                     Expr *LHS, Expr *RHS) {
8560   assert(LHS->getType()->isAnyPointerType());
8561   assert(RHS->getType()->isAnyPointerType());
8562   S.Diag(Loc, S.getLangOpts().CPlusPlus
8563                 ? diag::err_typecheck_pointer_arith_function_type
8564                 : diag::ext_gnu_ptr_func_arith)
8565     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8566     // We only show the second type if it differs from the first.
8567     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8568                                                    RHS->getType())
8569     << RHS->getType()->getPointeeType()
8570     << LHS->getSourceRange() << RHS->getSourceRange();
8571 }
8572
8573 /// \brief Diagnose invalid arithmetic on a function pointer.
8574 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8575                                                 Expr *Pointer) {
8576   assert(Pointer->getType()->isAnyPointerType());
8577   S.Diag(Loc, S.getLangOpts().CPlusPlus
8578                 ? diag::err_typecheck_pointer_arith_function_type
8579                 : diag::ext_gnu_ptr_func_arith)
8580     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8581     << 0 /* one pointer, so only one type */
8582     << Pointer->getSourceRange();
8583 }
8584
8585 /// \brief Emit error if Operand is incomplete pointer type
8586 ///
8587 /// \returns True if pointer has incomplete type
8588 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8589                                                  Expr *Operand) {
8590   QualType ResType = Operand->getType();
8591   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8592     ResType = ResAtomicType->getValueType();
8593
8594   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8595   QualType PointeeTy = ResType->getPointeeType();
8596   return S.RequireCompleteType(Loc, PointeeTy,
8597                                diag::err_typecheck_arithmetic_incomplete_type,
8598                                PointeeTy, Operand->getSourceRange());
8599 }
8600
8601 /// \brief Check the validity of an arithmetic pointer operand.
8602 ///
8603 /// If the operand has pointer type, this code will check for pointer types
8604 /// which are invalid in arithmetic operations. These will be diagnosed
8605 /// appropriately, including whether or not the use is supported as an
8606 /// extension.
8607 ///
8608 /// \returns True when the operand is valid to use (even if as an extension).
8609 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8610                                             Expr *Operand) {
8611   QualType ResType = Operand->getType();
8612   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8613     ResType = ResAtomicType->getValueType();
8614
8615   if (!ResType->isAnyPointerType()) return true;
8616
8617   QualType PointeeTy = ResType->getPointeeType();
8618   if (PointeeTy->isVoidType()) {
8619     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8620     return !S.getLangOpts().CPlusPlus;
8621   }
8622   if (PointeeTy->isFunctionType()) {
8623     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8624     return !S.getLangOpts().CPlusPlus;
8625   }
8626
8627   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8628
8629   return true;
8630 }
8631
8632 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8633 /// operands.
8634 ///
8635 /// This routine will diagnose any invalid arithmetic on pointer operands much
8636 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8637 /// for emitting a single diagnostic even for operations where both LHS and RHS
8638 /// are (potentially problematic) pointers.
8639 ///
8640 /// \returns True when the operand is valid to use (even if as an extension).
8641 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8642                                                 Expr *LHSExpr, Expr *RHSExpr) {
8643   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8644   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8645   if (!isLHSPointer && !isRHSPointer) return true;
8646
8647   QualType LHSPointeeTy, RHSPointeeTy;
8648   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8649   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8650
8651   // if both are pointers check if operation is valid wrt address spaces
8652   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8653     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8654     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8655     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8656       S.Diag(Loc,
8657              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8658           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8659           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8660       return false;
8661     }
8662   }
8663
8664   // Check for arithmetic on pointers to incomplete types.
8665   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8666   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8667   if (isLHSVoidPtr || isRHSVoidPtr) {
8668     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8669     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8670     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8671
8672     return !S.getLangOpts().CPlusPlus;
8673   }
8674
8675   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8676   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8677   if (isLHSFuncPtr || isRHSFuncPtr) {
8678     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8679     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8680                                                                 RHSExpr);
8681     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8682
8683     return !S.getLangOpts().CPlusPlus;
8684   }
8685
8686   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8687     return false;
8688   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8689     return false;
8690
8691   return true;
8692 }
8693
8694 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8695 /// literal.
8696 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8697                                   Expr *LHSExpr, Expr *RHSExpr) {
8698   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8699   Expr* IndexExpr = RHSExpr;
8700   if (!StrExpr) {
8701     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8702     IndexExpr = LHSExpr;
8703   }
8704
8705   bool IsStringPlusInt = StrExpr &&
8706       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8707   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8708     return;
8709
8710   llvm::APSInt index;
8711   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8712     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8713     if (index.isNonNegative() &&
8714         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8715                               index.isUnsigned()))
8716       return;
8717   }
8718
8719   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8720   Self.Diag(OpLoc, diag::warn_string_plus_int)
8721       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8722
8723   // Only print a fixit for "str" + int, not for int + "str".
8724   if (IndexExpr == RHSExpr) {
8725     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8726     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8727         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8728         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8729         << FixItHint::CreateInsertion(EndLoc, "]");
8730   } else
8731     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8732 }
8733
8734 /// \brief Emit a warning when adding a char literal to a string.
8735 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8736                                    Expr *LHSExpr, Expr *RHSExpr) {
8737   const Expr *StringRefExpr = LHSExpr;
8738   const CharacterLiteral *CharExpr =
8739       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8740
8741   if (!CharExpr) {
8742     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8743     StringRefExpr = RHSExpr;
8744   }
8745
8746   if (!CharExpr || !StringRefExpr)
8747     return;
8748
8749   const QualType StringType = StringRefExpr->getType();
8750
8751   // Return if not a PointerType.
8752   if (!StringType->isAnyPointerType())
8753     return;
8754
8755   // Return if not a CharacterType.
8756   if (!StringType->getPointeeType()->isAnyCharacterType())
8757     return;
8758
8759   ASTContext &Ctx = Self.getASTContext();
8760   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8761
8762   const QualType CharType = CharExpr->getType();
8763   if (!CharType->isAnyCharacterType() &&
8764       CharType->isIntegerType() &&
8765       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8766     Self.Diag(OpLoc, diag::warn_string_plus_char)
8767         << DiagRange << Ctx.CharTy;
8768   } else {
8769     Self.Diag(OpLoc, diag::warn_string_plus_char)
8770         << DiagRange << CharExpr->getType();
8771   }
8772
8773   // Only print a fixit for str + char, not for char + str.
8774   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8775     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8776     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8777         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8778         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8779         << FixItHint::CreateInsertion(EndLoc, "]");
8780   } else {
8781     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8782   }
8783 }
8784
8785 /// \brief Emit error when two pointers are incompatible.
8786 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8787                                            Expr *LHSExpr, Expr *RHSExpr) {
8788   assert(LHSExpr->getType()->isAnyPointerType());
8789   assert(RHSExpr->getType()->isAnyPointerType());
8790   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8791     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8792     << RHSExpr->getSourceRange();
8793 }
8794
8795 // C99 6.5.6
8796 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8797                                      SourceLocation Loc, BinaryOperatorKind Opc,
8798                                      QualType* CompLHSTy) {
8799   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8800
8801   if (LHS.get()->getType()->isVectorType() ||
8802       RHS.get()->getType()->isVectorType()) {
8803     QualType compType = CheckVectorOperands(
8804         LHS, RHS, Loc, CompLHSTy,
8805         /*AllowBothBool*/getLangOpts().AltiVec,
8806         /*AllowBoolConversions*/getLangOpts().ZVector);
8807     if (CompLHSTy) *CompLHSTy = compType;
8808     return compType;
8809   }
8810
8811   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8812   if (LHS.isInvalid() || RHS.isInvalid())
8813     return QualType();
8814
8815   // Diagnose "string literal" '+' int and string '+' "char literal".
8816   if (Opc == BO_Add) {
8817     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8818     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8819   }
8820
8821   // handle the common case first (both operands are arithmetic).
8822   if (!compType.isNull() && compType->isArithmeticType()) {
8823     if (CompLHSTy) *CompLHSTy = compType;
8824     return compType;
8825   }
8826
8827   // Type-checking.  Ultimately the pointer's going to be in PExp;
8828   // note that we bias towards the LHS being the pointer.
8829   Expr *PExp = LHS.get(), *IExp = RHS.get();
8830
8831   bool isObjCPointer;
8832   if (PExp->getType()->isPointerType()) {
8833     isObjCPointer = false;
8834   } else if (PExp->getType()->isObjCObjectPointerType()) {
8835     isObjCPointer = true;
8836   } else {
8837     std::swap(PExp, IExp);
8838     if (PExp->getType()->isPointerType()) {
8839       isObjCPointer = false;
8840     } else if (PExp->getType()->isObjCObjectPointerType()) {
8841       isObjCPointer = true;
8842     } else {
8843       return InvalidOperands(Loc, LHS, RHS);
8844     }
8845   }
8846   assert(PExp->getType()->isAnyPointerType());
8847
8848   if (!IExp->getType()->isIntegerType())
8849     return InvalidOperands(Loc, LHS, RHS);
8850
8851   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8852     return QualType();
8853
8854   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8855     return QualType();
8856
8857   // Check array bounds for pointer arithemtic
8858   CheckArrayAccess(PExp, IExp);
8859
8860   if (CompLHSTy) {
8861     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8862     if (LHSTy.isNull()) {
8863       LHSTy = LHS.get()->getType();
8864       if (LHSTy->isPromotableIntegerType())
8865         LHSTy = Context.getPromotedIntegerType(LHSTy);
8866     }
8867     *CompLHSTy = LHSTy;
8868   }
8869
8870   return PExp->getType();
8871 }
8872
8873 // C99 6.5.6
8874 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8875                                         SourceLocation Loc,
8876                                         QualType* CompLHSTy) {
8877   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8878
8879   if (LHS.get()->getType()->isVectorType() ||
8880       RHS.get()->getType()->isVectorType()) {
8881     QualType compType = CheckVectorOperands(
8882         LHS, RHS, Loc, CompLHSTy,
8883         /*AllowBothBool*/getLangOpts().AltiVec,
8884         /*AllowBoolConversions*/getLangOpts().ZVector);
8885     if (CompLHSTy) *CompLHSTy = compType;
8886     return compType;
8887   }
8888
8889   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8890   if (LHS.isInvalid() || RHS.isInvalid())
8891     return QualType();
8892
8893   // Enforce type constraints: C99 6.5.6p3.
8894
8895   // Handle the common case first (both operands are arithmetic).
8896   if (!compType.isNull() && compType->isArithmeticType()) {
8897     if (CompLHSTy) *CompLHSTy = compType;
8898     return compType;
8899   }
8900
8901   // Either ptr - int   or   ptr - ptr.
8902   if (LHS.get()->getType()->isAnyPointerType()) {
8903     QualType lpointee = LHS.get()->getType()->getPointeeType();
8904
8905     // Diagnose bad cases where we step over interface counts.
8906     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8907         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8908       return QualType();
8909
8910     // The result type of a pointer-int computation is the pointer type.
8911     if (RHS.get()->getType()->isIntegerType()) {
8912       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8913         return QualType();
8914
8915       // Check array bounds for pointer arithemtic
8916       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8917                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8918
8919       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8920       return LHS.get()->getType();
8921     }
8922
8923     // Handle pointer-pointer subtractions.
8924     if (const PointerType *RHSPTy
8925           = RHS.get()->getType()->getAs<PointerType>()) {
8926       QualType rpointee = RHSPTy->getPointeeType();
8927
8928       if (getLangOpts().CPlusPlus) {
8929         // Pointee types must be the same: C++ [expr.add]
8930         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8931           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8932         }
8933       } else {
8934         // Pointee types must be compatible C99 6.5.6p3
8935         if (!Context.typesAreCompatible(
8936                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8937                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8938           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8939           return QualType();
8940         }
8941       }
8942
8943       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8944                                                LHS.get(), RHS.get()))
8945         return QualType();
8946
8947       // The pointee type may have zero size.  As an extension, a structure or
8948       // union may have zero size or an array may have zero length.  In this
8949       // case subtraction does not make sense.
8950       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8951         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8952         if (ElementSize.isZero()) {
8953           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8954             << rpointee.getUnqualifiedType()
8955             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8956         }
8957       }
8958
8959       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8960       return Context.getPointerDiffType();
8961     }
8962   }
8963
8964   return InvalidOperands(Loc, LHS, RHS);
8965 }
8966
8967 static bool isScopedEnumerationType(QualType T) {
8968   if (const EnumType *ET = T->getAs<EnumType>())
8969     return ET->getDecl()->isScoped();
8970   return false;
8971 }
8972
8973 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8974                                    SourceLocation Loc, BinaryOperatorKind Opc,
8975                                    QualType LHSType) {
8976   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8977   // so skip remaining warnings as we don't want to modify values within Sema.
8978   if (S.getLangOpts().OpenCL)
8979     return;
8980
8981   llvm::APSInt Right;
8982   // Check right/shifter operand
8983   if (RHS.get()->isValueDependent() ||
8984       !RHS.get()->EvaluateAsInt(Right, S.Context))
8985     return;
8986
8987   if (Right.isNegative()) {
8988     S.DiagRuntimeBehavior(Loc, RHS.get(),
8989                           S.PDiag(diag::warn_shift_negative)
8990                             << RHS.get()->getSourceRange());
8991     return;
8992   }
8993   llvm::APInt LeftBits(Right.getBitWidth(),
8994                        S.Context.getTypeSize(LHS.get()->getType()));
8995   if (Right.uge(LeftBits)) {
8996     S.DiagRuntimeBehavior(Loc, RHS.get(),
8997                           S.PDiag(diag::warn_shift_gt_typewidth)
8998                             << RHS.get()->getSourceRange());
8999     return;
9000   }
9001   if (Opc != BO_Shl)
9002     return;
9003
9004   // When left shifting an ICE which is signed, we can check for overflow which
9005   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9006   // integers have defined behavior modulo one more than the maximum value
9007   // representable in the result type, so never warn for those.
9008   llvm::APSInt Left;
9009   if (LHS.get()->isValueDependent() ||
9010       LHSType->hasUnsignedIntegerRepresentation() ||
9011       !LHS.get()->EvaluateAsInt(Left, S.Context))
9012     return;
9013
9014   // If LHS does not have a signed type and non-negative value
9015   // then, the behavior is undefined. Warn about it.
9016   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9017     S.DiagRuntimeBehavior(Loc, LHS.get(),
9018                           S.PDiag(diag::warn_shift_lhs_negative)
9019                             << LHS.get()->getSourceRange());
9020     return;
9021   }
9022
9023   llvm::APInt ResultBits =
9024       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9025   if (LeftBits.uge(ResultBits))
9026     return;
9027   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9028   Result = Result.shl(Right);
9029
9030   // Print the bit representation of the signed integer as an unsigned
9031   // hexadecimal number.
9032   SmallString<40> HexResult;
9033   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9034
9035   // If we are only missing a sign bit, this is less likely to result in actual
9036   // bugs -- if the result is cast back to an unsigned type, it will have the
9037   // expected value. Thus we place this behind a different warning that can be
9038   // turned off separately if needed.
9039   if (LeftBits == ResultBits - 1) {
9040     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9041         << HexResult << LHSType
9042         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9043     return;
9044   }
9045
9046   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9047     << HexResult.str() << Result.getMinSignedBits() << LHSType
9048     << Left.getBitWidth() << LHS.get()->getSourceRange()
9049     << RHS.get()->getSourceRange();
9050 }
9051
9052 /// \brief Return the resulting type when a vector is shifted
9053 ///        by a scalar or vector shift amount.
9054 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9055                                  SourceLocation Loc, bool IsCompAssign) {
9056   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9057   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9058       !LHS.get()->getType()->isVectorType()) {
9059     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9060       << RHS.get()->getType() << LHS.get()->getType()
9061       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9062     return QualType();
9063   }
9064
9065   if (!IsCompAssign) {
9066     LHS = S.UsualUnaryConversions(LHS.get());
9067     if (LHS.isInvalid()) return QualType();
9068   }
9069
9070   RHS = S.UsualUnaryConversions(RHS.get());
9071   if (RHS.isInvalid()) return QualType();
9072
9073   QualType LHSType = LHS.get()->getType();
9074   // Note that LHS might be a scalar because the routine calls not only in
9075   // OpenCL case.
9076   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9077   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9078
9079   // Note that RHS might not be a vector.
9080   QualType RHSType = RHS.get()->getType();
9081   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9082   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9083
9084   // The operands need to be integers.
9085   if (!LHSEleType->isIntegerType()) {
9086     S.Diag(Loc, diag::err_typecheck_expect_int)
9087       << LHS.get()->getType() << LHS.get()->getSourceRange();
9088     return QualType();
9089   }
9090
9091   if (!RHSEleType->isIntegerType()) {
9092     S.Diag(Loc, diag::err_typecheck_expect_int)
9093       << RHS.get()->getType() << RHS.get()->getSourceRange();
9094     return QualType();
9095   }
9096
9097   if (!LHSVecTy) {
9098     assert(RHSVecTy);
9099     if (IsCompAssign)
9100       return RHSType;
9101     if (LHSEleType != RHSEleType) {
9102       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9103       LHSEleType = RHSEleType;
9104     }
9105     QualType VecTy =
9106         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9107     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9108     LHSType = VecTy;
9109   } else if (RHSVecTy) {
9110     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9111     // are applied component-wise. So if RHS is a vector, then ensure
9112     // that the number of elements is the same as LHS...
9113     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9114       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9115         << LHS.get()->getType() << RHS.get()->getType()
9116         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9117       return QualType();
9118     }
9119     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9120       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9121       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9122       if (LHSBT != RHSBT &&
9123           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9124         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9125             << LHS.get()->getType() << RHS.get()->getType()
9126             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9127       }
9128     }
9129   } else {
9130     // ...else expand RHS to match the number of elements in LHS.
9131     QualType VecTy =
9132       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9133     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9134   }
9135
9136   return LHSType;
9137 }
9138
9139 // C99 6.5.7
9140 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9141                                   SourceLocation Loc, BinaryOperatorKind Opc,
9142                                   bool IsCompAssign) {
9143   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9144
9145   // Vector shifts promote their scalar inputs to vector type.
9146   if (LHS.get()->getType()->isVectorType() ||
9147       RHS.get()->getType()->isVectorType()) {
9148     if (LangOpts.ZVector) {
9149       // The shift operators for the z vector extensions work basically
9150       // like general shifts, except that neither the LHS nor the RHS is
9151       // allowed to be a "vector bool".
9152       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9153         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9154           return InvalidOperands(Loc, LHS, RHS);
9155       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9156         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9157           return InvalidOperands(Loc, LHS, RHS);
9158     }
9159     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9160   }
9161
9162   // Shifts don't perform usual arithmetic conversions, they just do integer
9163   // promotions on each operand. C99 6.5.7p3
9164
9165   // For the LHS, do usual unary conversions, but then reset them away
9166   // if this is a compound assignment.
9167   ExprResult OldLHS = LHS;
9168   LHS = UsualUnaryConversions(LHS.get());
9169   if (LHS.isInvalid())
9170     return QualType();
9171   QualType LHSType = LHS.get()->getType();
9172   if (IsCompAssign) LHS = OldLHS;
9173
9174   // The RHS is simpler.
9175   RHS = UsualUnaryConversions(RHS.get());
9176   if (RHS.isInvalid())
9177     return QualType();
9178   QualType RHSType = RHS.get()->getType();
9179
9180   // C99 6.5.7p2: Each of the operands shall have integer type.
9181   if (!LHSType->hasIntegerRepresentation() ||
9182       !RHSType->hasIntegerRepresentation())
9183     return InvalidOperands(Loc, LHS, RHS);
9184
9185   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9186   // hasIntegerRepresentation() above instead of this.
9187   if (isScopedEnumerationType(LHSType) ||
9188       isScopedEnumerationType(RHSType)) {
9189     return InvalidOperands(Loc, LHS, RHS);
9190   }
9191   // Sanity-check shift operands
9192   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9193
9194   // "The type of the result is that of the promoted left operand."
9195   return LHSType;
9196 }
9197
9198 static bool IsWithinTemplateSpecialization(Decl *D) {
9199   if (DeclContext *DC = D->getDeclContext()) {
9200     if (isa<ClassTemplateSpecializationDecl>(DC))
9201       return true;
9202     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
9203       return FD->isFunctionTemplateSpecialization();
9204   }
9205   return false;
9206 }
9207
9208 /// If two different enums are compared, raise a warning.
9209 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9210                                 Expr *RHS) {
9211   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9212   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9213
9214   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9215   if (!LHSEnumType)
9216     return;
9217   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9218   if (!RHSEnumType)
9219     return;
9220
9221   // Ignore anonymous enums.
9222   if (!LHSEnumType->getDecl()->getIdentifier())
9223     return;
9224   if (!RHSEnumType->getDecl()->getIdentifier())
9225     return;
9226
9227   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9228     return;
9229
9230   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9231       << LHSStrippedType << RHSStrippedType
9232       << LHS->getSourceRange() << RHS->getSourceRange();
9233 }
9234
9235 /// \brief Diagnose bad pointer comparisons.
9236 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9237                                               ExprResult &LHS, ExprResult &RHS,
9238                                               bool IsError) {
9239   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9240                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9241     << LHS.get()->getType() << RHS.get()->getType()
9242     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9243 }
9244
9245 /// \brief Returns false if the pointers are converted to a composite type,
9246 /// true otherwise.
9247 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9248                                            ExprResult &LHS, ExprResult &RHS) {
9249   // C++ [expr.rel]p2:
9250   //   [...] Pointer conversions (4.10) and qualification
9251   //   conversions (4.4) are performed on pointer operands (or on
9252   //   a pointer operand and a null pointer constant) to bring
9253   //   them to their composite pointer type. [...]
9254   //
9255   // C++ [expr.eq]p1 uses the same notion for (in)equality
9256   // comparisons of pointers.
9257
9258   QualType LHSType = LHS.get()->getType();
9259   QualType RHSType = RHS.get()->getType();
9260   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9261          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9262
9263   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9264   if (T.isNull()) {
9265     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9266         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9267       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9268     else
9269       S.InvalidOperands(Loc, LHS, RHS);
9270     return true;
9271   }
9272
9273   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9274   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9275   return false;
9276 }
9277
9278 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9279                                                     ExprResult &LHS,
9280                                                     ExprResult &RHS,
9281                                                     bool IsError) {
9282   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9283                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9284     << LHS.get()->getType() << RHS.get()->getType()
9285     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9286 }
9287
9288 static bool isObjCObjectLiteral(ExprResult &E) {
9289   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9290   case Stmt::ObjCArrayLiteralClass:
9291   case Stmt::ObjCDictionaryLiteralClass:
9292   case Stmt::ObjCStringLiteralClass:
9293   case Stmt::ObjCBoxedExprClass:
9294     return true;
9295   default:
9296     // Note that ObjCBoolLiteral is NOT an object literal!
9297     return false;
9298   }
9299 }
9300
9301 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9302   const ObjCObjectPointerType *Type =
9303     LHS->getType()->getAs<ObjCObjectPointerType>();
9304
9305   // If this is not actually an Objective-C object, bail out.
9306   if (!Type)
9307     return false;
9308
9309   // Get the LHS object's interface type.
9310   QualType InterfaceType = Type->getPointeeType();
9311
9312   // If the RHS isn't an Objective-C object, bail out.
9313   if (!RHS->getType()->isObjCObjectPointerType())
9314     return false;
9315
9316   // Try to find the -isEqual: method.
9317   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9318   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9319                                                       InterfaceType,
9320                                                       /*instance=*/true);
9321   if (!Method) {
9322     if (Type->isObjCIdType()) {
9323       // For 'id', just check the global pool.
9324       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9325                                                   /*receiverId=*/true);
9326     } else {
9327       // Check protocols.
9328       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9329                                              /*instance=*/true);
9330     }
9331   }
9332
9333   if (!Method)
9334     return false;
9335
9336   QualType T = Method->parameters()[0]->getType();
9337   if (!T->isObjCObjectPointerType())
9338     return false;
9339
9340   QualType R = Method->getReturnType();
9341   if (!R->isScalarType())
9342     return false;
9343
9344   return true;
9345 }
9346
9347 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9348   FromE = FromE->IgnoreParenImpCasts();
9349   switch (FromE->getStmtClass()) {
9350     default:
9351       break;
9352     case Stmt::ObjCStringLiteralClass:
9353       // "string literal"
9354       return LK_String;
9355     case Stmt::ObjCArrayLiteralClass:
9356       // "array literal"
9357       return LK_Array;
9358     case Stmt::ObjCDictionaryLiteralClass:
9359       // "dictionary literal"
9360       return LK_Dictionary;
9361     case Stmt::BlockExprClass:
9362       return LK_Block;
9363     case Stmt::ObjCBoxedExprClass: {
9364       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9365       switch (Inner->getStmtClass()) {
9366         case Stmt::IntegerLiteralClass:
9367         case Stmt::FloatingLiteralClass:
9368         case Stmt::CharacterLiteralClass:
9369         case Stmt::ObjCBoolLiteralExprClass:
9370         case Stmt::CXXBoolLiteralExprClass:
9371           // "numeric literal"
9372           return LK_Numeric;
9373         case Stmt::ImplicitCastExprClass: {
9374           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9375           // Boolean literals can be represented by implicit casts.
9376           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9377             return LK_Numeric;
9378           break;
9379         }
9380         default:
9381           break;
9382       }
9383       return LK_Boxed;
9384     }
9385   }
9386   return LK_None;
9387 }
9388
9389 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9390                                           ExprResult &LHS, ExprResult &RHS,
9391                                           BinaryOperator::Opcode Opc){
9392   Expr *Literal;
9393   Expr *Other;
9394   if (isObjCObjectLiteral(LHS)) {
9395     Literal = LHS.get();
9396     Other = RHS.get();
9397   } else {
9398     Literal = RHS.get();
9399     Other = LHS.get();
9400   }
9401
9402   // Don't warn on comparisons against nil.
9403   Other = Other->IgnoreParenCasts();
9404   if (Other->isNullPointerConstant(S.getASTContext(),
9405                                    Expr::NPC_ValueDependentIsNotNull))
9406     return;
9407
9408   // This should be kept in sync with warn_objc_literal_comparison.
9409   // LK_String should always be after the other literals, since it has its own
9410   // warning flag.
9411   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9412   assert(LiteralKind != Sema::LK_Block);
9413   if (LiteralKind == Sema::LK_None) {
9414     llvm_unreachable("Unknown Objective-C object literal kind");
9415   }
9416
9417   if (LiteralKind == Sema::LK_String)
9418     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9419       << Literal->getSourceRange();
9420   else
9421     S.Diag(Loc, diag::warn_objc_literal_comparison)
9422       << LiteralKind << Literal->getSourceRange();
9423
9424   if (BinaryOperator::isEqualityOp(Opc) &&
9425       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9426     SourceLocation Start = LHS.get()->getLocStart();
9427     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9428     CharSourceRange OpRange =
9429       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9430
9431     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9432       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9433       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9434       << FixItHint::CreateInsertion(End, "]");
9435   }
9436 }
9437
9438 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9439 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9440                                            ExprResult &RHS, SourceLocation Loc,
9441                                            BinaryOperatorKind Opc) {
9442   // Check that left hand side is !something.
9443   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9444   if (!UO || UO->getOpcode() != UO_LNot) return;
9445
9446   // Only check if the right hand side is non-bool arithmetic type.
9447   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9448
9449   // Make sure that the something in !something is not bool.
9450   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9451   if (SubExpr->isKnownToHaveBooleanValue()) return;
9452
9453   // Emit warning.
9454   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9455   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9456       << Loc << IsBitwiseOp;
9457
9458   // First note suggest !(x < y)
9459   SourceLocation FirstOpen = SubExpr->getLocStart();
9460   SourceLocation FirstClose = RHS.get()->getLocEnd();
9461   FirstClose = S.getLocForEndOfToken(FirstClose);
9462   if (FirstClose.isInvalid())
9463     FirstOpen = SourceLocation();
9464   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9465       << IsBitwiseOp
9466       << FixItHint::CreateInsertion(FirstOpen, "(")
9467       << FixItHint::CreateInsertion(FirstClose, ")");
9468
9469   // Second note suggests (!x) < y
9470   SourceLocation SecondOpen = LHS.get()->getLocStart();
9471   SourceLocation SecondClose = LHS.get()->getLocEnd();
9472   SecondClose = S.getLocForEndOfToken(SecondClose);
9473   if (SecondClose.isInvalid())
9474     SecondOpen = SourceLocation();
9475   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9476       << FixItHint::CreateInsertion(SecondOpen, "(")
9477       << FixItHint::CreateInsertion(SecondClose, ")");
9478 }
9479
9480 // Get the decl for a simple expression: a reference to a variable,
9481 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9482 static ValueDecl *getCompareDecl(Expr *E) {
9483   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9484     return DR->getDecl();
9485   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9486     if (Ivar->isFreeIvar())
9487       return Ivar->getDecl();
9488   }
9489   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9490     if (Mem->isImplicitAccess())
9491       return Mem->getMemberDecl();
9492   }
9493   return nullptr;
9494 }
9495
9496 // C99 6.5.8, C++ [expr.rel]
9497 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9498                                     SourceLocation Loc, BinaryOperatorKind Opc,
9499                                     bool IsRelational) {
9500   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9501
9502   // Handle vector comparisons separately.
9503   if (LHS.get()->getType()->isVectorType() ||
9504       RHS.get()->getType()->isVectorType())
9505     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9506
9507   QualType LHSType = LHS.get()->getType();
9508   QualType RHSType = RHS.get()->getType();
9509
9510   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9511   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9512
9513   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9514   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9515
9516   if (!LHSType->hasFloatingRepresentation() &&
9517       !(LHSType->isBlockPointerType() && IsRelational) &&
9518       !LHS.get()->getLocStart().isMacroID() &&
9519       !RHS.get()->getLocStart().isMacroID() &&
9520       !inTemplateInstantiation()) {
9521     // For non-floating point types, check for self-comparisons of the form
9522     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9523     // often indicate logic errors in the program.
9524     //
9525     // NOTE: Don't warn about comparison expressions resulting from macro
9526     // expansion. Also don't warn about comparisons which are only self
9527     // comparisons within a template specialization. The warnings should catch
9528     // obvious cases in the definition of the template anyways. The idea is to
9529     // warn when the typed comparison operator will always evaluate to the same
9530     // result.
9531     ValueDecl *DL = getCompareDecl(LHSStripped);
9532     ValueDecl *DR = getCompareDecl(RHSStripped);
9533     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9534       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9535                           << 0 // self-
9536                           << (Opc == BO_EQ
9537                               || Opc == BO_LE
9538                               || Opc == BO_GE));
9539     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9540                !DL->getType()->isReferenceType() &&
9541                !DR->getType()->isReferenceType()) {
9542         // what is it always going to eval to?
9543         char always_evals_to;
9544         switch(Opc) {
9545         case BO_EQ: // e.g. array1 == array2
9546           always_evals_to = 0; // false
9547           break;
9548         case BO_NE: // e.g. array1 != array2
9549           always_evals_to = 1; // true
9550           break;
9551         default:
9552           // best we can say is 'a constant'
9553           always_evals_to = 2; // e.g. array1 <= array2
9554           break;
9555         }
9556         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9557                             << 1 // array
9558                             << always_evals_to);
9559     }
9560
9561     if (isa<CastExpr>(LHSStripped))
9562       LHSStripped = LHSStripped->IgnoreParenCasts();
9563     if (isa<CastExpr>(RHSStripped))
9564       RHSStripped = RHSStripped->IgnoreParenCasts();
9565
9566     // Warn about comparisons against a string constant (unless the other
9567     // operand is null), the user probably wants strcmp.
9568     Expr *literalString = nullptr;
9569     Expr *literalStringStripped = nullptr;
9570     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9571         !RHSStripped->isNullPointerConstant(Context,
9572                                             Expr::NPC_ValueDependentIsNull)) {
9573       literalString = LHS.get();
9574       literalStringStripped = LHSStripped;
9575     } else if ((isa<StringLiteral>(RHSStripped) ||
9576                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9577                !LHSStripped->isNullPointerConstant(Context,
9578                                             Expr::NPC_ValueDependentIsNull)) {
9579       literalString = RHS.get();
9580       literalStringStripped = RHSStripped;
9581     }
9582
9583     if (literalString) {
9584       DiagRuntimeBehavior(Loc, nullptr,
9585         PDiag(diag::warn_stringcompare)
9586           << isa<ObjCEncodeExpr>(literalStringStripped)
9587           << literalString->getSourceRange());
9588     }
9589   }
9590
9591   // C99 6.5.8p3 / C99 6.5.9p4
9592   UsualArithmeticConversions(LHS, RHS);
9593   if (LHS.isInvalid() || RHS.isInvalid())
9594     return QualType();
9595
9596   LHSType = LHS.get()->getType();
9597   RHSType = RHS.get()->getType();
9598
9599   // The result of comparisons is 'bool' in C++, 'int' in C.
9600   QualType ResultTy = Context.getLogicalOperationType();
9601
9602   if (IsRelational) {
9603     if (LHSType->isRealType() && RHSType->isRealType())
9604       return ResultTy;
9605   } else {
9606     // Check for comparisons of floating point operands using != and ==.
9607     if (LHSType->hasFloatingRepresentation())
9608       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9609
9610     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9611       return ResultTy;
9612   }
9613
9614   const Expr::NullPointerConstantKind LHSNullKind =
9615       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9616   const Expr::NullPointerConstantKind RHSNullKind =
9617       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9618   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9619   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9620
9621   if (!IsRelational && LHSIsNull != RHSIsNull) {
9622     bool IsEquality = Opc == BO_EQ;
9623     if (RHSIsNull)
9624       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9625                                    RHS.get()->getSourceRange());
9626     else
9627       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9628                                    LHS.get()->getSourceRange());
9629   }
9630
9631   if ((LHSType->isIntegerType() && !LHSIsNull) ||
9632       (RHSType->isIntegerType() && !RHSIsNull)) {
9633     // Skip normal pointer conversion checks in this case; we have better
9634     // diagnostics for this below.
9635   } else if (getLangOpts().CPlusPlus) {
9636     // Equality comparison of a function pointer to a void pointer is invalid,
9637     // but we allow it as an extension.
9638     // FIXME: If we really want to allow this, should it be part of composite
9639     // pointer type computation so it works in conditionals too?
9640     if (!IsRelational &&
9641         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9642          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9643       // This is a gcc extension compatibility comparison.
9644       // In a SFINAE context, we treat this as a hard error to maintain
9645       // conformance with the C++ standard.
9646       diagnoseFunctionPointerToVoidComparison(
9647           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9648       
9649       if (isSFINAEContext())
9650         return QualType();
9651       
9652       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9653       return ResultTy;
9654     }
9655
9656     // C++ [expr.eq]p2:
9657     //   If at least one operand is a pointer [...] bring them to their
9658     //   composite pointer type.
9659     // C++ [expr.rel]p2:
9660     //   If both operands are pointers, [...] bring them to their composite
9661     //   pointer type.
9662     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9663             (IsRelational ? 2 : 1) &&
9664         (!LangOpts.ObjCAutoRefCount ||
9665          !(LHSType->isObjCObjectPointerType() ||
9666            RHSType->isObjCObjectPointerType()))) {
9667       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9668         return QualType();
9669       else
9670         return ResultTy;
9671     }
9672   } else if (LHSType->isPointerType() &&
9673              RHSType->isPointerType()) { // C99 6.5.8p2
9674     // All of the following pointer-related warnings are GCC extensions, except
9675     // when handling null pointer constants.
9676     QualType LCanPointeeTy =
9677       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9678     QualType RCanPointeeTy =
9679       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9680
9681     // C99 6.5.9p2 and C99 6.5.8p2
9682     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9683                                    RCanPointeeTy.getUnqualifiedType())) {
9684       // Valid unless a relational comparison of function pointers
9685       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9686         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9687           << LHSType << RHSType << LHS.get()->getSourceRange()
9688           << RHS.get()->getSourceRange();
9689       }
9690     } else if (!IsRelational &&
9691                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9692       // Valid unless comparison between non-null pointer and function pointer
9693       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9694           && !LHSIsNull && !RHSIsNull)
9695         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9696                                                 /*isError*/false);
9697     } else {
9698       // Invalid
9699       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9700     }
9701     if (LCanPointeeTy != RCanPointeeTy) {
9702       // Treat NULL constant as a special case in OpenCL.
9703       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9704         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9705         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9706           Diag(Loc,
9707                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9708               << LHSType << RHSType << 0 /* comparison */
9709               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9710         }
9711       }
9712       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9713       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9714       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9715                                                : CK_BitCast;
9716       if (LHSIsNull && !RHSIsNull)
9717         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9718       else
9719         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9720     }
9721     return ResultTy;
9722   }
9723
9724   if (getLangOpts().CPlusPlus) {
9725     // C++ [expr.eq]p4:
9726     //   Two operands of type std::nullptr_t or one operand of type
9727     //   std::nullptr_t and the other a null pointer constant compare equal.
9728     if (!IsRelational && LHSIsNull && RHSIsNull) {
9729       if (LHSType->isNullPtrType()) {
9730         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9731         return ResultTy;
9732       }
9733       if (RHSType->isNullPtrType()) {
9734         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9735         return ResultTy;
9736       }
9737     }
9738
9739     // Comparison of Objective-C pointers and block pointers against nullptr_t.
9740     // These aren't covered by the composite pointer type rules.
9741     if (!IsRelational && RHSType->isNullPtrType() &&
9742         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9743       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9744       return ResultTy;
9745     }
9746     if (!IsRelational && LHSType->isNullPtrType() &&
9747         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9748       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9749       return ResultTy;
9750     }
9751
9752     if (IsRelational &&
9753         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9754          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9755       // HACK: Relational comparison of nullptr_t against a pointer type is
9756       // invalid per DR583, but we allow it within std::less<> and friends,
9757       // since otherwise common uses of it break.
9758       // FIXME: Consider removing this hack once LWG fixes std::less<> and
9759       // friends to have std::nullptr_t overload candidates.
9760       DeclContext *DC = CurContext;
9761       if (isa<FunctionDecl>(DC))
9762         DC = DC->getParent();
9763       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9764         if (CTSD->isInStdNamespace() &&
9765             llvm::StringSwitch<bool>(CTSD->getName())
9766                 .Cases("less", "less_equal", "greater", "greater_equal", true)
9767                 .Default(false)) {
9768           if (RHSType->isNullPtrType())
9769             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9770           else
9771             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9772           return ResultTy;
9773         }
9774       }
9775     }
9776
9777     // C++ [expr.eq]p2:
9778     //   If at least one operand is a pointer to member, [...] bring them to
9779     //   their composite pointer type.
9780     if (!IsRelational &&
9781         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9782       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9783         return QualType();
9784       else
9785         return ResultTy;
9786     }
9787
9788     // Handle scoped enumeration types specifically, since they don't promote
9789     // to integers.
9790     if (LHS.get()->getType()->isEnumeralType() &&
9791         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9792                                        RHS.get()->getType()))
9793       return ResultTy;
9794   }
9795
9796   // Handle block pointer types.
9797   if (!IsRelational && LHSType->isBlockPointerType() &&
9798       RHSType->isBlockPointerType()) {
9799     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9800     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9801
9802     if (!LHSIsNull && !RHSIsNull &&
9803         !Context.typesAreCompatible(lpointee, rpointee)) {
9804       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9805         << LHSType << RHSType << LHS.get()->getSourceRange()
9806         << RHS.get()->getSourceRange();
9807     }
9808     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9809     return ResultTy;
9810   }
9811
9812   // Allow block pointers to be compared with null pointer constants.
9813   if (!IsRelational
9814       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9815           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9816     if (!LHSIsNull && !RHSIsNull) {
9817       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9818              ->getPointeeType()->isVoidType())
9819             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9820                 ->getPointeeType()->isVoidType())))
9821         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9822           << LHSType << RHSType << LHS.get()->getSourceRange()
9823           << RHS.get()->getSourceRange();
9824     }
9825     if (LHSIsNull && !RHSIsNull)
9826       LHS = ImpCastExprToType(LHS.get(), RHSType,
9827                               RHSType->isPointerType() ? CK_BitCast
9828                                 : CK_AnyPointerToBlockPointerCast);
9829     else
9830       RHS = ImpCastExprToType(RHS.get(), LHSType,
9831                               LHSType->isPointerType() ? CK_BitCast
9832                                 : CK_AnyPointerToBlockPointerCast);
9833     return ResultTy;
9834   }
9835
9836   if (LHSType->isObjCObjectPointerType() ||
9837       RHSType->isObjCObjectPointerType()) {
9838     const PointerType *LPT = LHSType->getAs<PointerType>();
9839     const PointerType *RPT = RHSType->getAs<PointerType>();
9840     if (LPT || RPT) {
9841       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9842       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9843
9844       if (!LPtrToVoid && !RPtrToVoid &&
9845           !Context.typesAreCompatible(LHSType, RHSType)) {
9846         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9847                                           /*isError*/false);
9848       }
9849       if (LHSIsNull && !RHSIsNull) {
9850         Expr *E = LHS.get();
9851         if (getLangOpts().ObjCAutoRefCount)
9852           CheckObjCConversion(SourceRange(), RHSType, E,
9853                               CCK_ImplicitConversion);
9854         LHS = ImpCastExprToType(E, RHSType,
9855                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9856       }
9857       else {
9858         Expr *E = RHS.get();
9859         if (getLangOpts().ObjCAutoRefCount)
9860           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
9861                               /*Diagnose=*/true,
9862                               /*DiagnoseCFAudited=*/false, Opc);
9863         RHS = ImpCastExprToType(E, LHSType,
9864                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9865       }
9866       return ResultTy;
9867     }
9868     if (LHSType->isObjCObjectPointerType() &&
9869         RHSType->isObjCObjectPointerType()) {
9870       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9871         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9872                                           /*isError*/false);
9873       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9874         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9875
9876       if (LHSIsNull && !RHSIsNull)
9877         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9878       else
9879         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9880       return ResultTy;
9881     }
9882   }
9883   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9884       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9885     unsigned DiagID = 0;
9886     bool isError = false;
9887     if (LangOpts.DebuggerSupport) {
9888       // Under a debugger, allow the comparison of pointers to integers,
9889       // since users tend to want to compare addresses.
9890     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9891                (RHSIsNull && RHSType->isIntegerType())) {
9892       if (IsRelational) {
9893         isError = getLangOpts().CPlusPlus;
9894         DiagID =
9895           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9896                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9897       }
9898     } else if (getLangOpts().CPlusPlus) {
9899       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9900       isError = true;
9901     } else if (IsRelational)
9902       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9903     else
9904       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9905
9906     if (DiagID) {
9907       Diag(Loc, DiagID)
9908         << LHSType << RHSType << LHS.get()->getSourceRange()
9909         << RHS.get()->getSourceRange();
9910       if (isError)
9911         return QualType();
9912     }
9913     
9914     if (LHSType->isIntegerType())
9915       LHS = ImpCastExprToType(LHS.get(), RHSType,
9916                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9917     else
9918       RHS = ImpCastExprToType(RHS.get(), LHSType,
9919                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9920     return ResultTy;
9921   }
9922   
9923   // Handle block pointers.
9924   if (!IsRelational && RHSIsNull
9925       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9926     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9927     return ResultTy;
9928   }
9929   if (!IsRelational && LHSIsNull
9930       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9931     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9932     return ResultTy;
9933   }
9934
9935   if (getLangOpts().OpenCLVersion >= 200) {
9936     if (LHSIsNull && RHSType->isQueueT()) {
9937       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9938       return ResultTy;
9939     }
9940
9941     if (LHSType->isQueueT() && RHSIsNull) {
9942       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9943       return ResultTy;
9944     }
9945   }
9946
9947   return InvalidOperands(Loc, LHS, RHS);
9948 }
9949
9950 // Return a signed ext_vector_type that is of identical size and number of
9951 // elements. For floating point vectors, return an integer type of identical
9952 // size and number of elements. In the non ext_vector_type case, search from
9953 // the largest type to the smallest type to avoid cases where long long == long,
9954 // where long gets picked over long long.
9955 QualType Sema::GetSignedVectorType(QualType V) {
9956   const VectorType *VTy = V->getAs<VectorType>();
9957   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9958
9959   if (isa<ExtVectorType>(VTy)) {
9960     if (TypeSize == Context.getTypeSize(Context.CharTy))
9961       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9962     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9963       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9964     else if (TypeSize == Context.getTypeSize(Context.IntTy))
9965       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9966     else if (TypeSize == Context.getTypeSize(Context.LongTy))
9967       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9968     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9969            "Unhandled vector element size in vector compare");
9970     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9971   }
9972
9973   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
9974     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
9975                                  VectorType::GenericVector);
9976   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9977     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
9978                                  VectorType::GenericVector);
9979   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9980     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
9981                                  VectorType::GenericVector);
9982   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9983     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
9984                                  VectorType::GenericVector);
9985   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
9986          "Unhandled vector element size in vector compare");
9987   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
9988                                VectorType::GenericVector);
9989 }
9990
9991 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9992 /// operates on extended vector types.  Instead of producing an IntTy result,
9993 /// like a scalar comparison, a vector comparison produces a vector of integer
9994 /// types.
9995 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9996                                           SourceLocation Loc,
9997                                           bool IsRelational) {
9998   // Check to make sure we're operating on vectors of the same type and width,
9999   // Allowing one side to be a scalar of element type.
10000   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10001                               /*AllowBothBool*/true,
10002                               /*AllowBoolConversions*/getLangOpts().ZVector);
10003   if (vType.isNull())
10004     return vType;
10005
10006   QualType LHSType = LHS.get()->getType();
10007
10008   // If AltiVec, the comparison results in a numeric type, i.e.
10009   // bool for C++, int for C
10010   if (getLangOpts().AltiVec &&
10011       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10012     return Context.getLogicalOperationType();
10013
10014   // For non-floating point types, check for self-comparisons of the form
10015   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10016   // often indicate logic errors in the program.
10017   if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) {
10018     if (DeclRefExpr* DRL
10019           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
10020       if (DeclRefExpr* DRR
10021             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
10022         if (DRL->getDecl() == DRR->getDecl())
10023           DiagRuntimeBehavior(Loc, nullptr,
10024                               PDiag(diag::warn_comparison_always)
10025                                 << 0 // self-
10026                                 << 2 // "a constant"
10027                               );
10028   }
10029
10030   // Check for comparisons of floating point operands using != and ==.
10031   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
10032     assert (RHS.get()->getType()->hasFloatingRepresentation());
10033     CheckFloatComparison(Loc, LHS.get(), RHS.get());
10034   }
10035
10036   // Return a signed type for the vector.
10037   return GetSignedVectorType(vType);
10038 }
10039
10040 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10041                                           SourceLocation Loc) {
10042   // Ensure that either both operands are of the same vector type, or
10043   // one operand is of a vector type and the other is of its element type.
10044   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10045                                        /*AllowBothBool*/true,
10046                                        /*AllowBoolConversions*/false);
10047   if (vType.isNull())
10048     return InvalidOperands(Loc, LHS, RHS);
10049   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10050       vType->hasFloatingRepresentation())
10051     return InvalidOperands(Loc, LHS, RHS);
10052   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10053   //        usage of the logical operators && and || with vectors in C. This
10054   //        check could be notionally dropped.
10055   if (!getLangOpts().CPlusPlus &&
10056       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10057     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10058
10059   return GetSignedVectorType(LHS.get()->getType());
10060 }
10061
10062 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10063                                            SourceLocation Loc,
10064                                            BinaryOperatorKind Opc) {
10065   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10066
10067   bool IsCompAssign =
10068       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10069
10070   if (LHS.get()->getType()->isVectorType() ||
10071       RHS.get()->getType()->isVectorType()) {
10072     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10073         RHS.get()->getType()->hasIntegerRepresentation())
10074       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10075                         /*AllowBothBool*/true,
10076                         /*AllowBoolConversions*/getLangOpts().ZVector);
10077     return InvalidOperands(Loc, LHS, RHS);
10078   }
10079
10080   if (Opc == BO_And)
10081     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10082
10083   ExprResult LHSResult = LHS, RHSResult = RHS;
10084   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10085                                                  IsCompAssign);
10086   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10087     return QualType();
10088   LHS = LHSResult.get();
10089   RHS = RHSResult.get();
10090
10091   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10092     return compType;
10093   return InvalidOperands(Loc, LHS, RHS);
10094 }
10095
10096 // C99 6.5.[13,14]
10097 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10098                                            SourceLocation Loc,
10099                                            BinaryOperatorKind Opc) {
10100   // Check vector operands differently.
10101   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10102     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10103   
10104   // Diagnose cases where the user write a logical and/or but probably meant a
10105   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10106   // is a constant.
10107   if (LHS.get()->getType()->isIntegerType() &&
10108       !LHS.get()->getType()->isBooleanType() &&
10109       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10110       // Don't warn in macros or template instantiations.
10111       !Loc.isMacroID() && !inTemplateInstantiation()) {
10112     // If the RHS can be constant folded, and if it constant folds to something
10113     // that isn't 0 or 1 (which indicate a potential logical operation that
10114     // happened to fold to true/false) then warn.
10115     // Parens on the RHS are ignored.
10116     llvm::APSInt Result;
10117     if (RHS.get()->EvaluateAsInt(Result, Context))
10118       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10119            !RHS.get()->getExprLoc().isMacroID()) ||
10120           (Result != 0 && Result != 1)) {
10121         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10122           << RHS.get()->getSourceRange()
10123           << (Opc == BO_LAnd ? "&&" : "||");
10124         // Suggest replacing the logical operator with the bitwise version
10125         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10126             << (Opc == BO_LAnd ? "&" : "|")
10127             << FixItHint::CreateReplacement(SourceRange(
10128                                                  Loc, getLocForEndOfToken(Loc)),
10129                                             Opc == BO_LAnd ? "&" : "|");
10130         if (Opc == BO_LAnd)
10131           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10132           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10133               << FixItHint::CreateRemoval(
10134                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
10135                               RHS.get()->getLocEnd()));
10136       }
10137   }
10138
10139   if (!Context.getLangOpts().CPlusPlus) {
10140     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10141     // not operate on the built-in scalar and vector float types.
10142     if (Context.getLangOpts().OpenCL &&
10143         Context.getLangOpts().OpenCLVersion < 120) {
10144       if (LHS.get()->getType()->isFloatingType() ||
10145           RHS.get()->getType()->isFloatingType())
10146         return InvalidOperands(Loc, LHS, RHS);
10147     }
10148
10149     LHS = UsualUnaryConversions(LHS.get());
10150     if (LHS.isInvalid())
10151       return QualType();
10152
10153     RHS = UsualUnaryConversions(RHS.get());
10154     if (RHS.isInvalid())
10155       return QualType();
10156
10157     if (!LHS.get()->getType()->isScalarType() ||
10158         !RHS.get()->getType()->isScalarType())
10159       return InvalidOperands(Loc, LHS, RHS);
10160
10161     return Context.IntTy;
10162   }
10163
10164   // The following is safe because we only use this method for
10165   // non-overloadable operands.
10166
10167   // C++ [expr.log.and]p1
10168   // C++ [expr.log.or]p1
10169   // The operands are both contextually converted to type bool.
10170   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10171   if (LHSRes.isInvalid())
10172     return InvalidOperands(Loc, LHS, RHS);
10173   LHS = LHSRes;
10174
10175   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10176   if (RHSRes.isInvalid())
10177     return InvalidOperands(Loc, LHS, RHS);
10178   RHS = RHSRes;
10179
10180   // C++ [expr.log.and]p2
10181   // C++ [expr.log.or]p2
10182   // The result is a bool.
10183   return Context.BoolTy;
10184 }
10185
10186 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10187   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10188   if (!ME) return false;
10189   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10190   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10191       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
10192   if (!Base) return false;
10193   return Base->getMethodDecl() != nullptr;
10194 }
10195
10196 /// Is the given expression (which must be 'const') a reference to a
10197 /// variable which was originally non-const, but which has become
10198 /// 'const' due to being captured within a block?
10199 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
10200 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
10201   assert(E->isLValue() && E->getType().isConstQualified());
10202   E = E->IgnoreParens();
10203
10204   // Must be a reference to a declaration from an enclosing scope.
10205   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10206   if (!DRE) return NCCK_None;
10207   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10208
10209   // The declaration must be a variable which is not declared 'const'.
10210   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10211   if (!var) return NCCK_None;
10212   if (var->getType().isConstQualified()) return NCCK_None;
10213   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10214
10215   // Decide whether the first capture was for a block or a lambda.
10216   DeclContext *DC = S.CurContext, *Prev = nullptr;
10217   // Decide whether the first capture was for a block or a lambda.
10218   while (DC) {
10219     // For init-capture, it is possible that the variable belongs to the
10220     // template pattern of the current context.
10221     if (auto *FD = dyn_cast<FunctionDecl>(DC))
10222       if (var->isInitCapture() &&
10223           FD->getTemplateInstantiationPattern() == var->getDeclContext())
10224         break;
10225     if (DC == var->getDeclContext())
10226       break;
10227     Prev = DC;
10228     DC = DC->getParent();
10229   }
10230   // Unless we have an init-capture, we've gone one step too far.
10231   if (!var->isInitCapture())
10232     DC = Prev;
10233   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10234 }
10235
10236 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10237   Ty = Ty.getNonReferenceType();
10238   if (IsDereference && Ty->isPointerType())
10239     Ty = Ty->getPointeeType();
10240   return !Ty.isConstQualified();
10241 }
10242
10243 /// Emit the "read-only variable not assignable" error and print notes to give
10244 /// more information about why the variable is not assignable, such as pointing
10245 /// to the declaration of a const variable, showing that a method is const, or
10246 /// that the function is returning a const reference.
10247 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10248                                     SourceLocation Loc) {
10249   // Update err_typecheck_assign_const and note_typecheck_assign_const
10250   // when this enum is changed.
10251   enum {
10252     ConstFunction,
10253     ConstVariable,
10254     ConstMember,
10255     ConstMethod,
10256     ConstUnknown,  // Keep as last element
10257   };
10258
10259   SourceRange ExprRange = E->getSourceRange();
10260
10261   // Only emit one error on the first const found.  All other consts will emit
10262   // a note to the error.
10263   bool DiagnosticEmitted = false;
10264
10265   // Track if the current expression is the result of a dereference, and if the
10266   // next checked expression is the result of a dereference.
10267   bool IsDereference = false;
10268   bool NextIsDereference = false;
10269
10270   // Loop to process MemberExpr chains.
10271   while (true) {
10272     IsDereference = NextIsDereference;
10273
10274     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10275     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10276       NextIsDereference = ME->isArrow();
10277       const ValueDecl *VD = ME->getMemberDecl();
10278       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10279         // Mutable fields can be modified even if the class is const.
10280         if (Field->isMutable()) {
10281           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10282           break;
10283         }
10284
10285         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10286           if (!DiagnosticEmitted) {
10287             S.Diag(Loc, diag::err_typecheck_assign_const)
10288                 << ExprRange << ConstMember << false /*static*/ << Field
10289                 << Field->getType();
10290             DiagnosticEmitted = true;
10291           }
10292           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10293               << ConstMember << false /*static*/ << Field << Field->getType()
10294               << Field->getSourceRange();
10295         }
10296         E = ME->getBase();
10297         continue;
10298       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10299         if (VDecl->getType().isConstQualified()) {
10300           if (!DiagnosticEmitted) {
10301             S.Diag(Loc, diag::err_typecheck_assign_const)
10302                 << ExprRange << ConstMember << true /*static*/ << VDecl
10303                 << VDecl->getType();
10304             DiagnosticEmitted = true;
10305           }
10306           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10307               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10308               << VDecl->getSourceRange();
10309         }
10310         // Static fields do not inherit constness from parents.
10311         break;
10312       }
10313       break;
10314     } // End MemberExpr
10315     break;
10316   }
10317
10318   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10319     // Function calls
10320     const FunctionDecl *FD = CE->getDirectCallee();
10321     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10322       if (!DiagnosticEmitted) {
10323         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10324                                                       << ConstFunction << FD;
10325         DiagnosticEmitted = true;
10326       }
10327       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10328              diag::note_typecheck_assign_const)
10329           << ConstFunction << FD << FD->getReturnType()
10330           << FD->getReturnTypeSourceRange();
10331     }
10332   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10333     // Point to variable declaration.
10334     if (const ValueDecl *VD = DRE->getDecl()) {
10335       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10336         if (!DiagnosticEmitted) {
10337           S.Diag(Loc, diag::err_typecheck_assign_const)
10338               << ExprRange << ConstVariable << VD << VD->getType();
10339           DiagnosticEmitted = true;
10340         }
10341         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10342             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10343       }
10344     }
10345   } else if (isa<CXXThisExpr>(E)) {
10346     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10347       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10348         if (MD->isConst()) {
10349           if (!DiagnosticEmitted) {
10350             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10351                                                           << ConstMethod << MD;
10352             DiagnosticEmitted = true;
10353           }
10354           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10355               << ConstMethod << MD << MD->getSourceRange();
10356         }
10357       }
10358     }
10359   }
10360
10361   if (DiagnosticEmitted)
10362     return;
10363
10364   // Can't determine a more specific message, so display the generic error.
10365   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10366 }
10367
10368 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10369 /// emit an error and return true.  If so, return false.
10370 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10371   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10372
10373   S.CheckShadowingDeclModification(E, Loc);
10374
10375   SourceLocation OrigLoc = Loc;
10376   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10377                                                               &Loc);
10378   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10379     IsLV = Expr::MLV_InvalidMessageExpression;
10380   if (IsLV == Expr::MLV_Valid)
10381     return false;
10382
10383   unsigned DiagID = 0;
10384   bool NeedType = false;
10385   switch (IsLV) { // C99 6.5.16p2
10386   case Expr::MLV_ConstQualified:
10387     // Use a specialized diagnostic when we're assigning to an object
10388     // from an enclosing function or block.
10389     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10390       if (NCCK == NCCK_Block)
10391         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10392       else
10393         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10394       break;
10395     }
10396
10397     // In ARC, use some specialized diagnostics for occasions where we
10398     // infer 'const'.  These are always pseudo-strong variables.
10399     if (S.getLangOpts().ObjCAutoRefCount) {
10400       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10401       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10402         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10403
10404         // Use the normal diagnostic if it's pseudo-__strong but the
10405         // user actually wrote 'const'.
10406         if (var->isARCPseudoStrong() &&
10407             (!var->getTypeSourceInfo() ||
10408              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10409           // There are two pseudo-strong cases:
10410           //  - self
10411           ObjCMethodDecl *method = S.getCurMethodDecl();
10412           if (method && var == method->getSelfDecl())
10413             DiagID = method->isClassMethod()
10414               ? diag::err_typecheck_arc_assign_self_class_method
10415               : diag::err_typecheck_arc_assign_self;
10416
10417           //  - fast enumeration variables
10418           else
10419             DiagID = diag::err_typecheck_arr_assign_enumeration;
10420
10421           SourceRange Assign;
10422           if (Loc != OrigLoc)
10423             Assign = SourceRange(OrigLoc, OrigLoc);
10424           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10425           // We need to preserve the AST regardless, so migration tool
10426           // can do its job.
10427           return false;
10428         }
10429       }
10430     }
10431
10432     // If none of the special cases above are triggered, then this is a
10433     // simple const assignment.
10434     if (DiagID == 0) {
10435       DiagnoseConstAssignment(S, E, Loc);
10436       return true;
10437     }
10438
10439     break;
10440   case Expr::MLV_ConstAddrSpace:
10441     DiagnoseConstAssignment(S, E, Loc);
10442     return true;
10443   case Expr::MLV_ArrayType:
10444   case Expr::MLV_ArrayTemporary:
10445     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10446     NeedType = true;
10447     break;
10448   case Expr::MLV_NotObjectType:
10449     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10450     NeedType = true;
10451     break;
10452   case Expr::MLV_LValueCast:
10453     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10454     break;
10455   case Expr::MLV_Valid:
10456     llvm_unreachable("did not take early return for MLV_Valid");
10457   case Expr::MLV_InvalidExpression:
10458   case Expr::MLV_MemberFunction:
10459   case Expr::MLV_ClassTemporary:
10460     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10461     break;
10462   case Expr::MLV_IncompleteType:
10463   case Expr::MLV_IncompleteVoidType:
10464     return S.RequireCompleteType(Loc, E->getType(),
10465              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10466   case Expr::MLV_DuplicateVectorComponents:
10467     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10468     break;
10469   case Expr::MLV_NoSetterProperty:
10470     llvm_unreachable("readonly properties should be processed differently");
10471   case Expr::MLV_InvalidMessageExpression:
10472     DiagID = diag::err_readonly_message_assignment;
10473     break;
10474   case Expr::MLV_SubObjCPropertySetting:
10475     DiagID = diag::err_no_subobject_property_setting;
10476     break;
10477   }
10478
10479   SourceRange Assign;
10480   if (Loc != OrigLoc)
10481     Assign = SourceRange(OrigLoc, OrigLoc);
10482   if (NeedType)
10483     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10484   else
10485     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10486   return true;
10487 }
10488
10489 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10490                                          SourceLocation Loc,
10491                                          Sema &Sema) {
10492   // C / C++ fields
10493   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10494   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10495   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10496     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10497       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10498   }
10499
10500   // Objective-C instance variables
10501   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10502   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10503   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10504     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10505     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10506     if (RL && RR && RL->getDecl() == RR->getDecl())
10507       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10508   }
10509 }
10510
10511 // C99 6.5.16.1
10512 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10513                                        SourceLocation Loc,
10514                                        QualType CompoundType) {
10515   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10516
10517   // Verify that LHS is a modifiable lvalue, and emit error if not.
10518   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10519     return QualType();
10520
10521   QualType LHSType = LHSExpr->getType();
10522   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10523                                              CompoundType;
10524   // OpenCL v1.2 s6.1.1.1 p2:
10525   // The half data type can only be used to declare a pointer to a buffer that
10526   // contains half values
10527   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10528     LHSType->isHalfType()) {
10529     Diag(Loc, diag::err_opencl_half_load_store) << 1
10530         << LHSType.getUnqualifiedType();
10531     return QualType();
10532   }
10533     
10534   AssignConvertType ConvTy;
10535   if (CompoundType.isNull()) {
10536     Expr *RHSCheck = RHS.get();
10537
10538     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10539
10540     QualType LHSTy(LHSType);
10541     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10542     if (RHS.isInvalid())
10543       return QualType();
10544     // Special case of NSObject attributes on c-style pointer types.
10545     if (ConvTy == IncompatiblePointer &&
10546         ((Context.isObjCNSObjectType(LHSType) &&
10547           RHSType->isObjCObjectPointerType()) ||
10548          (Context.isObjCNSObjectType(RHSType) &&
10549           LHSType->isObjCObjectPointerType())))
10550       ConvTy = Compatible;
10551
10552     if (ConvTy == Compatible &&
10553         LHSType->isObjCObjectType())
10554         Diag(Loc, diag::err_objc_object_assignment)
10555           << LHSType;
10556
10557     // If the RHS is a unary plus or minus, check to see if they = and + are
10558     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10559     // instead of "x += 4".
10560     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10561       RHSCheck = ICE->getSubExpr();
10562     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10563       if ((UO->getOpcode() == UO_Plus ||
10564            UO->getOpcode() == UO_Minus) &&
10565           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10566           // Only if the two operators are exactly adjacent.
10567           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10568           // And there is a space or other character before the subexpr of the
10569           // unary +/-.  We don't want to warn on "x=-1".
10570           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10571           UO->getSubExpr()->getLocStart().isFileID()) {
10572         Diag(Loc, diag::warn_not_compound_assign)
10573           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10574           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10575       }
10576     }
10577
10578     if (ConvTy == Compatible) {
10579       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10580         // Warn about retain cycles where a block captures the LHS, but
10581         // not if the LHS is a simple variable into which the block is
10582         // being stored...unless that variable can be captured by reference!
10583         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10584         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10585         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10586           checkRetainCycles(LHSExpr, RHS.get());
10587       }
10588
10589       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
10590           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
10591         // It is safe to assign a weak reference into a strong variable.
10592         // Although this code can still have problems:
10593         //   id x = self.weakProp;
10594         //   id y = self.weakProp;
10595         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10596         // paths through the function. This should be revisited if
10597         // -Wrepeated-use-of-weak is made flow-sensitive.
10598         // For ObjCWeak only, we do not warn if the assign is to a non-weak
10599         // variable, which will be valid for the current autorelease scope.
10600         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10601                              RHS.get()->getLocStart()))
10602           getCurFunction()->markSafeWeakUse(RHS.get());
10603
10604       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
10605         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10606       }
10607     }
10608   } else {
10609     // Compound assignment "x += y"
10610     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10611   }
10612
10613   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10614                                RHS.get(), AA_Assigning))
10615     return QualType();
10616
10617   CheckForNullPointerDereference(*this, LHSExpr);
10618
10619   // C99 6.5.16p3: The type of an assignment expression is the type of the
10620   // left operand unless the left operand has qualified type, in which case
10621   // it is the unqualified version of the type of the left operand.
10622   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10623   // is converted to the type of the assignment expression (above).
10624   // C++ 5.17p1: the type of the assignment expression is that of its left
10625   // operand.
10626   return (getLangOpts().CPlusPlus
10627           ? LHSType : LHSType.getUnqualifiedType());
10628 }
10629
10630 // Only ignore explicit casts to void.
10631 static bool IgnoreCommaOperand(const Expr *E) {
10632   E = E->IgnoreParens();
10633
10634   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10635     if (CE->getCastKind() == CK_ToVoid) {
10636       return true;
10637     }
10638   }
10639
10640   return false;
10641 }
10642
10643 // Look for instances where it is likely the comma operator is confused with
10644 // another operator.  There is a whitelist of acceptable expressions for the
10645 // left hand side of the comma operator, otherwise emit a warning.
10646 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10647   // No warnings in macros
10648   if (Loc.isMacroID())
10649     return;
10650
10651   // Don't warn in template instantiations.
10652   if (inTemplateInstantiation())
10653     return;
10654
10655   // Scope isn't fine-grained enough to whitelist the specific cases, so
10656   // instead, skip more than needed, then call back into here with the
10657   // CommaVisitor in SemaStmt.cpp.
10658   // The whitelisted locations are the initialization and increment portions
10659   // of a for loop.  The additional checks are on the condition of
10660   // if statements, do/while loops, and for loops.
10661   const unsigned ForIncrementFlags =
10662       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10663   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10664   const unsigned ScopeFlags = getCurScope()->getFlags();
10665   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10666       (ScopeFlags & ForInitFlags) == ForInitFlags)
10667     return;
10668
10669   // If there are multiple comma operators used together, get the RHS of the
10670   // of the comma operator as the LHS.
10671   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10672     if (BO->getOpcode() != BO_Comma)
10673       break;
10674     LHS = BO->getRHS();
10675   }
10676
10677   // Only allow some expressions on LHS to not warn.
10678   if (IgnoreCommaOperand(LHS))
10679     return;
10680
10681   Diag(Loc, diag::warn_comma_operator);
10682   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10683       << LHS->getSourceRange()
10684       << FixItHint::CreateInsertion(LHS->getLocStart(),
10685                                     LangOpts.CPlusPlus ? "static_cast<void>("
10686                                                        : "(void)(")
10687       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10688                                     ")");
10689 }
10690
10691 // C99 6.5.17
10692 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10693                                    SourceLocation Loc) {
10694   LHS = S.CheckPlaceholderExpr(LHS.get());
10695   RHS = S.CheckPlaceholderExpr(RHS.get());
10696   if (LHS.isInvalid() || RHS.isInvalid())
10697     return QualType();
10698
10699   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10700   // operands, but not unary promotions.
10701   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10702
10703   // So we treat the LHS as a ignored value, and in C++ we allow the
10704   // containing site to determine what should be done with the RHS.
10705   LHS = S.IgnoredValueConversions(LHS.get());
10706   if (LHS.isInvalid())
10707     return QualType();
10708
10709   S.DiagnoseUnusedExprResult(LHS.get());
10710
10711   if (!S.getLangOpts().CPlusPlus) {
10712     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10713     if (RHS.isInvalid())
10714       return QualType();
10715     if (!RHS.get()->getType()->isVoidType())
10716       S.RequireCompleteType(Loc, RHS.get()->getType(),
10717                             diag::err_incomplete_type);
10718   }
10719
10720   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10721     S.DiagnoseCommaOperator(LHS.get(), Loc);
10722
10723   return RHS.get()->getType();
10724 }
10725
10726 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10727 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10728 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10729                                                ExprValueKind &VK,
10730                                                ExprObjectKind &OK,
10731                                                SourceLocation OpLoc,
10732                                                bool IsInc, bool IsPrefix) {
10733   if (Op->isTypeDependent())
10734     return S.Context.DependentTy;
10735
10736   QualType ResType = Op->getType();
10737   // Atomic types can be used for increment / decrement where the non-atomic
10738   // versions can, so ignore the _Atomic() specifier for the purpose of
10739   // checking.
10740   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10741     ResType = ResAtomicType->getValueType();
10742
10743   assert(!ResType.isNull() && "no type for increment/decrement expression");
10744
10745   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10746     // Decrement of bool is not allowed.
10747     if (!IsInc) {
10748       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10749       return QualType();
10750     }
10751     // Increment of bool sets it to true, but is deprecated.
10752     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10753                                               : diag::warn_increment_bool)
10754       << Op->getSourceRange();
10755   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10756     // Error on enum increments and decrements in C++ mode
10757     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10758     return QualType();
10759   } else if (ResType->isRealType()) {
10760     // OK!
10761   } else if (ResType->isPointerType()) {
10762     // C99 6.5.2.4p2, 6.5.6p2
10763     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10764       return QualType();
10765   } else if (ResType->isObjCObjectPointerType()) {
10766     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10767     // Otherwise, we just need a complete type.
10768     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10769         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10770       return QualType();    
10771   } else if (ResType->isAnyComplexType()) {
10772     // C99 does not support ++/-- on complex types, we allow as an extension.
10773     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10774       << ResType << Op->getSourceRange();
10775   } else if (ResType->isPlaceholderType()) {
10776     ExprResult PR = S.CheckPlaceholderExpr(Op);
10777     if (PR.isInvalid()) return QualType();
10778     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10779                                           IsInc, IsPrefix);
10780   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10781     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10782   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10783              (ResType->getAs<VectorType>()->getVectorKind() !=
10784               VectorType::AltiVecBool)) {
10785     // The z vector extensions allow ++ and -- for non-bool vectors.
10786   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10787             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10788     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10789   } else {
10790     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10791       << ResType << int(IsInc) << Op->getSourceRange();
10792     return QualType();
10793   }
10794   // At this point, we know we have a real, complex or pointer type.
10795   // Now make sure the operand is a modifiable lvalue.
10796   if (CheckForModifiableLvalue(Op, OpLoc, S))
10797     return QualType();
10798   // In C++, a prefix increment is the same type as the operand. Otherwise
10799   // (in C or with postfix), the increment is the unqualified type of the
10800   // operand.
10801   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10802     VK = VK_LValue;
10803     OK = Op->getObjectKind();
10804     return ResType;
10805   } else {
10806     VK = VK_RValue;
10807     return ResType.getUnqualifiedType();
10808   }
10809 }
10810   
10811
10812 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10813 /// This routine allows us to typecheck complex/recursive expressions
10814 /// where the declaration is needed for type checking. We only need to
10815 /// handle cases when the expression references a function designator
10816 /// or is an lvalue. Here are some examples:
10817 ///  - &(x) => x
10818 ///  - &*****f => f for f a function designator.
10819 ///  - &s.xx => s
10820 ///  - &s.zz[1].yy -> s, if zz is an array
10821 ///  - *(x + 1) -> x, if x is an array
10822 ///  - &"123"[2] -> 0
10823 ///  - & __real__ x -> x
10824 static ValueDecl *getPrimaryDecl(Expr *E) {
10825   switch (E->getStmtClass()) {
10826   case Stmt::DeclRefExprClass:
10827     return cast<DeclRefExpr>(E)->getDecl();
10828   case Stmt::MemberExprClass:
10829     // If this is an arrow operator, the address is an offset from
10830     // the base's value, so the object the base refers to is
10831     // irrelevant.
10832     if (cast<MemberExpr>(E)->isArrow())
10833       return nullptr;
10834     // Otherwise, the expression refers to a part of the base
10835     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10836   case Stmt::ArraySubscriptExprClass: {
10837     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10838     // promotion of register arrays earlier.
10839     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10840     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10841       if (ICE->getSubExpr()->getType()->isArrayType())
10842         return getPrimaryDecl(ICE->getSubExpr());
10843     }
10844     return nullptr;
10845   }
10846   case Stmt::UnaryOperatorClass: {
10847     UnaryOperator *UO = cast<UnaryOperator>(E);
10848
10849     switch(UO->getOpcode()) {
10850     case UO_Real:
10851     case UO_Imag:
10852     case UO_Extension:
10853       return getPrimaryDecl(UO->getSubExpr());
10854     default:
10855       return nullptr;
10856     }
10857   }
10858   case Stmt::ParenExprClass:
10859     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10860   case Stmt::ImplicitCastExprClass:
10861     // If the result of an implicit cast is an l-value, we care about
10862     // the sub-expression; otherwise, the result here doesn't matter.
10863     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10864   default:
10865     return nullptr;
10866   }
10867 }
10868
10869 namespace {
10870   enum {
10871     AO_Bit_Field = 0,
10872     AO_Vector_Element = 1,
10873     AO_Property_Expansion = 2,
10874     AO_Register_Variable = 3,
10875     AO_No_Error = 4
10876   };
10877 }
10878 /// \brief Diagnose invalid operand for address of operations.
10879 ///
10880 /// \param Type The type of operand which cannot have its address taken.
10881 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10882                                          Expr *E, unsigned Type) {
10883   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10884 }
10885
10886 /// CheckAddressOfOperand - The operand of & must be either a function
10887 /// designator or an lvalue designating an object. If it is an lvalue, the
10888 /// object cannot be declared with storage class register or be a bit field.
10889 /// Note: The usual conversions are *not* applied to the operand of the &
10890 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10891 /// In C++, the operand might be an overloaded function name, in which case
10892 /// we allow the '&' but retain the overloaded-function type.
10893 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10894   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10895     if (PTy->getKind() == BuiltinType::Overload) {
10896       Expr *E = OrigOp.get()->IgnoreParens();
10897       if (!isa<OverloadExpr>(E)) {
10898         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10899         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10900           << OrigOp.get()->getSourceRange();
10901         return QualType();
10902       }
10903
10904       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10905       if (isa<UnresolvedMemberExpr>(Ovl))
10906         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10907           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10908             << OrigOp.get()->getSourceRange();
10909           return QualType();
10910         }
10911
10912       return Context.OverloadTy;
10913     }
10914
10915     if (PTy->getKind() == BuiltinType::UnknownAny)
10916       return Context.UnknownAnyTy;
10917
10918     if (PTy->getKind() == BuiltinType::BoundMember) {
10919       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10920         << OrigOp.get()->getSourceRange();
10921       return QualType();
10922     }
10923
10924     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10925     if (OrigOp.isInvalid()) return QualType();
10926   }
10927
10928   if (OrigOp.get()->isTypeDependent())
10929     return Context.DependentTy;
10930
10931   assert(!OrigOp.get()->getType()->isPlaceholderType());
10932
10933   // Make sure to ignore parentheses in subsequent checks
10934   Expr *op = OrigOp.get()->IgnoreParens();
10935
10936   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10937   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10938     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10939     return QualType();
10940   }
10941
10942   if (getLangOpts().C99) {
10943     // Implement C99-only parts of addressof rules.
10944     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10945       if (uOp->getOpcode() == UO_Deref)
10946         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10947         // (assuming the deref expression is valid).
10948         return uOp->getSubExpr()->getType();
10949     }
10950     // Technically, there should be a check for array subscript
10951     // expressions here, but the result of one is always an lvalue anyway.
10952   }
10953   ValueDecl *dcl = getPrimaryDecl(op);
10954
10955   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10956     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10957                                            op->getLocStart()))
10958       return QualType();
10959
10960   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10961   unsigned AddressOfError = AO_No_Error;
10962
10963   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 
10964     bool sfinae = (bool)isSFINAEContext();
10965     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10966                                   : diag::ext_typecheck_addrof_temporary)
10967       << op->getType() << op->getSourceRange();
10968     if (sfinae)
10969       return QualType();
10970     // Materialize the temporary as an lvalue so that we can take its address.
10971     OrigOp = op =
10972         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10973   } else if (isa<ObjCSelectorExpr>(op)) {
10974     return Context.getPointerType(op->getType());
10975   } else if (lval == Expr::LV_MemberFunction) {
10976     // If it's an instance method, make a member pointer.
10977     // The expression must have exactly the form &A::foo.
10978
10979     // If the underlying expression isn't a decl ref, give up.
10980     if (!isa<DeclRefExpr>(op)) {
10981       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10982         << OrigOp.get()->getSourceRange();
10983       return QualType();
10984     }
10985     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10986     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10987
10988     // The id-expression was parenthesized.
10989     if (OrigOp.get() != DRE) {
10990       Diag(OpLoc, diag::err_parens_pointer_member_function)
10991         << OrigOp.get()->getSourceRange();
10992
10993     // The method was named without a qualifier.
10994     } else if (!DRE->getQualifier()) {
10995       if (MD->getParent()->getName().empty())
10996         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10997           << op->getSourceRange();
10998       else {
10999         SmallString<32> Str;
11000         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11001         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11002           << op->getSourceRange()
11003           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
11004       }
11005     }
11006
11007     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11008     if (isa<CXXDestructorDecl>(MD))
11009       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11010
11011     QualType MPTy = Context.getMemberPointerType(
11012         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11013     // Under the MS ABI, lock down the inheritance model now.
11014     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11015       (void)isCompleteType(OpLoc, MPTy);
11016     return MPTy;
11017   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11018     // C99 6.5.3.2p1
11019     // The operand must be either an l-value or a function designator
11020     if (!op->getType()->isFunctionType()) {
11021       // Use a special diagnostic for loads from property references.
11022       if (isa<PseudoObjectExpr>(op)) {
11023         AddressOfError = AO_Property_Expansion;
11024       } else {
11025         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11026           << op->getType() << op->getSourceRange();
11027         return QualType();
11028       }
11029     }
11030   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
11031     // The operand cannot be a bit-field
11032     AddressOfError = AO_Bit_Field;
11033   } else if (op->getObjectKind() == OK_VectorComponent) {
11034     // The operand cannot be an element of a vector
11035     AddressOfError = AO_Vector_Element;
11036   } else if (dcl) { // C99 6.5.3.2p1
11037     // We have an lvalue with a decl. Make sure the decl is not declared
11038     // with the register storage-class specifier.
11039     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
11040       // in C++ it is not error to take address of a register
11041       // variable (c++03 7.1.1P3)
11042       if (vd->getStorageClass() == SC_Register &&
11043           !getLangOpts().CPlusPlus) {
11044         AddressOfError = AO_Register_Variable;
11045       }
11046     } else if (isa<MSPropertyDecl>(dcl)) {
11047       AddressOfError = AO_Property_Expansion;
11048     } else if (isa<FunctionTemplateDecl>(dcl)) {
11049       return Context.OverloadTy;
11050     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
11051       // Okay: we can take the address of a field.
11052       // Could be a pointer to member, though, if there is an explicit
11053       // scope qualifier for the class.
11054       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
11055         DeclContext *Ctx = dcl->getDeclContext();
11056         if (Ctx && Ctx->isRecord()) {
11057           if (dcl->getType()->isReferenceType()) {
11058             Diag(OpLoc,
11059                  diag::err_cannot_form_pointer_to_member_of_reference_type)
11060               << dcl->getDeclName() << dcl->getType();
11061             return QualType();
11062           }
11063
11064           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
11065             Ctx = Ctx->getParent();
11066
11067           QualType MPTy = Context.getMemberPointerType(
11068               op->getType(),
11069               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
11070           // Under the MS ABI, lock down the inheritance model now.
11071           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11072             (void)isCompleteType(OpLoc, MPTy);
11073           return MPTy;
11074         }
11075       }
11076     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
11077                !isa<BindingDecl>(dcl))
11078       llvm_unreachable("Unknown/unexpected decl type");
11079   }
11080
11081   if (AddressOfError != AO_No_Error) {
11082     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
11083     return QualType();
11084   }
11085
11086   if (lval == Expr::LV_IncompleteVoidType) {
11087     // Taking the address of a void variable is technically illegal, but we
11088     // allow it in cases which are otherwise valid.
11089     // Example: "extern void x; void* y = &x;".
11090     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
11091   }
11092
11093   // If the operand has type "type", the result has type "pointer to type".
11094   if (op->getType()->isObjCObjectType())
11095     return Context.getObjCObjectPointerType(op->getType());
11096
11097   CheckAddressOfPackedMember(op);
11098
11099   return Context.getPointerType(op->getType());
11100 }
11101
11102 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11103   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11104   if (!DRE)
11105     return;
11106   const Decl *D = DRE->getDecl();
11107   if (!D)
11108     return;
11109   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11110   if (!Param)
11111     return;
11112   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11113     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11114       return;
11115   if (FunctionScopeInfo *FD = S.getCurFunction())
11116     if (!FD->ModifiedNonNullParams.count(Param))
11117       FD->ModifiedNonNullParams.insert(Param);
11118 }
11119
11120 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11121 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
11122                                         SourceLocation OpLoc) {
11123   if (Op->isTypeDependent())
11124     return S.Context.DependentTy;
11125
11126   ExprResult ConvResult = S.UsualUnaryConversions(Op);
11127   if (ConvResult.isInvalid())
11128     return QualType();
11129   Op = ConvResult.get();
11130   QualType OpTy = Op->getType();
11131   QualType Result;
11132
11133   if (isa<CXXReinterpretCastExpr>(Op)) {
11134     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11135     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11136                                      Op->getSourceRange());
11137   }
11138
11139   if (const PointerType *PT = OpTy->getAs<PointerType>())
11140   {
11141     Result = PT->getPointeeType();
11142   }
11143   else if (const ObjCObjectPointerType *OPT =
11144              OpTy->getAs<ObjCObjectPointerType>())
11145     Result = OPT->getPointeeType();
11146   else {
11147     ExprResult PR = S.CheckPlaceholderExpr(Op);
11148     if (PR.isInvalid()) return QualType();
11149     if (PR.get() != Op)
11150       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
11151   }
11152
11153   if (Result.isNull()) {
11154     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
11155       << OpTy << Op->getSourceRange();
11156     return QualType();
11157   }
11158
11159   // Note that per both C89 and C99, indirection is always legal, even if Result
11160   // is an incomplete type or void.  It would be possible to warn about
11161   // dereferencing a void pointer, but it's completely well-defined, and such a
11162   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
11163   // for pointers to 'void' but is fine for any other pointer type:
11164   //
11165   // C++ [expr.unary.op]p1:
11166   //   [...] the expression to which [the unary * operator] is applied shall
11167   //   be a pointer to an object type, or a pointer to a function type
11168   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
11169     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
11170       << OpTy << Op->getSourceRange();
11171
11172   // Dereferences are usually l-values...
11173   VK = VK_LValue;
11174
11175   // ...except that certain expressions are never l-values in C.
11176   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
11177     VK = VK_RValue;
11178   
11179   return Result;
11180 }
11181
11182 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
11183   BinaryOperatorKind Opc;
11184   switch (Kind) {
11185   default: llvm_unreachable("Unknown binop!");
11186   case tok::periodstar:           Opc = BO_PtrMemD; break;
11187   case tok::arrowstar:            Opc = BO_PtrMemI; break;
11188   case tok::star:                 Opc = BO_Mul; break;
11189   case tok::slash:                Opc = BO_Div; break;
11190   case tok::percent:              Opc = BO_Rem; break;
11191   case tok::plus:                 Opc = BO_Add; break;
11192   case tok::minus:                Opc = BO_Sub; break;
11193   case tok::lessless:             Opc = BO_Shl; break;
11194   case tok::greatergreater:       Opc = BO_Shr; break;
11195   case tok::lessequal:            Opc = BO_LE; break;
11196   case tok::less:                 Opc = BO_LT; break;
11197   case tok::greaterequal:         Opc = BO_GE; break;
11198   case tok::greater:              Opc = BO_GT; break;
11199   case tok::exclaimequal:         Opc = BO_NE; break;
11200   case tok::equalequal:           Opc = BO_EQ; break;
11201   case tok::amp:                  Opc = BO_And; break;
11202   case tok::caret:                Opc = BO_Xor; break;
11203   case tok::pipe:                 Opc = BO_Or; break;
11204   case tok::ampamp:               Opc = BO_LAnd; break;
11205   case tok::pipepipe:             Opc = BO_LOr; break;
11206   case tok::equal:                Opc = BO_Assign; break;
11207   case tok::starequal:            Opc = BO_MulAssign; break;
11208   case tok::slashequal:           Opc = BO_DivAssign; break;
11209   case tok::percentequal:         Opc = BO_RemAssign; break;
11210   case tok::plusequal:            Opc = BO_AddAssign; break;
11211   case tok::minusequal:           Opc = BO_SubAssign; break;
11212   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
11213   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
11214   case tok::ampequal:             Opc = BO_AndAssign; break;
11215   case tok::caretequal:           Opc = BO_XorAssign; break;
11216   case tok::pipeequal:            Opc = BO_OrAssign; break;
11217   case tok::comma:                Opc = BO_Comma; break;
11218   }
11219   return Opc;
11220 }
11221
11222 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
11223   tok::TokenKind Kind) {
11224   UnaryOperatorKind Opc;
11225   switch (Kind) {
11226   default: llvm_unreachable("Unknown unary op!");
11227   case tok::plusplus:     Opc = UO_PreInc; break;
11228   case tok::minusminus:   Opc = UO_PreDec; break;
11229   case tok::amp:          Opc = UO_AddrOf; break;
11230   case tok::star:         Opc = UO_Deref; break;
11231   case tok::plus:         Opc = UO_Plus; break;
11232   case tok::minus:        Opc = UO_Minus; break;
11233   case tok::tilde:        Opc = UO_Not; break;
11234   case tok::exclaim:      Opc = UO_LNot; break;
11235   case tok::kw___real:    Opc = UO_Real; break;
11236   case tok::kw___imag:    Opc = UO_Imag; break;
11237   case tok::kw___extension__: Opc = UO_Extension; break;
11238   }
11239   return Opc;
11240 }
11241
11242 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11243 /// This warning is only emitted for builtin assignment operations. It is also
11244 /// suppressed in the event of macro expansions.
11245 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11246                                    SourceLocation OpLoc) {
11247   if (S.inTemplateInstantiation())
11248     return;
11249   if (OpLoc.isInvalid() || OpLoc.isMacroID())
11250     return;
11251   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11252   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11253   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11254   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11255   if (!LHSDeclRef || !RHSDeclRef ||
11256       LHSDeclRef->getLocation().isMacroID() ||
11257       RHSDeclRef->getLocation().isMacroID())
11258     return;
11259   const ValueDecl *LHSDecl =
11260     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11261   const ValueDecl *RHSDecl =
11262     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11263   if (LHSDecl != RHSDecl)
11264     return;
11265   if (LHSDecl->getType().isVolatileQualified())
11266     return;
11267   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11268     if (RefTy->getPointeeType().isVolatileQualified())
11269       return;
11270
11271   S.Diag(OpLoc, diag::warn_self_assignment)
11272       << LHSDeclRef->getType()
11273       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11274 }
11275
11276 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
11277 /// is usually indicative of introspection within the Objective-C pointer.
11278 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11279                                           SourceLocation OpLoc) {
11280   if (!S.getLangOpts().ObjC1)
11281     return;
11282
11283   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11284   const Expr *LHS = L.get();
11285   const Expr *RHS = R.get();
11286
11287   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11288     ObjCPointerExpr = LHS;
11289     OtherExpr = RHS;
11290   }
11291   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11292     ObjCPointerExpr = RHS;
11293     OtherExpr = LHS;
11294   }
11295
11296   // This warning is deliberately made very specific to reduce false
11297   // positives with logic that uses '&' for hashing.  This logic mainly
11298   // looks for code trying to introspect into tagged pointers, which
11299   // code should generally never do.
11300   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11301     unsigned Diag = diag::warn_objc_pointer_masking;
11302     // Determine if we are introspecting the result of performSelectorXXX.
11303     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11304     // Special case messages to -performSelector and friends, which
11305     // can return non-pointer values boxed in a pointer value.
11306     // Some clients may wish to silence warnings in this subcase.
11307     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11308       Selector S = ME->getSelector();
11309       StringRef SelArg0 = S.getNameForSlot(0);
11310       if (SelArg0.startswith("performSelector"))
11311         Diag = diag::warn_objc_pointer_masking_performSelector;
11312     }
11313     
11314     S.Diag(OpLoc, Diag)
11315       << ObjCPointerExpr->getSourceRange();
11316   }
11317 }
11318
11319 static NamedDecl *getDeclFromExpr(Expr *E) {
11320   if (!E)
11321     return nullptr;
11322   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11323     return DRE->getDecl();
11324   if (auto *ME = dyn_cast<MemberExpr>(E))
11325     return ME->getMemberDecl();
11326   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11327     return IRE->getDecl();
11328   return nullptr;
11329 }
11330
11331 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11332 /// operator @p Opc at location @c TokLoc. This routine only supports
11333 /// built-in operations; ActOnBinOp handles overloaded operators.
11334 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11335                                     BinaryOperatorKind Opc,
11336                                     Expr *LHSExpr, Expr *RHSExpr) {
11337   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11338     // The syntax only allows initializer lists on the RHS of assignment,
11339     // so we don't need to worry about accepting invalid code for
11340     // non-assignment operators.
11341     // C++11 5.17p9:
11342     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11343     //   of x = {} is x = T().
11344     InitializationKind Kind =
11345         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
11346     InitializedEntity Entity =
11347         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11348     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11349     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11350     if (Init.isInvalid())
11351       return Init;
11352     RHSExpr = Init.get();
11353   }
11354
11355   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11356   QualType ResultTy;     // Result type of the binary operator.
11357   // The following two variables are used for compound assignment operators
11358   QualType CompLHSTy;    // Type of LHS after promotions for computation
11359   QualType CompResultTy; // Type of computation result
11360   ExprValueKind VK = VK_RValue;
11361   ExprObjectKind OK = OK_Ordinary;
11362
11363   if (!getLangOpts().CPlusPlus) {
11364     // C cannot handle TypoExpr nodes on either side of a binop because it
11365     // doesn't handle dependent types properly, so make sure any TypoExprs have
11366     // been dealt with before checking the operands.
11367     LHS = CorrectDelayedTyposInExpr(LHSExpr);
11368     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
11369       if (Opc != BO_Assign)
11370         return ExprResult(E);
11371       // Avoid correcting the RHS to the same Expr as the LHS.
11372       Decl *D = getDeclFromExpr(E);
11373       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11374     });
11375     if (!LHS.isUsable() || !RHS.isUsable())
11376       return ExprError();
11377   }
11378
11379   if (getLangOpts().OpenCL) {
11380     QualType LHSTy = LHSExpr->getType();
11381     QualType RHSTy = RHSExpr->getType();
11382     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11383     // the ATOMIC_VAR_INIT macro.
11384     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11385       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11386       if (BO_Assign == Opc)
11387         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
11388       else
11389         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11390       return ExprError();
11391     }
11392
11393     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11394     // only with a builtin functions and therefore should be disallowed here.
11395     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11396         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11397         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11398         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11399       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11400       return ExprError();
11401     }
11402   }
11403
11404   switch (Opc) {
11405   case BO_Assign:
11406     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11407     if (getLangOpts().CPlusPlus &&
11408         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11409       VK = LHS.get()->getValueKind();
11410       OK = LHS.get()->getObjectKind();
11411     }
11412     if (!ResultTy.isNull()) {
11413       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11414       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11415     }
11416     RecordModifiableNonNullParam(*this, LHS.get());
11417     break;
11418   case BO_PtrMemD:
11419   case BO_PtrMemI:
11420     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11421                                             Opc == BO_PtrMemI);
11422     break;
11423   case BO_Mul:
11424   case BO_Div:
11425     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11426                                            Opc == BO_Div);
11427     break;
11428   case BO_Rem:
11429     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11430     break;
11431   case BO_Add:
11432     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11433     break;
11434   case BO_Sub:
11435     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11436     break;
11437   case BO_Shl:
11438   case BO_Shr:
11439     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11440     break;
11441   case BO_LE:
11442   case BO_LT:
11443   case BO_GE:
11444   case BO_GT:
11445     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11446     break;
11447   case BO_EQ:
11448   case BO_NE:
11449     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11450     break;
11451   case BO_And:
11452     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11453   case BO_Xor:
11454   case BO_Or:
11455     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11456     break;
11457   case BO_LAnd:
11458   case BO_LOr:
11459     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11460     break;
11461   case BO_MulAssign:
11462   case BO_DivAssign:
11463     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11464                                                Opc == BO_DivAssign);
11465     CompLHSTy = CompResultTy;
11466     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11467       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11468     break;
11469   case BO_RemAssign:
11470     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11471     CompLHSTy = CompResultTy;
11472     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11473       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11474     break;
11475   case BO_AddAssign:
11476     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11477     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11478       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11479     break;
11480   case BO_SubAssign:
11481     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11482     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11483       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11484     break;
11485   case BO_ShlAssign:
11486   case BO_ShrAssign:
11487     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11488     CompLHSTy = CompResultTy;
11489     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11490       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11491     break;
11492   case BO_AndAssign:
11493   case BO_OrAssign: // fallthrough
11494     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11495   case BO_XorAssign:
11496     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11497     CompLHSTy = CompResultTy;
11498     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11499       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11500     break;
11501   case BO_Comma:
11502     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11503     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11504       VK = RHS.get()->getValueKind();
11505       OK = RHS.get()->getObjectKind();
11506     }
11507     break;
11508   }
11509   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11510     return ExprError();
11511
11512   // Check for array bounds violations for both sides of the BinaryOperator
11513   CheckArrayAccess(LHS.get());
11514   CheckArrayAccess(RHS.get());
11515
11516   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11517     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11518                                                  &Context.Idents.get("object_setClass"),
11519                                                  SourceLocation(), LookupOrdinaryName);
11520     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11521       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11522       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11523       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11524       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11525       FixItHint::CreateInsertion(RHSLocEnd, ")");
11526     }
11527     else
11528       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11529   }
11530   else if (const ObjCIvarRefExpr *OIRE =
11531            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11532     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11533   
11534   if (CompResultTy.isNull())
11535     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11536                                         OK, OpLoc, FPFeatures);
11537   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11538       OK_ObjCProperty) {
11539     VK = VK_LValue;
11540     OK = LHS.get()->getObjectKind();
11541   }
11542   return new (Context) CompoundAssignOperator(
11543       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11544       OpLoc, FPFeatures);
11545 }
11546
11547 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11548 /// operators are mixed in a way that suggests that the programmer forgot that
11549 /// comparison operators have higher precedence. The most typical example of
11550 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11551 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11552                                       SourceLocation OpLoc, Expr *LHSExpr,
11553                                       Expr *RHSExpr) {
11554   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11555   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11556
11557   // Check that one of the sides is a comparison operator and the other isn't.
11558   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11559   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11560   if (isLeftComp == isRightComp)
11561     return;
11562
11563   // Bitwise operations are sometimes used as eager logical ops.
11564   // Don't diagnose this.
11565   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11566   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11567   if (isLeftBitwise || isRightBitwise)
11568     return;
11569
11570   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11571                                                    OpLoc)
11572                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11573   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11574   SourceRange ParensRange = isLeftComp ?
11575       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11576     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11577
11578   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11579     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11580   SuggestParentheses(Self, OpLoc,
11581     Self.PDiag(diag::note_precedence_silence) << OpStr,
11582     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11583   SuggestParentheses(Self, OpLoc,
11584     Self.PDiag(diag::note_precedence_bitwise_first)
11585       << BinaryOperator::getOpcodeStr(Opc),
11586     ParensRange);
11587 }
11588
11589 /// \brief It accepts a '&&' expr that is inside a '||' one.
11590 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11591 /// in parentheses.
11592 static void
11593 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11594                                        BinaryOperator *Bop) {
11595   assert(Bop->getOpcode() == BO_LAnd);
11596   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11597       << Bop->getSourceRange() << OpLoc;
11598   SuggestParentheses(Self, Bop->getOperatorLoc(),
11599     Self.PDiag(diag::note_precedence_silence)
11600       << Bop->getOpcodeStr(),
11601     Bop->getSourceRange());
11602 }
11603
11604 /// \brief Returns true if the given expression can be evaluated as a constant
11605 /// 'true'.
11606 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11607   bool Res;
11608   return !E->isValueDependent() &&
11609          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11610 }
11611
11612 /// \brief Returns true if the given expression can be evaluated as a constant
11613 /// 'false'.
11614 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11615   bool Res;
11616   return !E->isValueDependent() &&
11617          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11618 }
11619
11620 /// \brief Look for '&&' in the left hand of a '||' expr.
11621 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11622                                              Expr *LHSExpr, Expr *RHSExpr) {
11623   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11624     if (Bop->getOpcode() == BO_LAnd) {
11625       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11626       if (EvaluatesAsFalse(S, RHSExpr))
11627         return;
11628       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11629       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11630         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11631     } else if (Bop->getOpcode() == BO_LOr) {
11632       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11633         // If it's "a || b && 1 || c" we didn't warn earlier for
11634         // "a || b && 1", but warn now.
11635         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11636           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11637       }
11638     }
11639   }
11640 }
11641
11642 /// \brief Look for '&&' in the right hand of a '||' expr.
11643 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11644                                              Expr *LHSExpr, Expr *RHSExpr) {
11645   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11646     if (Bop->getOpcode() == BO_LAnd) {
11647       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11648       if (EvaluatesAsFalse(S, LHSExpr))
11649         return;
11650       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11651       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11652         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11653     }
11654   }
11655 }
11656
11657 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11658 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11659 /// the '&' expression in parentheses.
11660 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11661                                          SourceLocation OpLoc, Expr *SubExpr) {
11662   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11663     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11664       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11665         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11666         << Bop->getSourceRange() << OpLoc;
11667       SuggestParentheses(S, Bop->getOperatorLoc(),
11668         S.PDiag(diag::note_precedence_silence)
11669           << Bop->getOpcodeStr(),
11670         Bop->getSourceRange());
11671     }
11672   }
11673 }
11674
11675 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11676                                     Expr *SubExpr, StringRef Shift) {
11677   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11678     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11679       StringRef Op = Bop->getOpcodeStr();
11680       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11681           << Bop->getSourceRange() << OpLoc << Shift << Op;
11682       SuggestParentheses(S, Bop->getOperatorLoc(),
11683           S.PDiag(diag::note_precedence_silence) << Op,
11684           Bop->getSourceRange());
11685     }
11686   }
11687 }
11688
11689 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11690                                  Expr *LHSExpr, Expr *RHSExpr) {
11691   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11692   if (!OCE)
11693     return;
11694
11695   FunctionDecl *FD = OCE->getDirectCallee();
11696   if (!FD || !FD->isOverloadedOperator())
11697     return;
11698
11699   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11700   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11701     return;
11702
11703   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11704       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11705       << (Kind == OO_LessLess);
11706   SuggestParentheses(S, OCE->getOperatorLoc(),
11707                      S.PDiag(diag::note_precedence_silence)
11708                          << (Kind == OO_LessLess ? "<<" : ">>"),
11709                      OCE->getSourceRange());
11710   SuggestParentheses(S, OpLoc,
11711                      S.PDiag(diag::note_evaluate_comparison_first),
11712                      SourceRange(OCE->getArg(1)->getLocStart(),
11713                                  RHSExpr->getLocEnd()));
11714 }
11715
11716 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11717 /// precedence.
11718 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11719                                     SourceLocation OpLoc, Expr *LHSExpr,
11720                                     Expr *RHSExpr){
11721   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11722   if (BinaryOperator::isBitwiseOp(Opc))
11723     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11724
11725   // Diagnose "arg1 & arg2 | arg3"
11726   if ((Opc == BO_Or || Opc == BO_Xor) &&
11727       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11728     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11729     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11730   }
11731
11732   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11733   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11734   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11735     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11736     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11737   }
11738
11739   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11740       || Opc == BO_Shr) {
11741     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11742     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11743     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11744   }
11745
11746   // Warn on overloaded shift operators and comparisons, such as:
11747   // cout << 5 == 4;
11748   if (BinaryOperator::isComparisonOp(Opc))
11749     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11750 }
11751
11752 // Binary Operators.  'Tok' is the token for the operator.
11753 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11754                             tok::TokenKind Kind,
11755                             Expr *LHSExpr, Expr *RHSExpr) {
11756   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11757   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11758   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11759
11760   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11761   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11762
11763   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11764 }
11765
11766 /// Build an overloaded binary operator expression in the given scope.
11767 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11768                                        BinaryOperatorKind Opc,
11769                                        Expr *LHS, Expr *RHS) {
11770   // Find all of the overloaded operators visible from this
11771   // point. We perform both an operator-name lookup from the local
11772   // scope and an argument-dependent lookup based on the types of
11773   // the arguments.
11774   UnresolvedSet<16> Functions;
11775   OverloadedOperatorKind OverOp
11776     = BinaryOperator::getOverloadedOperator(Opc);
11777   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11778     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11779                                    RHS->getType(), Functions);
11780
11781   // Build the (potentially-overloaded, potentially-dependent)
11782   // binary operation.
11783   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11784 }
11785
11786 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11787                             BinaryOperatorKind Opc,
11788                             Expr *LHSExpr, Expr *RHSExpr) {
11789   // We want to end up calling one of checkPseudoObjectAssignment
11790   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11791   // both expressions are overloadable or either is type-dependent),
11792   // or CreateBuiltinBinOp (in any other case).  We also want to get
11793   // any placeholder types out of the way.
11794
11795   // Handle pseudo-objects in the LHS.
11796   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11797     // Assignments with a pseudo-object l-value need special analysis.
11798     if (pty->getKind() == BuiltinType::PseudoObject &&
11799         BinaryOperator::isAssignmentOp(Opc))
11800       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11801
11802     // Don't resolve overloads if the other type is overloadable.
11803     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
11804       // We can't actually test that if we still have a placeholder,
11805       // though.  Fortunately, none of the exceptions we see in that
11806       // code below are valid when the LHS is an overload set.  Note
11807       // that an overload set can be dependently-typed, but it never
11808       // instantiates to having an overloadable type.
11809       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11810       if (resolvedRHS.isInvalid()) return ExprError();
11811       RHSExpr = resolvedRHS.get();
11812
11813       if (RHSExpr->isTypeDependent() ||
11814           RHSExpr->getType()->isOverloadableType())
11815         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11816     }
11817         
11818     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11819     if (LHS.isInvalid()) return ExprError();
11820     LHSExpr = LHS.get();
11821   }
11822
11823   // Handle pseudo-objects in the RHS.
11824   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11825     // An overload in the RHS can potentially be resolved by the type
11826     // being assigned to.
11827     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11828       if (getLangOpts().CPlusPlus &&
11829           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
11830            LHSExpr->getType()->isOverloadableType()))
11831         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11832
11833       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11834     }
11835
11836     // Don't resolve overloads if the other type is overloadable.
11837     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
11838         LHSExpr->getType()->isOverloadableType())
11839       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11840
11841     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11842     if (!resolvedRHS.isUsable()) return ExprError();
11843     RHSExpr = resolvedRHS.get();
11844   }
11845
11846   if (getLangOpts().CPlusPlus) {
11847     // If either expression is type-dependent, always build an
11848     // overloaded op.
11849     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11850       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11851
11852     // Otherwise, build an overloaded op if either expression has an
11853     // overloadable type.
11854     if (LHSExpr->getType()->isOverloadableType() ||
11855         RHSExpr->getType()->isOverloadableType())
11856       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11857   }
11858
11859   // Build a built-in binary operation.
11860   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11861 }
11862
11863 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11864                                       UnaryOperatorKind Opc,
11865                                       Expr *InputExpr) {
11866   ExprResult Input = InputExpr;
11867   ExprValueKind VK = VK_RValue;
11868   ExprObjectKind OK = OK_Ordinary;
11869   QualType resultType;
11870   if (getLangOpts().OpenCL) {
11871     QualType Ty = InputExpr->getType();
11872     // The only legal unary operation for atomics is '&'.
11873     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11874     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11875     // only with a builtin functions and therefore should be disallowed here.
11876         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11877         || Ty->isBlockPointerType())) {
11878       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11879                        << InputExpr->getType()
11880                        << Input.get()->getSourceRange());
11881     }
11882   }
11883   switch (Opc) {
11884   case UO_PreInc:
11885   case UO_PreDec:
11886   case UO_PostInc:
11887   case UO_PostDec:
11888     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11889                                                 OpLoc,
11890                                                 Opc == UO_PreInc ||
11891                                                 Opc == UO_PostInc,
11892                                                 Opc == UO_PreInc ||
11893                                                 Opc == UO_PreDec);
11894     break;
11895   case UO_AddrOf:
11896     resultType = CheckAddressOfOperand(Input, OpLoc);
11897     RecordModifiableNonNullParam(*this, InputExpr);
11898     break;
11899   case UO_Deref: {
11900     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11901     if (Input.isInvalid()) return ExprError();
11902     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11903     break;
11904   }
11905   case UO_Plus:
11906   case UO_Minus:
11907     Input = UsualUnaryConversions(Input.get());
11908     if (Input.isInvalid()) return ExprError();
11909     resultType = Input.get()->getType();
11910     if (resultType->isDependentType())
11911       break;
11912     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11913       break;
11914     else if (resultType->isVectorType() &&
11915              // The z vector extensions don't allow + or - with bool vectors.
11916              (!Context.getLangOpts().ZVector ||
11917               resultType->getAs<VectorType>()->getVectorKind() !=
11918               VectorType::AltiVecBool))
11919       break;
11920     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11921              Opc == UO_Plus &&
11922              resultType->isPointerType())
11923       break;
11924
11925     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11926       << resultType << Input.get()->getSourceRange());
11927
11928   case UO_Not: // bitwise complement
11929     Input = UsualUnaryConversions(Input.get());
11930     if (Input.isInvalid())
11931       return ExprError();
11932     resultType = Input.get()->getType();
11933     if (resultType->isDependentType())
11934       break;
11935     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11936     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11937       // C99 does not support '~' for complex conjugation.
11938       Diag(OpLoc, diag::ext_integer_complement_complex)
11939           << resultType << Input.get()->getSourceRange();
11940     else if (resultType->hasIntegerRepresentation())
11941       break;
11942     else if (resultType->isExtVectorType()) {
11943       if (Context.getLangOpts().OpenCL) {
11944         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11945         // on vector float types.
11946         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11947         if (!T->isIntegerType())
11948           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11949                            << resultType << Input.get()->getSourceRange());
11950       }
11951       break;
11952     } else {
11953       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11954                        << resultType << Input.get()->getSourceRange());
11955     }
11956     break;
11957
11958   case UO_LNot: // logical negation
11959     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11960     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11961     if (Input.isInvalid()) return ExprError();
11962     resultType = Input.get()->getType();
11963
11964     // Though we still have to promote half FP to float...
11965     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11966       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11967       resultType = Context.FloatTy;
11968     }
11969
11970     if (resultType->isDependentType())
11971       break;
11972     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11973       // C99 6.5.3.3p1: ok, fallthrough;
11974       if (Context.getLangOpts().CPlusPlus) {
11975         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11976         // operand contextually converted to bool.
11977         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11978                                   ScalarTypeToBooleanCastKind(resultType));
11979       } else if (Context.getLangOpts().OpenCL &&
11980                  Context.getLangOpts().OpenCLVersion < 120) {
11981         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11982         // operate on scalar float types.
11983         if (!resultType->isIntegerType() && !resultType->isPointerType())
11984           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11985                            << resultType << Input.get()->getSourceRange());
11986       }
11987     } else if (resultType->isExtVectorType()) {
11988       if (Context.getLangOpts().OpenCL &&
11989           Context.getLangOpts().OpenCLVersion < 120) {
11990         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11991         // operate on vector float types.
11992         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11993         if (!T->isIntegerType())
11994           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11995                            << resultType << Input.get()->getSourceRange());
11996       }
11997       // Vector logical not returns the signed variant of the operand type.
11998       resultType = GetSignedVectorType(resultType);
11999       break;
12000     } else {
12001       // FIXME: GCC's vector extension permits the usage of '!' with a vector
12002       //        type in C++. We should allow that here too.
12003       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12004         << resultType << Input.get()->getSourceRange());
12005     }
12006     
12007     // LNot always has type int. C99 6.5.3.3p5.
12008     // In C++, it's bool. C++ 5.3.1p8
12009     resultType = Context.getLogicalOperationType();
12010     break;
12011   case UO_Real:
12012   case UO_Imag:
12013     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
12014     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
12015     // complex l-values to ordinary l-values and all other values to r-values.
12016     if (Input.isInvalid()) return ExprError();
12017     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
12018       if (Input.get()->getValueKind() != VK_RValue &&
12019           Input.get()->getObjectKind() == OK_Ordinary)
12020         VK = Input.get()->getValueKind();
12021     } else if (!getLangOpts().CPlusPlus) {
12022       // In C, a volatile scalar is read by __imag. In C++, it is not.
12023       Input = DefaultLvalueConversion(Input.get());
12024     }
12025     break;
12026   case UO_Extension:
12027   case UO_Coawait:
12028     resultType = Input.get()->getType();
12029     VK = Input.get()->getValueKind();
12030     OK = Input.get()->getObjectKind();
12031     break;
12032   }
12033   if (resultType.isNull() || Input.isInvalid())
12034     return ExprError();
12035
12036   // Check for array bounds violations in the operand of the UnaryOperator,
12037   // except for the '*' and '&' operators that have to be handled specially
12038   // by CheckArrayAccess (as there are special cases like &array[arraysize]
12039   // that are explicitly defined as valid by the standard).
12040   if (Opc != UO_AddrOf && Opc != UO_Deref)
12041     CheckArrayAccess(Input.get());
12042
12043   return new (Context)
12044       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
12045 }
12046
12047 /// \brief Determine whether the given expression is a qualified member
12048 /// access expression, of a form that could be turned into a pointer to member
12049 /// with the address-of operator.
12050 static bool isQualifiedMemberAccess(Expr *E) {
12051   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12052     if (!DRE->getQualifier())
12053       return false;
12054     
12055     ValueDecl *VD = DRE->getDecl();
12056     if (!VD->isCXXClassMember())
12057       return false;
12058     
12059     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
12060       return true;
12061     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
12062       return Method->isInstance();
12063       
12064     return false;
12065   }
12066   
12067   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12068     if (!ULE->getQualifier())
12069       return false;
12070     
12071     for (NamedDecl *D : ULE->decls()) {
12072       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
12073         if (Method->isInstance())
12074           return true;
12075       } else {
12076         // Overload set does not contain methods.
12077         break;
12078       }
12079     }
12080     
12081     return false;
12082   }
12083   
12084   return false;
12085 }
12086
12087 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
12088                               UnaryOperatorKind Opc, Expr *Input) {
12089   // First things first: handle placeholders so that the
12090   // overloaded-operator check considers the right type.
12091   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
12092     // Increment and decrement of pseudo-object references.
12093     if (pty->getKind() == BuiltinType::PseudoObject &&
12094         UnaryOperator::isIncrementDecrementOp(Opc))
12095       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
12096
12097     // extension is always a builtin operator.
12098     if (Opc == UO_Extension)
12099       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12100
12101     // & gets special logic for several kinds of placeholder.
12102     // The builtin code knows what to do.
12103     if (Opc == UO_AddrOf &&
12104         (pty->getKind() == BuiltinType::Overload ||
12105          pty->getKind() == BuiltinType::UnknownAny ||
12106          pty->getKind() == BuiltinType::BoundMember))
12107       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12108
12109     // Anything else needs to be handled now.
12110     ExprResult Result = CheckPlaceholderExpr(Input);
12111     if (Result.isInvalid()) return ExprError();
12112     Input = Result.get();
12113   }
12114
12115   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
12116       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
12117       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
12118     // Find all of the overloaded operators visible from this
12119     // point. We perform both an operator-name lookup from the local
12120     // scope and an argument-dependent lookup based on the types of
12121     // the arguments.
12122     UnresolvedSet<16> Functions;
12123     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
12124     if (S && OverOp != OO_None)
12125       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
12126                                    Functions);
12127
12128     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
12129   }
12130
12131   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12132 }
12133
12134 // Unary Operators.  'Tok' is the token for the operator.
12135 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
12136                               tok::TokenKind Op, Expr *Input) {
12137   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
12138 }
12139
12140 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
12141 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
12142                                 LabelDecl *TheDecl) {
12143   TheDecl->markUsed(Context);
12144   // Create the AST node.  The address of a label always has type 'void*'.
12145   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
12146                                      Context.getPointerType(Context.VoidTy));
12147 }
12148
12149 /// Given the last statement in a statement-expression, check whether
12150 /// the result is a producing expression (like a call to an
12151 /// ns_returns_retained function) and, if so, rebuild it to hoist the
12152 /// release out of the full-expression.  Otherwise, return null.
12153 /// Cannot fail.
12154 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
12155   // Should always be wrapped with one of these.
12156   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
12157   if (!cleanups) return nullptr;
12158
12159   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
12160   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
12161     return nullptr;
12162
12163   // Splice out the cast.  This shouldn't modify any interesting
12164   // features of the statement.
12165   Expr *producer = cast->getSubExpr();
12166   assert(producer->getType() == cast->getType());
12167   assert(producer->getValueKind() == cast->getValueKind());
12168   cleanups->setSubExpr(producer);
12169   return cleanups;
12170 }
12171
12172 void Sema::ActOnStartStmtExpr() {
12173   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12174 }
12175
12176 void Sema::ActOnStmtExprError() {
12177   // Note that function is also called by TreeTransform when leaving a
12178   // StmtExpr scope without rebuilding anything.
12179
12180   DiscardCleanupsInEvaluationContext();
12181   PopExpressionEvaluationContext();
12182 }
12183
12184 ExprResult
12185 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
12186                     SourceLocation RPLoc) { // "({..})"
12187   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
12188   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
12189
12190   if (hasAnyUnrecoverableErrorsInThisFunction())
12191     DiscardCleanupsInEvaluationContext();
12192   assert(!Cleanup.exprNeedsCleanups() &&
12193          "cleanups within StmtExpr not correctly bound!");
12194   PopExpressionEvaluationContext();
12195
12196   // FIXME: there are a variety of strange constraints to enforce here, for
12197   // example, it is not possible to goto into a stmt expression apparently.
12198   // More semantic analysis is needed.
12199
12200   // If there are sub-stmts in the compound stmt, take the type of the last one
12201   // as the type of the stmtexpr.
12202   QualType Ty = Context.VoidTy;
12203   bool StmtExprMayBindToTemp = false;
12204   if (!Compound->body_empty()) {
12205     Stmt *LastStmt = Compound->body_back();
12206     LabelStmt *LastLabelStmt = nullptr;
12207     // If LastStmt is a label, skip down through into the body.
12208     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
12209       LastLabelStmt = Label;
12210       LastStmt = Label->getSubStmt();
12211     }
12212
12213     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
12214       // Do function/array conversion on the last expression, but not
12215       // lvalue-to-rvalue.  However, initialize an unqualified type.
12216       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
12217       if (LastExpr.isInvalid())
12218         return ExprError();
12219       Ty = LastExpr.get()->getType().getUnqualifiedType();
12220
12221       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
12222         // In ARC, if the final expression ends in a consume, splice
12223         // the consume out and bind it later.  In the alternate case
12224         // (when dealing with a retainable type), the result
12225         // initialization will create a produce.  In both cases the
12226         // result will be +1, and we'll need to balance that out with
12227         // a bind.
12228         if (Expr *rebuiltLastStmt
12229               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
12230           LastExpr = rebuiltLastStmt;
12231         } else {
12232           LastExpr = PerformCopyInitialization(
12233                             InitializedEntity::InitializeResult(LPLoc, 
12234                                                                 Ty,
12235                                                                 false),
12236                                                    SourceLocation(),
12237                                                LastExpr);
12238         }
12239
12240         if (LastExpr.isInvalid())
12241           return ExprError();
12242         if (LastExpr.get() != nullptr) {
12243           if (!LastLabelStmt)
12244             Compound->setLastStmt(LastExpr.get());
12245           else
12246             LastLabelStmt->setSubStmt(LastExpr.get());
12247           StmtExprMayBindToTemp = true;
12248         }
12249       }
12250     }
12251   }
12252
12253   // FIXME: Check that expression type is complete/non-abstract; statement
12254   // expressions are not lvalues.
12255   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
12256   if (StmtExprMayBindToTemp)
12257     return MaybeBindToTemporary(ResStmtExpr);
12258   return ResStmtExpr;
12259 }
12260
12261 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
12262                                       TypeSourceInfo *TInfo,
12263                                       ArrayRef<OffsetOfComponent> Components,
12264                                       SourceLocation RParenLoc) {
12265   QualType ArgTy = TInfo->getType();
12266   bool Dependent = ArgTy->isDependentType();
12267   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
12268   
12269   // We must have at least one component that refers to the type, and the first
12270   // one is known to be a field designator.  Verify that the ArgTy represents
12271   // a struct/union/class.
12272   if (!Dependent && !ArgTy->isRecordType())
12273     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 
12274                        << ArgTy << TypeRange);
12275   
12276   // Type must be complete per C99 7.17p3 because a declaring a variable
12277   // with an incomplete type would be ill-formed.
12278   if (!Dependent 
12279       && RequireCompleteType(BuiltinLoc, ArgTy,
12280                              diag::err_offsetof_incomplete_type, TypeRange))
12281     return ExprError();
12282   
12283   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
12284   // GCC extension, diagnose them.
12285   // FIXME: This diagnostic isn't actually visible because the location is in
12286   // a system header!
12287   if (Components.size() != 1)
12288     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
12289       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
12290   
12291   bool DidWarnAboutNonPOD = false;
12292   QualType CurrentType = ArgTy;
12293   SmallVector<OffsetOfNode, 4> Comps;
12294   SmallVector<Expr*, 4> Exprs;
12295   for (const OffsetOfComponent &OC : Components) {
12296     if (OC.isBrackets) {
12297       // Offset of an array sub-field.  TODO: Should we allow vector elements?
12298       if (!CurrentType->isDependentType()) {
12299         const ArrayType *AT = Context.getAsArrayType(CurrentType);
12300         if(!AT)
12301           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
12302                            << CurrentType);
12303         CurrentType = AT->getElementType();
12304       } else
12305         CurrentType = Context.DependentTy;
12306       
12307       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
12308       if (IdxRval.isInvalid())
12309         return ExprError();
12310       Expr *Idx = IdxRval.get();
12311
12312       // The expression must be an integral expression.
12313       // FIXME: An integral constant expression?
12314       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
12315           !Idx->getType()->isIntegerType())
12316         return ExprError(Diag(Idx->getLocStart(),
12317                               diag::err_typecheck_subscript_not_integer)
12318                          << Idx->getSourceRange());
12319
12320       // Record this array index.
12321       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
12322       Exprs.push_back(Idx);
12323       continue;
12324     }
12325     
12326     // Offset of a field.
12327     if (CurrentType->isDependentType()) {
12328       // We have the offset of a field, but we can't look into the dependent
12329       // type. Just record the identifier of the field.
12330       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12331       CurrentType = Context.DependentTy;
12332       continue;
12333     }
12334     
12335     // We need to have a complete type to look into.
12336     if (RequireCompleteType(OC.LocStart, CurrentType,
12337                             diag::err_offsetof_incomplete_type))
12338       return ExprError();
12339     
12340     // Look for the designated field.
12341     const RecordType *RC = CurrentType->getAs<RecordType>();
12342     if (!RC) 
12343       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12344                        << CurrentType);
12345     RecordDecl *RD = RC->getDecl();
12346     
12347     // C++ [lib.support.types]p5:
12348     //   The macro offsetof accepts a restricted set of type arguments in this
12349     //   International Standard. type shall be a POD structure or a POD union
12350     //   (clause 9).
12351     // C++11 [support.types]p4:
12352     //   If type is not a standard-layout class (Clause 9), the results are
12353     //   undefined.
12354     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12355       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12356       unsigned DiagID =
12357         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12358                             : diag::ext_offsetof_non_pod_type;
12359
12360       if (!IsSafe && !DidWarnAboutNonPOD &&
12361           DiagRuntimeBehavior(BuiltinLoc, nullptr,
12362                               PDiag(DiagID)
12363                               << SourceRange(Components[0].LocStart, OC.LocEnd)
12364                               << CurrentType))
12365         DidWarnAboutNonPOD = true;
12366     }
12367     
12368     // Look for the field.
12369     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12370     LookupQualifiedName(R, RD);
12371     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12372     IndirectFieldDecl *IndirectMemberDecl = nullptr;
12373     if (!MemberDecl) {
12374       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12375         MemberDecl = IndirectMemberDecl->getAnonField();
12376     }
12377
12378     if (!MemberDecl)
12379       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12380                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 
12381                                                               OC.LocEnd));
12382     
12383     // C99 7.17p3:
12384     //   (If the specified member is a bit-field, the behavior is undefined.)
12385     //
12386     // We diagnose this as an error.
12387     if (MemberDecl->isBitField()) {
12388       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12389         << MemberDecl->getDeclName()
12390         << SourceRange(BuiltinLoc, RParenLoc);
12391       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12392       return ExprError();
12393     }
12394
12395     RecordDecl *Parent = MemberDecl->getParent();
12396     if (IndirectMemberDecl)
12397       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12398
12399     // If the member was found in a base class, introduce OffsetOfNodes for
12400     // the base class indirections.
12401     CXXBasePaths Paths;
12402     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12403                       Paths)) {
12404       if (Paths.getDetectedVirtual()) {
12405         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12406           << MemberDecl->getDeclName()
12407           << SourceRange(BuiltinLoc, RParenLoc);
12408         return ExprError();
12409       }
12410
12411       CXXBasePath &Path = Paths.front();
12412       for (const CXXBasePathElement &B : Path)
12413         Comps.push_back(OffsetOfNode(B.Base));
12414     }
12415
12416     if (IndirectMemberDecl) {
12417       for (auto *FI : IndirectMemberDecl->chain()) {
12418         assert(isa<FieldDecl>(FI));
12419         Comps.push_back(OffsetOfNode(OC.LocStart,
12420                                      cast<FieldDecl>(FI), OC.LocEnd));
12421       }
12422     } else
12423       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12424
12425     CurrentType = MemberDecl->getType().getNonReferenceType(); 
12426   }
12427   
12428   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12429                               Comps, Exprs, RParenLoc);
12430 }
12431
12432 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12433                                       SourceLocation BuiltinLoc,
12434                                       SourceLocation TypeLoc,
12435                                       ParsedType ParsedArgTy,
12436                                       ArrayRef<OffsetOfComponent> Components,
12437                                       SourceLocation RParenLoc) {
12438   
12439   TypeSourceInfo *ArgTInfo;
12440   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12441   if (ArgTy.isNull())
12442     return ExprError();
12443
12444   if (!ArgTInfo)
12445     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12446
12447   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12448 }
12449
12450
12451 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12452                                  Expr *CondExpr,
12453                                  Expr *LHSExpr, Expr *RHSExpr,
12454                                  SourceLocation RPLoc) {
12455   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12456
12457   ExprValueKind VK = VK_RValue;
12458   ExprObjectKind OK = OK_Ordinary;
12459   QualType resType;
12460   bool ValueDependent = false;
12461   bool CondIsTrue = false;
12462   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12463     resType = Context.DependentTy;
12464     ValueDependent = true;
12465   } else {
12466     // The conditional expression is required to be a constant expression.
12467     llvm::APSInt condEval(32);
12468     ExprResult CondICE
12469       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12470           diag::err_typecheck_choose_expr_requires_constant, false);
12471     if (CondICE.isInvalid())
12472       return ExprError();
12473     CondExpr = CondICE.get();
12474     CondIsTrue = condEval.getZExtValue();
12475
12476     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12477     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12478
12479     resType = ActiveExpr->getType();
12480     ValueDependent = ActiveExpr->isValueDependent();
12481     VK = ActiveExpr->getValueKind();
12482     OK = ActiveExpr->getObjectKind();
12483   }
12484
12485   return new (Context)
12486       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12487                  CondIsTrue, resType->isDependentType(), ValueDependent);
12488 }
12489
12490 //===----------------------------------------------------------------------===//
12491 // Clang Extensions.
12492 //===----------------------------------------------------------------------===//
12493
12494 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12495 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12496   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12497
12498   if (LangOpts.CPlusPlus) {
12499     Decl *ManglingContextDecl;
12500     if (MangleNumberingContext *MCtx =
12501             getCurrentMangleNumberContext(Block->getDeclContext(),
12502                                           ManglingContextDecl)) {
12503       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12504       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12505     }
12506   }
12507
12508   PushBlockScope(CurScope, Block);
12509   CurContext->addDecl(Block);
12510   if (CurScope)
12511     PushDeclContext(CurScope, Block);
12512   else
12513     CurContext = Block;
12514
12515   getCurBlock()->HasImplicitReturnType = true;
12516
12517   // Enter a new evaluation context to insulate the block from any
12518   // cleanups from the enclosing full-expression.
12519   PushExpressionEvaluationContext(
12520       ExpressionEvaluationContext::PotentiallyEvaluated);
12521 }
12522
12523 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12524                                Scope *CurScope) {
12525   assert(ParamInfo.getIdentifier() == nullptr &&
12526          "block-id should have no identifier!");
12527   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12528   BlockScopeInfo *CurBlock = getCurBlock();
12529
12530   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12531   QualType T = Sig->getType();
12532
12533   // FIXME: We should allow unexpanded parameter packs here, but that would,
12534   // in turn, make the block expression contain unexpanded parameter packs.
12535   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12536     // Drop the parameters.
12537     FunctionProtoType::ExtProtoInfo EPI;
12538     EPI.HasTrailingReturn = false;
12539     EPI.TypeQuals |= DeclSpec::TQ_const;
12540     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12541     Sig = Context.getTrivialTypeSourceInfo(T);
12542   }
12543   
12544   // GetTypeForDeclarator always produces a function type for a block
12545   // literal signature.  Furthermore, it is always a FunctionProtoType
12546   // unless the function was written with a typedef.
12547   assert(T->isFunctionType() &&
12548          "GetTypeForDeclarator made a non-function block signature");
12549
12550   // Look for an explicit signature in that function type.
12551   FunctionProtoTypeLoc ExplicitSignature;
12552
12553   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12554   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12555
12556     // Check whether that explicit signature was synthesized by
12557     // GetTypeForDeclarator.  If so, don't save that as part of the
12558     // written signature.
12559     if (ExplicitSignature.getLocalRangeBegin() ==
12560         ExplicitSignature.getLocalRangeEnd()) {
12561       // This would be much cheaper if we stored TypeLocs instead of
12562       // TypeSourceInfos.
12563       TypeLoc Result = ExplicitSignature.getReturnLoc();
12564       unsigned Size = Result.getFullDataSize();
12565       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12566       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12567
12568       ExplicitSignature = FunctionProtoTypeLoc();
12569     }
12570   }
12571
12572   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12573   CurBlock->FunctionType = T;
12574
12575   const FunctionType *Fn = T->getAs<FunctionType>();
12576   QualType RetTy = Fn->getReturnType();
12577   bool isVariadic =
12578     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12579
12580   CurBlock->TheDecl->setIsVariadic(isVariadic);
12581
12582   // Context.DependentTy is used as a placeholder for a missing block
12583   // return type.  TODO:  what should we do with declarators like:
12584   //   ^ * { ... }
12585   // If the answer is "apply template argument deduction"....
12586   if (RetTy != Context.DependentTy) {
12587     CurBlock->ReturnType = RetTy;
12588     CurBlock->TheDecl->setBlockMissingReturnType(false);
12589     CurBlock->HasImplicitReturnType = false;
12590   }
12591
12592   // Push block parameters from the declarator if we had them.
12593   SmallVector<ParmVarDecl*, 8> Params;
12594   if (ExplicitSignature) {
12595     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12596       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12597       if (Param->getIdentifier() == nullptr &&
12598           !Param->isImplicit() &&
12599           !Param->isInvalidDecl() &&
12600           !getLangOpts().CPlusPlus)
12601         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12602       Params.push_back(Param);
12603     }
12604
12605   // Fake up parameter variables if we have a typedef, like
12606   //   ^ fntype { ... }
12607   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12608     for (const auto &I : Fn->param_types()) {
12609       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12610           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12611       Params.push_back(Param);
12612     }
12613   }
12614
12615   // Set the parameters on the block decl.
12616   if (!Params.empty()) {
12617     CurBlock->TheDecl->setParams(Params);
12618     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12619                              /*CheckParameterNames=*/false);
12620   }
12621   
12622   // Finally we can process decl attributes.
12623   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12624
12625   // Put the parameter variables in scope.
12626   for (auto AI : CurBlock->TheDecl->parameters()) {
12627     AI->setOwningFunction(CurBlock->TheDecl);
12628
12629     // If this has an identifier, add it to the scope stack.
12630     if (AI->getIdentifier()) {
12631       CheckShadow(CurBlock->TheScope, AI);
12632
12633       PushOnScopeChains(AI, CurBlock->TheScope);
12634     }
12635   }
12636 }
12637
12638 /// ActOnBlockError - If there is an error parsing a block, this callback
12639 /// is invoked to pop the information about the block from the action impl.
12640 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12641   // Leave the expression-evaluation context.
12642   DiscardCleanupsInEvaluationContext();
12643   PopExpressionEvaluationContext();
12644
12645   // Pop off CurBlock, handle nested blocks.
12646   PopDeclContext();
12647   PopFunctionScopeInfo();
12648 }
12649
12650 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12651 /// literal was successfully completed.  ^(int x){...}
12652 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12653                                     Stmt *Body, Scope *CurScope) {
12654   // If blocks are disabled, emit an error.
12655   if (!LangOpts.Blocks)
12656     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12657
12658   // Leave the expression-evaluation context.
12659   if (hasAnyUnrecoverableErrorsInThisFunction())
12660     DiscardCleanupsInEvaluationContext();
12661   assert(!Cleanup.exprNeedsCleanups() &&
12662          "cleanups within block not correctly bound!");
12663   PopExpressionEvaluationContext();
12664
12665   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12666
12667   if (BSI->HasImplicitReturnType)
12668     deduceClosureReturnType(*BSI);
12669
12670   PopDeclContext();
12671
12672   QualType RetTy = Context.VoidTy;
12673   if (!BSI->ReturnType.isNull())
12674     RetTy = BSI->ReturnType;
12675
12676   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12677   QualType BlockTy;
12678
12679   // Set the captured variables on the block.
12680   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12681   SmallVector<BlockDecl::Capture, 4> Captures;
12682   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12683     if (Cap.isThisCapture())
12684       continue;
12685     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12686                               Cap.isNested(), Cap.getInitExpr());
12687     Captures.push_back(NewCap);
12688   }
12689   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12690
12691   // If the user wrote a function type in some form, try to use that.
12692   if (!BSI->FunctionType.isNull()) {
12693     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12694
12695     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12696     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12697     
12698     // Turn protoless block types into nullary block types.
12699     if (isa<FunctionNoProtoType>(FTy)) {
12700       FunctionProtoType::ExtProtoInfo EPI;
12701       EPI.ExtInfo = Ext;
12702       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12703
12704     // Otherwise, if we don't need to change anything about the function type,
12705     // preserve its sugar structure.
12706     } else if (FTy->getReturnType() == RetTy &&
12707                (!NoReturn || FTy->getNoReturnAttr())) {
12708       BlockTy = BSI->FunctionType;
12709
12710     // Otherwise, make the minimal modifications to the function type.
12711     } else {
12712       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12713       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12714       EPI.TypeQuals = 0; // FIXME: silently?
12715       EPI.ExtInfo = Ext;
12716       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12717     }
12718
12719   // If we don't have a function type, just build one from nothing.
12720   } else {
12721     FunctionProtoType::ExtProtoInfo EPI;
12722     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12723     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12724   }
12725
12726   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12727   BlockTy = Context.getBlockPointerType(BlockTy);
12728
12729   // If needed, diagnose invalid gotos and switches in the block.
12730   if (getCurFunction()->NeedsScopeChecking() &&
12731       !PP.isCodeCompletionEnabled())
12732     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12733
12734   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12735
12736   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12737     DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl);
12738
12739   // Try to apply the named return value optimization. We have to check again
12740   // if we can do this, though, because blocks keep return statements around
12741   // to deduce an implicit return type.
12742   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12743       !BSI->TheDecl->isDependentContext())
12744     computeNRVO(Body, BSI);
12745   
12746   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12747   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12748   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12749
12750   // If the block isn't obviously global, i.e. it captures anything at
12751   // all, then we need to do a few things in the surrounding context:
12752   if (Result->getBlockDecl()->hasCaptures()) {
12753     // First, this expression has a new cleanup object.
12754     ExprCleanupObjects.push_back(Result->getBlockDecl());
12755     Cleanup.setExprNeedsCleanups(true);
12756
12757     // It also gets a branch-protected scope if any of the captured
12758     // variables needs destruction.
12759     for (const auto &CI : Result->getBlockDecl()->captures()) {
12760       const VarDecl *var = CI.getVariable();
12761       if (var->getType().isDestructedType() != QualType::DK_none) {
12762         getCurFunction()->setHasBranchProtectedScope();
12763         break;
12764       }
12765     }
12766   }
12767
12768   return Result;
12769 }
12770
12771 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12772                             SourceLocation RPLoc) {
12773   TypeSourceInfo *TInfo;
12774   GetTypeFromParser(Ty, &TInfo);
12775   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12776 }
12777
12778 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12779                                 Expr *E, TypeSourceInfo *TInfo,
12780                                 SourceLocation RPLoc) {
12781   Expr *OrigExpr = E;
12782   bool IsMS = false;
12783
12784   // CUDA device code does not support varargs.
12785   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12786     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12787       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12788       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12789         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12790     }
12791   }
12792
12793   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12794   // as Microsoft ABI on an actual Microsoft platform, where
12795   // __builtin_ms_va_list and __builtin_va_list are the same.)
12796   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12797       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12798     QualType MSVaListType = Context.getBuiltinMSVaListType();
12799     if (Context.hasSameType(MSVaListType, E->getType())) {
12800       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12801         return ExprError();
12802       IsMS = true;
12803     }
12804   }
12805
12806   // Get the va_list type
12807   QualType VaListType = Context.getBuiltinVaListType();
12808   if (!IsMS) {
12809     if (VaListType->isArrayType()) {
12810       // Deal with implicit array decay; for example, on x86-64,
12811       // va_list is an array, but it's supposed to decay to
12812       // a pointer for va_arg.
12813       VaListType = Context.getArrayDecayedType(VaListType);
12814       // Make sure the input expression also decays appropriately.
12815       ExprResult Result = UsualUnaryConversions(E);
12816       if (Result.isInvalid())
12817         return ExprError();
12818       E = Result.get();
12819     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12820       // If va_list is a record type and we are compiling in C++ mode,
12821       // check the argument using reference binding.
12822       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12823           Context, Context.getLValueReferenceType(VaListType), false);
12824       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12825       if (Init.isInvalid())
12826         return ExprError();
12827       E = Init.getAs<Expr>();
12828     } else {
12829       // Otherwise, the va_list argument must be an l-value because
12830       // it is modified by va_arg.
12831       if (!E->isTypeDependent() &&
12832           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12833         return ExprError();
12834     }
12835   }
12836
12837   if (!IsMS && !E->isTypeDependent() &&
12838       !Context.hasSameType(VaListType, E->getType()))
12839     return ExprError(Diag(E->getLocStart(),
12840                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12841       << OrigExpr->getType() << E->getSourceRange());
12842
12843   if (!TInfo->getType()->isDependentType()) {
12844     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12845                             diag::err_second_parameter_to_va_arg_incomplete,
12846                             TInfo->getTypeLoc()))
12847       return ExprError();
12848
12849     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12850                                TInfo->getType(),
12851                                diag::err_second_parameter_to_va_arg_abstract,
12852                                TInfo->getTypeLoc()))
12853       return ExprError();
12854
12855     if (!TInfo->getType().isPODType(Context)) {
12856       Diag(TInfo->getTypeLoc().getBeginLoc(),
12857            TInfo->getType()->isObjCLifetimeType()
12858              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12859              : diag::warn_second_parameter_to_va_arg_not_pod)
12860         << TInfo->getType()
12861         << TInfo->getTypeLoc().getSourceRange();
12862     }
12863
12864     // Check for va_arg where arguments of the given type will be promoted
12865     // (i.e. this va_arg is guaranteed to have undefined behavior).
12866     QualType PromoteType;
12867     if (TInfo->getType()->isPromotableIntegerType()) {
12868       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12869       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12870         PromoteType = QualType();
12871     }
12872     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12873       PromoteType = Context.DoubleTy;
12874     if (!PromoteType.isNull())
12875       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12876                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12877                           << TInfo->getType()
12878                           << PromoteType
12879                           << TInfo->getTypeLoc().getSourceRange());
12880   }
12881
12882   QualType T = TInfo->getType().getNonLValueExprType(Context);
12883   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12884 }
12885
12886 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12887   // The type of __null will be int or long, depending on the size of
12888   // pointers on the target.
12889   QualType Ty;
12890   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12891   if (pw == Context.getTargetInfo().getIntWidth())
12892     Ty = Context.IntTy;
12893   else if (pw == Context.getTargetInfo().getLongWidth())
12894     Ty = Context.LongTy;
12895   else if (pw == Context.getTargetInfo().getLongLongWidth())
12896     Ty = Context.LongLongTy;
12897   else {
12898     llvm_unreachable("I don't know size of pointer!");
12899   }
12900
12901   return new (Context) GNUNullExpr(Ty, TokenLoc);
12902 }
12903
12904 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12905                                               bool Diagnose) {
12906   if (!getLangOpts().ObjC1)
12907     return false;
12908
12909   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12910   if (!PT)
12911     return false;
12912
12913   if (!PT->isObjCIdType()) {
12914     // Check if the destination is the 'NSString' interface.
12915     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12916     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12917       return false;
12918   }
12919   
12920   // Ignore any parens, implicit casts (should only be
12921   // array-to-pointer decays), and not-so-opaque values.  The last is
12922   // important for making this trigger for property assignments.
12923   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12924   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12925     if (OV->getSourceExpr())
12926       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12927
12928   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12929   if (!SL || !SL->isAscii())
12930     return false;
12931   if (Diagnose) {
12932     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12933       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12934     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12935   }
12936   return true;
12937 }
12938
12939 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12940                                               const Expr *SrcExpr) {
12941   if (!DstType->isFunctionPointerType() ||
12942       !SrcExpr->getType()->isFunctionType())
12943     return false;
12944
12945   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12946   if (!DRE)
12947     return false;
12948
12949   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12950   if (!FD)
12951     return false;
12952
12953   return !S.checkAddressOfFunctionIsAvailable(FD,
12954                                               /*Complain=*/true,
12955                                               SrcExpr->getLocStart());
12956 }
12957
12958 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12959                                     SourceLocation Loc,
12960                                     QualType DstType, QualType SrcType,
12961                                     Expr *SrcExpr, AssignmentAction Action,
12962                                     bool *Complained) {
12963   if (Complained)
12964     *Complained = false;
12965
12966   // Decode the result (notice that AST's are still created for extensions).
12967   bool CheckInferredResultType = false;
12968   bool isInvalid = false;
12969   unsigned DiagKind = 0;
12970   FixItHint Hint;
12971   ConversionFixItGenerator ConvHints;
12972   bool MayHaveConvFixit = false;
12973   bool MayHaveFunctionDiff = false;
12974   const ObjCInterfaceDecl *IFace = nullptr;
12975   const ObjCProtocolDecl *PDecl = nullptr;
12976
12977   switch (ConvTy) {
12978   case Compatible:
12979       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12980       return false;
12981
12982   case PointerToInt:
12983     DiagKind = diag::ext_typecheck_convert_pointer_int;
12984     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12985     MayHaveConvFixit = true;
12986     break;
12987   case IntToPointer:
12988     DiagKind = diag::ext_typecheck_convert_int_pointer;
12989     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12990     MayHaveConvFixit = true;
12991     break;
12992   case IncompatiblePointer:
12993     if (Action == AA_Passing_CFAudited)
12994       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12995     else if (SrcType->isFunctionPointerType() &&
12996              DstType->isFunctionPointerType())
12997       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12998     else
12999       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
13000
13001     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
13002       SrcType->isObjCObjectPointerType();
13003     if (Hint.isNull() && !CheckInferredResultType) {
13004       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13005     }
13006     else if (CheckInferredResultType) {
13007       SrcType = SrcType.getUnqualifiedType();
13008       DstType = DstType.getUnqualifiedType();
13009     }
13010     MayHaveConvFixit = true;
13011     break;
13012   case IncompatiblePointerSign:
13013     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
13014     break;
13015   case FunctionVoidPointer:
13016     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
13017     break;
13018   case IncompatiblePointerDiscardsQualifiers: {
13019     // Perform array-to-pointer decay if necessary.
13020     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
13021
13022     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
13023     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
13024     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
13025       DiagKind = diag::err_typecheck_incompatible_address_space;
13026       break;
13027
13028
13029     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
13030       DiagKind = diag::err_typecheck_incompatible_ownership;
13031       break;
13032     }
13033
13034     llvm_unreachable("unknown error case for discarding qualifiers!");
13035     // fallthrough
13036   }
13037   case CompatiblePointerDiscardsQualifiers:
13038     // If the qualifiers lost were because we were applying the
13039     // (deprecated) C++ conversion from a string literal to a char*
13040     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
13041     // Ideally, this check would be performed in
13042     // checkPointerTypesForAssignment. However, that would require a
13043     // bit of refactoring (so that the second argument is an
13044     // expression, rather than a type), which should be done as part
13045     // of a larger effort to fix checkPointerTypesForAssignment for
13046     // C++ semantics.
13047     if (getLangOpts().CPlusPlus &&
13048         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
13049       return false;
13050     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
13051     break;
13052   case IncompatibleNestedPointerQualifiers:
13053     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
13054     break;
13055   case IntToBlockPointer:
13056     DiagKind = diag::err_int_to_block_pointer;
13057     break;
13058   case IncompatibleBlockPointer:
13059     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
13060     break;
13061   case IncompatibleObjCQualifiedId: {
13062     if (SrcType->isObjCQualifiedIdType()) {
13063       const ObjCObjectPointerType *srcOPT =
13064                 SrcType->getAs<ObjCObjectPointerType>();
13065       for (auto *srcProto : srcOPT->quals()) {
13066         PDecl = srcProto;
13067         break;
13068       }
13069       if (const ObjCInterfaceType *IFaceT =
13070             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13071         IFace = IFaceT->getDecl();
13072     }
13073     else if (DstType->isObjCQualifiedIdType()) {
13074       const ObjCObjectPointerType *dstOPT =
13075         DstType->getAs<ObjCObjectPointerType>();
13076       for (auto *dstProto : dstOPT->quals()) {
13077         PDecl = dstProto;
13078         break;
13079       }
13080       if (const ObjCInterfaceType *IFaceT =
13081             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13082         IFace = IFaceT->getDecl();
13083     }
13084     DiagKind = diag::warn_incompatible_qualified_id;
13085     break;
13086   }
13087   case IncompatibleVectors:
13088     DiagKind = diag::warn_incompatible_vectors;
13089     break;
13090   case IncompatibleObjCWeakRef:
13091     DiagKind = diag::err_arc_weak_unavailable_assign;
13092     break;
13093   case Incompatible:
13094     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
13095       if (Complained)
13096         *Complained = true;
13097       return true;
13098     }
13099
13100     DiagKind = diag::err_typecheck_convert_incompatible;
13101     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13102     MayHaveConvFixit = true;
13103     isInvalid = true;
13104     MayHaveFunctionDiff = true;
13105     break;
13106   }
13107
13108   QualType FirstType, SecondType;
13109   switch (Action) {
13110   case AA_Assigning:
13111   case AA_Initializing:
13112     // The destination type comes first.
13113     FirstType = DstType;
13114     SecondType = SrcType;
13115     break;
13116
13117   case AA_Returning:
13118   case AA_Passing:
13119   case AA_Passing_CFAudited:
13120   case AA_Converting:
13121   case AA_Sending:
13122   case AA_Casting:
13123     // The source type comes first.
13124     FirstType = SrcType;
13125     SecondType = DstType;
13126     break;
13127   }
13128
13129   PartialDiagnostic FDiag = PDiag(DiagKind);
13130   if (Action == AA_Passing_CFAudited)
13131     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
13132   else
13133     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
13134
13135   // If we can fix the conversion, suggest the FixIts.
13136   assert(ConvHints.isNull() || Hint.isNull());
13137   if (!ConvHints.isNull()) {
13138     for (FixItHint &H : ConvHints.Hints)
13139       FDiag << H;
13140   } else {
13141     FDiag << Hint;
13142   }
13143   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
13144
13145   if (MayHaveFunctionDiff)
13146     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
13147
13148   Diag(Loc, FDiag);
13149   if (DiagKind == diag::warn_incompatible_qualified_id &&
13150       PDecl && IFace && !IFace->hasDefinition())
13151       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
13152         << IFace->getName() << PDecl->getName();
13153     
13154   if (SecondType == Context.OverloadTy)
13155     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
13156                               FirstType, /*TakingAddress=*/true);
13157
13158   if (CheckInferredResultType)
13159     EmitRelatedResultTypeNote(SrcExpr);
13160
13161   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
13162     EmitRelatedResultTypeNoteForReturn(DstType);
13163   
13164   if (Complained)
13165     *Complained = true;
13166   return isInvalid;
13167 }
13168
13169 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13170                                                  llvm::APSInt *Result) {
13171   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
13172   public:
13173     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13174       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
13175     }
13176   } Diagnoser;
13177   
13178   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
13179 }
13180
13181 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13182                                                  llvm::APSInt *Result,
13183                                                  unsigned DiagID,
13184                                                  bool AllowFold) {
13185   class IDDiagnoser : public VerifyICEDiagnoser {
13186     unsigned DiagID;
13187     
13188   public:
13189     IDDiagnoser(unsigned DiagID)
13190       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
13191     
13192     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13193       S.Diag(Loc, DiagID) << SR;
13194     }
13195   } Diagnoser(DiagID);
13196   
13197   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
13198 }
13199
13200 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
13201                                             SourceRange SR) {
13202   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
13203 }
13204
13205 ExprResult
13206 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
13207                                       VerifyICEDiagnoser &Diagnoser,
13208                                       bool AllowFold) {
13209   SourceLocation DiagLoc = E->getLocStart();
13210
13211   if (getLangOpts().CPlusPlus11) {
13212     // C++11 [expr.const]p5:
13213     //   If an expression of literal class type is used in a context where an
13214     //   integral constant expression is required, then that class type shall
13215     //   have a single non-explicit conversion function to an integral or
13216     //   unscoped enumeration type
13217     ExprResult Converted;
13218     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
13219     public:
13220       CXX11ConvertDiagnoser(bool Silent)
13221           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
13222                                 Silent, true) {}
13223
13224       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
13225                                            QualType T) override {
13226         return S.Diag(Loc, diag::err_ice_not_integral) << T;
13227       }
13228
13229       SemaDiagnosticBuilder diagnoseIncomplete(
13230           Sema &S, SourceLocation Loc, QualType T) override {
13231         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
13232       }
13233
13234       SemaDiagnosticBuilder diagnoseExplicitConv(
13235           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13236         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
13237       }
13238
13239       SemaDiagnosticBuilder noteExplicitConv(
13240           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13241         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13242                  << ConvTy->isEnumeralType() << ConvTy;
13243       }
13244
13245       SemaDiagnosticBuilder diagnoseAmbiguous(
13246           Sema &S, SourceLocation Loc, QualType T) override {
13247         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
13248       }
13249
13250       SemaDiagnosticBuilder noteAmbiguous(
13251           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13252         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13253                  << ConvTy->isEnumeralType() << ConvTy;
13254       }
13255
13256       SemaDiagnosticBuilder diagnoseConversion(
13257           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13258         llvm_unreachable("conversion functions are permitted");
13259       }
13260     } ConvertDiagnoser(Diagnoser.Suppress);
13261
13262     Converted = PerformContextualImplicitConversion(DiagLoc, E,
13263                                                     ConvertDiagnoser);
13264     if (Converted.isInvalid())
13265       return Converted;
13266     E = Converted.get();
13267     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
13268       return ExprError();
13269   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13270     // An ICE must be of integral or unscoped enumeration type.
13271     if (!Diagnoser.Suppress)
13272       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13273     return ExprError();
13274   }
13275
13276   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
13277   // in the non-ICE case.
13278   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
13279     if (Result)
13280       *Result = E->EvaluateKnownConstInt(Context);
13281     return E;
13282   }
13283
13284   Expr::EvalResult EvalResult;
13285   SmallVector<PartialDiagnosticAt, 8> Notes;
13286   EvalResult.Diag = &Notes;
13287
13288   // Try to evaluate the expression, and produce diagnostics explaining why it's
13289   // not a constant expression as a side-effect.
13290   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
13291                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
13292
13293   // In C++11, we can rely on diagnostics being produced for any expression
13294   // which is not a constant expression. If no diagnostics were produced, then
13295   // this is a constant expression.
13296   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
13297     if (Result)
13298       *Result = EvalResult.Val.getInt();
13299     return E;
13300   }
13301
13302   // If our only note is the usual "invalid subexpression" note, just point
13303   // the caret at its location rather than producing an essentially
13304   // redundant note.
13305   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13306         diag::note_invalid_subexpr_in_const_expr) {
13307     DiagLoc = Notes[0].first;
13308     Notes.clear();
13309   }
13310
13311   if (!Folded || !AllowFold) {
13312     if (!Diagnoser.Suppress) {
13313       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13314       for (const PartialDiagnosticAt &Note : Notes)
13315         Diag(Note.first, Note.second);
13316     }
13317
13318     return ExprError();
13319   }
13320
13321   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
13322   for (const PartialDiagnosticAt &Note : Notes)
13323     Diag(Note.first, Note.second);
13324
13325   if (Result)
13326     *Result = EvalResult.Val.getInt();
13327   return E;
13328 }
13329
13330 namespace {
13331   // Handle the case where we conclude a expression which we speculatively
13332   // considered to be unevaluated is actually evaluated.
13333   class TransformToPE : public TreeTransform<TransformToPE> {
13334     typedef TreeTransform<TransformToPE> BaseTransform;
13335
13336   public:
13337     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13338
13339     // Make sure we redo semantic analysis
13340     bool AlwaysRebuild() { return true; }
13341
13342     // Make sure we handle LabelStmts correctly.
13343     // FIXME: This does the right thing, but maybe we need a more general
13344     // fix to TreeTransform?
13345     StmtResult TransformLabelStmt(LabelStmt *S) {
13346       S->getDecl()->setStmt(nullptr);
13347       return BaseTransform::TransformLabelStmt(S);
13348     }
13349
13350     // We need to special-case DeclRefExprs referring to FieldDecls which
13351     // are not part of a member pointer formation; normal TreeTransforming
13352     // doesn't catch this case because of the way we represent them in the AST.
13353     // FIXME: This is a bit ugly; is it really the best way to handle this
13354     // case?
13355     //
13356     // Error on DeclRefExprs referring to FieldDecls.
13357     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13358       if (isa<FieldDecl>(E->getDecl()) &&
13359           !SemaRef.isUnevaluatedContext())
13360         return SemaRef.Diag(E->getLocation(),
13361                             diag::err_invalid_non_static_member_use)
13362             << E->getDecl() << E->getSourceRange();
13363
13364       return BaseTransform::TransformDeclRefExpr(E);
13365     }
13366
13367     // Exception: filter out member pointer formation
13368     ExprResult TransformUnaryOperator(UnaryOperator *E) {
13369       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13370         return E;
13371
13372       return BaseTransform::TransformUnaryOperator(E);
13373     }
13374
13375     ExprResult TransformLambdaExpr(LambdaExpr *E) {
13376       // Lambdas never need to be transformed.
13377       return E;
13378     }
13379   };
13380 }
13381
13382 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13383   assert(isUnevaluatedContext() &&
13384          "Should only transform unevaluated expressions");
13385   ExprEvalContexts.back().Context =
13386       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13387   if (isUnevaluatedContext())
13388     return E;
13389   return TransformToPE(*this).TransformExpr(E);
13390 }
13391
13392 void
13393 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13394                                       Decl *LambdaContextDecl,
13395                                       bool IsDecltype) {
13396   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13397                                 LambdaContextDecl, IsDecltype);
13398   Cleanup.reset();
13399   if (!MaybeODRUseExprs.empty())
13400     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13401 }
13402
13403 void
13404 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13405                                       ReuseLambdaContextDecl_t,
13406                                       bool IsDecltype) {
13407   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13408   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13409 }
13410
13411 void Sema::PopExpressionEvaluationContext() {
13412   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13413   unsigned NumTypos = Rec.NumTypos;
13414
13415   if (!Rec.Lambdas.empty()) {
13416     if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13417       unsigned D;
13418       if (Rec.isUnevaluated()) {
13419         // C++11 [expr.prim.lambda]p2:
13420         //   A lambda-expression shall not appear in an unevaluated operand
13421         //   (Clause 5).
13422         D = diag::err_lambda_unevaluated_operand;
13423       } else {
13424         // C++1y [expr.const]p2:
13425         //   A conditional-expression e is a core constant expression unless the
13426         //   evaluation of e, following the rules of the abstract machine, would
13427         //   evaluate [...] a lambda-expression.
13428         D = diag::err_lambda_in_constant_expression;
13429       }
13430
13431       // C++1z allows lambda expressions as core constant expressions.
13432       // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
13433       // 1607) from appearing within template-arguments and array-bounds that
13434       // are part of function-signatures.  Be mindful that P0315 (Lambdas in
13435       // unevaluated contexts) might lift some of these restrictions in a 
13436       // future version.
13437       if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus1z)
13438         for (const auto *L : Rec.Lambdas)
13439           Diag(L->getLocStart(), D);
13440     } else {
13441       // Mark the capture expressions odr-used. This was deferred
13442       // during lambda expression creation.
13443       for (auto *Lambda : Rec.Lambdas) {
13444         for (auto *C : Lambda->capture_inits())
13445           MarkDeclarationsReferencedInExpr(C);
13446       }
13447     }
13448   }
13449
13450   // When are coming out of an unevaluated context, clear out any
13451   // temporaries that we may have created as part of the evaluation of
13452   // the expression in that context: they aren't relevant because they
13453   // will never be constructed.
13454   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13455     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13456                              ExprCleanupObjects.end());
13457     Cleanup = Rec.ParentCleanup;
13458     CleanupVarDeclMarking();
13459     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13460   // Otherwise, merge the contexts together.
13461   } else {
13462     Cleanup.mergeFrom(Rec.ParentCleanup);
13463     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13464                             Rec.SavedMaybeODRUseExprs.end());
13465   }
13466
13467   // Pop the current expression evaluation context off the stack.
13468   ExprEvalContexts.pop_back();
13469
13470   if (!ExprEvalContexts.empty())
13471     ExprEvalContexts.back().NumTypos += NumTypos;
13472   else
13473     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13474                             "last ExpressionEvaluationContextRecord");
13475 }
13476
13477 void Sema::DiscardCleanupsInEvaluationContext() {
13478   ExprCleanupObjects.erase(
13479          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13480          ExprCleanupObjects.end());
13481   Cleanup.reset();
13482   MaybeODRUseExprs.clear();
13483 }
13484
13485 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13486   if (!E->getType()->isVariablyModifiedType())
13487     return E;
13488   return TransformToPotentiallyEvaluated(E);
13489 }
13490
13491 /// Are we within a context in which some evaluation could be performed (be it
13492 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
13493 /// captured by C++'s idea of an "unevaluated context".
13494 static bool isEvaluatableContext(Sema &SemaRef) {
13495   switch (SemaRef.ExprEvalContexts.back().Context) {
13496     case Sema::ExpressionEvaluationContext::Unevaluated:
13497     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13498     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13499       // Expressions in this context are never evaluated.
13500       return false;
13501
13502     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13503     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13504     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13505       // Expressions in this context could be evaluated.
13506       return true;
13507
13508     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13509       // Referenced declarations will only be used if the construct in the
13510       // containing expression is used, at which point we'll be given another
13511       // turn to mark them.
13512       return false;
13513   }
13514   llvm_unreachable("Invalid context");
13515 }
13516
13517 /// Are we within a context in which references to resolved functions or to
13518 /// variables result in odr-use?
13519 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
13520   // An expression in a template is not really an expression until it's been
13521   // instantiated, so it doesn't trigger odr-use.
13522   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
13523     return false;
13524
13525   switch (SemaRef.ExprEvalContexts.back().Context) {
13526     case Sema::ExpressionEvaluationContext::Unevaluated:
13527     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13528     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13529     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13530       return false;
13531
13532     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13533     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13534       return true;
13535
13536     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13537       return false;
13538   }
13539   llvm_unreachable("Invalid context");
13540 }
13541
13542 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
13543   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13544   return Func->isConstexpr() &&
13545          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
13546 }
13547
13548 /// \brief Mark a function referenced, and check whether it is odr-used
13549 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13550 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13551                                   bool MightBeOdrUse) {
13552   assert(Func && "No function?");
13553
13554   Func->setReferenced();
13555
13556   // C++11 [basic.def.odr]p3:
13557   //   A function whose name appears as a potentially-evaluated expression is
13558   //   odr-used if it is the unique lookup result or the selected member of a
13559   //   set of overloaded functions [...].
13560   //
13561   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13562   // can just check that here.
13563   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
13564
13565   // Determine whether we require a function definition to exist, per
13566   // C++11 [temp.inst]p3:
13567   //   Unless a function template specialization has been explicitly
13568   //   instantiated or explicitly specialized, the function template
13569   //   specialization is implicitly instantiated when the specialization is
13570   //   referenced in a context that requires a function definition to exist.
13571   //
13572   // That is either when this is an odr-use, or when a usage of a constexpr
13573   // function occurs within an evaluatable context.
13574   bool NeedDefinition =
13575       OdrUse || (isEvaluatableContext(*this) &&
13576                  isImplicitlyDefinableConstexprFunction(Func));
13577
13578   // C++14 [temp.expl.spec]p6:
13579   //   If a template [...] is explicitly specialized then that specialization
13580   //   shall be declared before the first use of that specialization that would
13581   //   cause an implicit instantiation to take place, in every translation unit
13582   //   in which such a use occurs
13583   if (NeedDefinition &&
13584       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13585        Func->getMemberSpecializationInfo()))
13586     checkSpecializationVisibility(Loc, Func);
13587
13588   // C++14 [except.spec]p17:
13589   //   An exception-specification is considered to be needed when:
13590   //   - the function is odr-used or, if it appears in an unevaluated operand,
13591   //     would be odr-used if the expression were potentially-evaluated;
13592   //
13593   // Note, we do this even if MightBeOdrUse is false. That indicates that the
13594   // function is a pure virtual function we're calling, and in that case the
13595   // function was selected by overload resolution and we need to resolve its
13596   // exception specification for a different reason.
13597   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13598   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13599     ResolveExceptionSpec(Loc, FPT);
13600
13601   // If we don't need to mark the function as used, and we don't need to
13602   // try to provide a definition, there's nothing more to do.
13603   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13604       (!NeedDefinition || Func->getBody()))
13605     return;
13606
13607   // Note that this declaration has been used.
13608   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13609     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13610     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13611       if (Constructor->isDefaultConstructor()) {
13612         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13613           return;
13614         DefineImplicitDefaultConstructor(Loc, Constructor);
13615       } else if (Constructor->isCopyConstructor()) {
13616         DefineImplicitCopyConstructor(Loc, Constructor);
13617       } else if (Constructor->isMoveConstructor()) {
13618         DefineImplicitMoveConstructor(Loc, Constructor);
13619       }
13620     } else if (Constructor->getInheritedConstructor()) {
13621       DefineInheritingConstructor(Loc, Constructor);
13622     }
13623   } else if (CXXDestructorDecl *Destructor =
13624                  dyn_cast<CXXDestructorDecl>(Func)) {
13625     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13626     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13627       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13628         return;
13629       DefineImplicitDestructor(Loc, Destructor);
13630     }
13631     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13632       MarkVTableUsed(Loc, Destructor->getParent());
13633   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13634     if (MethodDecl->isOverloadedOperator() &&
13635         MethodDecl->getOverloadedOperator() == OO_Equal) {
13636       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13637       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13638         if (MethodDecl->isCopyAssignmentOperator())
13639           DefineImplicitCopyAssignment(Loc, MethodDecl);
13640         else if (MethodDecl->isMoveAssignmentOperator())
13641           DefineImplicitMoveAssignment(Loc, MethodDecl);
13642       }
13643     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13644                MethodDecl->getParent()->isLambda()) {
13645       CXXConversionDecl *Conversion =
13646           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13647       if (Conversion->isLambdaToBlockPointerConversion())
13648         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13649       else
13650         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13651     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13652       MarkVTableUsed(Loc, MethodDecl->getParent());
13653   }
13654
13655   // Recursive functions should be marked when used from another function.
13656   // FIXME: Is this really right?
13657   if (CurContext == Func) return;
13658
13659   // Implicit instantiation of function templates and member functions of
13660   // class templates.
13661   if (Func->isImplicitlyInstantiable()) {
13662     bool AlreadyInstantiated = false;
13663     SourceLocation PointOfInstantiation = Loc;
13664     if (FunctionTemplateSpecializationInfo *SpecInfo
13665                               = Func->getTemplateSpecializationInfo()) {
13666       if (SpecInfo->getPointOfInstantiation().isInvalid())
13667         SpecInfo->setPointOfInstantiation(Loc);
13668       else if (SpecInfo->getTemplateSpecializationKind()
13669                  == TSK_ImplicitInstantiation) {
13670         AlreadyInstantiated = true;
13671         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13672       }
13673     } else if (MemberSpecializationInfo *MSInfo
13674                                 = Func->getMemberSpecializationInfo()) {
13675       if (MSInfo->getPointOfInstantiation().isInvalid())
13676         MSInfo->setPointOfInstantiation(Loc);
13677       else if (MSInfo->getTemplateSpecializationKind()
13678                  == TSK_ImplicitInstantiation) {
13679         AlreadyInstantiated = true;
13680         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13681       }
13682     }
13683
13684     if (!AlreadyInstantiated || Func->isConstexpr()) {
13685       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13686           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13687           CodeSynthesisContexts.size())
13688         PendingLocalImplicitInstantiations.push_back(
13689             std::make_pair(Func, PointOfInstantiation));
13690       else if (Func->isConstexpr())
13691         // Do not defer instantiations of constexpr functions, to avoid the
13692         // expression evaluator needing to call back into Sema if it sees a
13693         // call to such a function.
13694         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13695       else {
13696         PendingInstantiations.push_back(std::make_pair(Func,
13697                                                        PointOfInstantiation));
13698         // Notify the consumer that a function was implicitly instantiated.
13699         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13700       }
13701     }
13702   } else {
13703     // Walk redefinitions, as some of them may be instantiable.
13704     for (auto i : Func->redecls()) {
13705       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13706         MarkFunctionReferenced(Loc, i, OdrUse);
13707     }
13708   }
13709
13710   if (!OdrUse) return;
13711
13712   // Keep track of used but undefined functions.
13713   if (!Func->isDefined()) {
13714     if (mightHaveNonExternalLinkage(Func))
13715       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13716     else if (Func->getMostRecentDecl()->isInlined() &&
13717              !LangOpts.GNUInline &&
13718              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13719       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13720   }
13721
13722   Func->markUsed(Context);
13723 }
13724
13725 static void
13726 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13727                                    ValueDecl *var, DeclContext *DC) {
13728   DeclContext *VarDC = var->getDeclContext();
13729
13730   //  If the parameter still belongs to the translation unit, then
13731   //  we're actually just using one parameter in the declaration of
13732   //  the next.
13733   if (isa<ParmVarDecl>(var) &&
13734       isa<TranslationUnitDecl>(VarDC))
13735     return;
13736
13737   // For C code, don't diagnose about capture if we're not actually in code
13738   // right now; it's impossible to write a non-constant expression outside of
13739   // function context, so we'll get other (more useful) diagnostics later.
13740   //
13741   // For C++, things get a bit more nasty... it would be nice to suppress this
13742   // diagnostic for certain cases like using a local variable in an array bound
13743   // for a member of a local class, but the correct predicate is not obvious.
13744   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13745     return;
13746
13747   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13748   unsigned ContextKind = 3; // unknown
13749   if (isa<CXXMethodDecl>(VarDC) &&
13750       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13751     ContextKind = 2;
13752   } else if (isa<FunctionDecl>(VarDC)) {
13753     ContextKind = 0;
13754   } else if (isa<BlockDecl>(VarDC)) {
13755     ContextKind = 1;
13756   }
13757
13758   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13759     << var << ValueKind << ContextKind << VarDC;
13760   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13761       << var;
13762
13763   // FIXME: Add additional diagnostic info about class etc. which prevents
13764   // capture.
13765 }
13766
13767  
13768 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 
13769                                       bool &SubCapturesAreNested,
13770                                       QualType &CaptureType, 
13771                                       QualType &DeclRefType) {
13772    // Check whether we've already captured it.
13773   if (CSI->CaptureMap.count(Var)) {
13774     // If we found a capture, any subcaptures are nested.
13775     SubCapturesAreNested = true;
13776       
13777     // Retrieve the capture type for this variable.
13778     CaptureType = CSI->getCapture(Var).getCaptureType();
13779       
13780     // Compute the type of an expression that refers to this variable.
13781     DeclRefType = CaptureType.getNonReferenceType();
13782
13783     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13784     // are mutable in the sense that user can change their value - they are
13785     // private instances of the captured declarations.
13786     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13787     if (Cap.isCopyCapture() &&
13788         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13789         !(isa<CapturedRegionScopeInfo>(CSI) &&
13790           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13791       DeclRefType.addConst();
13792     return true;
13793   }
13794   return false;
13795 }
13796
13797 // Only block literals, captured statements, and lambda expressions can
13798 // capture; other scopes don't work.
13799 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 
13800                                  SourceLocation Loc, 
13801                                  const bool Diagnose, Sema &S) {
13802   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13803     return getLambdaAwareParentOfDeclContext(DC);
13804   else if (Var->hasLocalStorage()) {
13805     if (Diagnose)
13806        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13807   }
13808   return nullptr;
13809 }
13810
13811 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 
13812 // certain types of variables (unnamed, variably modified types etc.)
13813 // so check for eligibility.
13814 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 
13815                                  SourceLocation Loc, 
13816                                  const bool Diagnose, Sema &S) {
13817
13818   bool IsBlock = isa<BlockScopeInfo>(CSI);
13819   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13820
13821   // Lambdas are not allowed to capture unnamed variables
13822   // (e.g. anonymous unions).
13823   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13824   // assuming that's the intent.
13825   if (IsLambda && !Var->getDeclName()) {
13826     if (Diagnose) {
13827       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13828       S.Diag(Var->getLocation(), diag::note_declared_at);
13829     }
13830     return false;
13831   }
13832
13833   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13834   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13835     if (Diagnose) {
13836       S.Diag(Loc, diag::err_ref_vm_type);
13837       S.Diag(Var->getLocation(), diag::note_previous_decl) 
13838         << Var->getDeclName();
13839     }
13840     return false;
13841   }
13842   // Prohibit structs with flexible array members too.
13843   // We cannot capture what is in the tail end of the struct.
13844   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13845     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13846       if (Diagnose) {
13847         if (IsBlock)
13848           S.Diag(Loc, diag::err_ref_flexarray_type);
13849         else
13850           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13851             << Var->getDeclName();
13852         S.Diag(Var->getLocation(), diag::note_previous_decl)
13853           << Var->getDeclName();
13854       }
13855       return false;
13856     }
13857   }
13858   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13859   // Lambdas and captured statements are not allowed to capture __block
13860   // variables; they don't support the expected semantics.
13861   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13862     if (Diagnose) {
13863       S.Diag(Loc, diag::err_capture_block_variable)
13864         << Var->getDeclName() << !IsLambda;
13865       S.Diag(Var->getLocation(), diag::note_previous_decl)
13866         << Var->getDeclName();
13867     }
13868     return false;
13869   }
13870   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
13871   if (S.getLangOpts().OpenCL && IsBlock &&
13872       Var->getType()->isBlockPointerType()) {
13873     if (Diagnose)
13874       S.Diag(Loc, diag::err_opencl_block_ref_block);
13875     return false;
13876   }
13877
13878   return true;
13879 }
13880
13881 // Returns true if the capture by block was successful.
13882 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 
13883                                  SourceLocation Loc, 
13884                                  const bool BuildAndDiagnose, 
13885                                  QualType &CaptureType,
13886                                  QualType &DeclRefType, 
13887                                  const bool Nested,
13888                                  Sema &S) {
13889   Expr *CopyExpr = nullptr;
13890   bool ByRef = false;
13891       
13892   // Blocks are not allowed to capture arrays.
13893   if (CaptureType->isArrayType()) {
13894     if (BuildAndDiagnose) {
13895       S.Diag(Loc, diag::err_ref_array_type);
13896       S.Diag(Var->getLocation(), diag::note_previous_decl) 
13897       << Var->getDeclName();
13898     }
13899     return false;
13900   }
13901
13902   // Forbid the block-capture of autoreleasing variables.
13903   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13904     if (BuildAndDiagnose) {
13905       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13906         << /*block*/ 0;
13907       S.Diag(Var->getLocation(), diag::note_previous_decl)
13908         << Var->getDeclName();
13909     }
13910     return false;
13911   }
13912
13913   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13914   if (const auto *PT = CaptureType->getAs<PointerType>()) {
13915     // This function finds out whether there is an AttributedType of kind
13916     // attr_objc_ownership in Ty. The existence of AttributedType of kind
13917     // attr_objc_ownership implies __autoreleasing was explicitly specified
13918     // rather than being added implicitly by the compiler.
13919     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
13920       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
13921         if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
13922           return true;
13923
13924         // Peel off AttributedTypes that are not of kind objc_ownership.
13925         Ty = AttrTy->getModifiedType();
13926       }
13927
13928       return false;
13929     };
13930
13931     QualType PointeeTy = PT->getPointeeType();
13932
13933     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
13934         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13935         !IsObjCOwnershipAttributedType(PointeeTy)) {
13936       if (BuildAndDiagnose) {
13937         SourceLocation VarLoc = Var->getLocation();
13938         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13939         {
13940           auto AddAutoreleaseNote =
13941               S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing);
13942           // Provide a fix-it for the '__autoreleasing' keyword at the
13943           // appropriate location in the variable's type.
13944           if (const auto *TSI = Var->getTypeSourceInfo()) {
13945             PointerTypeLoc PTL =
13946                 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>();
13947             if (PTL) {
13948               SourceLocation Loc = PTL.getPointeeLoc().getEndLoc();
13949               Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(),
13950                                                S.getLangOpts());
13951               if (Loc.isValid()) {
13952                 StringRef CharAtLoc = Lexer::getSourceText(
13953                     CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)),
13954                     S.getSourceManager(), S.getLangOpts());
13955                 AddAutoreleaseNote << FixItHint::CreateInsertion(
13956                     Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0])
13957                              ? " __autoreleasing "
13958                              : " __autoreleasing");
13959               }
13960             }
13961           }
13962         }
13963         S.Diag(VarLoc, diag::note_declare_parameter_strong);
13964       }
13965     }
13966   }
13967
13968   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13969   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13970       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13971     // Block capture by reference does not change the capture or
13972     // declaration reference types.
13973     ByRef = true;
13974   } else {
13975     // Block capture by copy introduces 'const'.
13976     CaptureType = CaptureType.getNonReferenceType().withConst();
13977     DeclRefType = CaptureType;
13978                 
13979     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13980       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13981         // The capture logic needs the destructor, so make sure we mark it.
13982         // Usually this is unnecessary because most local variables have
13983         // their destructors marked at declaration time, but parameters are
13984         // an exception because it's technically only the call site that
13985         // actually requires the destructor.
13986         if (isa<ParmVarDecl>(Var))
13987           S.FinalizeVarWithDestructor(Var, Record);
13988
13989         // Enter a new evaluation context to insulate the copy
13990         // full-expression.
13991         EnterExpressionEvaluationContext scope(
13992             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
13993
13994         // According to the blocks spec, the capture of a variable from
13995         // the stack requires a const copy constructor.  This is not true
13996         // of the copy/move done to move a __block variable to the heap.
13997         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13998                                                   DeclRefType.withConst(), 
13999                                                   VK_LValue, Loc);
14000             
14001         ExprResult Result
14002           = S.PerformCopyInitialization(
14003               InitializedEntity::InitializeBlock(Var->getLocation(),
14004                                                   CaptureType, false),
14005               Loc, DeclRef);
14006             
14007         // Build a full-expression copy expression if initialization
14008         // succeeded and used a non-trivial constructor.  Recover from
14009         // errors by pretending that the copy isn't necessary.
14010         if (!Result.isInvalid() &&
14011             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14012                 ->isTrivial()) {
14013           Result = S.MaybeCreateExprWithCleanups(Result);
14014           CopyExpr = Result.get();
14015         }
14016       }
14017     }
14018   }
14019
14020   // Actually capture the variable.
14021   if (BuildAndDiagnose)
14022     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 
14023                     SourceLocation(), CaptureType, CopyExpr);
14024
14025   return true;
14026
14027 }
14028
14029
14030 /// \brief Capture the given variable in the captured region.
14031 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
14032                                     VarDecl *Var, 
14033                                     SourceLocation Loc, 
14034                                     const bool BuildAndDiagnose, 
14035                                     QualType &CaptureType,
14036                                     QualType &DeclRefType, 
14037                                     const bool RefersToCapturedVariable,
14038                                     Sema &S) {
14039   // By default, capture variables by reference.
14040   bool ByRef = true;
14041   // Using an LValue reference type is consistent with Lambdas (see below).
14042   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
14043     if (S.IsOpenMPCapturedDecl(Var))
14044       DeclRefType = DeclRefType.getUnqualifiedType();
14045     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
14046   }
14047
14048   if (ByRef)
14049     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14050   else
14051     CaptureType = DeclRefType;
14052
14053   Expr *CopyExpr = nullptr;
14054   if (BuildAndDiagnose) {
14055     // The current implementation assumes that all variables are captured
14056     // by references. Since there is no capture by copy, no expression
14057     // evaluation will be needed.
14058     RecordDecl *RD = RSI->TheRecordDecl;
14059
14060     FieldDecl *Field
14061       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
14062                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
14063                           nullptr, false, ICIS_NoInit);
14064     Field->setImplicit(true);
14065     Field->setAccess(AS_private);
14066     RD->addDecl(Field);
14067  
14068     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
14069                                             DeclRefType, VK_LValue, Loc);
14070     Var->setReferenced(true);
14071     Var->markUsed(S.Context);
14072   }
14073
14074   // Actually capture the variable.
14075   if (BuildAndDiagnose)
14076     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
14077                     SourceLocation(), CaptureType, CopyExpr);
14078   
14079   
14080   return true;
14081 }
14082
14083 /// \brief Create a field within the lambda class for the variable
14084 /// being captured.
14085 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 
14086                                     QualType FieldType, QualType DeclRefType,
14087                                     SourceLocation Loc,
14088                                     bool RefersToCapturedVariable) {
14089   CXXRecordDecl *Lambda = LSI->Lambda;
14090
14091   // Build the non-static data member.
14092   FieldDecl *Field
14093     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
14094                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
14095                         nullptr, false, ICIS_NoInit);
14096   Field->setImplicit(true);
14097   Field->setAccess(AS_private);
14098   Lambda->addDecl(Field);
14099 }
14100
14101 /// \brief Capture the given variable in the lambda.
14102 static bool captureInLambda(LambdaScopeInfo *LSI,
14103                             VarDecl *Var, 
14104                             SourceLocation Loc, 
14105                             const bool BuildAndDiagnose, 
14106                             QualType &CaptureType,
14107                             QualType &DeclRefType, 
14108                             const bool RefersToCapturedVariable,
14109                             const Sema::TryCaptureKind Kind, 
14110                             SourceLocation EllipsisLoc,
14111                             const bool IsTopScope,
14112                             Sema &S) {
14113
14114   // Determine whether we are capturing by reference or by value.
14115   bool ByRef = false;
14116   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
14117     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
14118   } else {
14119     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
14120   }
14121     
14122   // Compute the type of the field that will capture this variable.
14123   if (ByRef) {
14124     // C++11 [expr.prim.lambda]p15:
14125     //   An entity is captured by reference if it is implicitly or
14126     //   explicitly captured but not captured by copy. It is
14127     //   unspecified whether additional unnamed non-static data
14128     //   members are declared in the closure type for entities
14129     //   captured by reference.
14130     //
14131     // FIXME: It is not clear whether we want to build an lvalue reference
14132     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
14133     // to do the former, while EDG does the latter. Core issue 1249 will 
14134     // clarify, but for now we follow GCC because it's a more permissive and
14135     // easily defensible position.
14136     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14137   } else {
14138     // C++11 [expr.prim.lambda]p14:
14139     //   For each entity captured by copy, an unnamed non-static
14140     //   data member is declared in the closure type. The
14141     //   declaration order of these members is unspecified. The type
14142     //   of such a data member is the type of the corresponding
14143     //   captured entity if the entity is not a reference to an
14144     //   object, or the referenced type otherwise. [Note: If the
14145     //   captured entity is a reference to a function, the
14146     //   corresponding data member is also a reference to a
14147     //   function. - end note ]
14148     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
14149       if (!RefType->getPointeeType()->isFunctionType())
14150         CaptureType = RefType->getPointeeType();
14151     }
14152
14153     // Forbid the lambda copy-capture of autoreleasing variables.
14154     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14155       if (BuildAndDiagnose) {
14156         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
14157         S.Diag(Var->getLocation(), diag::note_previous_decl)
14158           << Var->getDeclName();
14159       }
14160       return false;
14161     }
14162
14163     // Make sure that by-copy captures are of a complete and non-abstract type.
14164     if (BuildAndDiagnose) {
14165       if (!CaptureType->isDependentType() &&
14166           S.RequireCompleteType(Loc, CaptureType,
14167                                 diag::err_capture_of_incomplete_type,
14168                                 Var->getDeclName()))
14169         return false;
14170
14171       if (S.RequireNonAbstractType(Loc, CaptureType,
14172                                    diag::err_capture_of_abstract_type))
14173         return false;
14174     }
14175   }
14176
14177   // Capture this variable in the lambda.
14178   if (BuildAndDiagnose)
14179     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
14180                             RefersToCapturedVariable);
14181     
14182   // Compute the type of a reference to this captured variable.
14183   if (ByRef)
14184     DeclRefType = CaptureType.getNonReferenceType();
14185   else {
14186     // C++ [expr.prim.lambda]p5:
14187     //   The closure type for a lambda-expression has a public inline 
14188     //   function call operator [...]. This function call operator is 
14189     //   declared const (9.3.1) if and only if the lambda-expression's 
14190     //   parameter-declaration-clause is not followed by mutable.
14191     DeclRefType = CaptureType.getNonReferenceType();
14192     if (!LSI->Mutable && !CaptureType->isReferenceType())
14193       DeclRefType.addConst();      
14194   }
14195     
14196   // Add the capture.
14197   if (BuildAndDiagnose)
14198     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 
14199                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
14200       
14201   return true;
14202 }
14203
14204 bool Sema::tryCaptureVariable(
14205     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
14206     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
14207     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
14208   // An init-capture is notionally from the context surrounding its
14209   // declaration, but its parent DC is the lambda class.
14210   DeclContext *VarDC = Var->getDeclContext();
14211   if (Var->isInitCapture())
14212     VarDC = VarDC->getParent();
14213   
14214   DeclContext *DC = CurContext;
14215   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 
14216       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;  
14217   // We need to sync up the Declaration Context with the
14218   // FunctionScopeIndexToStopAt
14219   if (FunctionScopeIndexToStopAt) {
14220     unsigned FSIndex = FunctionScopes.size() - 1;
14221     while (FSIndex != MaxFunctionScopesIndex) {
14222       DC = getLambdaAwareParentOfDeclContext(DC);
14223       --FSIndex;
14224     }
14225   }
14226
14227   
14228   // If the variable is declared in the current context, there is no need to
14229   // capture it.
14230   if (VarDC == DC) return true;
14231
14232   // Capture global variables if it is required to use private copy of this
14233   // variable.
14234   bool IsGlobal = !Var->hasLocalStorage();
14235   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
14236     return true;
14237
14238   // Walk up the stack to determine whether we can capture the variable,
14239   // performing the "simple" checks that don't depend on type. We stop when
14240   // we've either hit the declared scope of the variable or find an existing
14241   // capture of that variable.  We start from the innermost capturing-entity
14242   // (the DC) and ensure that all intervening capturing-entities 
14243   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
14244   // declcontext can either capture the variable or have already captured
14245   // the variable.
14246   CaptureType = Var->getType();
14247   DeclRefType = CaptureType.getNonReferenceType();
14248   bool Nested = false;
14249   bool Explicit = (Kind != TryCapture_Implicit);
14250   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
14251   do {
14252     // Only block literals, captured statements, and lambda expressions can
14253     // capture; other scopes don't work.
14254     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 
14255                                                               ExprLoc, 
14256                                                               BuildAndDiagnose,
14257                                                               *this);
14258     // We need to check for the parent *first* because, if we *have*
14259     // private-captured a global variable, we need to recursively capture it in
14260     // intermediate blocks, lambdas, etc.
14261     if (!ParentDC) {
14262       if (IsGlobal) {
14263         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
14264         break;
14265       }
14266       return true;
14267     }
14268
14269     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
14270     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
14271
14272
14273     // Check whether we've already captured it.
14274     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 
14275                                              DeclRefType)) {
14276       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
14277       break;
14278     }
14279     // If we are instantiating a generic lambda call operator body, 
14280     // we do not want to capture new variables.  What was captured
14281     // during either a lambdas transformation or initial parsing
14282     // should be used. 
14283     if (isGenericLambdaCallOperatorSpecialization(DC)) {
14284       if (BuildAndDiagnose) {
14285         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);   
14286         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
14287           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14288           Diag(Var->getLocation(), diag::note_previous_decl) 
14289              << Var->getDeclName();
14290           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);          
14291         } else
14292           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
14293       }
14294       return true;
14295     }
14296     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 
14297     // certain types of variables (unnamed, variably modified types etc.)
14298     // so check for eligibility.
14299     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
14300        return true;
14301
14302     // Try to capture variable-length arrays types.
14303     if (Var->getType()->isVariablyModifiedType()) {
14304       // We're going to walk down into the type and look for VLA
14305       // expressions.
14306       QualType QTy = Var->getType();
14307       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
14308         QTy = PVD->getOriginalType();
14309       captureVariablyModifiedType(Context, QTy, CSI);
14310     }
14311
14312     if (getLangOpts().OpenMP) {
14313       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14314         // OpenMP private variables should not be captured in outer scope, so
14315         // just break here. Similarly, global variables that are captured in a
14316         // target region should not be captured outside the scope of the region.
14317         if (RSI->CapRegionKind == CR_OpenMP) {
14318           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
14319           // When we detect target captures we are looking from inside the
14320           // target region, therefore we need to propagate the capture from the
14321           // enclosing region. Therefore, the capture is not initially nested.
14322           if (IsTargetCap)
14323             FunctionScopesIndex--;
14324
14325           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
14326             Nested = !IsTargetCap;
14327             DeclRefType = DeclRefType.getUnqualifiedType();
14328             CaptureType = Context.getLValueReferenceType(DeclRefType);
14329             break;
14330           }
14331         }
14332       }
14333     }
14334     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
14335       // No capture-default, and this is not an explicit capture 
14336       // so cannot capture this variable.  
14337       if (BuildAndDiagnose) {
14338         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14339         Diag(Var->getLocation(), diag::note_previous_decl) 
14340           << Var->getDeclName();
14341         if (cast<LambdaScopeInfo>(CSI)->Lambda)
14342           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
14343                diag::note_lambda_decl);
14344         // FIXME: If we error out because an outer lambda can not implicitly
14345         // capture a variable that an inner lambda explicitly captures, we
14346         // should have the inner lambda do the explicit capture - because
14347         // it makes for cleaner diagnostics later.  This would purely be done
14348         // so that the diagnostic does not misleadingly claim that a variable 
14349         // can not be captured by a lambda implicitly even though it is captured 
14350         // explicitly.  Suggestion:
14351         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit 
14352         //    at the function head
14353         //  - cache the StartingDeclContext - this must be a lambda 
14354         //  - captureInLambda in the innermost lambda the variable.
14355       }
14356       return true;
14357     }
14358
14359     FunctionScopesIndex--;
14360     DC = ParentDC;
14361     Explicit = false;
14362   } while (!VarDC->Equals(DC));
14363
14364   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
14365   // computing the type of the capture at each step, checking type-specific 
14366   // requirements, and adding captures if requested. 
14367   // If the variable had already been captured previously, we start capturing 
14368   // at the lambda nested within that one.   
14369   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 
14370        ++I) {
14371     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
14372     
14373     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
14374       if (!captureInBlock(BSI, Var, ExprLoc, 
14375                           BuildAndDiagnose, CaptureType, 
14376                           DeclRefType, Nested, *this))
14377         return true;
14378       Nested = true;
14379     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14380       if (!captureInCapturedRegion(RSI, Var, ExprLoc, 
14381                                    BuildAndDiagnose, CaptureType, 
14382                                    DeclRefType, Nested, *this))
14383         return true;
14384       Nested = true;
14385     } else {
14386       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14387       if (!captureInLambda(LSI, Var, ExprLoc, 
14388                            BuildAndDiagnose, CaptureType, 
14389                            DeclRefType, Nested, Kind, EllipsisLoc, 
14390                             /*IsTopScope*/I == N - 1, *this))
14391         return true;
14392       Nested = true;
14393     }
14394   }
14395   return false;
14396 }
14397
14398 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14399                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {  
14400   QualType CaptureType;
14401   QualType DeclRefType;
14402   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14403                             /*BuildAndDiagnose=*/true, CaptureType,
14404                             DeclRefType, nullptr);
14405 }
14406
14407 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14408   QualType CaptureType;
14409   QualType DeclRefType;
14410   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14411                              /*BuildAndDiagnose=*/false, CaptureType,
14412                              DeclRefType, nullptr);
14413 }
14414
14415 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14416   QualType CaptureType;
14417   QualType DeclRefType;
14418   
14419   // Determine whether we can capture this variable.
14420   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14421                          /*BuildAndDiagnose=*/false, CaptureType, 
14422                          DeclRefType, nullptr))
14423     return QualType();
14424
14425   return DeclRefType;
14426 }
14427
14428
14429
14430 // If either the type of the variable or the initializer is dependent, 
14431 // return false. Otherwise, determine whether the variable is a constant
14432 // expression. Use this if you need to know if a variable that might or
14433 // might not be dependent is truly a constant expression.
14434 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 
14435     ASTContext &Context) {
14436  
14437   if (Var->getType()->isDependentType()) 
14438     return false;
14439   const VarDecl *DefVD = nullptr;
14440   Var->getAnyInitializer(DefVD);
14441   if (!DefVD) 
14442     return false;
14443   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14444   Expr *Init = cast<Expr>(Eval->Value);
14445   if (Init->isValueDependent()) 
14446     return false;
14447   return IsVariableAConstantExpression(Var, Context); 
14448 }
14449
14450
14451 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14452   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 
14453   // an object that satisfies the requirements for appearing in a
14454   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14455   // is immediately applied."  This function handles the lvalue-to-rvalue
14456   // conversion part.
14457   MaybeODRUseExprs.erase(E->IgnoreParens());
14458   
14459   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14460   // to a variable that is a constant expression, and if so, identify it as
14461   // a reference to a variable that does not involve an odr-use of that 
14462   // variable. 
14463   if (LambdaScopeInfo *LSI = getCurLambda()) {
14464     Expr *SansParensExpr = E->IgnoreParens();
14465     VarDecl *Var = nullptr;
14466     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 
14467       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14468     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14469       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14470     
14471     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 
14472       LSI->markVariableExprAsNonODRUsed(SansParensExpr);    
14473   }
14474 }
14475
14476 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14477   Res = CorrectDelayedTyposInExpr(Res);
14478
14479   if (!Res.isUsable())
14480     return Res;
14481
14482   // If a constant-expression is a reference to a variable where we delay
14483   // deciding whether it is an odr-use, just assume we will apply the
14484   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
14485   // (a non-type template argument), we have special handling anyway.
14486   UpdateMarkingForLValueToRValue(Res.get());
14487   return Res;
14488 }
14489
14490 void Sema::CleanupVarDeclMarking() {
14491   for (Expr *E : MaybeODRUseExprs) {
14492     VarDecl *Var;
14493     SourceLocation Loc;
14494     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14495       Var = cast<VarDecl>(DRE->getDecl());
14496       Loc = DRE->getLocation();
14497     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14498       Var = cast<VarDecl>(ME->getMemberDecl());
14499       Loc = ME->getMemberLoc();
14500     } else {
14501       llvm_unreachable("Unexpected expression");
14502     }
14503
14504     MarkVarDeclODRUsed(Var, Loc, *this,
14505                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
14506   }
14507
14508   MaybeODRUseExprs.clear();
14509 }
14510
14511
14512 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14513                                     VarDecl *Var, Expr *E) {
14514   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14515          "Invalid Expr argument to DoMarkVarDeclReferenced");
14516   Var->setReferenced();
14517
14518   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14519
14520   bool OdrUseContext = isOdrUseContext(SemaRef);
14521   bool NeedDefinition =
14522       OdrUseContext || (isEvaluatableContext(SemaRef) &&
14523                         Var->isUsableInConstantExpressions(SemaRef.Context));
14524
14525   VarTemplateSpecializationDecl *VarSpec =
14526       dyn_cast<VarTemplateSpecializationDecl>(Var);
14527   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14528          "Can't instantiate a partial template specialization.");
14529
14530   // If this might be a member specialization of a static data member, check
14531   // the specialization is visible. We already did the checks for variable
14532   // template specializations when we created them.
14533   if (NeedDefinition && TSK != TSK_Undeclared &&
14534       !isa<VarTemplateSpecializationDecl>(Var))
14535     SemaRef.checkSpecializationVisibility(Loc, Var);
14536
14537   // Perform implicit instantiation of static data members, static data member
14538   // templates of class templates, and variable template specializations. Delay
14539   // instantiations of variable templates, except for those that could be used
14540   // in a constant expression.
14541   if (NeedDefinition && isTemplateInstantiation(TSK)) {
14542     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14543
14544     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14545       if (Var->getPointOfInstantiation().isInvalid()) {
14546         // This is a modification of an existing AST node. Notify listeners.
14547         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14548           L->StaticDataMemberInstantiated(Var);
14549       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14550         // Don't bother trying to instantiate it again, unless we might need
14551         // its initializer before we get to the end of the TU.
14552         TryInstantiating = false;
14553     }
14554
14555     if (Var->getPointOfInstantiation().isInvalid())
14556       Var->setTemplateSpecializationKind(TSK, Loc);
14557
14558     if (TryInstantiating) {
14559       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14560       bool InstantiationDependent = false;
14561       bool IsNonDependent =
14562           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14563                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14564                   : true;
14565
14566       // Do not instantiate specializations that are still type-dependent.
14567       if (IsNonDependent) {
14568         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14569           // Do not defer instantiations of variables which could be used in a
14570           // constant expression.
14571           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14572         } else {
14573           SemaRef.PendingInstantiations
14574               .push_back(std::make_pair(Var, PointOfInstantiation));
14575         }
14576       }
14577     }
14578   }
14579
14580   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14581   // the requirements for appearing in a constant expression (5.19) and, if
14582   // it is an object, the lvalue-to-rvalue conversion (4.1)
14583   // is immediately applied."  We check the first part here, and
14584   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14585   // Note that we use the C++11 definition everywhere because nothing in
14586   // C++03 depends on whether we get the C++03 version correct. The second
14587   // part does not apply to references, since they are not objects.
14588   if (OdrUseContext && E &&
14589       IsVariableAConstantExpression(Var, SemaRef.Context)) {
14590     // A reference initialized by a constant expression can never be
14591     // odr-used, so simply ignore it.
14592     if (!Var->getType()->isReferenceType())
14593       SemaRef.MaybeODRUseExprs.insert(E);
14594   } else if (OdrUseContext) {
14595     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14596                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14597   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
14598     // If this is a dependent context, we don't need to mark variables as
14599     // odr-used, but we may still need to track them for lambda capture.
14600     // FIXME: Do we also need to do this inside dependent typeid expressions
14601     // (which are modeled as unevaluated at this point)?
14602     const bool RefersToEnclosingScope =
14603         (SemaRef.CurContext != Var->getDeclContext() &&
14604          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14605     if (RefersToEnclosingScope) {
14606       LambdaScopeInfo *const LSI =
14607           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
14608       if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) {
14609         // If a variable could potentially be odr-used, defer marking it so
14610         // until we finish analyzing the full expression for any
14611         // lvalue-to-rvalue
14612         // or discarded value conversions that would obviate odr-use.
14613         // Add it to the list of potential captures that will be analyzed
14614         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14615         // unless the variable is a reference that was initialized by a constant
14616         // expression (this will never need to be captured or odr-used).
14617         assert(E && "Capture variable should be used in an expression.");
14618         if (!Var->getType()->isReferenceType() ||
14619             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14620           LSI->addPotentialCapture(E->IgnoreParens());
14621       }
14622     }
14623   }
14624 }
14625
14626 /// \brief Mark a variable referenced, and check whether it is odr-used
14627 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
14628 /// used directly for normal expressions referring to VarDecl.
14629 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14630   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14631 }
14632
14633 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14634                                Decl *D, Expr *E, bool MightBeOdrUse) {
14635   if (SemaRef.isInOpenMPDeclareTargetContext())
14636     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14637
14638   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14639     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14640     return;
14641   }
14642
14643   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14644
14645   // If this is a call to a method via a cast, also mark the method in the
14646   // derived class used in case codegen can devirtualize the call.
14647   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14648   if (!ME)
14649     return;
14650   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14651   if (!MD)
14652     return;
14653   // Only attempt to devirtualize if this is truly a virtual call.
14654   bool IsVirtualCall = MD->isVirtual() &&
14655                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14656   if (!IsVirtualCall)
14657     return;
14658   const Expr *Base = ME->getBase();
14659   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14660   if (!MostDerivedClassDecl)
14661     return;
14662   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14663   if (!DM || DM->isPure())
14664     return;
14665   SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14666
14667
14668 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14669 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14670   // TODO: update this with DR# once a defect report is filed.
14671   // C++11 defect. The address of a pure member should not be an ODR use, even
14672   // if it's a qualified reference.
14673   bool OdrUse = true;
14674   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14675     if (Method->isVirtual())
14676       OdrUse = false;
14677   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14678 }
14679
14680 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14681 void Sema::MarkMemberReferenced(MemberExpr *E) {
14682   // C++11 [basic.def.odr]p2:
14683   //   A non-overloaded function whose name appears as a potentially-evaluated
14684   //   expression or a member of a set of candidate functions, if selected by
14685   //   overload resolution when referred to from a potentially-evaluated
14686   //   expression, is odr-used, unless it is a pure virtual function and its
14687   //   name is not explicitly qualified.
14688   bool MightBeOdrUse = true;
14689   if (E->performsVirtualDispatch(getLangOpts())) {
14690     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14691       if (Method->isPure())
14692         MightBeOdrUse = false;
14693   }
14694   SourceLocation Loc = E->getMemberLoc().isValid() ?
14695                             E->getMemberLoc() : E->getLocStart();
14696   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14697 }
14698
14699 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14700 /// marks the declaration referenced, and performs odr-use checking for
14701 /// functions and variables. This method should not be used when building a
14702 /// normal expression which refers to a variable.
14703 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14704                                  bool MightBeOdrUse) {
14705   if (MightBeOdrUse) {
14706     if (auto *VD = dyn_cast<VarDecl>(D)) {
14707       MarkVariableReferenced(Loc, VD);
14708       return;
14709     }
14710   }
14711   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14712     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14713     return;
14714   }
14715   D->setReferenced();
14716 }
14717
14718 namespace {
14719   // Mark all of the declarations used by a type as referenced.
14720   // FIXME: Not fully implemented yet! We need to have a better understanding
14721   // of when we're entering a context we should not recurse into.
14722   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
14723   // TreeTransforms rebuilding the type in a new context. Rather than
14724   // duplicating the TreeTransform logic, we should consider reusing it here.
14725   // Currently that causes problems when rebuilding LambdaExprs.
14726   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14727     Sema &S;
14728     SourceLocation Loc;
14729
14730   public:
14731     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14732
14733     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14734
14735     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14736   };
14737 }
14738
14739 bool MarkReferencedDecls::TraverseTemplateArgument(
14740     const TemplateArgument &Arg) {
14741   {
14742     // A non-type template argument is a constant-evaluated context.
14743     EnterExpressionEvaluationContext Evaluated(
14744         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
14745     if (Arg.getKind() == TemplateArgument::Declaration) {
14746       if (Decl *D = Arg.getAsDecl())
14747         S.MarkAnyDeclReferenced(Loc, D, true);
14748     } else if (Arg.getKind() == TemplateArgument::Expression) {
14749       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
14750     }
14751   }
14752
14753   return Inherited::TraverseTemplateArgument(Arg);
14754 }
14755
14756 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14757   MarkReferencedDecls Marker(*this, Loc);
14758   Marker.TraverseType(T);
14759 }
14760
14761 namespace {
14762   /// \brief Helper class that marks all of the declarations referenced by
14763   /// potentially-evaluated subexpressions as "referenced".
14764   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14765     Sema &S;
14766     bool SkipLocalVariables;
14767     
14768   public:
14769     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14770     
14771     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 
14772       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14773     
14774     void VisitDeclRefExpr(DeclRefExpr *E) {
14775       // If we were asked not to visit local variables, don't.
14776       if (SkipLocalVariables) {
14777         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14778           if (VD->hasLocalStorage())
14779             return;
14780       }
14781       
14782       S.MarkDeclRefReferenced(E);
14783     }
14784
14785     void VisitMemberExpr(MemberExpr *E) {
14786       S.MarkMemberReferenced(E);
14787       Inherited::VisitMemberExpr(E);
14788     }
14789     
14790     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14791       S.MarkFunctionReferenced(E->getLocStart(),
14792             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14793       Visit(E->getSubExpr());
14794     }
14795     
14796     void VisitCXXNewExpr(CXXNewExpr *E) {
14797       if (E->getOperatorNew())
14798         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14799       if (E->getOperatorDelete())
14800         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14801       Inherited::VisitCXXNewExpr(E);
14802     }
14803
14804     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14805       if (E->getOperatorDelete())
14806         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14807       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14808       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14809         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14810         S.MarkFunctionReferenced(E->getLocStart(), 
14811                                     S.LookupDestructor(Record));
14812       }
14813       
14814       Inherited::VisitCXXDeleteExpr(E);
14815     }
14816     
14817     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14818       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14819       Inherited::VisitCXXConstructExpr(E);
14820     }
14821     
14822     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14823       Visit(E->getExpr());
14824     }
14825
14826     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14827       Inherited::VisitImplicitCastExpr(E);
14828
14829       if (E->getCastKind() == CK_LValueToRValue)
14830         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14831     }
14832   };
14833 }
14834
14835 /// \brief Mark any declarations that appear within this expression or any
14836 /// potentially-evaluated subexpressions as "referenced".
14837 ///
14838 /// \param SkipLocalVariables If true, don't mark local variables as 
14839 /// 'referenced'.
14840 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 
14841                                             bool SkipLocalVariables) {
14842   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14843 }
14844
14845 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14846 /// of the program being compiled.
14847 ///
14848 /// This routine emits the given diagnostic when the code currently being
14849 /// type-checked is "potentially evaluated", meaning that there is a
14850 /// possibility that the code will actually be executable. Code in sizeof()
14851 /// expressions, code used only during overload resolution, etc., are not
14852 /// potentially evaluated. This routine will suppress such diagnostics or,
14853 /// in the absolutely nutty case of potentially potentially evaluated
14854 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14855 /// later.
14856 ///
14857 /// This routine should be used for all diagnostics that describe the run-time
14858 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14859 /// Failure to do so will likely result in spurious diagnostics or failures
14860 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14861 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14862                                const PartialDiagnostic &PD) {
14863   switch (ExprEvalContexts.back().Context) {
14864   case ExpressionEvaluationContext::Unevaluated:
14865   case ExpressionEvaluationContext::UnevaluatedList:
14866   case ExpressionEvaluationContext::UnevaluatedAbstract:
14867   case ExpressionEvaluationContext::DiscardedStatement:
14868     // The argument will never be evaluated, so don't complain.
14869     break;
14870
14871   case ExpressionEvaluationContext::ConstantEvaluated:
14872     // Relevant diagnostics should be produced by constant evaluation.
14873     break;
14874
14875   case ExpressionEvaluationContext::PotentiallyEvaluated:
14876   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14877     if (Statement && getCurFunctionOrMethodDecl()) {
14878       FunctionScopes.back()->PossiblyUnreachableDiags.
14879         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14880     }
14881     else
14882       Diag(Loc, PD);
14883       
14884     return true;
14885   }
14886
14887   return false;
14888 }
14889
14890 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14891                                CallExpr *CE, FunctionDecl *FD) {
14892   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14893     return false;
14894
14895   // If we're inside a decltype's expression, don't check for a valid return
14896   // type or construct temporaries until we know whether this is the last call.
14897   if (ExprEvalContexts.back().IsDecltype) {
14898     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14899     return false;
14900   }
14901
14902   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14903     FunctionDecl *FD;
14904     CallExpr *CE;
14905     
14906   public:
14907     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14908       : FD(FD), CE(CE) { }
14909
14910     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14911       if (!FD) {
14912         S.Diag(Loc, diag::err_call_incomplete_return)
14913           << T << CE->getSourceRange();
14914         return;
14915       }
14916       
14917       S.Diag(Loc, diag::err_call_function_incomplete_return)
14918         << CE->getSourceRange() << FD->getDeclName() << T;
14919       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14920           << FD->getDeclName();
14921     }
14922   } Diagnoser(FD, CE);
14923   
14924   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14925     return true;
14926
14927   return false;
14928 }
14929
14930 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14931 // will prevent this condition from triggering, which is what we want.
14932 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14933   SourceLocation Loc;
14934
14935   unsigned diagnostic = diag::warn_condition_is_assignment;
14936   bool IsOrAssign = false;
14937
14938   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14939     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14940       return;
14941
14942     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14943
14944     // Greylist some idioms by putting them into a warning subcategory.
14945     if (ObjCMessageExpr *ME
14946           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14947       Selector Sel = ME->getSelector();
14948
14949       // self = [<foo> init...]
14950       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14951         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14952
14953       // <foo> = [<bar> nextObject]
14954       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14955         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14956     }
14957
14958     Loc = Op->getOperatorLoc();
14959   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14960     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14961       return;
14962
14963     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14964     Loc = Op->getOperatorLoc();
14965   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14966     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14967   else {
14968     // Not an assignment.
14969     return;
14970   }
14971
14972   Diag(Loc, diagnostic) << E->getSourceRange();
14973
14974   SourceLocation Open = E->getLocStart();
14975   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14976   Diag(Loc, diag::note_condition_assign_silence)
14977         << FixItHint::CreateInsertion(Open, "(")
14978         << FixItHint::CreateInsertion(Close, ")");
14979
14980   if (IsOrAssign)
14981     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14982       << FixItHint::CreateReplacement(Loc, "!=");
14983   else
14984     Diag(Loc, diag::note_condition_assign_to_comparison)
14985       << FixItHint::CreateReplacement(Loc, "==");
14986 }
14987
14988 /// \brief Redundant parentheses over an equality comparison can indicate
14989 /// that the user intended an assignment used as condition.
14990 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14991   // Don't warn if the parens came from a macro.
14992   SourceLocation parenLoc = ParenE->getLocStart();
14993   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14994     return;
14995   // Don't warn for dependent expressions.
14996   if (ParenE->isTypeDependent())
14997     return;
14998
14999   Expr *E = ParenE->IgnoreParens();
15000
15001   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
15002     if (opE->getOpcode() == BO_EQ &&
15003         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
15004                                                            == Expr::MLV_Valid) {
15005       SourceLocation Loc = opE->getOperatorLoc();
15006       
15007       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
15008       SourceRange ParenERange = ParenE->getSourceRange();
15009       Diag(Loc, diag::note_equality_comparison_silence)
15010         << FixItHint::CreateRemoval(ParenERange.getBegin())
15011         << FixItHint::CreateRemoval(ParenERange.getEnd());
15012       Diag(Loc, diag::note_equality_comparison_to_assign)
15013         << FixItHint::CreateReplacement(Loc, "=");
15014     }
15015 }
15016
15017 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
15018                                        bool IsConstexpr) {
15019   DiagnoseAssignmentAsCondition(E);
15020   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
15021     DiagnoseEqualityWithExtraParens(parenE);
15022
15023   ExprResult result = CheckPlaceholderExpr(E);
15024   if (result.isInvalid()) return ExprError();
15025   E = result.get();
15026
15027   if (!E->isTypeDependent()) {
15028     if (getLangOpts().CPlusPlus)
15029       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
15030
15031     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
15032     if (ERes.isInvalid())
15033       return ExprError();
15034     E = ERes.get();
15035
15036     QualType T = E->getType();
15037     if (!T->isScalarType()) { // C99 6.8.4.1p1
15038       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
15039         << T << E->getSourceRange();
15040       return ExprError();
15041     }
15042     CheckBoolLikeConversion(E, Loc);
15043   }
15044
15045   return E;
15046 }
15047
15048 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
15049                                            Expr *SubExpr, ConditionKind CK) {
15050   // Empty conditions are valid in for-statements.
15051   if (!SubExpr)
15052     return ConditionResult();
15053
15054   ExprResult Cond;
15055   switch (CK) {
15056   case ConditionKind::Boolean:
15057     Cond = CheckBooleanCondition(Loc, SubExpr);
15058     break;
15059
15060   case ConditionKind::ConstexprIf:
15061     Cond = CheckBooleanCondition(Loc, SubExpr, true);
15062     break;
15063
15064   case ConditionKind::Switch:
15065     Cond = CheckSwitchCondition(Loc, SubExpr);
15066     break;
15067   }
15068   if (Cond.isInvalid())
15069     return ConditionError();
15070
15071   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
15072   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
15073   if (!FullExpr.get())
15074     return ConditionError();
15075
15076   return ConditionResult(*this, nullptr, FullExpr,
15077                          CK == ConditionKind::ConstexprIf);
15078 }
15079
15080 namespace {
15081   /// A visitor for rebuilding a call to an __unknown_any expression
15082   /// to have an appropriate type.
15083   struct RebuildUnknownAnyFunction
15084     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
15085
15086     Sema &S;
15087
15088     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
15089
15090     ExprResult VisitStmt(Stmt *S) {
15091       llvm_unreachable("unexpected statement!");
15092     }
15093
15094     ExprResult VisitExpr(Expr *E) {
15095       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
15096         << E->getSourceRange();
15097       return ExprError();
15098     }
15099
15100     /// Rebuild an expression which simply semantically wraps another
15101     /// expression which it shares the type and value kind of.
15102     template <class T> ExprResult rebuildSugarExpr(T *E) {
15103       ExprResult SubResult = Visit(E->getSubExpr());
15104       if (SubResult.isInvalid()) return ExprError();
15105
15106       Expr *SubExpr = SubResult.get();
15107       E->setSubExpr(SubExpr);
15108       E->setType(SubExpr->getType());
15109       E->setValueKind(SubExpr->getValueKind());
15110       assert(E->getObjectKind() == OK_Ordinary);
15111       return E;
15112     }
15113
15114     ExprResult VisitParenExpr(ParenExpr *E) {
15115       return rebuildSugarExpr(E);
15116     }
15117
15118     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15119       return rebuildSugarExpr(E);
15120     }
15121
15122     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15123       ExprResult SubResult = Visit(E->getSubExpr());
15124       if (SubResult.isInvalid()) return ExprError();
15125
15126       Expr *SubExpr = SubResult.get();
15127       E->setSubExpr(SubExpr);
15128       E->setType(S.Context.getPointerType(SubExpr->getType()));
15129       assert(E->getValueKind() == VK_RValue);
15130       assert(E->getObjectKind() == OK_Ordinary);
15131       return E;
15132     }
15133
15134     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
15135       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
15136
15137       E->setType(VD->getType());
15138
15139       assert(E->getValueKind() == VK_RValue);
15140       if (S.getLangOpts().CPlusPlus &&
15141           !(isa<CXXMethodDecl>(VD) &&
15142             cast<CXXMethodDecl>(VD)->isInstance()))
15143         E->setValueKind(VK_LValue);
15144
15145       return E;
15146     }
15147
15148     ExprResult VisitMemberExpr(MemberExpr *E) {
15149       return resolveDecl(E, E->getMemberDecl());
15150     }
15151
15152     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15153       return resolveDecl(E, E->getDecl());
15154     }
15155   };
15156 }
15157
15158 /// Given a function expression of unknown-any type, try to rebuild it
15159 /// to have a function type.
15160 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
15161   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
15162   if (Result.isInvalid()) return ExprError();
15163   return S.DefaultFunctionArrayConversion(Result.get());
15164 }
15165
15166 namespace {
15167   /// A visitor for rebuilding an expression of type __unknown_anytype
15168   /// into one which resolves the type directly on the referring
15169   /// expression.  Strict preservation of the original source
15170   /// structure is not a goal.
15171   struct RebuildUnknownAnyExpr
15172     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
15173
15174     Sema &S;
15175
15176     /// The current destination type.
15177     QualType DestType;
15178
15179     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
15180       : S(S), DestType(CastType) {}
15181
15182     ExprResult VisitStmt(Stmt *S) {
15183       llvm_unreachable("unexpected statement!");
15184     }
15185
15186     ExprResult VisitExpr(Expr *E) {
15187       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15188         << E->getSourceRange();
15189       return ExprError();
15190     }
15191
15192     ExprResult VisitCallExpr(CallExpr *E);
15193     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
15194
15195     /// Rebuild an expression which simply semantically wraps another
15196     /// expression which it shares the type and value kind of.
15197     template <class T> ExprResult rebuildSugarExpr(T *E) {
15198       ExprResult SubResult = Visit(E->getSubExpr());
15199       if (SubResult.isInvalid()) return ExprError();
15200       Expr *SubExpr = SubResult.get();
15201       E->setSubExpr(SubExpr);
15202       E->setType(SubExpr->getType());
15203       E->setValueKind(SubExpr->getValueKind());
15204       assert(E->getObjectKind() == OK_Ordinary);
15205       return E;
15206     }
15207
15208     ExprResult VisitParenExpr(ParenExpr *E) {
15209       return rebuildSugarExpr(E);
15210     }
15211
15212     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15213       return rebuildSugarExpr(E);
15214     }
15215
15216     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15217       const PointerType *Ptr = DestType->getAs<PointerType>();
15218       if (!Ptr) {
15219         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
15220           << E->getSourceRange();
15221         return ExprError();
15222       }
15223
15224       if (isa<CallExpr>(E->getSubExpr())) {
15225         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
15226           << E->getSourceRange();
15227         return ExprError();
15228       }
15229
15230       assert(E->getValueKind() == VK_RValue);
15231       assert(E->getObjectKind() == OK_Ordinary);
15232       E->setType(DestType);
15233
15234       // Build the sub-expression as if it were an object of the pointee type.
15235       DestType = Ptr->getPointeeType();
15236       ExprResult SubResult = Visit(E->getSubExpr());
15237       if (SubResult.isInvalid()) return ExprError();
15238       E->setSubExpr(SubResult.get());
15239       return E;
15240     }
15241
15242     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
15243
15244     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
15245
15246     ExprResult VisitMemberExpr(MemberExpr *E) {
15247       return resolveDecl(E, E->getMemberDecl());
15248     }
15249
15250     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15251       return resolveDecl(E, E->getDecl());
15252     }
15253   };
15254 }
15255
15256 /// Rebuilds a call expression which yielded __unknown_anytype.
15257 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
15258   Expr *CalleeExpr = E->getCallee();
15259
15260   enum FnKind {
15261     FK_MemberFunction,
15262     FK_FunctionPointer,
15263     FK_BlockPointer
15264   };
15265
15266   FnKind Kind;
15267   QualType CalleeType = CalleeExpr->getType();
15268   if (CalleeType == S.Context.BoundMemberTy) {
15269     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
15270     Kind = FK_MemberFunction;
15271     CalleeType = Expr::findBoundMemberType(CalleeExpr);
15272   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
15273     CalleeType = Ptr->getPointeeType();
15274     Kind = FK_FunctionPointer;
15275   } else {
15276     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
15277     Kind = FK_BlockPointer;
15278   }
15279   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
15280
15281   // Verify that this is a legal result type of a function.
15282   if (DestType->isArrayType() || DestType->isFunctionType()) {
15283     unsigned diagID = diag::err_func_returning_array_function;
15284     if (Kind == FK_BlockPointer)
15285       diagID = diag::err_block_returning_array_function;
15286
15287     S.Diag(E->getExprLoc(), diagID)
15288       << DestType->isFunctionType() << DestType;
15289     return ExprError();
15290   }
15291
15292   // Otherwise, go ahead and set DestType as the call's result.
15293   E->setType(DestType.getNonLValueExprType(S.Context));
15294   E->setValueKind(Expr::getValueKindForType(DestType));
15295   assert(E->getObjectKind() == OK_Ordinary);
15296
15297   // Rebuild the function type, replacing the result type with DestType.
15298   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
15299   if (Proto) {
15300     // __unknown_anytype(...) is a special case used by the debugger when
15301     // it has no idea what a function's signature is.
15302     //
15303     // We want to build this call essentially under the K&R
15304     // unprototyped rules, but making a FunctionNoProtoType in C++
15305     // would foul up all sorts of assumptions.  However, we cannot
15306     // simply pass all arguments as variadic arguments, nor can we
15307     // portably just call the function under a non-variadic type; see
15308     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
15309     // However, it turns out that in practice it is generally safe to
15310     // call a function declared as "A foo(B,C,D);" under the prototype
15311     // "A foo(B,C,D,...);".  The only known exception is with the
15312     // Windows ABI, where any variadic function is implicitly cdecl
15313     // regardless of its normal CC.  Therefore we change the parameter
15314     // types to match the types of the arguments.
15315     //
15316     // This is a hack, but it is far superior to moving the
15317     // corresponding target-specific code from IR-gen to Sema/AST.
15318
15319     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
15320     SmallVector<QualType, 8> ArgTypes;
15321     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
15322       ArgTypes.reserve(E->getNumArgs());
15323       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
15324         Expr *Arg = E->getArg(i);
15325         QualType ArgType = Arg->getType();
15326         if (E->isLValue()) {
15327           ArgType = S.Context.getLValueReferenceType(ArgType);
15328         } else if (E->isXValue()) {
15329           ArgType = S.Context.getRValueReferenceType(ArgType);
15330         }
15331         ArgTypes.push_back(ArgType);
15332       }
15333       ParamTypes = ArgTypes;
15334     }
15335     DestType = S.Context.getFunctionType(DestType, ParamTypes,
15336                                          Proto->getExtProtoInfo());
15337   } else {
15338     DestType = S.Context.getFunctionNoProtoType(DestType,
15339                                                 FnType->getExtInfo());
15340   }
15341
15342   // Rebuild the appropriate pointer-to-function type.
15343   switch (Kind) { 
15344   case FK_MemberFunction:
15345     // Nothing to do.
15346     break;
15347
15348   case FK_FunctionPointer:
15349     DestType = S.Context.getPointerType(DestType);
15350     break;
15351
15352   case FK_BlockPointer:
15353     DestType = S.Context.getBlockPointerType(DestType);
15354     break;
15355   }
15356
15357   // Finally, we can recurse.
15358   ExprResult CalleeResult = Visit(CalleeExpr);
15359   if (!CalleeResult.isUsable()) return ExprError();
15360   E->setCallee(CalleeResult.get());
15361
15362   // Bind a temporary if necessary.
15363   return S.MaybeBindToTemporary(E);
15364 }
15365
15366 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
15367   // Verify that this is a legal result type of a call.
15368   if (DestType->isArrayType() || DestType->isFunctionType()) {
15369     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
15370       << DestType->isFunctionType() << DestType;
15371     return ExprError();
15372   }
15373
15374   // Rewrite the method result type if available.
15375   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
15376     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
15377     Method->setReturnType(DestType);
15378   }
15379
15380   // Change the type of the message.
15381   E->setType(DestType.getNonReferenceType());
15382   E->setValueKind(Expr::getValueKindForType(DestType));
15383
15384   return S.MaybeBindToTemporary(E);
15385 }
15386
15387 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15388   // The only case we should ever see here is a function-to-pointer decay.
15389   if (E->getCastKind() == CK_FunctionToPointerDecay) {
15390     assert(E->getValueKind() == VK_RValue);
15391     assert(E->getObjectKind() == OK_Ordinary);
15392   
15393     E->setType(DestType);
15394   
15395     // Rebuild the sub-expression as the pointee (function) type.
15396     DestType = DestType->castAs<PointerType>()->getPointeeType();
15397   
15398     ExprResult Result = Visit(E->getSubExpr());
15399     if (!Result.isUsable()) return ExprError();
15400   
15401     E->setSubExpr(Result.get());
15402     return E;
15403   } else if (E->getCastKind() == CK_LValueToRValue) {
15404     assert(E->getValueKind() == VK_RValue);
15405     assert(E->getObjectKind() == OK_Ordinary);
15406
15407     assert(isa<BlockPointerType>(E->getType()));
15408
15409     E->setType(DestType);
15410
15411     // The sub-expression has to be a lvalue reference, so rebuild it as such.
15412     DestType = S.Context.getLValueReferenceType(DestType);
15413
15414     ExprResult Result = Visit(E->getSubExpr());
15415     if (!Result.isUsable()) return ExprError();
15416
15417     E->setSubExpr(Result.get());
15418     return E;
15419   } else {
15420     llvm_unreachable("Unhandled cast type!");
15421   }
15422 }
15423
15424 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15425   ExprValueKind ValueKind = VK_LValue;
15426   QualType Type = DestType;
15427
15428   // We know how to make this work for certain kinds of decls:
15429
15430   //  - functions
15431   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15432     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15433       DestType = Ptr->getPointeeType();
15434       ExprResult Result = resolveDecl(E, VD);
15435       if (Result.isInvalid()) return ExprError();
15436       return S.ImpCastExprToType(Result.get(), Type,
15437                                  CK_FunctionToPointerDecay, VK_RValue);
15438     }
15439
15440     if (!Type->isFunctionType()) {
15441       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15442         << VD << E->getSourceRange();
15443       return ExprError();
15444     }
15445     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15446       // We must match the FunctionDecl's type to the hack introduced in
15447       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15448       // type. See the lengthy commentary in that routine.
15449       QualType FDT = FD->getType();
15450       const FunctionType *FnType = FDT->castAs<FunctionType>();
15451       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15452       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15453       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15454         SourceLocation Loc = FD->getLocation();
15455         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15456                                       FD->getDeclContext(),
15457                                       Loc, Loc, FD->getNameInfo().getName(),
15458                                       DestType, FD->getTypeSourceInfo(),
15459                                       SC_None, false/*isInlineSpecified*/,
15460                                       FD->hasPrototype(),
15461                                       false/*isConstexprSpecified*/);
15462           
15463         if (FD->getQualifier())
15464           NewFD->setQualifierInfo(FD->getQualifierLoc());
15465
15466         SmallVector<ParmVarDecl*, 16> Params;
15467         for (const auto &AI : FT->param_types()) {
15468           ParmVarDecl *Param =
15469             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15470           Param->setScopeInfo(0, Params.size());
15471           Params.push_back(Param);
15472         }
15473         NewFD->setParams(Params);
15474         DRE->setDecl(NewFD);
15475         VD = DRE->getDecl();
15476       }
15477     }
15478
15479     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15480       if (MD->isInstance()) {
15481         ValueKind = VK_RValue;
15482         Type = S.Context.BoundMemberTy;
15483       }
15484
15485     // Function references aren't l-values in C.
15486     if (!S.getLangOpts().CPlusPlus)
15487       ValueKind = VK_RValue;
15488
15489   //  - variables
15490   } else if (isa<VarDecl>(VD)) {
15491     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15492       Type = RefTy->getPointeeType();
15493     } else if (Type->isFunctionType()) {
15494       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15495         << VD << E->getSourceRange();
15496       return ExprError();
15497     }
15498
15499   //  - nothing else
15500   } else {
15501     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15502       << VD << E->getSourceRange();
15503     return ExprError();
15504   }
15505
15506   // Modifying the declaration like this is friendly to IR-gen but
15507   // also really dangerous.
15508   VD->setType(DestType);
15509   E->setType(Type);
15510   E->setValueKind(ValueKind);
15511   return E;
15512 }
15513
15514 /// Check a cast of an unknown-any type.  We intentionally only
15515 /// trigger this for C-style casts.
15516 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15517                                      Expr *CastExpr, CastKind &CastKind,
15518                                      ExprValueKind &VK, CXXCastPath &Path) {
15519   // The type we're casting to must be either void or complete.
15520   if (!CastType->isVoidType() &&
15521       RequireCompleteType(TypeRange.getBegin(), CastType,
15522                           diag::err_typecheck_cast_to_incomplete))
15523     return ExprError();
15524
15525   // Rewrite the casted expression from scratch.
15526   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15527   if (!result.isUsable()) return ExprError();
15528
15529   CastExpr = result.get();
15530   VK = CastExpr->getValueKind();
15531   CastKind = CK_NoOp;
15532
15533   return CastExpr;
15534 }
15535
15536 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15537   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15538 }
15539
15540 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15541                                     Expr *arg, QualType &paramType) {
15542   // If the syntactic form of the argument is not an explicit cast of
15543   // any sort, just do default argument promotion.
15544   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15545   if (!castArg) {
15546     ExprResult result = DefaultArgumentPromotion(arg);
15547     if (result.isInvalid()) return ExprError();
15548     paramType = result.get()->getType();
15549     return result;
15550   }
15551
15552   // Otherwise, use the type that was written in the explicit cast.
15553   assert(!arg->hasPlaceholderType());
15554   paramType = castArg->getTypeAsWritten();
15555
15556   // Copy-initialize a parameter of that type.
15557   InitializedEntity entity =
15558     InitializedEntity::InitializeParameter(Context, paramType,
15559                                            /*consumed*/ false);
15560   return PerformCopyInitialization(entity, callLoc, arg);
15561 }
15562
15563 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15564   Expr *orig = E;
15565   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15566   while (true) {
15567     E = E->IgnoreParenImpCasts();
15568     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15569       E = call->getCallee();
15570       diagID = diag::err_uncasted_call_of_unknown_any;
15571     } else {
15572       break;
15573     }
15574   }
15575
15576   SourceLocation loc;
15577   NamedDecl *d;
15578   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15579     loc = ref->getLocation();
15580     d = ref->getDecl();
15581   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15582     loc = mem->getMemberLoc();
15583     d = mem->getMemberDecl();
15584   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15585     diagID = diag::err_uncasted_call_of_unknown_any;
15586     loc = msg->getSelectorStartLoc();
15587     d = msg->getMethodDecl();
15588     if (!d) {
15589       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15590         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15591         << orig->getSourceRange();
15592       return ExprError();
15593     }
15594   } else {
15595     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15596       << E->getSourceRange();
15597     return ExprError();
15598   }
15599
15600   S.Diag(loc, diagID) << d << orig->getSourceRange();
15601
15602   // Never recoverable.
15603   return ExprError();
15604 }
15605
15606 /// Check for operands with placeholder types and complain if found.
15607 /// Returns ExprError() if there was an error and no recovery was possible.
15608 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15609   if (!getLangOpts().CPlusPlus) {
15610     // C cannot handle TypoExpr nodes on either side of a binop because it
15611     // doesn't handle dependent types properly, so make sure any TypoExprs have
15612     // been dealt with before checking the operands.
15613     ExprResult Result = CorrectDelayedTyposInExpr(E);
15614     if (!Result.isUsable()) return ExprError();
15615     E = Result.get();
15616   }
15617
15618   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15619   if (!placeholderType) return E;
15620
15621   switch (placeholderType->getKind()) {
15622
15623   // Overloaded expressions.
15624   case BuiltinType::Overload: {
15625     // Try to resolve a single function template specialization.
15626     // This is obligatory.
15627     ExprResult Result = E;
15628     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15629       return Result;
15630
15631     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15632     // leaves Result unchanged on failure.
15633     Result = E;
15634     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15635       return Result;
15636
15637     // If that failed, try to recover with a call.
15638     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15639                          /*complain*/ true);
15640     return Result;
15641   }
15642
15643   // Bound member functions.
15644   case BuiltinType::BoundMember: {
15645     ExprResult result = E;
15646     const Expr *BME = E->IgnoreParens();
15647     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15648     // Try to give a nicer diagnostic if it is a bound member that we recognize.
15649     if (isa<CXXPseudoDestructorExpr>(BME)) {
15650       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15651     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15652       if (ME->getMemberNameInfo().getName().getNameKind() ==
15653           DeclarationName::CXXDestructorName)
15654         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15655     }
15656     tryToRecoverWithCall(result, PD,
15657                          /*complain*/ true);
15658     return result;
15659   }
15660
15661   // ARC unbridged casts.
15662   case BuiltinType::ARCUnbridgedCast: {
15663     Expr *realCast = stripARCUnbridgedCast(E);
15664     diagnoseARCUnbridgedCast(realCast);
15665     return realCast;
15666   }
15667
15668   // Expressions of unknown type.
15669   case BuiltinType::UnknownAny:
15670     return diagnoseUnknownAnyExpr(*this, E);
15671
15672   // Pseudo-objects.
15673   case BuiltinType::PseudoObject:
15674     return checkPseudoObjectRValue(E);
15675
15676   case BuiltinType::BuiltinFn: {
15677     // Accept __noop without parens by implicitly converting it to a call expr.
15678     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15679     if (DRE) {
15680       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15681       if (FD->getBuiltinID() == Builtin::BI__noop) {
15682         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15683                               CK_BuiltinFnToFnPtr).get();
15684         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15685                                       VK_RValue, SourceLocation());
15686       }
15687     }
15688
15689     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15690     return ExprError();
15691   }
15692
15693   // Expressions of unknown type.
15694   case BuiltinType::OMPArraySection:
15695     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15696     return ExprError();
15697
15698   // Everything else should be impossible.
15699 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15700   case BuiltinType::Id:
15701 #include "clang/Basic/OpenCLImageTypes.def"
15702 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15703 #define PLACEHOLDER_TYPE(Id, SingletonId)
15704 #include "clang/AST/BuiltinTypes.def"
15705     break;
15706   }
15707
15708   llvm_unreachable("invalid placeholder type!");
15709 }
15710
15711 bool Sema::CheckCaseExpression(Expr *E) {
15712   if (E->isTypeDependent())
15713     return true;
15714   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15715     return E->getType()->isIntegralOrEnumerationType();
15716   return false;
15717 }
15718
15719 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15720 ExprResult
15721 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15722   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15723          "Unknown Objective-C Boolean value!");
15724   QualType BoolT = Context.ObjCBuiltinBoolTy;
15725   if (!Context.getBOOLDecl()) {
15726     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15727                         Sema::LookupOrdinaryName);
15728     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15729       NamedDecl *ND = Result.getFoundDecl();
15730       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 
15731         Context.setBOOLDecl(TD);
15732     }
15733   }
15734   if (Context.getBOOLDecl())
15735     BoolT = Context.getBOOLType();
15736   return new (Context)
15737       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15738 }
15739
15740 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15741     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15742     SourceLocation RParen) {
15743
15744   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15745
15746   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15747                            [&](const AvailabilitySpec &Spec) {
15748                              return Spec.getPlatform() == Platform;
15749                            });
15750
15751   VersionTuple Version;
15752   if (Spec != AvailSpecs.end())
15753     Version = Spec->getVersion();
15754
15755   // The use of `@available` in the enclosing function should be analyzed to
15756   // warn when it's used inappropriately (i.e. not if(@available)).
15757   if (getCurFunctionOrMethodDecl())
15758     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
15759   else if (getCurBlock() || getCurLambda())
15760     getCurFunction()->HasPotentialAvailabilityViolations = true;
15761
15762   return new (Context)
15763       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15764 }