]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaExpr.cpp
Merge ^/head r320971 through r320993.
[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 std::pair<AvailabilityResult, const NamedDecl *>
91 Sema::ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D,
92                                        std::string *Message) {
93   AvailabilityResult Result = D->getAvailability(Message);
94
95   // For typedefs, if the typedef declaration appears available look
96   // to the underlying type to see if it is more restrictive.
97   while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
98     if (Result == AR_Available) {
99       if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
100         D = TT->getDecl();
101         Result = D->getAvailability(Message);
102         continue;
103       }
104     }
105     break;
106   }
107
108   // Forward class declarations get their attributes from their definition.
109   if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
110     if (IDecl->getDefinition()) {
111       D = IDecl->getDefinition();
112       Result = D->getAvailability(Message);
113     }
114   }
115
116   if (const auto *ECD = dyn_cast<EnumConstantDecl>(D))
117     if (Result == AR_Available) {
118       const DeclContext *DC = ECD->getDeclContext();
119       if (const auto *TheEnumDecl = dyn_cast<EnumDecl>(DC)) {
120         Result = TheEnumDecl->getAvailability(Message);
121         D = TheEnumDecl;
122       }
123     }
124
125   return {Result, D};
126 }
127
128 static void
129 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
130                            const ObjCInterfaceDecl *UnknownObjCClass,
131                            bool ObjCPropertyAccess,
132                            bool AvoidPartialAvailabilityChecks = false) {
133   std::string Message;
134   AvailabilityResult Result;
135   const NamedDecl* OffendingDecl;
136   // See if this declaration is unavailable, deprecated, or partial.
137   std::tie(Result, OffendingDecl) = S.ShouldDiagnoseAvailabilityOfDecl(D, &Message);
138   if (Result == AR_Available)
139     return;
140
141   if (Result == AR_NotYetIntroduced) {
142     if (AvoidPartialAvailabilityChecks)
143       return;
144     if (S.getCurFunctionOrMethodDecl()) {
145       S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
146       return;
147     } else if (S.getCurBlock() || S.getCurLambda()) {
148       S.getCurFunction()->HasPotentialAvailabilityViolations = true;
149       return;
150     }
151   }
152
153   const ObjCPropertyDecl *ObjCPDecl = nullptr;
154   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
155     if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
156       AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
157       if (PDeclResult == Result)
158         ObjCPDecl = PD;
159     }
160   }
161
162   S.EmitAvailabilityWarning(Result, D, OffendingDecl, Message, Loc,
163                             UnknownObjCClass, ObjCPDecl, ObjCPropertyAccess);
164 }
165
166 /// \brief Emit a note explaining that this function is deleted.
167 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
168   assert(Decl->isDeleted());
169
170   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
171
172   if (Method && Method->isDeleted() && Method->isDefaulted()) {
173     // If the method was explicitly defaulted, point at that declaration.
174     if (!Method->isImplicit())
175       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
176
177     // Try to diagnose why this special member function was implicitly
178     // deleted. This might fail, if that reason no longer applies.
179     CXXSpecialMember CSM = getSpecialMember(Method);
180     if (CSM != CXXInvalid)
181       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
182
183     return;
184   }
185
186   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
187   if (Ctor && Ctor->isInheritingConstructor())
188     return NoteDeletedInheritingConstructor(Ctor);
189
190   Diag(Decl->getLocation(), diag::note_availability_specified_here)
191     << Decl << true;
192 }
193
194 /// \brief Determine whether a FunctionDecl was ever declared with an
195 /// explicit storage class.
196 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
197   for (auto I : D->redecls()) {
198     if (I->getStorageClass() != SC_None)
199       return true;
200   }
201   return false;
202 }
203
204 /// \brief Check whether we're in an extern inline function and referring to a
205 /// variable or function with internal linkage (C11 6.7.4p3).
206 ///
207 /// This is only a warning because we used to silently accept this code, but
208 /// in many cases it will not behave correctly. This is not enabled in C++ mode
209 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
210 /// and so while there may still be user mistakes, most of the time we can't
211 /// prove that there are errors.
212 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
213                                                       const NamedDecl *D,
214                                                       SourceLocation Loc) {
215   // This is disabled under C++; there are too many ways for this to fire in
216   // contexts where the warning is a false positive, or where it is technically
217   // correct but benign.
218   if (S.getLangOpts().CPlusPlus)
219     return;
220
221   // Check if this is an inlined function or method.
222   FunctionDecl *Current = S.getCurFunctionDecl();
223   if (!Current)
224     return;
225   if (!Current->isInlined())
226     return;
227   if (!Current->isExternallyVisible())
228     return;
229
230   // Check if the decl has internal linkage.
231   if (D->getFormalLinkage() != InternalLinkage)
232     return;
233
234   // Downgrade from ExtWarn to Extension if
235   //  (1) the supposedly external inline function is in the main file,
236   //      and probably won't be included anywhere else.
237   //  (2) the thing we're referencing is a pure function.
238   //  (3) the thing we're referencing is another inline function.
239   // This last can give us false negatives, but it's better than warning on
240   // wrappers for simple C library functions.
241   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
242   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
243   if (!DowngradeWarning && UsedFn)
244     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
245
246   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
247                                : diag::ext_internal_in_extern_inline)
248     << /*IsVar=*/!UsedFn << D;
249
250   S.MaybeSuggestAddingStaticToDecl(Current);
251
252   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
253       << D;
254 }
255
256 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
257   const FunctionDecl *First = Cur->getFirstDecl();
258
259   // Suggest "static" on the function, if possible.
260   if (!hasAnyExplicitStorageClass(First)) {
261     SourceLocation DeclBegin = First->getSourceRange().getBegin();
262     Diag(DeclBegin, diag::note_convert_inline_to_static)
263       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
264   }
265 }
266
267 /// \brief Determine whether the use of this declaration is valid, and
268 /// emit any corresponding diagnostics.
269 ///
270 /// This routine diagnoses various problems with referencing
271 /// declarations that can occur when using a declaration. For example,
272 /// it might warn if a deprecated or unavailable declaration is being
273 /// used, or produce an error (and return true) if a C++0x deleted
274 /// function is being used.
275 ///
276 /// \returns true if there was an error (this declaration cannot be
277 /// referenced), false otherwise.
278 ///
279 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
280                              const ObjCInterfaceDecl *UnknownObjCClass,
281                              bool ObjCPropertyAccess,
282                              bool AvoidPartialAvailabilityChecks) {
283   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
284     // If there were any diagnostics suppressed by template argument deduction,
285     // emit them now.
286     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
287     if (Pos != SuppressedDiagnostics.end()) {
288       for (const PartialDiagnosticAt &Suppressed : Pos->second)
289         Diag(Suppressed.first, Suppressed.second);
290
291       // Clear out the list of suppressed diagnostics, so that we don't emit
292       // them again for this specialization. However, we don't obsolete this
293       // entry from the table, because we want to avoid ever emitting these
294       // diagnostics again.
295       Pos->second.clear();
296     }
297
298     // C++ [basic.start.main]p3:
299     //   The function 'main' shall not be used within a program.
300     if (cast<FunctionDecl>(D)->isMain())
301       Diag(Loc, diag::ext_main_used);
302   }
303
304   // See if this is an auto-typed variable whose initializer we are parsing.
305   if (ParsingInitForAutoVars.count(D)) {
306     if (isa<BindingDecl>(D)) {
307       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
308         << D->getDeclName();
309     } else {
310       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
311         << D->getDeclName() << cast<VarDecl>(D)->getType();
312     }
313     return true;
314   }
315
316   // See if this is a deleted function.
317   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
318     if (FD->isDeleted()) {
319       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
320       if (Ctor && Ctor->isInheritingConstructor())
321         Diag(Loc, diag::err_deleted_inherited_ctor_use)
322             << Ctor->getParent()
323             << Ctor->getInheritedConstructor().getConstructor()->getParent();
324       else 
325         Diag(Loc, diag::err_deleted_function_use);
326       NoteDeletedFunction(FD);
327       return true;
328     }
329
330     // If the function has a deduced return type, and we can't deduce it,
331     // then we can't use it either.
332     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
333         DeduceReturnType(FD, Loc))
334       return true;
335
336     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
337       return true;
338   }
339
340   auto getReferencedObjCProp = [](const NamedDecl *D) ->
341                                       const ObjCPropertyDecl * {
342     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
343       return MD->findPropertyDecl();
344     return nullptr;
345   };
346   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
347     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
348       return true;
349   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
350       return true;
351   }
352
353   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
354   // Only the variables omp_in and omp_out are allowed in the combiner.
355   // Only the variables omp_priv and omp_orig are allowed in the
356   // initializer-clause.
357   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
358   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
359       isa<VarDecl>(D)) {
360     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
361         << getCurFunction()->HasOMPDeclareReductionCombiner;
362     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
363     return true;
364   }
365
366   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
367                              ObjCPropertyAccess,
368                              AvoidPartialAvailabilityChecks);
369
370   DiagnoseUnusedOfDecl(*this, D, Loc);
371
372   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
373
374   return false;
375 }
376
377 /// \brief Retrieve the message suffix that should be added to a
378 /// diagnostic complaining about the given function being deleted or
379 /// unavailable.
380 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
381   std::string Message;
382   if (FD->getAvailability(&Message))
383     return ": " + Message;
384
385   return std::string();
386 }
387
388 /// DiagnoseSentinelCalls - This routine checks whether a call or
389 /// message-send is to a declaration with the sentinel attribute, and
390 /// if so, it checks that the requirements of the sentinel are
391 /// satisfied.
392 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
393                                  ArrayRef<Expr *> Args) {
394   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
395   if (!attr)
396     return;
397
398   // The number of formal parameters of the declaration.
399   unsigned numFormalParams;
400
401   // The kind of declaration.  This is also an index into a %select in
402   // the diagnostic.
403   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
404
405   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
406     numFormalParams = MD->param_size();
407     calleeType = CT_Method;
408   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
409     numFormalParams = FD->param_size();
410     calleeType = CT_Function;
411   } else if (isa<VarDecl>(D)) {
412     QualType type = cast<ValueDecl>(D)->getType();
413     const FunctionType *fn = nullptr;
414     if (const PointerType *ptr = type->getAs<PointerType>()) {
415       fn = ptr->getPointeeType()->getAs<FunctionType>();
416       if (!fn) return;
417       calleeType = CT_Function;
418     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
419       fn = ptr->getPointeeType()->castAs<FunctionType>();
420       calleeType = CT_Block;
421     } else {
422       return;
423     }
424
425     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
426       numFormalParams = proto->getNumParams();
427     } else {
428       numFormalParams = 0;
429     }
430   } else {
431     return;
432   }
433
434   // "nullPos" is the number of formal parameters at the end which
435   // effectively count as part of the variadic arguments.  This is
436   // useful if you would prefer to not have *any* formal parameters,
437   // but the language forces you to have at least one.
438   unsigned nullPos = attr->getNullPos();
439   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
440   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
441
442   // The number of arguments which should follow the sentinel.
443   unsigned numArgsAfterSentinel = attr->getSentinel();
444
445   // If there aren't enough arguments for all the formal parameters,
446   // the sentinel, and the args after the sentinel, complain.
447   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
448     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
449     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
450     return;
451   }
452
453   // Otherwise, find the sentinel expression.
454   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
455   if (!sentinelExpr) return;
456   if (sentinelExpr->isValueDependent()) return;
457   if (Context.isSentinelNullExpr(sentinelExpr)) return;
458
459   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
460   // or 'NULL' if those are actually defined in the context.  Only use
461   // 'nil' for ObjC methods, where it's much more likely that the
462   // variadic arguments form a list of object pointers.
463   SourceLocation MissingNilLoc
464     = getLocForEndOfToken(sentinelExpr->getLocEnd());
465   std::string NullValue;
466   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
467     NullValue = "nil";
468   else if (getLangOpts().CPlusPlus11)
469     NullValue = "nullptr";
470   else if (PP.isMacroDefined("NULL"))
471     NullValue = "NULL";
472   else
473     NullValue = "(void*) 0";
474
475   if (MissingNilLoc.isInvalid())
476     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
477   else
478     Diag(MissingNilLoc, diag::warn_missing_sentinel) 
479       << int(calleeType)
480       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
481   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
482 }
483
484 SourceRange Sema::getExprRange(Expr *E) const {
485   return E ? E->getSourceRange() : SourceRange();
486 }
487
488 //===----------------------------------------------------------------------===//
489 //  Standard Promotions and Conversions
490 //===----------------------------------------------------------------------===//
491
492 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
493 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
494   // Handle any placeholder expressions which made it here.
495   if (E->getType()->isPlaceholderType()) {
496     ExprResult result = CheckPlaceholderExpr(E);
497     if (result.isInvalid()) return ExprError();
498     E = result.get();
499   }
500   
501   QualType Ty = E->getType();
502   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
503
504   if (Ty->isFunctionType()) {
505     // If we are here, we are not calling a function but taking
506     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
507     if (getLangOpts().OpenCL) {
508       if (Diagnose)
509         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
510       return ExprError();
511     }
512
513     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
514       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
515         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
516           return ExprError();
517
518     E = ImpCastExprToType(E, Context.getPointerType(Ty),
519                           CK_FunctionToPointerDecay).get();
520   } else if (Ty->isArrayType()) {
521     // In C90 mode, arrays only promote to pointers if the array expression is
522     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
523     // type 'array of type' is converted to an expression that has type 'pointer
524     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
525     // that has type 'array of type' ...".  The relevant change is "an lvalue"
526     // (C90) to "an expression" (C99).
527     //
528     // C++ 4.2p1:
529     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
530     // T" can be converted to an rvalue of type "pointer to T".
531     //
532     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
533       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
534                             CK_ArrayToPointerDecay).get();
535   }
536   return E;
537 }
538
539 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
540   // Check to see if we are dereferencing a null pointer.  If so,
541   // and if not volatile-qualified, this is undefined behavior that the
542   // optimizer will delete, so warn about it.  People sometimes try to use this
543   // to get a deterministic trap and are surprised by clang's behavior.  This
544   // only handles the pattern "*null", which is a very syntactic check.
545   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
546     if (UO->getOpcode() == UO_Deref &&
547         UO->getSubExpr()->IgnoreParenCasts()->
548           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
549         !UO->getType().isVolatileQualified()) {
550     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
551                           S.PDiag(diag::warn_indirection_through_null)
552                             << UO->getSubExpr()->getSourceRange());
553     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
554                         S.PDiag(diag::note_indirection_through_null));
555   }
556 }
557
558 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
559                                     SourceLocation AssignLoc,
560                                     const Expr* RHS) {
561   const ObjCIvarDecl *IV = OIRE->getDecl();
562   if (!IV)
563     return;
564   
565   DeclarationName MemberName = IV->getDeclName();
566   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
567   if (!Member || !Member->isStr("isa"))
568     return;
569   
570   const Expr *Base = OIRE->getBase();
571   QualType BaseType = Base->getType();
572   if (OIRE->isArrow())
573     BaseType = BaseType->getPointeeType();
574   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
575     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
576       ObjCInterfaceDecl *ClassDeclared = nullptr;
577       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
578       if (!ClassDeclared->getSuperClass()
579           && (*ClassDeclared->ivar_begin()) == IV) {
580         if (RHS) {
581           NamedDecl *ObjectSetClass =
582             S.LookupSingleName(S.TUScope,
583                                &S.Context.Idents.get("object_setClass"),
584                                SourceLocation(), S.LookupOrdinaryName);
585           if (ObjectSetClass) {
586             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
587             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
588             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
589             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
590                                                      AssignLoc), ",") <<
591             FixItHint::CreateInsertion(RHSLocEnd, ")");
592           }
593           else
594             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
595         } else {
596           NamedDecl *ObjectGetClass =
597             S.LookupSingleName(S.TUScope,
598                                &S.Context.Idents.get("object_getClass"),
599                                SourceLocation(), S.LookupOrdinaryName);
600           if (ObjectGetClass)
601             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
602             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
603             FixItHint::CreateReplacement(
604                                          SourceRange(OIRE->getOpLoc(),
605                                                      OIRE->getLocEnd()), ")");
606           else
607             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
608         }
609         S.Diag(IV->getLocation(), diag::note_ivar_decl);
610       }
611     }
612 }
613
614 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
615   // Handle any placeholder expressions which made it here.
616   if (E->getType()->isPlaceholderType()) {
617     ExprResult result = CheckPlaceholderExpr(E);
618     if (result.isInvalid()) return ExprError();
619     E = result.get();
620   }
621   
622   // C++ [conv.lval]p1:
623   //   A glvalue of a non-function, non-array type T can be
624   //   converted to a prvalue.
625   if (!E->isGLValue()) return E;
626
627   QualType T = E->getType();
628   assert(!T.isNull() && "r-value conversion on typeless expression?");
629
630   // We don't want to throw lvalue-to-rvalue casts on top of
631   // expressions of certain types in C++.
632   if (getLangOpts().CPlusPlus &&
633       (E->getType() == Context.OverloadTy ||
634        T->isDependentType() ||
635        T->isRecordType()))
636     return E;
637
638   // The C standard is actually really unclear on this point, and
639   // DR106 tells us what the result should be but not why.  It's
640   // generally best to say that void types just doesn't undergo
641   // lvalue-to-rvalue at all.  Note that expressions of unqualified
642   // 'void' type are never l-values, but qualified void can be.
643   if (T->isVoidType())
644     return E;
645
646   // OpenCL usually rejects direct accesses to values of 'half' type.
647   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
648       T->isHalfType()) {
649     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
650       << 0 << T;
651     return ExprError();
652   }
653
654   CheckForNullPointerDereference(*this, E);
655   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
656     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
657                                      &Context.Idents.get("object_getClass"),
658                                      SourceLocation(), LookupOrdinaryName);
659     if (ObjectGetClass)
660       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
661         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
662         FixItHint::CreateReplacement(
663                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
664     else
665       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
666   }
667   else if (const ObjCIvarRefExpr *OIRE =
668             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
669     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
670
671   // C++ [conv.lval]p1:
672   //   [...] If T is a non-class type, the type of the prvalue is the
673   //   cv-unqualified version of T. Otherwise, the type of the
674   //   rvalue is T.
675   //
676   // C99 6.3.2.1p2:
677   //   If the lvalue has qualified type, the value has the unqualified
678   //   version of the type of the lvalue; otherwise, the value has the
679   //   type of the lvalue.
680   if (T.hasQualifiers())
681     T = T.getUnqualifiedType();
682
683   // Under the MS ABI, lock down the inheritance model now.
684   if (T->isMemberPointerType() &&
685       Context.getTargetInfo().getCXXABI().isMicrosoft())
686     (void)isCompleteType(E->getExprLoc(), T);
687
688   UpdateMarkingForLValueToRValue(E);
689   
690   // Loading a __weak object implicitly retains the value, so we need a cleanup to 
691   // balance that.
692   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
693     Cleanup.setExprNeedsCleanups(true);
694
695   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
696                                             nullptr, VK_RValue);
697
698   // C11 6.3.2.1p2:
699   //   ... if the lvalue has atomic type, the value has the non-atomic version 
700   //   of the type of the lvalue ...
701   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
702     T = Atomic->getValueType().getUnqualifiedType();
703     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
704                                    nullptr, VK_RValue);
705   }
706   
707   return Res;
708 }
709
710 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
711   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
712   if (Res.isInvalid())
713     return ExprError();
714   Res = DefaultLvalueConversion(Res.get());
715   if (Res.isInvalid())
716     return ExprError();
717   return Res;
718 }
719
720 /// CallExprUnaryConversions - a special case of an unary conversion
721 /// performed on a function designator of a call expression.
722 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
723   QualType Ty = E->getType();
724   ExprResult Res = E;
725   // Only do implicit cast for a function type, but not for a pointer
726   // to function type.
727   if (Ty->isFunctionType()) {
728     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
729                             CK_FunctionToPointerDecay).get();
730     if (Res.isInvalid())
731       return ExprError();
732   }
733   Res = DefaultLvalueConversion(Res.get());
734   if (Res.isInvalid())
735     return ExprError();
736   return Res.get();
737 }
738
739 /// UsualUnaryConversions - Performs various conversions that are common to most
740 /// operators (C99 6.3). The conversions of array and function types are
741 /// sometimes suppressed. For example, the array->pointer conversion doesn't
742 /// apply if the array is an argument to the sizeof or address (&) operators.
743 /// In these instances, this routine should *not* be called.
744 ExprResult Sema::UsualUnaryConversions(Expr *E) {
745   // First, convert to an r-value.
746   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
747   if (Res.isInvalid())
748     return ExprError();
749   E = Res.get();
750
751   QualType Ty = E->getType();
752   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
753
754   // Half FP have to be promoted to float unless it is natively supported
755   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
756     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
757
758   // Try to perform integral promotions if the object has a theoretically
759   // promotable type.
760   if (Ty->isIntegralOrUnscopedEnumerationType()) {
761     // C99 6.3.1.1p2:
762     //
763     //   The following may be used in an expression wherever an int or
764     //   unsigned int may be used:
765     //     - an object or expression with an integer type whose integer
766     //       conversion rank is less than or equal to the rank of int
767     //       and unsigned int.
768     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
769     //
770     //   If an int can represent all values of the original type, the
771     //   value is converted to an int; otherwise, it is converted to an
772     //   unsigned int. These are called the integer promotions. All
773     //   other types are unchanged by the integer promotions.
774
775     QualType PTy = Context.isPromotableBitField(E);
776     if (!PTy.isNull()) {
777       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
778       return E;
779     }
780     if (Ty->isPromotableIntegerType()) {
781       QualType PT = Context.getPromotedIntegerType(Ty);
782       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
783       return E;
784     }
785   }
786   return E;
787 }
788
789 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
790 /// do not have a prototype. Arguments that have type float or __fp16
791 /// are promoted to double. All other argument types are converted by
792 /// UsualUnaryConversions().
793 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
794   QualType Ty = E->getType();
795   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
796
797   ExprResult Res = UsualUnaryConversions(E);
798   if (Res.isInvalid())
799     return ExprError();
800   E = Res.get();
801
802   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
803   // double.
804   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
805   if (BTy && (BTy->getKind() == BuiltinType::Half ||
806               BTy->getKind() == BuiltinType::Float)) {
807     if (getLangOpts().OpenCL &&
808         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
809         if (BTy->getKind() == BuiltinType::Half) {
810             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
811         }
812     } else {
813       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
814     }
815   }
816
817   // C++ performs lvalue-to-rvalue conversion as a default argument
818   // promotion, even on class types, but note:
819   //   C++11 [conv.lval]p2:
820   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
821   //     operand or a subexpression thereof the value contained in the
822   //     referenced object is not accessed. Otherwise, if the glvalue
823   //     has a class type, the conversion copy-initializes a temporary
824   //     of type T from the glvalue and the result of the conversion
825   //     is a prvalue for the temporary.
826   // FIXME: add some way to gate this entire thing for correctness in
827   // potentially potentially evaluated contexts.
828   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
829     ExprResult Temp = PerformCopyInitialization(
830                        InitializedEntity::InitializeTemporary(E->getType()),
831                                                 E->getExprLoc(), E);
832     if (Temp.isInvalid())
833       return ExprError();
834     E = Temp.get();
835   }
836
837   return E;
838 }
839
840 /// Determine the degree of POD-ness for an expression.
841 /// Incomplete types are considered POD, since this check can be performed
842 /// when we're in an unevaluated context.
843 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
844   if (Ty->isIncompleteType()) {
845     // C++11 [expr.call]p7:
846     //   After these conversions, if the argument does not have arithmetic,
847     //   enumeration, pointer, pointer to member, or class type, the program
848     //   is ill-formed.
849     //
850     // Since we've already performed array-to-pointer and function-to-pointer
851     // decay, the only such type in C++ is cv void. This also handles
852     // initializer lists as variadic arguments.
853     if (Ty->isVoidType())
854       return VAK_Invalid;
855
856     if (Ty->isObjCObjectType())
857       return VAK_Invalid;
858     return VAK_Valid;
859   }
860
861   if (Ty.isCXX98PODType(Context))
862     return VAK_Valid;
863
864   // C++11 [expr.call]p7:
865   //   Passing a potentially-evaluated argument of class type (Clause 9)
866   //   having a non-trivial copy constructor, a non-trivial move constructor,
867   //   or a non-trivial destructor, with no corresponding parameter,
868   //   is conditionally-supported with implementation-defined semantics.
869   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
870     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
871       if (!Record->hasNonTrivialCopyConstructor() &&
872           !Record->hasNonTrivialMoveConstructor() &&
873           !Record->hasNonTrivialDestructor())
874         return VAK_ValidInCXX11;
875
876   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
877     return VAK_Valid;
878
879   if (Ty->isObjCObjectType())
880     return VAK_Invalid;
881
882   if (getLangOpts().MSVCCompat)
883     return VAK_MSVCUndefined;
884
885   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
886   // permitted to reject them. We should consider doing so.
887   return VAK_Undefined;
888 }
889
890 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
891   // Don't allow one to pass an Objective-C interface to a vararg.
892   const QualType &Ty = E->getType();
893   VarArgKind VAK = isValidVarArgType(Ty);
894
895   // Complain about passing non-POD types through varargs.
896   switch (VAK) {
897   case VAK_ValidInCXX11:
898     DiagRuntimeBehavior(
899         E->getLocStart(), nullptr,
900         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
901           << Ty << CT);
902     // Fall through.
903   case VAK_Valid:
904     if (Ty->isRecordType()) {
905       // This is unlikely to be what the user intended. If the class has a
906       // 'c_str' member function, the user probably meant to call that.
907       DiagRuntimeBehavior(E->getLocStart(), nullptr,
908                           PDiag(diag::warn_pass_class_arg_to_vararg)
909                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
910     }
911     break;
912
913   case VAK_Undefined:
914   case VAK_MSVCUndefined:
915     DiagRuntimeBehavior(
916         E->getLocStart(), nullptr,
917         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
918           << getLangOpts().CPlusPlus11 << Ty << CT);
919     break;
920
921   case VAK_Invalid:
922     if (Ty->isObjCObjectType())
923       DiagRuntimeBehavior(
924           E->getLocStart(), nullptr,
925           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
926             << Ty << CT);
927     else
928       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
929         << isa<InitListExpr>(E) << Ty << CT;
930     break;
931   }
932 }
933
934 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
935 /// will create a trap if the resulting type is not a POD type.
936 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
937                                                   FunctionDecl *FDecl) {
938   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
939     // Strip the unbridged-cast placeholder expression off, if applicable.
940     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
941         (CT == VariadicMethod ||
942          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
943       E = stripARCUnbridgedCast(E);
944
945     // Otherwise, do normal placeholder checking.
946     } else {
947       ExprResult ExprRes = CheckPlaceholderExpr(E);
948       if (ExprRes.isInvalid())
949         return ExprError();
950       E = ExprRes.get();
951     }
952   }
953   
954   ExprResult ExprRes = DefaultArgumentPromotion(E);
955   if (ExprRes.isInvalid())
956     return ExprError();
957   E = ExprRes.get();
958
959   // Diagnostics regarding non-POD argument types are
960   // emitted along with format string checking in Sema::CheckFunctionCall().
961   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
962     // Turn this into a trap.
963     CXXScopeSpec SS;
964     SourceLocation TemplateKWLoc;
965     UnqualifiedId Name;
966     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
967                        E->getLocStart());
968     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
969                                           Name, true, false);
970     if (TrapFn.isInvalid())
971       return ExprError();
972
973     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
974                                     E->getLocStart(), None,
975                                     E->getLocEnd());
976     if (Call.isInvalid())
977       return ExprError();
978
979     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
980                                   Call.get(), E);
981     if (Comma.isInvalid())
982       return ExprError();
983     return Comma.get();
984   }
985
986   if (!getLangOpts().CPlusPlus &&
987       RequireCompleteType(E->getExprLoc(), E->getType(),
988                           diag::err_call_incomplete_argument))
989     return ExprError();
990
991   return E;
992 }
993
994 /// \brief Converts an integer to complex float type.  Helper function of
995 /// UsualArithmeticConversions()
996 ///
997 /// \return false if the integer expression is an integer type and is
998 /// successfully converted to the complex type.
999 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1000                                                   ExprResult &ComplexExpr,
1001                                                   QualType IntTy,
1002                                                   QualType ComplexTy,
1003                                                   bool SkipCast) {
1004   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1005   if (SkipCast) return false;
1006   if (IntTy->isIntegerType()) {
1007     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1008     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1009     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1010                                   CK_FloatingRealToComplex);
1011   } else {
1012     assert(IntTy->isComplexIntegerType());
1013     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1014                                   CK_IntegralComplexToFloatingComplex);
1015   }
1016   return false;
1017 }
1018
1019 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1020 /// UsualArithmeticConversions()
1021 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1022                                              ExprResult &RHS, QualType LHSType,
1023                                              QualType RHSType,
1024                                              bool IsCompAssign) {
1025   // if we have an integer operand, the result is the complex type.
1026   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1027                                              /*skipCast*/false))
1028     return LHSType;
1029   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1030                                              /*skipCast*/IsCompAssign))
1031     return RHSType;
1032
1033   // This handles complex/complex, complex/float, or float/complex.
1034   // When both operands are complex, the shorter operand is converted to the
1035   // type of the longer, and that is the type of the result. This corresponds
1036   // to what is done when combining two real floating-point operands.
1037   // The fun begins when size promotion occur across type domains.
1038   // From H&S 6.3.4: When one operand is complex and the other is a real
1039   // floating-point type, the less precise type is converted, within it's
1040   // real or complex domain, to the precision of the other type. For example,
1041   // when combining a "long double" with a "double _Complex", the
1042   // "double _Complex" is promoted to "long double _Complex".
1043
1044   // Compute the rank of the two types, regardless of whether they are complex.
1045   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1046
1047   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1048   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1049   QualType LHSElementType =
1050       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1051   QualType RHSElementType =
1052       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1053
1054   QualType ResultType = S.Context.getComplexType(LHSElementType);
1055   if (Order < 0) {
1056     // Promote the precision of the LHS if not an assignment.
1057     ResultType = S.Context.getComplexType(RHSElementType);
1058     if (!IsCompAssign) {
1059       if (LHSComplexType)
1060         LHS =
1061             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1062       else
1063         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1064     }
1065   } else if (Order > 0) {
1066     // Promote the precision of the RHS.
1067     if (RHSComplexType)
1068       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1069     else
1070       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1071   }
1072   return ResultType;
1073 }
1074
1075 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1076 /// of UsualArithmeticConversions()
1077 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1078                                            ExprResult &IntExpr,
1079                                            QualType FloatTy, QualType IntTy,
1080                                            bool ConvertFloat, bool ConvertInt) {
1081   if (IntTy->isIntegerType()) {
1082     if (ConvertInt)
1083       // Convert intExpr to the lhs floating point type.
1084       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1085                                     CK_IntegralToFloating);
1086     return FloatTy;
1087   }
1088      
1089   // Convert both sides to the appropriate complex float.
1090   assert(IntTy->isComplexIntegerType());
1091   QualType result = S.Context.getComplexType(FloatTy);
1092
1093   // _Complex int -> _Complex float
1094   if (ConvertInt)
1095     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1096                                   CK_IntegralComplexToFloatingComplex);
1097
1098   // float -> _Complex float
1099   if (ConvertFloat)
1100     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1101                                     CK_FloatingRealToComplex);
1102
1103   return result;
1104 }
1105
1106 /// \brief Handle arithmethic conversion with floating point types.  Helper
1107 /// function of UsualArithmeticConversions()
1108 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1109                                       ExprResult &RHS, QualType LHSType,
1110                                       QualType RHSType, bool IsCompAssign) {
1111   bool LHSFloat = LHSType->isRealFloatingType();
1112   bool RHSFloat = RHSType->isRealFloatingType();
1113
1114   // If we have two real floating types, convert the smaller operand
1115   // to the bigger result.
1116   if (LHSFloat && RHSFloat) {
1117     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1118     if (order > 0) {
1119       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1120       return LHSType;
1121     }
1122
1123     assert(order < 0 && "illegal float comparison");
1124     if (!IsCompAssign)
1125       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1126     return RHSType;
1127   }
1128
1129   if (LHSFloat) {
1130     // Half FP has to be promoted to float unless it is natively supported
1131     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1132       LHSType = S.Context.FloatTy;
1133
1134     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1135                                       /*convertFloat=*/!IsCompAssign,
1136                                       /*convertInt=*/ true);
1137   }
1138   assert(RHSFloat);
1139   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1140                                     /*convertInt=*/ true,
1141                                     /*convertFloat=*/!IsCompAssign);
1142 }
1143
1144 /// \brief Diagnose attempts to convert between __float128 and long double if
1145 /// there is no support for such conversion. Helper function of
1146 /// UsualArithmeticConversions().
1147 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1148                                       QualType RHSType) {
1149   /*  No issue converting if at least one of the types is not a floating point
1150       type or the two types have the same rank.
1151   */
1152   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1153       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1154     return false;
1155
1156   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1157          "The remaining types must be floating point types.");
1158
1159   auto *LHSComplex = LHSType->getAs<ComplexType>();
1160   auto *RHSComplex = RHSType->getAs<ComplexType>();
1161
1162   QualType LHSElemType = LHSComplex ?
1163     LHSComplex->getElementType() : LHSType;
1164   QualType RHSElemType = RHSComplex ?
1165     RHSComplex->getElementType() : RHSType;
1166
1167   // No issue if the two types have the same representation
1168   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1169       &S.Context.getFloatTypeSemantics(RHSElemType))
1170     return false;
1171
1172   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1173                                 RHSElemType == S.Context.LongDoubleTy);
1174   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1175                             RHSElemType == S.Context.Float128Ty);
1176
1177   /* We've handled the situation where __float128 and long double have the same
1178      representation. The only other allowable conversion is if long double is
1179      really just double.
1180   */
1181   return Float128AndLongDouble &&
1182     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1183      &llvm::APFloat::IEEEdouble());
1184 }
1185
1186 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1187
1188 namespace {
1189 /// These helper callbacks are placed in an anonymous namespace to
1190 /// permit their use as function template parameters.
1191 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1192   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1193 }
1194
1195 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1196   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1197                              CK_IntegralComplexCast);
1198 }
1199 }
1200
1201 /// \brief Handle integer arithmetic conversions.  Helper function of
1202 /// UsualArithmeticConversions()
1203 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1204 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1205                                         ExprResult &RHS, QualType LHSType,
1206                                         QualType RHSType, bool IsCompAssign) {
1207   // The rules for this case are in C99 6.3.1.8
1208   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1209   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1210   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1211   if (LHSSigned == RHSSigned) {
1212     // Same signedness; use the higher-ranked type
1213     if (order >= 0) {
1214       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1215       return LHSType;
1216     } else if (!IsCompAssign)
1217       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1218     return RHSType;
1219   } else if (order != (LHSSigned ? 1 : -1)) {
1220     // The unsigned type has greater than or equal rank to the
1221     // signed type, so use the unsigned type
1222     if (RHSSigned) {
1223       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1224       return LHSType;
1225     } else if (!IsCompAssign)
1226       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1227     return RHSType;
1228   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1229     // The two types are different widths; if we are here, that
1230     // means the signed type is larger than the unsigned type, so
1231     // use the signed type.
1232     if (LHSSigned) {
1233       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1234       return LHSType;
1235     } else if (!IsCompAssign)
1236       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1237     return RHSType;
1238   } else {
1239     // The signed type is higher-ranked than the unsigned type,
1240     // but isn't actually any bigger (like unsigned int and long
1241     // on most 32-bit systems).  Use the unsigned type corresponding
1242     // to the signed type.
1243     QualType result =
1244       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1245     RHS = (*doRHSCast)(S, RHS.get(), result);
1246     if (!IsCompAssign)
1247       LHS = (*doLHSCast)(S, LHS.get(), result);
1248     return result;
1249   }
1250 }
1251
1252 /// \brief Handle conversions with GCC complex int extension.  Helper function
1253 /// of UsualArithmeticConversions()
1254 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1255                                            ExprResult &RHS, QualType LHSType,
1256                                            QualType RHSType,
1257                                            bool IsCompAssign) {
1258   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1259   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1260
1261   if (LHSComplexInt && RHSComplexInt) {
1262     QualType LHSEltType = LHSComplexInt->getElementType();
1263     QualType RHSEltType = RHSComplexInt->getElementType();
1264     QualType ScalarType =
1265       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1266         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1267
1268     return S.Context.getComplexType(ScalarType);
1269   }
1270
1271   if (LHSComplexInt) {
1272     QualType LHSEltType = LHSComplexInt->getElementType();
1273     QualType ScalarType =
1274       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1275         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1276     QualType ComplexType = S.Context.getComplexType(ScalarType);
1277     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1278                               CK_IntegralRealToComplex);
1279  
1280     return ComplexType;
1281   }
1282
1283   assert(RHSComplexInt);
1284
1285   QualType RHSEltType = RHSComplexInt->getElementType();
1286   QualType ScalarType =
1287     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1288       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1289   QualType ComplexType = S.Context.getComplexType(ScalarType);
1290   
1291   if (!IsCompAssign)
1292     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1293                               CK_IntegralRealToComplex);
1294   return ComplexType;
1295 }
1296
1297 /// UsualArithmeticConversions - Performs various conversions that are common to
1298 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1299 /// routine returns the first non-arithmetic type found. The client is
1300 /// responsible for emitting appropriate error diagnostics.
1301 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1302                                           bool IsCompAssign) {
1303   if (!IsCompAssign) {
1304     LHS = UsualUnaryConversions(LHS.get());
1305     if (LHS.isInvalid())
1306       return QualType();
1307   }
1308
1309   RHS = UsualUnaryConversions(RHS.get());
1310   if (RHS.isInvalid())
1311     return QualType();
1312
1313   // For conversion purposes, we ignore any qualifiers.
1314   // For example, "const float" and "float" are equivalent.
1315   QualType LHSType =
1316     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1317   QualType RHSType =
1318     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1319
1320   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1321   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1322     LHSType = AtomicLHS->getValueType();
1323
1324   // If both types are identical, no conversion is needed.
1325   if (LHSType == RHSType)
1326     return LHSType;
1327
1328   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1329   // The caller can deal with this (e.g. pointer + int).
1330   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1331     return QualType();
1332
1333   // Apply unary and bitfield promotions to the LHS's type.
1334   QualType LHSUnpromotedType = LHSType;
1335   if (LHSType->isPromotableIntegerType())
1336     LHSType = Context.getPromotedIntegerType(LHSType);
1337   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1338   if (!LHSBitfieldPromoteTy.isNull())
1339     LHSType = LHSBitfieldPromoteTy;
1340   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1341     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1342
1343   // If both types are identical, no conversion is needed.
1344   if (LHSType == RHSType)
1345     return LHSType;
1346
1347   // At this point, we have two different arithmetic types.
1348
1349   // Diagnose attempts to convert between __float128 and long double where
1350   // such conversions currently can't be handled.
1351   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1352     return QualType();
1353
1354   // Handle complex types first (C99 6.3.1.8p1).
1355   if (LHSType->isComplexType() || RHSType->isComplexType())
1356     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1357                                         IsCompAssign);
1358
1359   // Now handle "real" floating types (i.e. float, double, long double).
1360   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1361     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1362                                  IsCompAssign);
1363
1364   // Handle GCC complex int extension.
1365   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1366     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1367                                       IsCompAssign);
1368
1369   // Finally, we have two differing integer types.
1370   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1371            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1372 }
1373
1374
1375 //===----------------------------------------------------------------------===//
1376 //  Semantic Analysis for various Expression Types
1377 //===----------------------------------------------------------------------===//
1378
1379
1380 ExprResult
1381 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1382                                 SourceLocation DefaultLoc,
1383                                 SourceLocation RParenLoc,
1384                                 Expr *ControllingExpr,
1385                                 ArrayRef<ParsedType> ArgTypes,
1386                                 ArrayRef<Expr *> ArgExprs) {
1387   unsigned NumAssocs = ArgTypes.size();
1388   assert(NumAssocs == ArgExprs.size());
1389
1390   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1391   for (unsigned i = 0; i < NumAssocs; ++i) {
1392     if (ArgTypes[i])
1393       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1394     else
1395       Types[i] = nullptr;
1396   }
1397
1398   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1399                                              ControllingExpr,
1400                                              llvm::makeArrayRef(Types, NumAssocs),
1401                                              ArgExprs);
1402   delete [] Types;
1403   return ER;
1404 }
1405
1406 ExprResult
1407 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1408                                  SourceLocation DefaultLoc,
1409                                  SourceLocation RParenLoc,
1410                                  Expr *ControllingExpr,
1411                                  ArrayRef<TypeSourceInfo *> Types,
1412                                  ArrayRef<Expr *> Exprs) {
1413   unsigned NumAssocs = Types.size();
1414   assert(NumAssocs == Exprs.size());
1415
1416   // Decay and strip qualifiers for the controlling expression type, and handle
1417   // placeholder type replacement. See committee discussion from WG14 DR423.
1418   {
1419     EnterExpressionEvaluationContext Unevaluated(
1420         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1421     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1422     if (R.isInvalid())
1423       return ExprError();
1424     ControllingExpr = R.get();
1425   }
1426
1427   // The controlling expression is an unevaluated operand, so side effects are
1428   // likely unintended.
1429   if (!inTemplateInstantiation() &&
1430       ControllingExpr->HasSideEffects(Context, false))
1431     Diag(ControllingExpr->getExprLoc(),
1432          diag::warn_side_effects_unevaluated_context);
1433
1434   bool TypeErrorFound = false,
1435        IsResultDependent = ControllingExpr->isTypeDependent(),
1436        ContainsUnexpandedParameterPack
1437          = ControllingExpr->containsUnexpandedParameterPack();
1438
1439   for (unsigned i = 0; i < NumAssocs; ++i) {
1440     if (Exprs[i]->containsUnexpandedParameterPack())
1441       ContainsUnexpandedParameterPack = true;
1442
1443     if (Types[i]) {
1444       if (Types[i]->getType()->containsUnexpandedParameterPack())
1445         ContainsUnexpandedParameterPack = true;
1446
1447       if (Types[i]->getType()->isDependentType()) {
1448         IsResultDependent = true;
1449       } else {
1450         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1451         // complete object type other than a variably modified type."
1452         unsigned D = 0;
1453         if (Types[i]->getType()->isIncompleteType())
1454           D = diag::err_assoc_type_incomplete;
1455         else if (!Types[i]->getType()->isObjectType())
1456           D = diag::err_assoc_type_nonobject;
1457         else if (Types[i]->getType()->isVariablyModifiedType())
1458           D = diag::err_assoc_type_variably_modified;
1459
1460         if (D != 0) {
1461           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1462             << Types[i]->getTypeLoc().getSourceRange()
1463             << Types[i]->getType();
1464           TypeErrorFound = true;
1465         }
1466
1467         // C11 6.5.1.1p2 "No two generic associations in the same generic
1468         // selection shall specify compatible types."
1469         for (unsigned j = i+1; j < NumAssocs; ++j)
1470           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1471               Context.typesAreCompatible(Types[i]->getType(),
1472                                          Types[j]->getType())) {
1473             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1474                  diag::err_assoc_compatible_types)
1475               << Types[j]->getTypeLoc().getSourceRange()
1476               << Types[j]->getType()
1477               << Types[i]->getType();
1478             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1479                  diag::note_compat_assoc)
1480               << Types[i]->getTypeLoc().getSourceRange()
1481               << Types[i]->getType();
1482             TypeErrorFound = true;
1483           }
1484       }
1485     }
1486   }
1487   if (TypeErrorFound)
1488     return ExprError();
1489
1490   // If we determined that the generic selection is result-dependent, don't
1491   // try to compute the result expression.
1492   if (IsResultDependent)
1493     return new (Context) GenericSelectionExpr(
1494         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1495         ContainsUnexpandedParameterPack);
1496
1497   SmallVector<unsigned, 1> CompatIndices;
1498   unsigned DefaultIndex = -1U;
1499   for (unsigned i = 0; i < NumAssocs; ++i) {
1500     if (!Types[i])
1501       DefaultIndex = i;
1502     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1503                                         Types[i]->getType()))
1504       CompatIndices.push_back(i);
1505   }
1506
1507   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1508   // type compatible with at most one of the types named in its generic
1509   // association list."
1510   if (CompatIndices.size() > 1) {
1511     // We strip parens here because the controlling expression is typically
1512     // parenthesized in macro definitions.
1513     ControllingExpr = ControllingExpr->IgnoreParens();
1514     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1515       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1516       << (unsigned) CompatIndices.size();
1517     for (unsigned I : CompatIndices) {
1518       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1519            diag::note_compat_assoc)
1520         << Types[I]->getTypeLoc().getSourceRange()
1521         << Types[I]->getType();
1522     }
1523     return ExprError();
1524   }
1525
1526   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1527   // its controlling expression shall have type compatible with exactly one of
1528   // the types named in its generic association list."
1529   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1530     // We strip parens here because the controlling expression is typically
1531     // parenthesized in macro definitions.
1532     ControllingExpr = ControllingExpr->IgnoreParens();
1533     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1534       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1535     return ExprError();
1536   }
1537
1538   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1539   // type name that is compatible with the type of the controlling expression,
1540   // then the result expression of the generic selection is the expression
1541   // in that generic association. Otherwise, the result expression of the
1542   // generic selection is the expression in the default generic association."
1543   unsigned ResultIndex =
1544     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1545
1546   return new (Context) GenericSelectionExpr(
1547       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1548       ContainsUnexpandedParameterPack, ResultIndex);
1549 }
1550
1551 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1552 /// location of the token and the offset of the ud-suffix within it.
1553 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1554                                      unsigned Offset) {
1555   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1556                                         S.getLangOpts());
1557 }
1558
1559 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1560 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1561 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1562                                                  IdentifierInfo *UDSuffix,
1563                                                  SourceLocation UDSuffixLoc,
1564                                                  ArrayRef<Expr*> Args,
1565                                                  SourceLocation LitEndLoc) {
1566   assert(Args.size() <= 2 && "too many arguments for literal operator");
1567
1568   QualType ArgTy[2];
1569   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1570     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1571     if (ArgTy[ArgIdx]->isArrayType())
1572       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1573   }
1574
1575   DeclarationName OpName =
1576     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1577   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1578   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1579
1580   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1581   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1582                               /*AllowRaw*/false, /*AllowTemplate*/false,
1583                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1584     return ExprError();
1585
1586   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1587 }
1588
1589 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1590 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1591 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1592 /// multiple tokens.  However, the common case is that StringToks points to one
1593 /// string.
1594 ///
1595 ExprResult
1596 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1597   assert(!StringToks.empty() && "Must have at least one string!");
1598
1599   StringLiteralParser Literal(StringToks, PP);
1600   if (Literal.hadError)
1601     return ExprError();
1602
1603   SmallVector<SourceLocation, 4> StringTokLocs;
1604   for (const Token &Tok : StringToks)
1605     StringTokLocs.push_back(Tok.getLocation());
1606
1607   QualType CharTy = Context.CharTy;
1608   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1609   if (Literal.isWide()) {
1610     CharTy = Context.getWideCharType();
1611     Kind = StringLiteral::Wide;
1612   } else if (Literal.isUTF8()) {
1613     Kind = StringLiteral::UTF8;
1614   } else if (Literal.isUTF16()) {
1615     CharTy = Context.Char16Ty;
1616     Kind = StringLiteral::UTF16;
1617   } else if (Literal.isUTF32()) {
1618     CharTy = Context.Char32Ty;
1619     Kind = StringLiteral::UTF32;
1620   } else if (Literal.isPascal()) {
1621     CharTy = Context.UnsignedCharTy;
1622   }
1623
1624   QualType CharTyConst = CharTy;
1625   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1626   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1627     CharTyConst.addConst();
1628
1629   // Get an array type for the string, according to C99 6.4.5.  This includes
1630   // the nul terminator character as well as the string length for pascal
1631   // strings.
1632   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1633                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1634                                  ArrayType::Normal, 0);
1635
1636   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1637   if (getLangOpts().OpenCL) {
1638     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1639   }
1640
1641   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1642   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1643                                              Kind, Literal.Pascal, StrTy,
1644                                              &StringTokLocs[0],
1645                                              StringTokLocs.size());
1646   if (Literal.getUDSuffix().empty())
1647     return Lit;
1648
1649   // We're building a user-defined literal.
1650   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1651   SourceLocation UDSuffixLoc =
1652     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1653                    Literal.getUDSuffixOffset());
1654
1655   // Make sure we're allowed user-defined literals here.
1656   if (!UDLScope)
1657     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1658
1659   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1660   //   operator "" X (str, len)
1661   QualType SizeType = Context.getSizeType();
1662
1663   DeclarationName OpName =
1664     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1665   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1666   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1667
1668   QualType ArgTy[] = {
1669     Context.getArrayDecayedType(StrTy), SizeType
1670   };
1671
1672   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1673   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1674                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1675                                 /*AllowStringTemplate*/true)) {
1676
1677   case LOLR_Cooked: {
1678     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1679     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1680                                                     StringTokLocs[0]);
1681     Expr *Args[] = { Lit, LenArg };
1682
1683     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1684   }
1685
1686   case LOLR_StringTemplate: {
1687     TemplateArgumentListInfo ExplicitArgs;
1688
1689     unsigned CharBits = Context.getIntWidth(CharTy);
1690     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1691     llvm::APSInt Value(CharBits, CharIsUnsigned);
1692
1693     TemplateArgument TypeArg(CharTy);
1694     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1695     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1696
1697     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1698       Value = Lit->getCodeUnit(I);
1699       TemplateArgument Arg(Context, Value, CharTy);
1700       TemplateArgumentLocInfo ArgInfo;
1701       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1702     }
1703     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1704                                     &ExplicitArgs);
1705   }
1706   case LOLR_Raw:
1707   case LOLR_Template:
1708     llvm_unreachable("unexpected literal operator lookup result");
1709   case LOLR_Error:
1710     return ExprError();
1711   }
1712   llvm_unreachable("unexpected literal operator lookup result");
1713 }
1714
1715 ExprResult
1716 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1717                        SourceLocation Loc,
1718                        const CXXScopeSpec *SS) {
1719   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1720   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1721 }
1722
1723 /// BuildDeclRefExpr - Build an expression that references a
1724 /// declaration that does not require a closure capture.
1725 ExprResult
1726 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1727                        const DeclarationNameInfo &NameInfo,
1728                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1729                        const TemplateArgumentListInfo *TemplateArgs) {
1730   bool RefersToCapturedVariable =
1731       isa<VarDecl>(D) &&
1732       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1733
1734   DeclRefExpr *E;
1735   if (isa<VarTemplateSpecializationDecl>(D)) {
1736     VarTemplateSpecializationDecl *VarSpec =
1737         cast<VarTemplateSpecializationDecl>(D);
1738
1739     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1740                                         : NestedNameSpecifierLoc(),
1741                             VarSpec->getTemplateKeywordLoc(), D,
1742                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1743                             FoundD, TemplateArgs);
1744   } else {
1745     assert(!TemplateArgs && "No template arguments for non-variable"
1746                             " template specialization references");
1747     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1748                                         : NestedNameSpecifierLoc(),
1749                             SourceLocation(), D, RefersToCapturedVariable,
1750                             NameInfo, Ty, VK, FoundD);
1751   }
1752
1753   MarkDeclRefReferenced(E);
1754
1755   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1756       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1757       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1758       recordUseOfEvaluatedWeak(E);
1759
1760   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1761   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1762     FD = IFD->getAnonField();
1763   if (FD) {
1764     UnusedPrivateFields.remove(FD);
1765     // Just in case we're building an illegal pointer-to-member.
1766     if (FD->isBitField())
1767       E->setObjectKind(OK_BitField);
1768   }
1769
1770   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1771   // designates a bit-field.
1772   if (auto *BD = dyn_cast<BindingDecl>(D))
1773     if (auto *BE = BD->getBinding())
1774       E->setObjectKind(BE->getObjectKind());
1775
1776   return E;
1777 }
1778
1779 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1780 /// possibly a list of template arguments.
1781 ///
1782 /// If this produces template arguments, it is permitted to call
1783 /// DecomposeTemplateName.
1784 ///
1785 /// This actually loses a lot of source location information for
1786 /// non-standard name kinds; we should consider preserving that in
1787 /// some way.
1788 void
1789 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1790                              TemplateArgumentListInfo &Buffer,
1791                              DeclarationNameInfo &NameInfo,
1792                              const TemplateArgumentListInfo *&TemplateArgs) {
1793   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1794     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1795     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1796
1797     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1798                                        Id.TemplateId->NumArgs);
1799     translateTemplateArguments(TemplateArgsPtr, Buffer);
1800
1801     TemplateName TName = Id.TemplateId->Template.get();
1802     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1803     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1804     TemplateArgs = &Buffer;
1805   } else {
1806     NameInfo = GetNameFromUnqualifiedId(Id);
1807     TemplateArgs = nullptr;
1808   }
1809 }
1810
1811 static void emitEmptyLookupTypoDiagnostic(
1812     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1813     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1814     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1815   DeclContext *Ctx =
1816       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1817   if (!TC) {
1818     // Emit a special diagnostic for failed member lookups.
1819     // FIXME: computing the declaration context might fail here (?)
1820     if (Ctx)
1821       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1822                                                  << SS.getRange();
1823     else
1824       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1825     return;
1826   }
1827
1828   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1829   bool DroppedSpecifier =
1830       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1831   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1832                         ? diag::note_implicit_param_decl
1833                         : diag::note_previous_decl;
1834   if (!Ctx)
1835     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1836                          SemaRef.PDiag(NoteID));
1837   else
1838     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1839                                  << Typo << Ctx << DroppedSpecifier
1840                                  << SS.getRange(),
1841                          SemaRef.PDiag(NoteID));
1842 }
1843
1844 /// Diagnose an empty lookup.
1845 ///
1846 /// \return false if new lookup candidates were found
1847 bool
1848 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1849                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1850                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1851                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1852   DeclarationName Name = R.getLookupName();
1853
1854   unsigned diagnostic = diag::err_undeclared_var_use;
1855   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1856   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1857       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1858       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1859     diagnostic = diag::err_undeclared_use;
1860     diagnostic_suggest = diag::err_undeclared_use_suggest;
1861   }
1862
1863   // If the original lookup was an unqualified lookup, fake an
1864   // unqualified lookup.  This is useful when (for example) the
1865   // original lookup would not have found something because it was a
1866   // dependent name.
1867   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1868   while (DC) {
1869     if (isa<CXXRecordDecl>(DC)) {
1870       LookupQualifiedName(R, DC);
1871
1872       if (!R.empty()) {
1873         // Don't give errors about ambiguities in this lookup.
1874         R.suppressDiagnostics();
1875
1876         // During a default argument instantiation the CurContext points
1877         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1878         // function parameter list, hence add an explicit check.
1879         bool isDefaultArgument =
1880             !CodeSynthesisContexts.empty() &&
1881             CodeSynthesisContexts.back().Kind ==
1882                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1883         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1884         bool isInstance = CurMethod &&
1885                           CurMethod->isInstance() &&
1886                           DC == CurMethod->getParent() && !isDefaultArgument;
1887
1888         // Give a code modification hint to insert 'this->'.
1889         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1890         // Actually quite difficult!
1891         if (getLangOpts().MSVCCompat)
1892           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1893         if (isInstance) {
1894           Diag(R.getNameLoc(), diagnostic) << Name
1895             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1896           CheckCXXThisCapture(R.getNameLoc());
1897         } else {
1898           Diag(R.getNameLoc(), diagnostic) << Name;
1899         }
1900
1901         // Do we really want to note all of these?
1902         for (NamedDecl *D : R)
1903           Diag(D->getLocation(), diag::note_dependent_var_use);
1904
1905         // Return true if we are inside a default argument instantiation
1906         // and the found name refers to an instance member function, otherwise
1907         // the function calling DiagnoseEmptyLookup will try to create an
1908         // implicit member call and this is wrong for default argument.
1909         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1910           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1911           return true;
1912         }
1913
1914         // Tell the callee to try to recover.
1915         return false;
1916       }
1917
1918       R.clear();
1919     }
1920
1921     // In Microsoft mode, if we are performing lookup from within a friend
1922     // function definition declared at class scope then we must set
1923     // DC to the lexical parent to be able to search into the parent
1924     // class.
1925     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1926         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1927         DC->getLexicalParent()->isRecord())
1928       DC = DC->getLexicalParent();
1929     else
1930       DC = DC->getParent();
1931   }
1932
1933   // We didn't find anything, so try to correct for a typo.
1934   TypoCorrection Corrected;
1935   if (S && Out) {
1936     SourceLocation TypoLoc = R.getNameLoc();
1937     assert(!ExplicitTemplateArgs &&
1938            "Diagnosing an empty lookup with explicit template args!");
1939     *Out = CorrectTypoDelayed(
1940         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1941         [=](const TypoCorrection &TC) {
1942           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1943                                         diagnostic, diagnostic_suggest);
1944         },
1945         nullptr, CTK_ErrorRecovery);
1946     if (*Out)
1947       return true;
1948   } else if (S && (Corrected =
1949                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1950                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1951     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1952     bool DroppedSpecifier =
1953         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1954     R.setLookupName(Corrected.getCorrection());
1955
1956     bool AcceptableWithRecovery = false;
1957     bool AcceptableWithoutRecovery = false;
1958     NamedDecl *ND = Corrected.getFoundDecl();
1959     if (ND) {
1960       if (Corrected.isOverloaded()) {
1961         OverloadCandidateSet OCS(R.getNameLoc(),
1962                                  OverloadCandidateSet::CSK_Normal);
1963         OverloadCandidateSet::iterator Best;
1964         for (NamedDecl *CD : Corrected) {
1965           if (FunctionTemplateDecl *FTD =
1966                    dyn_cast<FunctionTemplateDecl>(CD))
1967             AddTemplateOverloadCandidate(
1968                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1969                 Args, OCS);
1970           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1971             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1972               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1973                                    Args, OCS);
1974         }
1975         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1976         case OR_Success:
1977           ND = Best->FoundDecl;
1978           Corrected.setCorrectionDecl(ND);
1979           break;
1980         default:
1981           // FIXME: Arbitrarily pick the first declaration for the note.
1982           Corrected.setCorrectionDecl(ND);
1983           break;
1984         }
1985       }
1986       R.addDecl(ND);
1987       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1988         CXXRecordDecl *Record = nullptr;
1989         if (Corrected.getCorrectionSpecifier()) {
1990           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1991           Record = Ty->getAsCXXRecordDecl();
1992         }
1993         if (!Record)
1994           Record = cast<CXXRecordDecl>(
1995               ND->getDeclContext()->getRedeclContext());
1996         R.setNamingClass(Record);
1997       }
1998
1999       auto *UnderlyingND = ND->getUnderlyingDecl();
2000       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2001                                isa<FunctionTemplateDecl>(UnderlyingND);
2002       // FIXME: If we ended up with a typo for a type name or
2003       // Objective-C class name, we're in trouble because the parser
2004       // is in the wrong place to recover. Suggest the typo
2005       // correction, but don't make it a fix-it since we're not going
2006       // to recover well anyway.
2007       AcceptableWithoutRecovery =
2008           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2009     } else {
2010       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2011       // because we aren't able to recover.
2012       AcceptableWithoutRecovery = true;
2013     }
2014
2015     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2016       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2017                             ? diag::note_implicit_param_decl
2018                             : diag::note_previous_decl;
2019       if (SS.isEmpty())
2020         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2021                      PDiag(NoteID), AcceptableWithRecovery);
2022       else
2023         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2024                                   << Name << computeDeclContext(SS, false)
2025                                   << DroppedSpecifier << SS.getRange(),
2026                      PDiag(NoteID), AcceptableWithRecovery);
2027
2028       // Tell the callee whether to try to recover.
2029       return !AcceptableWithRecovery;
2030     }
2031   }
2032   R.clear();
2033
2034   // Emit a special diagnostic for failed member lookups.
2035   // FIXME: computing the declaration context might fail here (?)
2036   if (!SS.isEmpty()) {
2037     Diag(R.getNameLoc(), diag::err_no_member)
2038       << Name << computeDeclContext(SS, false)
2039       << SS.getRange();
2040     return true;
2041   }
2042
2043   // Give up, we can't recover.
2044   Diag(R.getNameLoc(), diagnostic) << Name;
2045   return true;
2046 }
2047
2048 /// In Microsoft mode, if we are inside a template class whose parent class has
2049 /// dependent base classes, and we can't resolve an unqualified identifier, then
2050 /// assume the identifier is a member of a dependent base class.  We can only
2051 /// recover successfully in static methods, instance methods, and other contexts
2052 /// where 'this' is available.  This doesn't precisely match MSVC's
2053 /// instantiation model, but it's close enough.
2054 static Expr *
2055 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2056                                DeclarationNameInfo &NameInfo,
2057                                SourceLocation TemplateKWLoc,
2058                                const TemplateArgumentListInfo *TemplateArgs) {
2059   // Only try to recover from lookup into dependent bases in static methods or
2060   // contexts where 'this' is available.
2061   QualType ThisType = S.getCurrentThisType();
2062   const CXXRecordDecl *RD = nullptr;
2063   if (!ThisType.isNull())
2064     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2065   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2066     RD = MD->getParent();
2067   if (!RD || !RD->hasAnyDependentBases())
2068     return nullptr;
2069
2070   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2071   // is available, suggest inserting 'this->' as a fixit.
2072   SourceLocation Loc = NameInfo.getLoc();
2073   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2074   DB << NameInfo.getName() << RD;
2075
2076   if (!ThisType.isNull()) {
2077     DB << FixItHint::CreateInsertion(Loc, "this->");
2078     return CXXDependentScopeMemberExpr::Create(
2079         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2080         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2081         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2082   }
2083
2084   // Synthesize a fake NNS that points to the derived class.  This will
2085   // perform name lookup during template instantiation.
2086   CXXScopeSpec SS;
2087   auto *NNS =
2088       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2089   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2090   return DependentScopeDeclRefExpr::Create(
2091       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2092       TemplateArgs);
2093 }
2094
2095 ExprResult
2096 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2097                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2098                         bool HasTrailingLParen, bool IsAddressOfOperand,
2099                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2100                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2101   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2102          "cannot be direct & operand and have a trailing lparen");
2103   if (SS.isInvalid())
2104     return ExprError();
2105
2106   TemplateArgumentListInfo TemplateArgsBuffer;
2107
2108   // Decompose the UnqualifiedId into the following data.
2109   DeclarationNameInfo NameInfo;
2110   const TemplateArgumentListInfo *TemplateArgs;
2111   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2112
2113   DeclarationName Name = NameInfo.getName();
2114   IdentifierInfo *II = Name.getAsIdentifierInfo();
2115   SourceLocation NameLoc = NameInfo.getLoc();
2116
2117   if (II && II->isEditorPlaceholder()) {
2118     // FIXME: When typed placeholders are supported we can create a typed
2119     // placeholder expression node.
2120     return ExprError();
2121   }
2122
2123   // C++ [temp.dep.expr]p3:
2124   //   An id-expression is type-dependent if it contains:
2125   //     -- an identifier that was declared with a dependent type,
2126   //        (note: handled after lookup)
2127   //     -- a template-id that is dependent,
2128   //        (note: handled in BuildTemplateIdExpr)
2129   //     -- a conversion-function-id that specifies a dependent type,
2130   //     -- a nested-name-specifier that contains a class-name that
2131   //        names a dependent type.
2132   // Determine whether this is a member of an unknown specialization;
2133   // we need to handle these differently.
2134   bool DependentID = false;
2135   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2136       Name.getCXXNameType()->isDependentType()) {
2137     DependentID = true;
2138   } else if (SS.isSet()) {
2139     if (DeclContext *DC = computeDeclContext(SS, false)) {
2140       if (RequireCompleteDeclContext(SS, DC))
2141         return ExprError();
2142     } else {
2143       DependentID = true;
2144     }
2145   }
2146
2147   if (DependentID)
2148     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2149                                       IsAddressOfOperand, TemplateArgs);
2150
2151   // Perform the required lookup.
2152   LookupResult R(*this, NameInfo, 
2153                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 
2154                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2155   if (TemplateArgs) {
2156     // Lookup the template name again to correctly establish the context in
2157     // which it was found. This is really unfortunate as we already did the
2158     // lookup to determine that it was a template name in the first place. If
2159     // this becomes a performance hit, we can work harder to preserve those
2160     // results until we get here but it's likely not worth it.
2161     bool MemberOfUnknownSpecialization;
2162     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2163                        MemberOfUnknownSpecialization);
2164     
2165     if (MemberOfUnknownSpecialization ||
2166         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2167       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2168                                         IsAddressOfOperand, TemplateArgs);
2169   } else {
2170     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2171     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2172
2173     // If the result might be in a dependent base class, this is a dependent 
2174     // id-expression.
2175     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2176       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2177                                         IsAddressOfOperand, TemplateArgs);
2178
2179     // If this reference is in an Objective-C method, then we need to do
2180     // some special Objective-C lookup, too.
2181     if (IvarLookupFollowUp) {
2182       ExprResult E(LookupInObjCMethod(R, S, II, true));
2183       if (E.isInvalid())
2184         return ExprError();
2185
2186       if (Expr *Ex = E.getAs<Expr>())
2187         return Ex;
2188     }
2189   }
2190
2191   if (R.isAmbiguous())
2192     return ExprError();
2193
2194   // This could be an implicitly declared function reference (legal in C90,
2195   // extension in C99, forbidden in C++).
2196   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2197     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2198     if (D) R.addDecl(D);
2199   }
2200
2201   // Determine whether this name might be a candidate for
2202   // argument-dependent lookup.
2203   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2204
2205   if (R.empty() && !ADL) {
2206     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2207       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2208                                                    TemplateKWLoc, TemplateArgs))
2209         return E;
2210     }
2211
2212     // Don't diagnose an empty lookup for inline assembly.
2213     if (IsInlineAsmIdentifier)
2214       return ExprError();
2215
2216     // If this name wasn't predeclared and if this is not a function
2217     // call, diagnose the problem.
2218     TypoExpr *TE = nullptr;
2219     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2220         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2221     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2222     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2223            "Typo correction callback misconfigured");
2224     if (CCC) {
2225       // Make sure the callback knows what the typo being diagnosed is.
2226       CCC->setTypoName(II);
2227       if (SS.isValid())
2228         CCC->setTypoNNS(SS.getScopeRep());
2229     }
2230     if (DiagnoseEmptyLookup(S, SS, R,
2231                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2232                             nullptr, None, &TE)) {
2233       if (TE && KeywordReplacement) {
2234         auto &State = getTypoExprState(TE);
2235         auto BestTC = State.Consumer->getNextCorrection();
2236         if (BestTC.isKeyword()) {
2237           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2238           if (State.DiagHandler)
2239             State.DiagHandler(BestTC);
2240           KeywordReplacement->startToken();
2241           KeywordReplacement->setKind(II->getTokenID());
2242           KeywordReplacement->setIdentifierInfo(II);
2243           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2244           // Clean up the state associated with the TypoExpr, since it has
2245           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2246           clearDelayedTypo(TE);
2247           // Signal that a correction to a keyword was performed by returning a
2248           // valid-but-null ExprResult.
2249           return (Expr*)nullptr;
2250         }
2251         State.Consumer->resetCorrectionStream();
2252       }
2253       return TE ? TE : ExprError();
2254     }
2255
2256     assert(!R.empty() &&
2257            "DiagnoseEmptyLookup returned false but added no results");
2258
2259     // If we found an Objective-C instance variable, let
2260     // LookupInObjCMethod build the appropriate expression to
2261     // reference the ivar.
2262     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2263       R.clear();
2264       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2265       // In a hopelessly buggy code, Objective-C instance variable
2266       // lookup fails and no expression will be built to reference it.
2267       if (!E.isInvalid() && !E.get())
2268         return ExprError();
2269       return E;
2270     }
2271   }
2272
2273   // This is guaranteed from this point on.
2274   assert(!R.empty() || ADL);
2275
2276   // Check whether this might be a C++ implicit instance member access.
2277   // C++ [class.mfct.non-static]p3:
2278   //   When an id-expression that is not part of a class member access
2279   //   syntax and not used to form a pointer to member is used in the
2280   //   body of a non-static member function of class X, if name lookup
2281   //   resolves the name in the id-expression to a non-static non-type
2282   //   member of some class C, the id-expression is transformed into a
2283   //   class member access expression using (*this) as the
2284   //   postfix-expression to the left of the . operator.
2285   //
2286   // But we don't actually need to do this for '&' operands if R
2287   // resolved to a function or overloaded function set, because the
2288   // expression is ill-formed if it actually works out to be a
2289   // non-static member function:
2290   //
2291   // C++ [expr.ref]p4:
2292   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2293   //   [t]he expression can be used only as the left-hand operand of a
2294   //   member function call.
2295   //
2296   // There are other safeguards against such uses, but it's important
2297   // to get this right here so that we don't end up making a
2298   // spuriously dependent expression if we're inside a dependent
2299   // instance method.
2300   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2301     bool MightBeImplicitMember;
2302     if (!IsAddressOfOperand)
2303       MightBeImplicitMember = true;
2304     else if (!SS.isEmpty())
2305       MightBeImplicitMember = false;
2306     else if (R.isOverloadedResult())
2307       MightBeImplicitMember = false;
2308     else if (R.isUnresolvableResult())
2309       MightBeImplicitMember = true;
2310     else
2311       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2312                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2313                               isa<MSPropertyDecl>(R.getFoundDecl());
2314
2315     if (MightBeImplicitMember)
2316       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2317                                              R, TemplateArgs, S);
2318   }
2319
2320   if (TemplateArgs || TemplateKWLoc.isValid()) {
2321
2322     // In C++1y, if this is a variable template id, then check it
2323     // in BuildTemplateIdExpr().
2324     // The single lookup result must be a variable template declaration.
2325     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2326         Id.TemplateId->Kind == TNK_Var_template) {
2327       assert(R.getAsSingle<VarTemplateDecl>() &&
2328              "There should only be one declaration found.");
2329     }
2330
2331     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2332   }
2333
2334   return BuildDeclarationNameExpr(SS, R, ADL);
2335 }
2336
2337 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2338 /// declaration name, generally during template instantiation.
2339 /// There's a large number of things which don't need to be done along
2340 /// this path.
2341 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2342     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2343     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2344   DeclContext *DC = computeDeclContext(SS, false);
2345   if (!DC)
2346     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2347                                      NameInfo, /*TemplateArgs=*/nullptr);
2348
2349   if (RequireCompleteDeclContext(SS, DC))
2350     return ExprError();
2351
2352   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2353   LookupQualifiedName(R, DC);
2354
2355   if (R.isAmbiguous())
2356     return ExprError();
2357
2358   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2359     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2360                                      NameInfo, /*TemplateArgs=*/nullptr);
2361
2362   if (R.empty()) {
2363     Diag(NameInfo.getLoc(), diag::err_no_member)
2364       << NameInfo.getName() << DC << SS.getRange();
2365     return ExprError();
2366   }
2367
2368   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2369     // Diagnose a missing typename if this resolved unambiguously to a type in
2370     // a dependent context.  If we can recover with a type, downgrade this to
2371     // a warning in Microsoft compatibility mode.
2372     unsigned DiagID = diag::err_typename_missing;
2373     if (RecoveryTSI && getLangOpts().MSVCCompat)
2374       DiagID = diag::ext_typename_missing;
2375     SourceLocation Loc = SS.getBeginLoc();
2376     auto D = Diag(Loc, DiagID);
2377     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2378       << SourceRange(Loc, NameInfo.getEndLoc());
2379
2380     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2381     // context.
2382     if (!RecoveryTSI)
2383       return ExprError();
2384
2385     // Only issue the fixit if we're prepared to recover.
2386     D << FixItHint::CreateInsertion(Loc, "typename ");
2387
2388     // Recover by pretending this was an elaborated type.
2389     QualType Ty = Context.getTypeDeclType(TD);
2390     TypeLocBuilder TLB;
2391     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2392
2393     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2394     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2395     QTL.setElaboratedKeywordLoc(SourceLocation());
2396     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2397
2398     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2399
2400     return ExprEmpty();
2401   }
2402
2403   // Defend against this resolving to an implicit member access. We usually
2404   // won't get here if this might be a legitimate a class member (we end up in
2405   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2406   // a pointer-to-member or in an unevaluated context in C++11.
2407   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2408     return BuildPossibleImplicitMemberExpr(SS,
2409                                            /*TemplateKWLoc=*/SourceLocation(),
2410                                            R, /*TemplateArgs=*/nullptr, S);
2411
2412   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2413 }
2414
2415 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2416 /// detected that we're currently inside an ObjC method.  Perform some
2417 /// additional lookup.
2418 ///
2419 /// Ideally, most of this would be done by lookup, but there's
2420 /// actually quite a lot of extra work involved.
2421 ///
2422 /// Returns a null sentinel to indicate trivial success.
2423 ExprResult
2424 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2425                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2426   SourceLocation Loc = Lookup.getNameLoc();
2427   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2428   
2429   // Check for error condition which is already reported.
2430   if (!CurMethod)
2431     return ExprError();
2432
2433   // There are two cases to handle here.  1) scoped lookup could have failed,
2434   // in which case we should look for an ivar.  2) scoped lookup could have
2435   // found a decl, but that decl is outside the current instance method (i.e.
2436   // a global variable).  In these two cases, we do a lookup for an ivar with
2437   // this name, if the lookup sucedes, we replace it our current decl.
2438
2439   // If we're in a class method, we don't normally want to look for
2440   // ivars.  But if we don't find anything else, and there's an
2441   // ivar, that's an error.
2442   bool IsClassMethod = CurMethod->isClassMethod();
2443
2444   bool LookForIvars;
2445   if (Lookup.empty())
2446     LookForIvars = true;
2447   else if (IsClassMethod)
2448     LookForIvars = false;
2449   else
2450     LookForIvars = (Lookup.isSingleResult() &&
2451                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2452   ObjCInterfaceDecl *IFace = nullptr;
2453   if (LookForIvars) {
2454     IFace = CurMethod->getClassInterface();
2455     ObjCInterfaceDecl *ClassDeclared;
2456     ObjCIvarDecl *IV = nullptr;
2457     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2458       // Diagnose using an ivar in a class method.
2459       if (IsClassMethod)
2460         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2461                          << IV->getDeclName());
2462
2463       // If we're referencing an invalid decl, just return this as a silent
2464       // error node.  The error diagnostic was already emitted on the decl.
2465       if (IV->isInvalidDecl())
2466         return ExprError();
2467
2468       // Check if referencing a field with __attribute__((deprecated)).
2469       if (DiagnoseUseOfDecl(IV, Loc))
2470         return ExprError();
2471
2472       // Diagnose the use of an ivar outside of the declaring class.
2473       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2474           !declaresSameEntity(ClassDeclared, IFace) &&
2475           !getLangOpts().DebuggerSupport)
2476         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2477
2478       // FIXME: This should use a new expr for a direct reference, don't
2479       // turn this into Self->ivar, just return a BareIVarExpr or something.
2480       IdentifierInfo &II = Context.Idents.get("self");
2481       UnqualifiedId SelfName;
2482       SelfName.setIdentifier(&II, SourceLocation());
2483       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2484       CXXScopeSpec SelfScopeSpec;
2485       SourceLocation TemplateKWLoc;
2486       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2487                                               SelfName, false, false);
2488       if (SelfExpr.isInvalid())
2489         return ExprError();
2490
2491       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2492       if (SelfExpr.isInvalid())
2493         return ExprError();
2494
2495       MarkAnyDeclReferenced(Loc, IV, true);
2496
2497       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2498       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2499           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2500         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2501
2502       ObjCIvarRefExpr *Result = new (Context)
2503           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2504                           IV->getLocation(), SelfExpr.get(), true, true);
2505
2506       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2507         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2508           recordUseOfEvaluatedWeak(Result);
2509       }
2510       if (getLangOpts().ObjCAutoRefCount) {
2511         if (CurContext->isClosure())
2512           Diag(Loc, diag::warn_implicitly_retains_self)
2513             << FixItHint::CreateInsertion(Loc, "self->");
2514       }
2515       
2516       return Result;
2517     }
2518   } else if (CurMethod->isInstanceMethod()) {
2519     // We should warn if a local variable hides an ivar.
2520     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2521       ObjCInterfaceDecl *ClassDeclared;
2522       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2523         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2524             declaresSameEntity(IFace, ClassDeclared))
2525           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2526       }
2527     }
2528   } else if (Lookup.isSingleResult() &&
2529              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2530     // If accessing a stand-alone ivar in a class method, this is an error.
2531     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2532       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2533                        << IV->getDeclName());
2534   }
2535
2536   if (Lookup.empty() && II && AllowBuiltinCreation) {
2537     // FIXME. Consolidate this with similar code in LookupName.
2538     if (unsigned BuiltinID = II->getBuiltinID()) {
2539       if (!(getLangOpts().CPlusPlus &&
2540             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2541         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2542                                            S, Lookup.isForRedeclaration(),
2543                                            Lookup.getNameLoc());
2544         if (D) Lookup.addDecl(D);
2545       }
2546     }
2547   }
2548   // Sentinel value saying that we didn't do anything special.
2549   return ExprResult((Expr *)nullptr);
2550 }
2551
2552 /// \brief Cast a base object to a member's actual type.
2553 ///
2554 /// Logically this happens in three phases:
2555 ///
2556 /// * First we cast from the base type to the naming class.
2557 ///   The naming class is the class into which we were looking
2558 ///   when we found the member;  it's the qualifier type if a
2559 ///   qualifier was provided, and otherwise it's the base type.
2560 ///
2561 /// * Next we cast from the naming class to the declaring class.
2562 ///   If the member we found was brought into a class's scope by
2563 ///   a using declaration, this is that class;  otherwise it's
2564 ///   the class declaring the member.
2565 ///
2566 /// * Finally we cast from the declaring class to the "true"
2567 ///   declaring class of the member.  This conversion does not
2568 ///   obey access control.
2569 ExprResult
2570 Sema::PerformObjectMemberConversion(Expr *From,
2571                                     NestedNameSpecifier *Qualifier,
2572                                     NamedDecl *FoundDecl,
2573                                     NamedDecl *Member) {
2574   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2575   if (!RD)
2576     return From;
2577
2578   QualType DestRecordType;
2579   QualType DestType;
2580   QualType FromRecordType;
2581   QualType FromType = From->getType();
2582   bool PointerConversions = false;
2583   if (isa<FieldDecl>(Member)) {
2584     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2585
2586     if (FromType->getAs<PointerType>()) {
2587       DestType = Context.getPointerType(DestRecordType);
2588       FromRecordType = FromType->getPointeeType();
2589       PointerConversions = true;
2590     } else {
2591       DestType = DestRecordType;
2592       FromRecordType = FromType;
2593     }
2594   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2595     if (Method->isStatic())
2596       return From;
2597
2598     DestType = Method->getThisType(Context);
2599     DestRecordType = DestType->getPointeeType();
2600
2601     if (FromType->getAs<PointerType>()) {
2602       FromRecordType = FromType->getPointeeType();
2603       PointerConversions = true;
2604     } else {
2605       FromRecordType = FromType;
2606       DestType = DestRecordType;
2607     }
2608   } else {
2609     // No conversion necessary.
2610     return From;
2611   }
2612
2613   if (DestType->isDependentType() || FromType->isDependentType())
2614     return From;
2615
2616   // If the unqualified types are the same, no conversion is necessary.
2617   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2618     return From;
2619
2620   SourceRange FromRange = From->getSourceRange();
2621   SourceLocation FromLoc = FromRange.getBegin();
2622
2623   ExprValueKind VK = From->getValueKind();
2624
2625   // C++ [class.member.lookup]p8:
2626   //   [...] Ambiguities can often be resolved by qualifying a name with its
2627   //   class name.
2628   //
2629   // If the member was a qualified name and the qualified referred to a
2630   // specific base subobject type, we'll cast to that intermediate type
2631   // first and then to the object in which the member is declared. That allows
2632   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2633   //
2634   //   class Base { public: int x; };
2635   //   class Derived1 : public Base { };
2636   //   class Derived2 : public Base { };
2637   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2638   //
2639   //   void VeryDerived::f() {
2640   //     x = 17; // error: ambiguous base subobjects
2641   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2642   //   }
2643   if (Qualifier && Qualifier->getAsType()) {
2644     QualType QType = QualType(Qualifier->getAsType(), 0);
2645     assert(QType->isRecordType() && "lookup done with non-record type");
2646
2647     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2648
2649     // In C++98, the qualifier type doesn't actually have to be a base
2650     // type of the object type, in which case we just ignore it.
2651     // Otherwise build the appropriate casts.
2652     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2653       CXXCastPath BasePath;
2654       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2655                                        FromLoc, FromRange, &BasePath))
2656         return ExprError();
2657
2658       if (PointerConversions)
2659         QType = Context.getPointerType(QType);
2660       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2661                                VK, &BasePath).get();
2662
2663       FromType = QType;
2664       FromRecordType = QRecordType;
2665
2666       // If the qualifier type was the same as the destination type,
2667       // we're done.
2668       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2669         return From;
2670     }
2671   }
2672
2673   bool IgnoreAccess = false;
2674
2675   // If we actually found the member through a using declaration, cast
2676   // down to the using declaration's type.
2677   //
2678   // Pointer equality is fine here because only one declaration of a
2679   // class ever has member declarations.
2680   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2681     assert(isa<UsingShadowDecl>(FoundDecl));
2682     QualType URecordType = Context.getTypeDeclType(
2683                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2684
2685     // We only need to do this if the naming-class to declaring-class
2686     // conversion is non-trivial.
2687     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2688       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2689       CXXCastPath BasePath;
2690       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2691                                        FromLoc, FromRange, &BasePath))
2692         return ExprError();
2693
2694       QualType UType = URecordType;
2695       if (PointerConversions)
2696         UType = Context.getPointerType(UType);
2697       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2698                                VK, &BasePath).get();
2699       FromType = UType;
2700       FromRecordType = URecordType;
2701     }
2702
2703     // We don't do access control for the conversion from the
2704     // declaring class to the true declaring class.
2705     IgnoreAccess = true;
2706   }
2707
2708   CXXCastPath BasePath;
2709   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2710                                    FromLoc, FromRange, &BasePath,
2711                                    IgnoreAccess))
2712     return ExprError();
2713
2714   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2715                            VK, &BasePath);
2716 }
2717
2718 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2719                                       const LookupResult &R,
2720                                       bool HasTrailingLParen) {
2721   // Only when used directly as the postfix-expression of a call.
2722   if (!HasTrailingLParen)
2723     return false;
2724
2725   // Never if a scope specifier was provided.
2726   if (SS.isSet())
2727     return false;
2728
2729   // Only in C++ or ObjC++.
2730   if (!getLangOpts().CPlusPlus)
2731     return false;
2732
2733   // Turn off ADL when we find certain kinds of declarations during
2734   // normal lookup:
2735   for (NamedDecl *D : R) {
2736     // C++0x [basic.lookup.argdep]p3:
2737     //     -- a declaration of a class member
2738     // Since using decls preserve this property, we check this on the
2739     // original decl.
2740     if (D->isCXXClassMember())
2741       return false;
2742
2743     // C++0x [basic.lookup.argdep]p3:
2744     //     -- a block-scope function declaration that is not a
2745     //        using-declaration
2746     // NOTE: we also trigger this for function templates (in fact, we
2747     // don't check the decl type at all, since all other decl types
2748     // turn off ADL anyway).
2749     if (isa<UsingShadowDecl>(D))
2750       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2751     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2752       return false;
2753
2754     // C++0x [basic.lookup.argdep]p3:
2755     //     -- a declaration that is neither a function or a function
2756     //        template
2757     // And also for builtin functions.
2758     if (isa<FunctionDecl>(D)) {
2759       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2760
2761       // But also builtin functions.
2762       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2763         return false;
2764     } else if (!isa<FunctionTemplateDecl>(D))
2765       return false;
2766   }
2767
2768   return true;
2769 }
2770
2771
2772 /// Diagnoses obvious problems with the use of the given declaration
2773 /// as an expression.  This is only actually called for lookups that
2774 /// were not overloaded, and it doesn't promise that the declaration
2775 /// will in fact be used.
2776 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2777   if (D->isInvalidDecl())
2778     return true;
2779
2780   if (isa<TypedefNameDecl>(D)) {
2781     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2782     return true;
2783   }
2784
2785   if (isa<ObjCInterfaceDecl>(D)) {
2786     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2787     return true;
2788   }
2789
2790   if (isa<NamespaceDecl>(D)) {
2791     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2792     return true;
2793   }
2794
2795   return false;
2796 }
2797
2798 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2799                                           LookupResult &R, bool NeedsADL,
2800                                           bool AcceptInvalidDecl) {
2801   // If this is a single, fully-resolved result and we don't need ADL,
2802   // just build an ordinary singleton decl ref.
2803   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2804     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2805                                     R.getRepresentativeDecl(), nullptr,
2806                                     AcceptInvalidDecl);
2807
2808   // We only need to check the declaration if there's exactly one
2809   // result, because in the overloaded case the results can only be
2810   // functions and function templates.
2811   if (R.isSingleResult() &&
2812       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2813     return ExprError();
2814
2815   // Otherwise, just build an unresolved lookup expression.  Suppress
2816   // any lookup-related diagnostics; we'll hash these out later, when
2817   // we've picked a target.
2818   R.suppressDiagnostics();
2819
2820   UnresolvedLookupExpr *ULE
2821     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2822                                    SS.getWithLocInContext(Context),
2823                                    R.getLookupNameInfo(),
2824                                    NeedsADL, R.isOverloadedResult(),
2825                                    R.begin(), R.end());
2826
2827   return ULE;
2828 }
2829
2830 static void
2831 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2832                                    ValueDecl *var, DeclContext *DC);
2833
2834 /// \brief Complete semantic analysis for a reference to the given declaration.
2835 ExprResult Sema::BuildDeclarationNameExpr(
2836     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2837     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2838     bool AcceptInvalidDecl) {
2839   assert(D && "Cannot refer to a NULL declaration");
2840   assert(!isa<FunctionTemplateDecl>(D) &&
2841          "Cannot refer unambiguously to a function template");
2842
2843   SourceLocation Loc = NameInfo.getLoc();
2844   if (CheckDeclInExpr(*this, Loc, D))
2845     return ExprError();
2846
2847   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2848     // Specifically diagnose references to class templates that are missing
2849     // a template argument list.
2850     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2851                                            << Template << SS.getRange();
2852     Diag(Template->getLocation(), diag::note_template_decl_here);
2853     return ExprError();
2854   }
2855
2856   // Make sure that we're referring to a value.
2857   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2858   if (!VD) {
2859     Diag(Loc, diag::err_ref_non_value)
2860       << D << SS.getRange();
2861     Diag(D->getLocation(), diag::note_declared_at);
2862     return ExprError();
2863   }
2864
2865   // Check whether this declaration can be used. Note that we suppress
2866   // this check when we're going to perform argument-dependent lookup
2867   // on this function name, because this might not be the function
2868   // that overload resolution actually selects.
2869   if (DiagnoseUseOfDecl(VD, Loc))
2870     return ExprError();
2871
2872   // Only create DeclRefExpr's for valid Decl's.
2873   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2874     return ExprError();
2875
2876   // Handle members of anonymous structs and unions.  If we got here,
2877   // and the reference is to a class member indirect field, then this
2878   // must be the subject of a pointer-to-member expression.
2879   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2880     if (!indirectField->isCXXClassMember())
2881       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2882                                                       indirectField);
2883
2884   {
2885     QualType type = VD->getType();
2886     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2887       // C++ [except.spec]p17:
2888       //   An exception-specification is considered to be needed when:
2889       //   - in an expression, the function is the unique lookup result or
2890       //     the selected member of a set of overloaded functions.
2891       ResolveExceptionSpec(Loc, FPT);
2892       type = VD->getType();
2893     }
2894     ExprValueKind valueKind = VK_RValue;
2895
2896     switch (D->getKind()) {
2897     // Ignore all the non-ValueDecl kinds.
2898 #define ABSTRACT_DECL(kind)
2899 #define VALUE(type, base)
2900 #define DECL(type, base) \
2901     case Decl::type:
2902 #include "clang/AST/DeclNodes.inc"
2903       llvm_unreachable("invalid value decl kind");
2904
2905     // These shouldn't make it here.
2906     case Decl::ObjCAtDefsField:
2907     case Decl::ObjCIvar:
2908       llvm_unreachable("forming non-member reference to ivar?");
2909
2910     // Enum constants are always r-values and never references.
2911     // Unresolved using declarations are dependent.
2912     case Decl::EnumConstant:
2913     case Decl::UnresolvedUsingValue:
2914     case Decl::OMPDeclareReduction:
2915       valueKind = VK_RValue;
2916       break;
2917
2918     // Fields and indirect fields that got here must be for
2919     // pointer-to-member expressions; we just call them l-values for
2920     // internal consistency, because this subexpression doesn't really
2921     // exist in the high-level semantics.
2922     case Decl::Field:
2923     case Decl::IndirectField:
2924       assert(getLangOpts().CPlusPlus &&
2925              "building reference to field in C?");
2926
2927       // These can't have reference type in well-formed programs, but
2928       // for internal consistency we do this anyway.
2929       type = type.getNonReferenceType();
2930       valueKind = VK_LValue;
2931       break;
2932
2933     // Non-type template parameters are either l-values or r-values
2934     // depending on the type.
2935     case Decl::NonTypeTemplateParm: {
2936       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2937         type = reftype->getPointeeType();
2938         valueKind = VK_LValue; // even if the parameter is an r-value reference
2939         break;
2940       }
2941
2942       // For non-references, we need to strip qualifiers just in case
2943       // the template parameter was declared as 'const int' or whatever.
2944       valueKind = VK_RValue;
2945       type = type.getUnqualifiedType();
2946       break;
2947     }
2948
2949     case Decl::Var:
2950     case Decl::VarTemplateSpecialization:
2951     case Decl::VarTemplatePartialSpecialization:
2952     case Decl::Decomposition:
2953     case Decl::OMPCapturedExpr:
2954       // In C, "extern void blah;" is valid and is an r-value.
2955       if (!getLangOpts().CPlusPlus &&
2956           !type.hasQualifiers() &&
2957           type->isVoidType()) {
2958         valueKind = VK_RValue;
2959         break;
2960       }
2961       // fallthrough
2962
2963     case Decl::ImplicitParam:
2964     case Decl::ParmVar: {
2965       // These are always l-values.
2966       valueKind = VK_LValue;
2967       type = type.getNonReferenceType();
2968
2969       // FIXME: Does the addition of const really only apply in
2970       // potentially-evaluated contexts? Since the variable isn't actually
2971       // captured in an unevaluated context, it seems that the answer is no.
2972       if (!isUnevaluatedContext()) {
2973         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2974         if (!CapturedType.isNull())
2975           type = CapturedType;
2976       }
2977       
2978       break;
2979     }
2980
2981     case Decl::Binding: {
2982       // These are always lvalues.
2983       valueKind = VK_LValue;
2984       type = type.getNonReferenceType();
2985       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2986       // decides how that's supposed to work.
2987       auto *BD = cast<BindingDecl>(VD);
2988       if (BD->getDeclContext()->isFunctionOrMethod() &&
2989           BD->getDeclContext() != CurContext)
2990         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2991       break;
2992     }
2993         
2994     case Decl::Function: {
2995       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2996         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2997           type = Context.BuiltinFnTy;
2998           valueKind = VK_RValue;
2999           break;
3000         }
3001       }
3002
3003       const FunctionType *fty = type->castAs<FunctionType>();
3004
3005       // If we're referring to a function with an __unknown_anytype
3006       // result type, make the entire expression __unknown_anytype.
3007       if (fty->getReturnType() == Context.UnknownAnyTy) {
3008         type = Context.UnknownAnyTy;
3009         valueKind = VK_RValue;
3010         break;
3011       }
3012
3013       // Functions are l-values in C++.
3014       if (getLangOpts().CPlusPlus) {
3015         valueKind = VK_LValue;
3016         break;
3017       }
3018       
3019       // C99 DR 316 says that, if a function type comes from a
3020       // function definition (without a prototype), that type is only
3021       // used for checking compatibility. Therefore, when referencing
3022       // the function, we pretend that we don't have the full function
3023       // type.
3024       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3025           isa<FunctionProtoType>(fty))
3026         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3027                                               fty->getExtInfo());
3028
3029       // Functions are r-values in C.
3030       valueKind = VK_RValue;
3031       break;
3032     }
3033
3034     case Decl::CXXDeductionGuide:
3035       llvm_unreachable("building reference to deduction guide");
3036
3037     case Decl::MSProperty:
3038       valueKind = VK_LValue;
3039       break;
3040
3041     case Decl::CXXMethod:
3042       // If we're referring to a method with an __unknown_anytype
3043       // result type, make the entire expression __unknown_anytype.
3044       // This should only be possible with a type written directly.
3045       if (const FunctionProtoType *proto
3046             = dyn_cast<FunctionProtoType>(VD->getType()))
3047         if (proto->getReturnType() == Context.UnknownAnyTy) {
3048           type = Context.UnknownAnyTy;
3049           valueKind = VK_RValue;
3050           break;
3051         }
3052
3053       // C++ methods are l-values if static, r-values if non-static.
3054       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3055         valueKind = VK_LValue;
3056         break;
3057       }
3058       // fallthrough
3059
3060     case Decl::CXXConversion:
3061     case Decl::CXXDestructor:
3062     case Decl::CXXConstructor:
3063       valueKind = VK_RValue;
3064       break;
3065     }
3066
3067     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3068                             TemplateArgs);
3069   }
3070 }
3071
3072 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3073                                     SmallString<32> &Target) {
3074   Target.resize(CharByteWidth * (Source.size() + 1));
3075   char *ResultPtr = &Target[0];
3076   const llvm::UTF8 *ErrorPtr;
3077   bool success =
3078       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3079   (void)success;
3080   assert(success);
3081   Target.resize(ResultPtr - &Target[0]);
3082 }
3083
3084 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3085                                      PredefinedExpr::IdentType IT) {
3086   // Pick the current block, lambda, captured statement or function.
3087   Decl *currentDecl = nullptr;
3088   if (const BlockScopeInfo *BSI = getCurBlock())
3089     currentDecl = BSI->TheDecl;
3090   else if (const LambdaScopeInfo *LSI = getCurLambda())
3091     currentDecl = LSI->CallOperator;
3092   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3093     currentDecl = CSI->TheCapturedDecl;
3094   else
3095     currentDecl = getCurFunctionOrMethodDecl();
3096
3097   if (!currentDecl) {
3098     Diag(Loc, diag::ext_predef_outside_function);
3099     currentDecl = Context.getTranslationUnitDecl();
3100   }
3101
3102   QualType ResTy;
3103   StringLiteral *SL = nullptr;
3104   if (cast<DeclContext>(currentDecl)->isDependentContext())
3105     ResTy = Context.DependentTy;
3106   else {
3107     // Pre-defined identifiers are of type char[x], where x is the length of
3108     // the string.
3109     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3110     unsigned Length = Str.length();
3111
3112     llvm::APInt LengthI(32, Length + 1);
3113     if (IT == PredefinedExpr::LFunction) {
3114       ResTy = Context.WideCharTy.withConst();
3115       SmallString<32> RawChars;
3116       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3117                               Str, RawChars);
3118       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3119                                            /*IndexTypeQuals*/ 0);
3120       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3121                                  /*Pascal*/ false, ResTy, Loc);
3122     } else {
3123       ResTy = Context.CharTy.withConst();
3124       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3125                                            /*IndexTypeQuals*/ 0);
3126       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3127                                  /*Pascal*/ false, ResTy, Loc);
3128     }
3129   }
3130
3131   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3132 }
3133
3134 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3135   PredefinedExpr::IdentType IT;
3136
3137   switch (Kind) {
3138   default: llvm_unreachable("Unknown simple primary expr!");
3139   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3140   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3141   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3142   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3143   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3144   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3145   }
3146
3147   return BuildPredefinedExpr(Loc, IT);
3148 }
3149
3150 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3151   SmallString<16> CharBuffer;
3152   bool Invalid = false;
3153   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3154   if (Invalid)
3155     return ExprError();
3156
3157   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3158                             PP, Tok.getKind());
3159   if (Literal.hadError())
3160     return ExprError();
3161
3162   QualType Ty;
3163   if (Literal.isWide())
3164     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3165   else if (Literal.isUTF16())
3166     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3167   else if (Literal.isUTF32())
3168     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3169   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3170     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3171   else
3172     Ty = Context.CharTy;  // 'x' -> char in C++
3173
3174   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3175   if (Literal.isWide())
3176     Kind = CharacterLiteral::Wide;
3177   else if (Literal.isUTF16())
3178     Kind = CharacterLiteral::UTF16;
3179   else if (Literal.isUTF32())
3180     Kind = CharacterLiteral::UTF32;
3181   else if (Literal.isUTF8())
3182     Kind = CharacterLiteral::UTF8;
3183
3184   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3185                                              Tok.getLocation());
3186
3187   if (Literal.getUDSuffix().empty())
3188     return Lit;
3189
3190   // We're building a user-defined literal.
3191   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3192   SourceLocation UDSuffixLoc =
3193     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3194
3195   // Make sure we're allowed user-defined literals here.
3196   if (!UDLScope)
3197     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3198
3199   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3200   //   operator "" X (ch)
3201   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3202                                         Lit, Tok.getLocation());
3203 }
3204
3205 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3206   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3207   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3208                                 Context.IntTy, Loc);
3209 }
3210
3211 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3212                                   QualType Ty, SourceLocation Loc) {
3213   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3214
3215   using llvm::APFloat;
3216   APFloat Val(Format);
3217
3218   APFloat::opStatus result = Literal.GetFloatValue(Val);
3219
3220   // Overflow is always an error, but underflow is only an error if
3221   // we underflowed to zero (APFloat reports denormals as underflow).
3222   if ((result & APFloat::opOverflow) ||
3223       ((result & APFloat::opUnderflow) && Val.isZero())) {
3224     unsigned diagnostic;
3225     SmallString<20> buffer;
3226     if (result & APFloat::opOverflow) {
3227       diagnostic = diag::warn_float_overflow;
3228       APFloat::getLargest(Format).toString(buffer);
3229     } else {
3230       diagnostic = diag::warn_float_underflow;
3231       APFloat::getSmallest(Format).toString(buffer);
3232     }
3233
3234     S.Diag(Loc, diagnostic)
3235       << Ty
3236       << StringRef(buffer.data(), buffer.size());
3237   }
3238
3239   bool isExact = (result == APFloat::opOK);
3240   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3241 }
3242
3243 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3244   assert(E && "Invalid expression");
3245
3246   if (E->isValueDependent())
3247     return false;
3248
3249   QualType QT = E->getType();
3250   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3251     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3252     return true;
3253   }
3254
3255   llvm::APSInt ValueAPS;
3256   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3257
3258   if (R.isInvalid())
3259     return true;
3260
3261   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3262   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3263     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3264         << ValueAPS.toString(10) << ValueIsPositive;
3265     return true;
3266   }
3267
3268   return false;
3269 }
3270
3271 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3272   // Fast path for a single digit (which is quite common).  A single digit
3273   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3274   if (Tok.getLength() == 1) {
3275     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3276     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3277   }
3278
3279   SmallString<128> SpellingBuffer;
3280   // NumericLiteralParser wants to overread by one character.  Add padding to
3281   // the buffer in case the token is copied to the buffer.  If getSpelling()
3282   // returns a StringRef to the memory buffer, it should have a null char at
3283   // the EOF, so it is also safe.
3284   SpellingBuffer.resize(Tok.getLength() + 1);
3285
3286   // Get the spelling of the token, which eliminates trigraphs, etc.
3287   bool Invalid = false;
3288   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3289   if (Invalid)
3290     return ExprError();
3291
3292   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3293   if (Literal.hadError)
3294     return ExprError();
3295
3296   if (Literal.hasUDSuffix()) {
3297     // We're building a user-defined literal.
3298     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3299     SourceLocation UDSuffixLoc =
3300       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3301
3302     // Make sure we're allowed user-defined literals here.
3303     if (!UDLScope)
3304       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3305
3306     QualType CookedTy;
3307     if (Literal.isFloatingLiteral()) {
3308       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3309       // long double, the literal is treated as a call of the form
3310       //   operator "" X (f L)
3311       CookedTy = Context.LongDoubleTy;
3312     } else {
3313       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3314       // unsigned long long, the literal is treated as a call of the form
3315       //   operator "" X (n ULL)
3316       CookedTy = Context.UnsignedLongLongTy;
3317     }
3318
3319     DeclarationName OpName =
3320       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3321     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3322     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3323
3324     SourceLocation TokLoc = Tok.getLocation();
3325
3326     // Perform literal operator lookup to determine if we're building a raw
3327     // literal or a cooked one.
3328     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3329     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3330                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3331                                   /*AllowStringTemplate*/false)) {
3332     case LOLR_Error:
3333       return ExprError();
3334
3335     case LOLR_Cooked: {
3336       Expr *Lit;
3337       if (Literal.isFloatingLiteral()) {
3338         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3339       } else {
3340         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3341         if (Literal.GetIntegerValue(ResultVal))
3342           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3343               << /* Unsigned */ 1;
3344         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3345                                      Tok.getLocation());
3346       }
3347       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3348     }
3349
3350     case LOLR_Raw: {
3351       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3352       // literal is treated as a call of the form
3353       //   operator "" X ("n")
3354       unsigned Length = Literal.getUDSuffixOffset();
3355       QualType StrTy = Context.getConstantArrayType(
3356           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3357           ArrayType::Normal, 0);
3358       Expr *Lit = StringLiteral::Create(
3359           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3360           /*Pascal*/false, StrTy, &TokLoc, 1);
3361       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3362     }
3363
3364     case LOLR_Template: {
3365       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3366       // template), L is treated as a call fo the form
3367       //   operator "" X <'c1', 'c2', ... 'ck'>()
3368       // where n is the source character sequence c1 c2 ... ck.
3369       TemplateArgumentListInfo ExplicitArgs;
3370       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3371       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3372       llvm::APSInt Value(CharBits, CharIsUnsigned);
3373       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3374         Value = TokSpelling[I];
3375         TemplateArgument Arg(Context, Value, Context.CharTy);
3376         TemplateArgumentLocInfo ArgInfo;
3377         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3378       }
3379       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3380                                       &ExplicitArgs);
3381     }
3382     case LOLR_StringTemplate:
3383       llvm_unreachable("unexpected literal operator lookup result");
3384     }
3385   }
3386
3387   Expr *Res;
3388
3389   if (Literal.isFloatingLiteral()) {
3390     QualType Ty;
3391     if (Literal.isHalf){
3392       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3393         Ty = Context.HalfTy;
3394       else {
3395         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3396         return ExprError();
3397       }
3398     } else if (Literal.isFloat)
3399       Ty = Context.FloatTy;
3400     else if (Literal.isLong)
3401       Ty = Context.LongDoubleTy;
3402     else if (Literal.isFloat128)
3403       Ty = Context.Float128Ty;
3404     else
3405       Ty = Context.DoubleTy;
3406
3407     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3408
3409     if (Ty == Context.DoubleTy) {
3410       if (getLangOpts().SinglePrecisionConstants) {
3411         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3412         if (BTy->getKind() != BuiltinType::Float) {
3413           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3414         }
3415       } else if (getLangOpts().OpenCL &&
3416                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3417         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3418         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3419         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3420       }
3421     }
3422   } else if (!Literal.isIntegerLiteral()) {
3423     return ExprError();
3424   } else {
3425     QualType Ty;
3426
3427     // 'long long' is a C99 or C++11 feature.
3428     if (!getLangOpts().C99 && Literal.isLongLong) {
3429       if (getLangOpts().CPlusPlus)
3430         Diag(Tok.getLocation(),
3431              getLangOpts().CPlusPlus11 ?
3432              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3433       else
3434         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3435     }
3436
3437     // Get the value in the widest-possible width.
3438     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3439     llvm::APInt ResultVal(MaxWidth, 0);
3440
3441     if (Literal.GetIntegerValue(ResultVal)) {
3442       // If this value didn't fit into uintmax_t, error and force to ull.
3443       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3444           << /* Unsigned */ 1;
3445       Ty = Context.UnsignedLongLongTy;
3446       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3447              "long long is not intmax_t?");
3448     } else {
3449       // If this value fits into a ULL, try to figure out what else it fits into
3450       // according to the rules of C99 6.4.4.1p5.
3451
3452       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3453       // be an unsigned int.
3454       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3455
3456       // Check from smallest to largest, picking the smallest type we can.
3457       unsigned Width = 0;
3458
3459       // Microsoft specific integer suffixes are explicitly sized.
3460       if (Literal.MicrosoftInteger) {
3461         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3462           Width = 8;
3463           Ty = Context.CharTy;
3464         } else {
3465           Width = Literal.MicrosoftInteger;
3466           Ty = Context.getIntTypeForBitwidth(Width,
3467                                              /*Signed=*/!Literal.isUnsigned);
3468         }
3469       }
3470
3471       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3472         // Are int/unsigned possibilities?
3473         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3474
3475         // Does it fit in a unsigned int?
3476         if (ResultVal.isIntN(IntSize)) {
3477           // Does it fit in a signed int?
3478           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3479             Ty = Context.IntTy;
3480           else if (AllowUnsigned)
3481             Ty = Context.UnsignedIntTy;
3482           Width = IntSize;
3483         }
3484       }
3485
3486       // Are long/unsigned long possibilities?
3487       if (Ty.isNull() && !Literal.isLongLong) {
3488         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3489
3490         // Does it fit in a unsigned long?
3491         if (ResultVal.isIntN(LongSize)) {
3492           // Does it fit in a signed long?
3493           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3494             Ty = Context.LongTy;
3495           else if (AllowUnsigned)
3496             Ty = Context.UnsignedLongTy;
3497           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3498           // is compatible.
3499           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3500             const unsigned LongLongSize =
3501                 Context.getTargetInfo().getLongLongWidth();
3502             Diag(Tok.getLocation(),
3503                  getLangOpts().CPlusPlus
3504                      ? Literal.isLong
3505                            ? diag::warn_old_implicitly_unsigned_long_cxx
3506                            : /*C++98 UB*/ diag::
3507                                  ext_old_implicitly_unsigned_long_cxx
3508                      : diag::warn_old_implicitly_unsigned_long)
3509                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3510                                             : /*will be ill-formed*/ 1);
3511             Ty = Context.UnsignedLongTy;
3512           }
3513           Width = LongSize;
3514         }
3515       }
3516
3517       // Check long long if needed.
3518       if (Ty.isNull()) {
3519         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3520
3521         // Does it fit in a unsigned long long?
3522         if (ResultVal.isIntN(LongLongSize)) {
3523           // Does it fit in a signed long long?
3524           // To be compatible with MSVC, hex integer literals ending with the
3525           // LL or i64 suffix are always signed in Microsoft mode.
3526           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3527               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3528             Ty = Context.LongLongTy;
3529           else if (AllowUnsigned)
3530             Ty = Context.UnsignedLongLongTy;
3531           Width = LongLongSize;
3532         }
3533       }
3534
3535       // If we still couldn't decide a type, we probably have something that
3536       // does not fit in a signed long long, but has no U suffix.
3537       if (Ty.isNull()) {
3538         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3539         Ty = Context.UnsignedLongLongTy;
3540         Width = Context.getTargetInfo().getLongLongWidth();
3541       }
3542
3543       if (ResultVal.getBitWidth() != Width)
3544         ResultVal = ResultVal.trunc(Width);
3545     }
3546     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3547   }
3548
3549   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3550   if (Literal.isImaginary)
3551     Res = new (Context) ImaginaryLiteral(Res,
3552                                         Context.getComplexType(Res->getType()));
3553
3554   return Res;
3555 }
3556
3557 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3558   assert(E && "ActOnParenExpr() missing expr");
3559   return new (Context) ParenExpr(L, R, E);
3560 }
3561
3562 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3563                                          SourceLocation Loc,
3564                                          SourceRange ArgRange) {
3565   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3566   // scalar or vector data type argument..."
3567   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3568   // type (C99 6.2.5p18) or void.
3569   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3570     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3571       << T << ArgRange;
3572     return true;
3573   }
3574
3575   assert((T->isVoidType() || !T->isIncompleteType()) &&
3576          "Scalar types should always be complete");
3577   return false;
3578 }
3579
3580 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3581                                            SourceLocation Loc,
3582                                            SourceRange ArgRange,
3583                                            UnaryExprOrTypeTrait TraitKind) {
3584   // Invalid types must be hard errors for SFINAE in C++.
3585   if (S.LangOpts.CPlusPlus)
3586     return true;
3587
3588   // C99 6.5.3.4p1:
3589   if (T->isFunctionType() &&
3590       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3591     // sizeof(function)/alignof(function) is allowed as an extension.
3592     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3593       << TraitKind << ArgRange;
3594     return false;
3595   }
3596
3597   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3598   // this is an error (OpenCL v1.1 s6.3.k)
3599   if (T->isVoidType()) {
3600     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3601                                         : diag::ext_sizeof_alignof_void_type;
3602     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3603     return false;
3604   }
3605
3606   return true;
3607 }
3608
3609 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3610                                              SourceLocation Loc,
3611                                              SourceRange ArgRange,
3612                                              UnaryExprOrTypeTrait TraitKind) {
3613   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3614   // runtime doesn't allow it.
3615   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3616     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3617       << T << (TraitKind == UETT_SizeOf)
3618       << ArgRange;
3619     return true;
3620   }
3621
3622   return false;
3623 }
3624
3625 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3626 /// pointer type is equal to T) and emit a warning if it is.
3627 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3628                                      Expr *E) {
3629   // Don't warn if the operation changed the type.
3630   if (T != E->getType())
3631     return;
3632
3633   // Now look for array decays.
3634   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3635   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3636     return;
3637
3638   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3639                                              << ICE->getType()
3640                                              << ICE->getSubExpr()->getType();
3641 }
3642
3643 /// \brief Check the constraints on expression operands to unary type expression
3644 /// and type traits.
3645 ///
3646 /// Completes any types necessary and validates the constraints on the operand
3647 /// expression. The logic mostly mirrors the type-based overload, but may modify
3648 /// the expression as it completes the type for that expression through template
3649 /// instantiation, etc.
3650 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3651                                             UnaryExprOrTypeTrait ExprKind) {
3652   QualType ExprTy = E->getType();
3653   assert(!ExprTy->isReferenceType());
3654
3655   if (ExprKind == UETT_VecStep)
3656     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3657                                         E->getSourceRange());
3658
3659   // Whitelist some types as extensions
3660   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3661                                       E->getSourceRange(), ExprKind))
3662     return false;
3663
3664   // 'alignof' applied to an expression only requires the base element type of
3665   // the expression to be complete. 'sizeof' requires the expression's type to
3666   // be complete (and will attempt to complete it if it's an array of unknown
3667   // bound).
3668   if (ExprKind == UETT_AlignOf) {
3669     if (RequireCompleteType(E->getExprLoc(),
3670                             Context.getBaseElementType(E->getType()),
3671                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3672                             E->getSourceRange()))
3673       return true;
3674   } else {
3675     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3676                                 ExprKind, E->getSourceRange()))
3677       return true;
3678   }
3679
3680   // Completing the expression's type may have changed it.
3681   ExprTy = E->getType();
3682   assert(!ExprTy->isReferenceType());
3683
3684   if (ExprTy->isFunctionType()) {
3685     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3686       << ExprKind << E->getSourceRange();
3687     return true;
3688   }
3689
3690   // The operand for sizeof and alignof is in an unevaluated expression context,
3691   // so side effects could result in unintended consequences.
3692   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3693       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3694     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3695
3696   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3697                                        E->getSourceRange(), ExprKind))
3698     return true;
3699
3700   if (ExprKind == UETT_SizeOf) {
3701     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3702       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3703         QualType OType = PVD->getOriginalType();
3704         QualType Type = PVD->getType();
3705         if (Type->isPointerType() && OType->isArrayType()) {
3706           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3707             << Type << OType;
3708           Diag(PVD->getLocation(), diag::note_declared_at);
3709         }
3710       }
3711     }
3712
3713     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3714     // decays into a pointer and returns an unintended result. This is most
3715     // likely a typo for "sizeof(array) op x".
3716     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3717       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3718                                BO->getLHS());
3719       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3720                                BO->getRHS());
3721     }
3722   }
3723
3724   return false;
3725 }
3726
3727 /// \brief Check the constraints on operands to unary expression and type
3728 /// traits.
3729 ///
3730 /// This will complete any types necessary, and validate the various constraints
3731 /// on those operands.
3732 ///
3733 /// The UsualUnaryConversions() function is *not* called by this routine.
3734 /// C99 6.3.2.1p[2-4] all state:
3735 ///   Except when it is the operand of the sizeof operator ...
3736 ///
3737 /// C++ [expr.sizeof]p4
3738 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3739 ///   standard conversions are not applied to the operand of sizeof.
3740 ///
3741 /// This policy is followed for all of the unary trait expressions.
3742 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3743                                             SourceLocation OpLoc,
3744                                             SourceRange ExprRange,
3745                                             UnaryExprOrTypeTrait ExprKind) {
3746   if (ExprType->isDependentType())
3747     return false;
3748
3749   // C++ [expr.sizeof]p2:
3750   //     When applied to a reference or a reference type, the result
3751   //     is the size of the referenced type.
3752   // C++11 [expr.alignof]p3:
3753   //     When alignof is applied to a reference type, the result
3754   //     shall be the alignment of the referenced type.
3755   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3756     ExprType = Ref->getPointeeType();
3757
3758   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3759   //   When alignof or _Alignof is applied to an array type, the result
3760   //   is the alignment of the element type.
3761   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3762     ExprType = Context.getBaseElementType(ExprType);
3763
3764   if (ExprKind == UETT_VecStep)
3765     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3766
3767   // Whitelist some types as extensions
3768   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3769                                       ExprKind))
3770     return false;
3771
3772   if (RequireCompleteType(OpLoc, ExprType,
3773                           diag::err_sizeof_alignof_incomplete_type,
3774                           ExprKind, ExprRange))
3775     return true;
3776
3777   if (ExprType->isFunctionType()) {
3778     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3779       << ExprKind << ExprRange;
3780     return true;
3781   }
3782
3783   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3784                                        ExprKind))
3785     return true;
3786
3787   return false;
3788 }
3789
3790 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3791   E = E->IgnoreParens();
3792
3793   // Cannot know anything else if the expression is dependent.
3794   if (E->isTypeDependent())
3795     return false;
3796
3797   if (E->getObjectKind() == OK_BitField) {
3798     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3799        << 1 << E->getSourceRange();
3800     return true;
3801   }
3802
3803   ValueDecl *D = nullptr;
3804   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3805     D = DRE->getDecl();
3806   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3807     D = ME->getMemberDecl();
3808   }
3809
3810   // If it's a field, require the containing struct to have a
3811   // complete definition so that we can compute the layout.
3812   //
3813   // This can happen in C++11 onwards, either by naming the member
3814   // in a way that is not transformed into a member access expression
3815   // (in an unevaluated operand, for instance), or by naming the member
3816   // in a trailing-return-type.
3817   //
3818   // For the record, since __alignof__ on expressions is a GCC
3819   // extension, GCC seems to permit this but always gives the
3820   // nonsensical answer 0.
3821   //
3822   // We don't really need the layout here --- we could instead just
3823   // directly check for all the appropriate alignment-lowing
3824   // attributes --- but that would require duplicating a lot of
3825   // logic that just isn't worth duplicating for such a marginal
3826   // use-case.
3827   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3828     // Fast path this check, since we at least know the record has a
3829     // definition if we can find a member of it.
3830     if (!FD->getParent()->isCompleteDefinition()) {
3831       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3832         << E->getSourceRange();
3833       return true;
3834     }
3835
3836     // Otherwise, if it's a field, and the field doesn't have
3837     // reference type, then it must have a complete type (or be a
3838     // flexible array member, which we explicitly want to
3839     // white-list anyway), which makes the following checks trivial.
3840     if (!FD->getType()->isReferenceType())
3841       return false;
3842   }
3843
3844   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3845 }
3846
3847 bool Sema::CheckVecStepExpr(Expr *E) {
3848   E = E->IgnoreParens();
3849
3850   // Cannot know anything else if the expression is dependent.
3851   if (E->isTypeDependent())
3852     return false;
3853
3854   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3855 }
3856
3857 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3858                                         CapturingScopeInfo *CSI) {
3859   assert(T->isVariablyModifiedType());
3860   assert(CSI != nullptr);
3861
3862   // We're going to walk down into the type and look for VLA expressions.
3863   do {
3864     const Type *Ty = T.getTypePtr();
3865     switch (Ty->getTypeClass()) {
3866 #define TYPE(Class, Base)
3867 #define ABSTRACT_TYPE(Class, Base)
3868 #define NON_CANONICAL_TYPE(Class, Base)
3869 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3870 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3871 #include "clang/AST/TypeNodes.def"
3872       T = QualType();
3873       break;
3874     // These types are never variably-modified.
3875     case Type::Builtin:
3876     case Type::Complex:
3877     case Type::Vector:
3878     case Type::ExtVector:
3879     case Type::Record:
3880     case Type::Enum:
3881     case Type::Elaborated:
3882     case Type::TemplateSpecialization:
3883     case Type::ObjCObject:
3884     case Type::ObjCInterface:
3885     case Type::ObjCObjectPointer:
3886     case Type::ObjCTypeParam:
3887     case Type::Pipe:
3888       llvm_unreachable("type class is never variably-modified!");
3889     case Type::Adjusted:
3890       T = cast<AdjustedType>(Ty)->getOriginalType();
3891       break;
3892     case Type::Decayed:
3893       T = cast<DecayedType>(Ty)->getPointeeType();
3894       break;
3895     case Type::Pointer:
3896       T = cast<PointerType>(Ty)->getPointeeType();
3897       break;
3898     case Type::BlockPointer:
3899       T = cast<BlockPointerType>(Ty)->getPointeeType();
3900       break;
3901     case Type::LValueReference:
3902     case Type::RValueReference:
3903       T = cast<ReferenceType>(Ty)->getPointeeType();
3904       break;
3905     case Type::MemberPointer:
3906       T = cast<MemberPointerType>(Ty)->getPointeeType();
3907       break;
3908     case Type::ConstantArray:
3909     case Type::IncompleteArray:
3910       // Losing element qualification here is fine.
3911       T = cast<ArrayType>(Ty)->getElementType();
3912       break;
3913     case Type::VariableArray: {
3914       // Losing element qualification here is fine.
3915       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3916
3917       // Unknown size indication requires no size computation.
3918       // Otherwise, evaluate and record it.
3919       if (auto Size = VAT->getSizeExpr()) {
3920         if (!CSI->isVLATypeCaptured(VAT)) {
3921           RecordDecl *CapRecord = nullptr;
3922           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3923             CapRecord = LSI->Lambda;
3924           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3925             CapRecord = CRSI->TheRecordDecl;
3926           }
3927           if (CapRecord) {
3928             auto ExprLoc = Size->getExprLoc();
3929             auto SizeType = Context.getSizeType();
3930             // Build the non-static data member.
3931             auto Field =
3932                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3933                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3934                                   /*BW*/ nullptr, /*Mutable*/ false,
3935                                   /*InitStyle*/ ICIS_NoInit);
3936             Field->setImplicit(true);
3937             Field->setAccess(AS_private);
3938             Field->setCapturedVLAType(VAT);
3939             CapRecord->addDecl(Field);
3940
3941             CSI->addVLATypeCapture(ExprLoc, SizeType);
3942           }
3943         }
3944       }
3945       T = VAT->getElementType();
3946       break;
3947     }
3948     case Type::FunctionProto:
3949     case Type::FunctionNoProto:
3950       T = cast<FunctionType>(Ty)->getReturnType();
3951       break;
3952     case Type::Paren:
3953     case Type::TypeOf:
3954     case Type::UnaryTransform:
3955     case Type::Attributed:
3956     case Type::SubstTemplateTypeParm:
3957     case Type::PackExpansion:
3958       // Keep walking after single level desugaring.
3959       T = T.getSingleStepDesugaredType(Context);
3960       break;
3961     case Type::Typedef:
3962       T = cast<TypedefType>(Ty)->desugar();
3963       break;
3964     case Type::Decltype:
3965       T = cast<DecltypeType>(Ty)->desugar();
3966       break;
3967     case Type::Auto:
3968     case Type::DeducedTemplateSpecialization:
3969       T = cast<DeducedType>(Ty)->getDeducedType();
3970       break;
3971     case Type::TypeOfExpr:
3972       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3973       break;
3974     case Type::Atomic:
3975       T = cast<AtomicType>(Ty)->getValueType();
3976       break;
3977     }
3978   } while (!T.isNull() && T->isVariablyModifiedType());
3979 }
3980
3981 /// \brief Build a sizeof or alignof expression given a type operand.
3982 ExprResult
3983 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3984                                      SourceLocation OpLoc,
3985                                      UnaryExprOrTypeTrait ExprKind,
3986                                      SourceRange R) {
3987   if (!TInfo)
3988     return ExprError();
3989
3990   QualType T = TInfo->getType();
3991
3992   if (!T->isDependentType() &&
3993       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3994     return ExprError();
3995
3996   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3997     if (auto *TT = T->getAs<TypedefType>()) {
3998       for (auto I = FunctionScopes.rbegin(),
3999                 E = std::prev(FunctionScopes.rend());
4000            I != E; ++I) {
4001         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4002         if (CSI == nullptr)
4003           break;
4004         DeclContext *DC = nullptr;
4005         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4006           DC = LSI->CallOperator;
4007         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4008           DC = CRSI->TheCapturedDecl;
4009         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4010           DC = BSI->TheDecl;
4011         if (DC) {
4012           if (DC->containsDecl(TT->getDecl()))
4013             break;
4014           captureVariablyModifiedType(Context, T, CSI);
4015         }
4016       }
4017     }
4018   }
4019
4020   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4021   return new (Context) UnaryExprOrTypeTraitExpr(
4022       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4023 }
4024
4025 /// \brief Build a sizeof or alignof expression given an expression
4026 /// operand.
4027 ExprResult
4028 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4029                                      UnaryExprOrTypeTrait ExprKind) {
4030   ExprResult PE = CheckPlaceholderExpr(E);
4031   if (PE.isInvalid()) 
4032     return ExprError();
4033
4034   E = PE.get();
4035   
4036   // Verify that the operand is valid.
4037   bool isInvalid = false;
4038   if (E->isTypeDependent()) {
4039     // Delay type-checking for type-dependent expressions.
4040   } else if (ExprKind == UETT_AlignOf) {
4041     isInvalid = CheckAlignOfExpr(*this, E);
4042   } else if (ExprKind == UETT_VecStep) {
4043     isInvalid = CheckVecStepExpr(E);
4044   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4045       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4046       isInvalid = true;
4047   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4048     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4049     isInvalid = true;
4050   } else {
4051     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4052   }
4053
4054   if (isInvalid)
4055     return ExprError();
4056
4057   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4058     PE = TransformToPotentiallyEvaluated(E);
4059     if (PE.isInvalid()) return ExprError();
4060     E = PE.get();
4061   }
4062
4063   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4064   return new (Context) UnaryExprOrTypeTraitExpr(
4065       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4066 }
4067
4068 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4069 /// expr and the same for @c alignof and @c __alignof
4070 /// Note that the ArgRange is invalid if isType is false.
4071 ExprResult
4072 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4073                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4074                                     void *TyOrEx, SourceRange ArgRange) {
4075   // If error parsing type, ignore.
4076   if (!TyOrEx) return ExprError();
4077
4078   if (IsType) {
4079     TypeSourceInfo *TInfo;
4080     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4081     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4082   }
4083
4084   Expr *ArgEx = (Expr *)TyOrEx;
4085   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4086   return Result;
4087 }
4088
4089 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4090                                      bool IsReal) {
4091   if (V.get()->isTypeDependent())
4092     return S.Context.DependentTy;
4093
4094   // _Real and _Imag are only l-values for normal l-values.
4095   if (V.get()->getObjectKind() != OK_Ordinary) {
4096     V = S.DefaultLvalueConversion(V.get());
4097     if (V.isInvalid())
4098       return QualType();
4099   }
4100
4101   // These operators return the element type of a complex type.
4102   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4103     return CT->getElementType();
4104
4105   // Otherwise they pass through real integer and floating point types here.
4106   if (V.get()->getType()->isArithmeticType())
4107     return V.get()->getType();
4108
4109   // Test for placeholders.
4110   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4111   if (PR.isInvalid()) return QualType();
4112   if (PR.get() != V.get()) {
4113     V = PR;
4114     return CheckRealImagOperand(S, V, Loc, IsReal);
4115   }
4116
4117   // Reject anything else.
4118   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4119     << (IsReal ? "__real" : "__imag");
4120   return QualType();
4121 }
4122
4123
4124
4125 ExprResult
4126 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4127                           tok::TokenKind Kind, Expr *Input) {
4128   UnaryOperatorKind Opc;
4129   switch (Kind) {
4130   default: llvm_unreachable("Unknown unary op!");
4131   case tok::plusplus:   Opc = UO_PostInc; break;
4132   case tok::minusminus: Opc = UO_PostDec; break;
4133   }
4134
4135   // Since this might is a postfix expression, get rid of ParenListExprs.
4136   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4137   if (Result.isInvalid()) return ExprError();
4138   Input = Result.get();
4139
4140   return BuildUnaryOp(S, OpLoc, Opc, Input);
4141 }
4142
4143 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4144 ///
4145 /// \return true on error
4146 static bool checkArithmeticOnObjCPointer(Sema &S,
4147                                          SourceLocation opLoc,
4148                                          Expr *op) {
4149   assert(op->getType()->isObjCObjectPointerType());
4150   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4151       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4152     return false;
4153
4154   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4155     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4156     << op->getSourceRange();
4157   return true;
4158 }
4159
4160 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4161   auto *BaseNoParens = Base->IgnoreParens();
4162   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4163     return MSProp->getPropertyDecl()->getType()->isArrayType();
4164   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4165 }
4166
4167 ExprResult
4168 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4169                               Expr *idx, SourceLocation rbLoc) {
4170   if (base && !base->getType().isNull() &&
4171       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4172     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4173                                     /*Length=*/nullptr, rbLoc);
4174
4175   // Since this might be a postfix expression, get rid of ParenListExprs.
4176   if (isa<ParenListExpr>(base)) {
4177     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4178     if (result.isInvalid()) return ExprError();
4179     base = result.get();
4180   }
4181
4182   // Handle any non-overload placeholder types in the base and index
4183   // expressions.  We can't handle overloads here because the other
4184   // operand might be an overloadable type, in which case the overload
4185   // resolution for the operator overload should get the first crack
4186   // at the overload.
4187   bool IsMSPropertySubscript = false;
4188   if (base->getType()->isNonOverloadPlaceholderType()) {
4189     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4190     if (!IsMSPropertySubscript) {
4191       ExprResult result = CheckPlaceholderExpr(base);
4192       if (result.isInvalid())
4193         return ExprError();
4194       base = result.get();
4195     }
4196   }
4197   if (idx->getType()->isNonOverloadPlaceholderType()) {
4198     ExprResult result = CheckPlaceholderExpr(idx);
4199     if (result.isInvalid()) return ExprError();
4200     idx = result.get();
4201   }
4202
4203   // Build an unanalyzed expression if either operand is type-dependent.
4204   if (getLangOpts().CPlusPlus &&
4205       (base->isTypeDependent() || idx->isTypeDependent())) {
4206     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4207                                             VK_LValue, OK_Ordinary, rbLoc);
4208   }
4209
4210   // MSDN, property (C++)
4211   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4212   // This attribute can also be used in the declaration of an empty array in a
4213   // class or structure definition. For example:
4214   // __declspec(property(get=GetX, put=PutX)) int x[];
4215   // The above statement indicates that x[] can be used with one or more array
4216   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4217   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4218   if (IsMSPropertySubscript) {
4219     // Build MS property subscript expression if base is MS property reference
4220     // or MS property subscript.
4221     return new (Context) MSPropertySubscriptExpr(
4222         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4223   }
4224
4225   // Use C++ overloaded-operator rules if either operand has record
4226   // type.  The spec says to do this if either type is *overloadable*,
4227   // but enum types can't declare subscript operators or conversion
4228   // operators, so there's nothing interesting for overload resolution
4229   // to do if there aren't any record types involved.
4230   //
4231   // ObjC pointers have their own subscripting logic that is not tied
4232   // to overload resolution and so should not take this path.
4233   if (getLangOpts().CPlusPlus &&
4234       (base->getType()->isRecordType() ||
4235        (!base->getType()->isObjCObjectPointerType() &&
4236         idx->getType()->isRecordType()))) {
4237     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4238   }
4239
4240   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4241 }
4242
4243 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4244                                           Expr *LowerBound,
4245                                           SourceLocation ColonLoc, Expr *Length,
4246                                           SourceLocation RBLoc) {
4247   if (Base->getType()->isPlaceholderType() &&
4248       !Base->getType()->isSpecificPlaceholderType(
4249           BuiltinType::OMPArraySection)) {
4250     ExprResult Result = CheckPlaceholderExpr(Base);
4251     if (Result.isInvalid())
4252       return ExprError();
4253     Base = Result.get();
4254   }
4255   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4256     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4257     if (Result.isInvalid())
4258       return ExprError();
4259     Result = DefaultLvalueConversion(Result.get());
4260     if (Result.isInvalid())
4261       return ExprError();
4262     LowerBound = Result.get();
4263   }
4264   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4265     ExprResult Result = CheckPlaceholderExpr(Length);
4266     if (Result.isInvalid())
4267       return ExprError();
4268     Result = DefaultLvalueConversion(Result.get());
4269     if (Result.isInvalid())
4270       return ExprError();
4271     Length = Result.get();
4272   }
4273
4274   // Build an unanalyzed expression if either operand is type-dependent.
4275   if (Base->isTypeDependent() ||
4276       (LowerBound &&
4277        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4278       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4279     return new (Context)
4280         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4281                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4282   }
4283
4284   // Perform default conversions.
4285   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4286   QualType ResultTy;
4287   if (OriginalTy->isAnyPointerType()) {
4288     ResultTy = OriginalTy->getPointeeType();
4289   } else if (OriginalTy->isArrayType()) {
4290     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4291   } else {
4292     return ExprError(
4293         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4294         << Base->getSourceRange());
4295   }
4296   // C99 6.5.2.1p1
4297   if (LowerBound) {
4298     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4299                                                       LowerBound);
4300     if (Res.isInvalid())
4301       return ExprError(Diag(LowerBound->getExprLoc(),
4302                             diag::err_omp_typecheck_section_not_integer)
4303                        << 0 << LowerBound->getSourceRange());
4304     LowerBound = Res.get();
4305
4306     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4307         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4308       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4309           << 0 << LowerBound->getSourceRange();
4310   }
4311   if (Length) {
4312     auto Res =
4313         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4314     if (Res.isInvalid())
4315       return ExprError(Diag(Length->getExprLoc(),
4316                             diag::err_omp_typecheck_section_not_integer)
4317                        << 1 << Length->getSourceRange());
4318     Length = Res.get();
4319
4320     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4321         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4322       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4323           << 1 << Length->getSourceRange();
4324   }
4325
4326   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4327   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4328   // type. Note that functions are not objects, and that (in C99 parlance)
4329   // incomplete types are not object types.
4330   if (ResultTy->isFunctionType()) {
4331     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4332         << ResultTy << Base->getSourceRange();
4333     return ExprError();
4334   }
4335
4336   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4337                           diag::err_omp_section_incomplete_type, Base))
4338     return ExprError();
4339
4340   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4341     llvm::APSInt LowerBoundValue;
4342     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4343       // OpenMP 4.5, [2.4 Array Sections]
4344       // The array section must be a subset of the original array.
4345       if (LowerBoundValue.isNegative()) {
4346         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4347             << LowerBound->getSourceRange();
4348         return ExprError();
4349       }
4350     }
4351   }
4352
4353   if (Length) {
4354     llvm::APSInt LengthValue;
4355     if (Length->EvaluateAsInt(LengthValue, Context)) {
4356       // OpenMP 4.5, [2.4 Array Sections]
4357       // The length must evaluate to non-negative integers.
4358       if (LengthValue.isNegative()) {
4359         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4360             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4361             << Length->getSourceRange();
4362         return ExprError();
4363       }
4364     }
4365   } else if (ColonLoc.isValid() &&
4366              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4367                                       !OriginalTy->isVariableArrayType()))) {
4368     // OpenMP 4.5, [2.4 Array Sections]
4369     // When the size of the array dimension is not known, the length must be
4370     // specified explicitly.
4371     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4372         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4373     return ExprError();
4374   }
4375
4376   if (!Base->getType()->isSpecificPlaceholderType(
4377           BuiltinType::OMPArraySection)) {
4378     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4379     if (Result.isInvalid())
4380       return ExprError();
4381     Base = Result.get();
4382   }
4383   return new (Context)
4384       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4385                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4386 }
4387
4388 ExprResult
4389 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4390                                       Expr *Idx, SourceLocation RLoc) {
4391   Expr *LHSExp = Base;
4392   Expr *RHSExp = Idx;
4393
4394   ExprValueKind VK = VK_LValue;
4395   ExprObjectKind OK = OK_Ordinary;
4396
4397   // Per C++ core issue 1213, the result is an xvalue if either operand is
4398   // a non-lvalue array, and an lvalue otherwise.
4399   if (getLangOpts().CPlusPlus11 &&
4400       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4401        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4402     VK = VK_XValue;
4403
4404   // Perform default conversions.
4405   if (!LHSExp->getType()->getAs<VectorType>()) {
4406     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4407     if (Result.isInvalid())
4408       return ExprError();
4409     LHSExp = Result.get();
4410   }
4411   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4412   if (Result.isInvalid())
4413     return ExprError();
4414   RHSExp = Result.get();
4415
4416   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4417
4418   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4419   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4420   // in the subscript position. As a result, we need to derive the array base
4421   // and index from the expression types.
4422   Expr *BaseExpr, *IndexExpr;
4423   QualType ResultType;
4424   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4425     BaseExpr = LHSExp;
4426     IndexExpr = RHSExp;
4427     ResultType = Context.DependentTy;
4428   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4429     BaseExpr = LHSExp;
4430     IndexExpr = RHSExp;
4431     ResultType = PTy->getPointeeType();
4432   } else if (const ObjCObjectPointerType *PTy =
4433                LHSTy->getAs<ObjCObjectPointerType>()) {
4434     BaseExpr = LHSExp;
4435     IndexExpr = RHSExp;
4436
4437     // Use custom logic if this should be the pseudo-object subscript
4438     // expression.
4439     if (!LangOpts.isSubscriptPointerArithmetic())
4440       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4441                                           nullptr);
4442
4443     ResultType = PTy->getPointeeType();
4444   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4445      // Handle the uncommon case of "123[Ptr]".
4446     BaseExpr = RHSExp;
4447     IndexExpr = LHSExp;
4448     ResultType = PTy->getPointeeType();
4449   } else if (const ObjCObjectPointerType *PTy =
4450                RHSTy->getAs<ObjCObjectPointerType>()) {
4451      // Handle the uncommon case of "123[Ptr]".
4452     BaseExpr = RHSExp;
4453     IndexExpr = LHSExp;
4454     ResultType = PTy->getPointeeType();
4455     if (!LangOpts.isSubscriptPointerArithmetic()) {
4456       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4457         << ResultType << BaseExpr->getSourceRange();
4458       return ExprError();
4459     }
4460   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4461     BaseExpr = LHSExp;    // vectors: V[123]
4462     IndexExpr = RHSExp;
4463     VK = LHSExp->getValueKind();
4464     if (VK != VK_RValue)
4465       OK = OK_VectorComponent;
4466
4467     // FIXME: need to deal with const...
4468     ResultType = VTy->getElementType();
4469   } else if (LHSTy->isArrayType()) {
4470     // If we see an array that wasn't promoted by
4471     // DefaultFunctionArrayLvalueConversion, it must be an array that
4472     // wasn't promoted because of the C90 rule that doesn't
4473     // allow promoting non-lvalue arrays.  Warn, then
4474     // force the promotion here.
4475     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4476         LHSExp->getSourceRange();
4477     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4478                                CK_ArrayToPointerDecay).get();
4479     LHSTy = LHSExp->getType();
4480
4481     BaseExpr = LHSExp;
4482     IndexExpr = RHSExp;
4483     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4484   } else if (RHSTy->isArrayType()) {
4485     // Same as previous, except for 123[f().a] case
4486     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4487         RHSExp->getSourceRange();
4488     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4489                                CK_ArrayToPointerDecay).get();
4490     RHSTy = RHSExp->getType();
4491
4492     BaseExpr = RHSExp;
4493     IndexExpr = LHSExp;
4494     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4495   } else {
4496     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4497        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4498   }
4499   // C99 6.5.2.1p1
4500   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4501     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4502                      << IndexExpr->getSourceRange());
4503
4504   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4505        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4506          && !IndexExpr->isTypeDependent())
4507     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4508
4509   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4510   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4511   // type. Note that Functions are not objects, and that (in C99 parlance)
4512   // incomplete types are not object types.
4513   if (ResultType->isFunctionType()) {
4514     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4515       << ResultType << BaseExpr->getSourceRange();
4516     return ExprError();
4517   }
4518
4519   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4520     // GNU extension: subscripting on pointer to void
4521     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4522       << BaseExpr->getSourceRange();
4523
4524     // C forbids expressions of unqualified void type from being l-values.
4525     // See IsCForbiddenLValueType.
4526     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4527   } else if (!ResultType->isDependentType() &&
4528       RequireCompleteType(LLoc, ResultType,
4529                           diag::err_subscript_incomplete_type, BaseExpr))
4530     return ExprError();
4531
4532   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4533          !ResultType.isCForbiddenLValueType());
4534
4535   return new (Context)
4536       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4537 }
4538
4539 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4540                                   ParmVarDecl *Param) {
4541   if (Param->hasUnparsedDefaultArg()) {
4542     Diag(CallLoc,
4543          diag::err_use_of_default_argument_to_function_declared_later) <<
4544       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4545     Diag(UnparsedDefaultArgLocs[Param],
4546          diag::note_default_argument_declared_here);
4547     return true;
4548   }
4549   
4550   if (Param->hasUninstantiatedDefaultArg()) {
4551     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4552
4553     EnterExpressionEvaluationContext EvalContext(
4554         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4555
4556     // Instantiate the expression.
4557     MultiLevelTemplateArgumentList MutiLevelArgList
4558       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4559
4560     InstantiatingTemplate Inst(*this, CallLoc, Param,
4561                                MutiLevelArgList.getInnermost());
4562     if (Inst.isInvalid())
4563       return true;
4564     if (Inst.isAlreadyInstantiating()) {
4565       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4566       Param->setInvalidDecl();
4567       return true;
4568     }
4569
4570     ExprResult Result;
4571     {
4572       // C++ [dcl.fct.default]p5:
4573       //   The names in the [default argument] expression are bound, and
4574       //   the semantic constraints are checked, at the point where the
4575       //   default argument expression appears.
4576       ContextRAII SavedContext(*this, FD);
4577       LocalInstantiationScope Local(*this);
4578       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4579                                 /*DirectInit*/false);
4580     }
4581     if (Result.isInvalid())
4582       return true;
4583
4584     // Check the expression as an initializer for the parameter.
4585     InitializedEntity Entity
4586       = InitializedEntity::InitializeParameter(Context, Param);
4587     InitializationKind Kind
4588       = InitializationKind::CreateCopy(Param->getLocation(),
4589              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4590     Expr *ResultE = Result.getAs<Expr>();
4591
4592     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4593     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4594     if (Result.isInvalid())
4595       return true;
4596
4597     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4598                                  Param->getOuterLocStart());
4599     if (Result.isInvalid())
4600       return true;
4601
4602     // Remember the instantiated default argument.
4603     Param->setDefaultArg(Result.getAs<Expr>());
4604     if (ASTMutationListener *L = getASTMutationListener()) {
4605       L->DefaultArgumentInstantiated(Param);
4606     }
4607   }
4608
4609   // If the default argument expression is not set yet, we are building it now.
4610   if (!Param->hasInit()) {
4611     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4612     Param->setInvalidDecl();
4613     return true;
4614   }
4615
4616   // If the default expression creates temporaries, we need to
4617   // push them to the current stack of expression temporaries so they'll
4618   // be properly destroyed.
4619   // FIXME: We should really be rebuilding the default argument with new
4620   // bound temporaries; see the comment in PR5810.
4621   // We don't need to do that with block decls, though, because
4622   // blocks in default argument expression can never capture anything.
4623   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4624     // Set the "needs cleanups" bit regardless of whether there are
4625     // any explicit objects.
4626     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4627
4628     // Append all the objects to the cleanup list.  Right now, this
4629     // should always be a no-op, because blocks in default argument
4630     // expressions should never be able to capture anything.
4631     assert(!Init->getNumObjects() &&
4632            "default argument expression has capturing blocks?");
4633   }
4634
4635   // We already type-checked the argument, so we know it works. 
4636   // Just mark all of the declarations in this potentially-evaluated expression
4637   // as being "referenced".
4638   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4639                                    /*SkipLocalVariables=*/true);
4640   return false;
4641 }
4642
4643 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4644                                         FunctionDecl *FD, ParmVarDecl *Param) {
4645   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4646     return ExprError();
4647   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4648 }
4649
4650 Sema::VariadicCallType
4651 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4652                           Expr *Fn) {
4653   if (Proto && Proto->isVariadic()) {
4654     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4655       return VariadicConstructor;
4656     else if (Fn && Fn->getType()->isBlockPointerType())
4657       return VariadicBlock;
4658     else if (FDecl) {
4659       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4660         if (Method->isInstance())
4661           return VariadicMethod;
4662     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4663       return VariadicMethod;
4664     return VariadicFunction;
4665   }
4666   return VariadicDoesNotApply;
4667 }
4668
4669 namespace {
4670 class FunctionCallCCC : public FunctionCallFilterCCC {
4671 public:
4672   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4673                   unsigned NumArgs, MemberExpr *ME)
4674       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4675         FunctionName(FuncName) {}
4676
4677   bool ValidateCandidate(const TypoCorrection &candidate) override {
4678     if (!candidate.getCorrectionSpecifier() ||
4679         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4680       return false;
4681     }
4682
4683     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4684   }
4685
4686 private:
4687   const IdentifierInfo *const FunctionName;
4688 };
4689 }
4690
4691 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4692                                                FunctionDecl *FDecl,
4693                                                ArrayRef<Expr *> Args) {
4694   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4695   DeclarationName FuncName = FDecl->getDeclName();
4696   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4697
4698   if (TypoCorrection Corrected = S.CorrectTypo(
4699           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4700           S.getScopeForContext(S.CurContext), nullptr,
4701           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4702                                              Args.size(), ME),
4703           Sema::CTK_ErrorRecovery)) {
4704     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4705       if (Corrected.isOverloaded()) {
4706         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4707         OverloadCandidateSet::iterator Best;
4708         for (NamedDecl *CD : Corrected) {
4709           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4710             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4711                                    OCS);
4712         }
4713         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4714         case OR_Success:
4715           ND = Best->FoundDecl;
4716           Corrected.setCorrectionDecl(ND);
4717           break;
4718         default:
4719           break;
4720         }
4721       }
4722       ND = ND->getUnderlyingDecl();
4723       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4724         return Corrected;
4725     }
4726   }
4727   return TypoCorrection();
4728 }
4729
4730 /// ConvertArgumentsForCall - Converts the arguments specified in
4731 /// Args/NumArgs to the parameter types of the function FDecl with
4732 /// function prototype Proto. Call is the call expression itself, and
4733 /// Fn is the function expression. For a C++ member function, this
4734 /// routine does not attempt to convert the object argument. Returns
4735 /// true if the call is ill-formed.
4736 bool
4737 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4738                               FunctionDecl *FDecl,
4739                               const FunctionProtoType *Proto,
4740                               ArrayRef<Expr *> Args,
4741                               SourceLocation RParenLoc,
4742                               bool IsExecConfig) {
4743   // Bail out early if calling a builtin with custom typechecking.
4744   if (FDecl)
4745     if (unsigned ID = FDecl->getBuiltinID())
4746       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4747         return false;
4748
4749   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4750   // assignment, to the types of the corresponding parameter, ...
4751   unsigned NumParams = Proto->getNumParams();
4752   bool Invalid = false;
4753   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4754   unsigned FnKind = Fn->getType()->isBlockPointerType()
4755                        ? 1 /* block */
4756                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4757                                        : 0 /* function */);
4758
4759   // If too few arguments are available (and we don't have default
4760   // arguments for the remaining parameters), don't make the call.
4761   if (Args.size() < NumParams) {
4762     if (Args.size() < MinArgs) {
4763       TypoCorrection TC;
4764       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4765         unsigned diag_id =
4766             MinArgs == NumParams && !Proto->isVariadic()
4767                 ? diag::err_typecheck_call_too_few_args_suggest
4768                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4769         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4770                                         << static_cast<unsigned>(Args.size())
4771                                         << TC.getCorrectionRange());
4772       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4773         Diag(RParenLoc,
4774              MinArgs == NumParams && !Proto->isVariadic()
4775                  ? diag::err_typecheck_call_too_few_args_one
4776                  : diag::err_typecheck_call_too_few_args_at_least_one)
4777             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4778       else
4779         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4780                             ? diag::err_typecheck_call_too_few_args
4781                             : diag::err_typecheck_call_too_few_args_at_least)
4782             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4783             << Fn->getSourceRange();
4784
4785       // Emit the location of the prototype.
4786       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4787         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4788           << FDecl;
4789
4790       return true;
4791     }
4792     Call->setNumArgs(Context, NumParams);
4793   }
4794
4795   // If too many are passed and not variadic, error on the extras and drop
4796   // them.
4797   if (Args.size() > NumParams) {
4798     if (!Proto->isVariadic()) {
4799       TypoCorrection TC;
4800       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4801         unsigned diag_id =
4802             MinArgs == NumParams && !Proto->isVariadic()
4803                 ? diag::err_typecheck_call_too_many_args_suggest
4804                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4805         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4806                                         << static_cast<unsigned>(Args.size())
4807                                         << TC.getCorrectionRange());
4808       } else if (NumParams == 1 && FDecl &&
4809                  FDecl->getParamDecl(0)->getDeclName())
4810         Diag(Args[NumParams]->getLocStart(),
4811              MinArgs == NumParams
4812                  ? diag::err_typecheck_call_too_many_args_one
4813                  : diag::err_typecheck_call_too_many_args_at_most_one)
4814             << FnKind << FDecl->getParamDecl(0)
4815             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4816             << SourceRange(Args[NumParams]->getLocStart(),
4817                            Args.back()->getLocEnd());
4818       else
4819         Diag(Args[NumParams]->getLocStart(),
4820              MinArgs == NumParams
4821                  ? diag::err_typecheck_call_too_many_args
4822                  : diag::err_typecheck_call_too_many_args_at_most)
4823             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4824             << Fn->getSourceRange()
4825             << SourceRange(Args[NumParams]->getLocStart(),
4826                            Args.back()->getLocEnd());
4827
4828       // Emit the location of the prototype.
4829       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4830         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4831           << FDecl;
4832       
4833       // This deletes the extra arguments.
4834       Call->setNumArgs(Context, NumParams);
4835       return true;
4836     }
4837   }
4838   SmallVector<Expr *, 8> AllArgs;
4839   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4840   
4841   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4842                                    Proto, 0, Args, AllArgs, CallType);
4843   if (Invalid)
4844     return true;
4845   unsigned TotalNumArgs = AllArgs.size();
4846   for (unsigned i = 0; i < TotalNumArgs; ++i)
4847     Call->setArg(i, AllArgs[i]);
4848
4849   return false;
4850 }
4851
4852 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4853                                   const FunctionProtoType *Proto,
4854                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4855                                   SmallVectorImpl<Expr *> &AllArgs,
4856                                   VariadicCallType CallType, bool AllowExplicit,
4857                                   bool IsListInitialization) {
4858   unsigned NumParams = Proto->getNumParams();
4859   bool Invalid = false;
4860   size_t ArgIx = 0;
4861   // Continue to check argument types (even if we have too few/many args).
4862   for (unsigned i = FirstParam; i < NumParams; i++) {
4863     QualType ProtoArgType = Proto->getParamType(i);
4864
4865     Expr *Arg;
4866     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4867     if (ArgIx < Args.size()) {
4868       Arg = Args[ArgIx++];
4869
4870       if (RequireCompleteType(Arg->getLocStart(),
4871                               ProtoArgType,
4872                               diag::err_call_incomplete_argument, Arg))
4873         return true;
4874
4875       // Strip the unbridged-cast placeholder expression off, if applicable.
4876       bool CFAudited = false;
4877       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4878           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4879           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4880         Arg = stripARCUnbridgedCast(Arg);
4881       else if (getLangOpts().ObjCAutoRefCount &&
4882                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4883                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4884         CFAudited = true;
4885
4886       InitializedEntity Entity =
4887           Param ? InitializedEntity::InitializeParameter(Context, Param,
4888                                                          ProtoArgType)
4889                 : InitializedEntity::InitializeParameter(
4890                       Context, ProtoArgType, Proto->isParamConsumed(i));
4891
4892       // Remember that parameter belongs to a CF audited API.
4893       if (CFAudited)
4894         Entity.setParameterCFAudited();
4895
4896       ExprResult ArgE = PerformCopyInitialization(
4897           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4898       if (ArgE.isInvalid())
4899         return true;
4900
4901       Arg = ArgE.getAs<Expr>();
4902     } else {
4903       assert(Param && "can't use default arguments without a known callee");
4904
4905       ExprResult ArgExpr =
4906         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4907       if (ArgExpr.isInvalid())
4908         return true;
4909
4910       Arg = ArgExpr.getAs<Expr>();
4911     }
4912
4913     // Check for array bounds violations for each argument to the call. This
4914     // check only triggers warnings when the argument isn't a more complex Expr
4915     // with its own checking, such as a BinaryOperator.
4916     CheckArrayAccess(Arg);
4917
4918     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4919     CheckStaticArrayArgument(CallLoc, Param, Arg);
4920
4921     AllArgs.push_back(Arg);
4922   }
4923
4924   // If this is a variadic call, handle args passed through "...".
4925   if (CallType != VariadicDoesNotApply) {
4926     // Assume that extern "C" functions with variadic arguments that
4927     // return __unknown_anytype aren't *really* variadic.
4928     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4929         FDecl->isExternC()) {
4930       for (Expr *A : Args.slice(ArgIx)) {
4931         QualType paramType; // ignored
4932         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4933         Invalid |= arg.isInvalid();
4934         AllArgs.push_back(arg.get());
4935       }
4936
4937     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4938     } else {
4939       for (Expr *A : Args.slice(ArgIx)) {
4940         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4941         Invalid |= Arg.isInvalid();
4942         AllArgs.push_back(Arg.get());
4943       }
4944     }
4945
4946     // Check for array bounds violations.
4947     for (Expr *A : Args.slice(ArgIx))
4948       CheckArrayAccess(A);
4949   }
4950   return Invalid;
4951 }
4952
4953 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4954   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4955   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4956     TL = DTL.getOriginalLoc();
4957   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4958     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4959       << ATL.getLocalSourceRange();
4960 }
4961
4962 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4963 /// array parameter, check that it is non-null, and that if it is formed by
4964 /// array-to-pointer decay, the underlying array is sufficiently large.
4965 ///
4966 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4967 /// array type derivation, then for each call to the function, the value of the
4968 /// corresponding actual argument shall provide access to the first element of
4969 /// an array with at least as many elements as specified by the size expression.
4970 void
4971 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4972                                ParmVarDecl *Param,
4973                                const Expr *ArgExpr) {
4974   // Static array parameters are not supported in C++.
4975   if (!Param || getLangOpts().CPlusPlus)
4976     return;
4977
4978   QualType OrigTy = Param->getOriginalType();
4979
4980   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4981   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4982     return;
4983
4984   if (ArgExpr->isNullPointerConstant(Context,
4985                                      Expr::NPC_NeverValueDependent)) {
4986     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4987     DiagnoseCalleeStaticArrayParam(*this, Param);
4988     return;
4989   }
4990
4991   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4992   if (!CAT)
4993     return;
4994
4995   const ConstantArrayType *ArgCAT =
4996     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4997   if (!ArgCAT)
4998     return;
4999
5000   if (ArgCAT->getSize().ult(CAT->getSize())) {
5001     Diag(CallLoc, diag::warn_static_array_too_small)
5002       << ArgExpr->getSourceRange()
5003       << (unsigned) ArgCAT->getSize().getZExtValue()
5004       << (unsigned) CAT->getSize().getZExtValue();
5005     DiagnoseCalleeStaticArrayParam(*this, Param);
5006   }
5007 }
5008
5009 /// Given a function expression of unknown-any type, try to rebuild it
5010 /// to have a function type.
5011 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5012
5013 /// Is the given type a placeholder that we need to lower out
5014 /// immediately during argument processing?
5015 static bool isPlaceholderToRemoveAsArg(QualType type) {
5016   // Placeholders are never sugared.
5017   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5018   if (!placeholder) return false;
5019
5020   switch (placeholder->getKind()) {
5021   // Ignore all the non-placeholder types.
5022 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5023   case BuiltinType::Id:
5024 #include "clang/Basic/OpenCLImageTypes.def"
5025 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5026 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5027 #include "clang/AST/BuiltinTypes.def"
5028     return false;
5029
5030   // We cannot lower out overload sets; they might validly be resolved
5031   // by the call machinery.
5032   case BuiltinType::Overload:
5033     return false;
5034
5035   // Unbridged casts in ARC can be handled in some call positions and
5036   // should be left in place.
5037   case BuiltinType::ARCUnbridgedCast:
5038     return false;
5039
5040   // Pseudo-objects should be converted as soon as possible.
5041   case BuiltinType::PseudoObject:
5042     return true;
5043
5044   // The debugger mode could theoretically but currently does not try
5045   // to resolve unknown-typed arguments based on known parameter types.
5046   case BuiltinType::UnknownAny:
5047     return true;
5048
5049   // These are always invalid as call arguments and should be reported.
5050   case BuiltinType::BoundMember:
5051   case BuiltinType::BuiltinFn:
5052   case BuiltinType::OMPArraySection:
5053     return true;
5054
5055   }
5056   llvm_unreachable("bad builtin type kind");
5057 }
5058
5059 /// Check an argument list for placeholders that we won't try to
5060 /// handle later.
5061 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5062   // Apply this processing to all the arguments at once instead of
5063   // dying at the first failure.
5064   bool hasInvalid = false;
5065   for (size_t i = 0, e = args.size(); i != e; i++) {
5066     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5067       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5068       if (result.isInvalid()) hasInvalid = true;
5069       else args[i] = result.get();
5070     } else if (hasInvalid) {
5071       (void)S.CorrectDelayedTyposInExpr(args[i]);
5072     }
5073   }
5074   return hasInvalid;
5075 }
5076
5077 /// If a builtin function has a pointer argument with no explicit address
5078 /// space, then it should be able to accept a pointer to any address
5079 /// space as input.  In order to do this, we need to replace the
5080 /// standard builtin declaration with one that uses the same address space
5081 /// as the call.
5082 ///
5083 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5084 ///                  it does not contain any pointer arguments without
5085 ///                  an address space qualifer.  Otherwise the rewritten
5086 ///                  FunctionDecl is returned.
5087 /// TODO: Handle pointer return types.
5088 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5089                                                 const FunctionDecl *FDecl,
5090                                                 MultiExprArg ArgExprs) {
5091
5092   QualType DeclType = FDecl->getType();
5093   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5094
5095   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5096       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5097     return nullptr;
5098
5099   bool NeedsNewDecl = false;
5100   unsigned i = 0;
5101   SmallVector<QualType, 8> OverloadParams;
5102
5103   for (QualType ParamType : FT->param_types()) {
5104
5105     // Convert array arguments to pointer to simplify type lookup.
5106     ExprResult ArgRes =
5107         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5108     if (ArgRes.isInvalid())
5109       return nullptr;
5110     Expr *Arg = ArgRes.get();
5111     QualType ArgType = Arg->getType();
5112     if (!ParamType->isPointerType() ||
5113         ParamType.getQualifiers().hasAddressSpace() ||
5114         !ArgType->isPointerType() ||
5115         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5116       OverloadParams.push_back(ParamType);
5117       continue;
5118     }
5119
5120     NeedsNewDecl = true;
5121     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5122
5123     QualType PointeeType = ParamType->getPointeeType();
5124     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5125     OverloadParams.push_back(Context.getPointerType(PointeeType));
5126   }
5127
5128   if (!NeedsNewDecl)
5129     return nullptr;
5130
5131   FunctionProtoType::ExtProtoInfo EPI;
5132   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5133                                                 OverloadParams, EPI);
5134   DeclContext *Parent = Context.getTranslationUnitDecl();
5135   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5136                                                     FDecl->getLocation(),
5137                                                     FDecl->getLocation(),
5138                                                     FDecl->getIdentifier(),
5139                                                     OverloadTy,
5140                                                     /*TInfo=*/nullptr,
5141                                                     SC_Extern, false,
5142                                                     /*hasPrototype=*/true);
5143   SmallVector<ParmVarDecl*, 16> Params;
5144   FT = cast<FunctionProtoType>(OverloadTy);
5145   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5146     QualType ParamType = FT->getParamType(i);
5147     ParmVarDecl *Parm =
5148         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5149                                 SourceLocation(), nullptr, ParamType,
5150                                 /*TInfo=*/nullptr, SC_None, nullptr);
5151     Parm->setScopeInfo(0, i);
5152     Params.push_back(Parm);
5153   }
5154   OverloadDecl->setParams(Params);
5155   return OverloadDecl;
5156 }
5157
5158 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5159                                     FunctionDecl *Callee,
5160                                     MultiExprArg ArgExprs) {
5161   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5162   // similar attributes) really don't like it when functions are called with an
5163   // invalid number of args.
5164   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5165                          /*PartialOverloading=*/false) &&
5166       !Callee->isVariadic())
5167     return;
5168   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5169     return;
5170
5171   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5172     S.Diag(Fn->getLocStart(),
5173            isa<CXXMethodDecl>(Callee)
5174                ? diag::err_ovl_no_viable_member_function_in_call
5175                : diag::err_ovl_no_viable_function_in_call)
5176         << Callee << Callee->getSourceRange();
5177     S.Diag(Callee->getLocation(),
5178            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5179         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5180     return;
5181   }
5182 }
5183
5184 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5185 /// This provides the location of the left/right parens and a list of comma
5186 /// locations.
5187 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5188                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5189                                Expr *ExecConfig, bool IsExecConfig) {
5190   // Since this might be a postfix expression, get rid of ParenListExprs.
5191   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5192   if (Result.isInvalid()) return ExprError();
5193   Fn = Result.get();
5194
5195   if (checkArgsForPlaceholders(*this, ArgExprs))
5196     return ExprError();
5197
5198   if (getLangOpts().CPlusPlus) {
5199     // If this is a pseudo-destructor expression, build the call immediately.
5200     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5201       if (!ArgExprs.empty()) {
5202         // Pseudo-destructor calls should not have any arguments.
5203         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5204             << FixItHint::CreateRemoval(
5205                    SourceRange(ArgExprs.front()->getLocStart(),
5206                                ArgExprs.back()->getLocEnd()));
5207       }
5208
5209       return new (Context)
5210           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5211     }
5212     if (Fn->getType() == Context.PseudoObjectTy) {
5213       ExprResult result = CheckPlaceholderExpr(Fn);
5214       if (result.isInvalid()) return ExprError();
5215       Fn = result.get();
5216     }
5217
5218     // Determine whether this is a dependent call inside a C++ template,
5219     // in which case we won't do any semantic analysis now.
5220     bool Dependent = false;
5221     if (Fn->isTypeDependent())
5222       Dependent = true;
5223     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5224       Dependent = true;
5225
5226     if (Dependent) {
5227       if (ExecConfig) {
5228         return new (Context) CUDAKernelCallExpr(
5229             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5230             Context.DependentTy, VK_RValue, RParenLoc);
5231       } else {
5232         return new (Context) CallExpr(
5233             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5234       }
5235     }
5236
5237     // Determine whether this is a call to an object (C++ [over.call.object]).
5238     if (Fn->getType()->isRecordType())
5239       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5240                                           RParenLoc);
5241
5242     if (Fn->getType() == Context.UnknownAnyTy) {
5243       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5244       if (result.isInvalid()) return ExprError();
5245       Fn = result.get();
5246     }
5247
5248     if (Fn->getType() == Context.BoundMemberTy) {
5249       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5250                                        RParenLoc);
5251     }
5252   }
5253
5254   // Check for overloaded calls.  This can happen even in C due to extensions.
5255   if (Fn->getType() == Context.OverloadTy) {
5256     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5257
5258     // We aren't supposed to apply this logic if there's an '&' involved.
5259     if (!find.HasFormOfMemberPointer) {
5260       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5261         return new (Context) CallExpr(
5262             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5263       OverloadExpr *ovl = find.Expression;
5264       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5265         return BuildOverloadedCallExpr(
5266             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5267             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5268       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5269                                        RParenLoc);
5270     }
5271   }
5272
5273   // If we're directly calling a function, get the appropriate declaration.
5274   if (Fn->getType() == Context.UnknownAnyTy) {
5275     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5276     if (result.isInvalid()) return ExprError();
5277     Fn = result.get();
5278   }
5279
5280   Expr *NakedFn = Fn->IgnoreParens();
5281
5282   bool CallingNDeclIndirectly = false;
5283   NamedDecl *NDecl = nullptr;
5284   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5285     if (UnOp->getOpcode() == UO_AddrOf) {
5286       CallingNDeclIndirectly = true;
5287       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5288     }
5289   }
5290
5291   if (isa<DeclRefExpr>(NakedFn)) {
5292     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5293
5294     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5295     if (FDecl && FDecl->getBuiltinID()) {
5296       // Rewrite the function decl for this builtin by replacing parameters
5297       // with no explicit address space with the address space of the arguments
5298       // in ArgExprs.
5299       if ((FDecl =
5300                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5301         NDecl = FDecl;
5302         Fn = DeclRefExpr::Create(
5303             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5304             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5305       }
5306     }
5307   } else if (isa<MemberExpr>(NakedFn))
5308     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5309
5310   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5311     if (CallingNDeclIndirectly &&
5312         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5313                                            Fn->getLocStart()))
5314       return ExprError();
5315
5316     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5317       return ExprError();
5318
5319     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5320   }
5321
5322   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5323                                ExecConfig, IsExecConfig);
5324 }
5325
5326 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5327 ///
5328 /// __builtin_astype( value, dst type )
5329 ///
5330 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5331                                  SourceLocation BuiltinLoc,
5332                                  SourceLocation RParenLoc) {
5333   ExprValueKind VK = VK_RValue;
5334   ExprObjectKind OK = OK_Ordinary;
5335   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5336   QualType SrcTy = E->getType();
5337   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5338     return ExprError(Diag(BuiltinLoc,
5339                           diag::err_invalid_astype_of_different_size)
5340                      << DstTy
5341                      << SrcTy
5342                      << E->getSourceRange());
5343   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5344 }
5345
5346 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5347 /// provided arguments.
5348 ///
5349 /// __builtin_convertvector( value, dst type )
5350 ///
5351 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5352                                         SourceLocation BuiltinLoc,
5353                                         SourceLocation RParenLoc) {
5354   TypeSourceInfo *TInfo;
5355   GetTypeFromParser(ParsedDestTy, &TInfo);
5356   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5357 }
5358
5359 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5360 /// i.e. an expression not of \p OverloadTy.  The expression should
5361 /// unary-convert to an expression of function-pointer or
5362 /// block-pointer type.
5363 ///
5364 /// \param NDecl the declaration being called, if available
5365 ExprResult
5366 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5367                             SourceLocation LParenLoc,
5368                             ArrayRef<Expr *> Args,
5369                             SourceLocation RParenLoc,
5370                             Expr *Config, bool IsExecConfig) {
5371   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5372   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5373
5374   // Functions with 'interrupt' attribute cannot be called directly.
5375   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5376     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5377     return ExprError();
5378   }
5379
5380   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5381   // so there's some risk when calling out to non-interrupt handler functions
5382   // that the callee might not preserve them. This is easy to diagnose here,
5383   // but can be very challenging to debug.
5384   if (auto *Caller = getCurFunctionDecl())
5385     if (Caller->hasAttr<ARMInterruptAttr>()) {
5386       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5387       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5388         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5389     }
5390
5391   // Promote the function operand.
5392   // We special-case function promotion here because we only allow promoting
5393   // builtin functions to function pointers in the callee of a call.
5394   ExprResult Result;
5395   if (BuiltinID &&
5396       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5397     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5398                                CK_BuiltinFnToFnPtr).get();
5399   } else {
5400     Result = CallExprUnaryConversions(Fn);
5401   }
5402   if (Result.isInvalid())
5403     return ExprError();
5404   Fn = Result.get();
5405
5406   // Make the call expr early, before semantic checks.  This guarantees cleanup
5407   // of arguments and function on error.
5408   CallExpr *TheCall;
5409   if (Config)
5410     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5411                                                cast<CallExpr>(Config), Args,
5412                                                Context.BoolTy, VK_RValue,
5413                                                RParenLoc);
5414   else
5415     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5416                                      VK_RValue, RParenLoc);
5417
5418   if (!getLangOpts().CPlusPlus) {
5419     // C cannot always handle TypoExpr nodes in builtin calls and direct
5420     // function calls as their argument checking don't necessarily handle
5421     // dependent types properly, so make sure any TypoExprs have been
5422     // dealt with.
5423     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5424     if (!Result.isUsable()) return ExprError();
5425     TheCall = dyn_cast<CallExpr>(Result.get());
5426     if (!TheCall) return Result;
5427     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5428   }
5429
5430   // Bail out early if calling a builtin with custom typechecking.
5431   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5432     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5433
5434  retry:
5435   const FunctionType *FuncT;
5436   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5437     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5438     // have type pointer to function".
5439     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5440     if (!FuncT)
5441       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5442                          << Fn->getType() << Fn->getSourceRange());
5443   } else if (const BlockPointerType *BPT =
5444                Fn->getType()->getAs<BlockPointerType>()) {
5445     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5446   } else {
5447     // Handle calls to expressions of unknown-any type.
5448     if (Fn->getType() == Context.UnknownAnyTy) {
5449       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5450       if (rewrite.isInvalid()) return ExprError();
5451       Fn = rewrite.get();
5452       TheCall->setCallee(Fn);
5453       goto retry;
5454     }
5455
5456     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5457       << Fn->getType() << Fn->getSourceRange());
5458   }
5459
5460   if (getLangOpts().CUDA) {
5461     if (Config) {
5462       // CUDA: Kernel calls must be to global functions
5463       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5464         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5465             << FDecl->getName() << Fn->getSourceRange());
5466
5467       // CUDA: Kernel function must have 'void' return type
5468       if (!FuncT->getReturnType()->isVoidType())
5469         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5470             << Fn->getType() << Fn->getSourceRange());
5471     } else {
5472       // CUDA: Calls to global functions must be configured
5473       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5474         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5475             << FDecl->getName() << Fn->getSourceRange());
5476     }
5477   }
5478
5479   // Check for a valid return type
5480   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5481                           FDecl))
5482     return ExprError();
5483
5484   // We know the result type of the call, set it.
5485   TheCall->setType(FuncT->getCallResultType(Context));
5486   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5487
5488   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5489   if (Proto) {
5490     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5491                                 IsExecConfig))
5492       return ExprError();
5493   } else {
5494     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5495
5496     if (FDecl) {
5497       // Check if we have too few/too many template arguments, based
5498       // on our knowledge of the function definition.
5499       const FunctionDecl *Def = nullptr;
5500       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5501         Proto = Def->getType()->getAs<FunctionProtoType>();
5502        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5503           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5504           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5505       }
5506       
5507       // If the function we're calling isn't a function prototype, but we have
5508       // a function prototype from a prior declaratiom, use that prototype.
5509       if (!FDecl->hasPrototype())
5510         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5511     }
5512
5513     // Promote the arguments (C99 6.5.2.2p6).
5514     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5515       Expr *Arg = Args[i];
5516
5517       if (Proto && i < Proto->getNumParams()) {
5518         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5519             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5520         ExprResult ArgE =
5521             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5522         if (ArgE.isInvalid())
5523           return true;
5524         
5525         Arg = ArgE.getAs<Expr>();
5526
5527       } else {
5528         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5529
5530         if (ArgE.isInvalid())
5531           return true;
5532
5533         Arg = ArgE.getAs<Expr>();
5534       }
5535       
5536       if (RequireCompleteType(Arg->getLocStart(),
5537                               Arg->getType(),
5538                               diag::err_call_incomplete_argument, Arg))
5539         return ExprError();
5540
5541       TheCall->setArg(i, Arg);
5542     }
5543   }
5544
5545   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5546     if (!Method->isStatic())
5547       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5548         << Fn->getSourceRange());
5549
5550   // Check for sentinels
5551   if (NDecl)
5552     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5553
5554   // Do special checking on direct calls to functions.
5555   if (FDecl) {
5556     if (CheckFunctionCall(FDecl, TheCall, Proto))
5557       return ExprError();
5558
5559     if (BuiltinID)
5560       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5561   } else if (NDecl) {
5562     if (CheckPointerCall(NDecl, TheCall, Proto))
5563       return ExprError();
5564   } else {
5565     if (CheckOtherCall(TheCall, Proto))
5566       return ExprError();
5567   }
5568
5569   return MaybeBindToTemporary(TheCall);
5570 }
5571
5572 ExprResult
5573 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5574                            SourceLocation RParenLoc, Expr *InitExpr) {
5575   assert(Ty && "ActOnCompoundLiteral(): missing type");
5576   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5577
5578   TypeSourceInfo *TInfo;
5579   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5580   if (!TInfo)
5581     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5582
5583   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5584 }
5585
5586 ExprResult
5587 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5588                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5589   QualType literalType = TInfo->getType();
5590
5591   if (literalType->isArrayType()) {
5592     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5593           diag::err_illegal_decl_array_incomplete_type,
5594           SourceRange(LParenLoc,
5595                       LiteralExpr->getSourceRange().getEnd())))
5596       return ExprError();
5597     if (literalType->isVariableArrayType())
5598       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5599         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5600   } else if (!literalType->isDependentType() &&
5601              RequireCompleteType(LParenLoc, literalType,
5602                diag::err_typecheck_decl_incomplete_type,
5603                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5604     return ExprError();
5605
5606   InitializedEntity Entity
5607     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5608   InitializationKind Kind
5609     = InitializationKind::CreateCStyleCast(LParenLoc, 
5610                                            SourceRange(LParenLoc, RParenLoc),
5611                                            /*InitList=*/true);
5612   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5613   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5614                                       &literalType);
5615   if (Result.isInvalid())
5616     return ExprError();
5617   LiteralExpr = Result.get();
5618
5619   bool isFileScope = !CurContext->isFunctionOrMethod();
5620   if (isFileScope &&
5621       !LiteralExpr->isTypeDependent() &&
5622       !LiteralExpr->isValueDependent() &&
5623       !literalType->isDependentType()) { // 6.5.2.5p3
5624     if (CheckForConstantInitializer(LiteralExpr, literalType))
5625       return ExprError();
5626   }
5627
5628   // In C, compound literals are l-values for some reason.
5629   // For GCC compatibility, in C++, file-scope array compound literals with
5630   // constant initializers are also l-values, and compound literals are
5631   // otherwise prvalues.
5632   //
5633   // (GCC also treats C++ list-initialized file-scope array prvalues with
5634   // constant initializers as l-values, but that's non-conforming, so we don't
5635   // follow it there.)
5636   //
5637   // FIXME: It would be better to handle the lvalue cases as materializing and
5638   // lifetime-extending a temporary object, but our materialized temporaries
5639   // representation only supports lifetime extension from a variable, not "out
5640   // of thin air".
5641   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5642   // is bound to the result of applying array-to-pointer decay to the compound
5643   // literal.
5644   // FIXME: GCC supports compound literals of reference type, which should
5645   // obviously have a value kind derived from the kind of reference involved.
5646   ExprValueKind VK =
5647       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5648           ? VK_RValue
5649           : VK_LValue;
5650
5651   return MaybeBindToTemporary(
5652       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5653                                         VK, LiteralExpr, isFileScope));
5654 }
5655
5656 ExprResult
5657 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5658                     SourceLocation RBraceLoc) {
5659   // Immediately handle non-overload placeholders.  Overloads can be
5660   // resolved contextually, but everything else here can't.
5661   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5662     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5663       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5664
5665       // Ignore failures; dropping the entire initializer list because
5666       // of one failure would be terrible for indexing/etc.
5667       if (result.isInvalid()) continue;
5668
5669       InitArgList[I] = result.get();
5670     }
5671   }
5672
5673   // Semantic analysis for initializers is done by ActOnDeclarator() and
5674   // CheckInitializer() - it requires knowledge of the object being intialized.
5675
5676   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5677                                                RBraceLoc);
5678   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5679   return E;
5680 }
5681
5682 /// Do an explicit extend of the given block pointer if we're in ARC.
5683 void Sema::maybeExtendBlockObject(ExprResult &E) {
5684   assert(E.get()->getType()->isBlockPointerType());
5685   assert(E.get()->isRValue());
5686
5687   // Only do this in an r-value context.
5688   if (!getLangOpts().ObjCAutoRefCount) return;
5689
5690   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5691                                CK_ARCExtendBlockObject, E.get(),
5692                                /*base path*/ nullptr, VK_RValue);
5693   Cleanup.setExprNeedsCleanups(true);
5694 }
5695
5696 /// Prepare a conversion of the given expression to an ObjC object
5697 /// pointer type.
5698 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5699   QualType type = E.get()->getType();
5700   if (type->isObjCObjectPointerType()) {
5701     return CK_BitCast;
5702   } else if (type->isBlockPointerType()) {
5703     maybeExtendBlockObject(E);
5704     return CK_BlockPointerToObjCPointerCast;
5705   } else {
5706     assert(type->isPointerType());
5707     return CK_CPointerToObjCPointerCast;
5708   }
5709 }
5710
5711 /// Prepares for a scalar cast, performing all the necessary stages
5712 /// except the final cast and returning the kind required.
5713 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5714   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5715   // Also, callers should have filtered out the invalid cases with
5716   // pointers.  Everything else should be possible.
5717
5718   QualType SrcTy = Src.get()->getType();
5719   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5720     return CK_NoOp;
5721
5722   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5723   case Type::STK_MemberPointer:
5724     llvm_unreachable("member pointer type in C");
5725
5726   case Type::STK_CPointer:
5727   case Type::STK_BlockPointer:
5728   case Type::STK_ObjCObjectPointer:
5729     switch (DestTy->getScalarTypeKind()) {
5730     case Type::STK_CPointer: {
5731       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5732       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5733       if (SrcAS != DestAS)
5734         return CK_AddressSpaceConversion;
5735       return CK_BitCast;
5736     }
5737     case Type::STK_BlockPointer:
5738       return (SrcKind == Type::STK_BlockPointer
5739                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5740     case Type::STK_ObjCObjectPointer:
5741       if (SrcKind == Type::STK_ObjCObjectPointer)
5742         return CK_BitCast;
5743       if (SrcKind == Type::STK_CPointer)
5744         return CK_CPointerToObjCPointerCast;
5745       maybeExtendBlockObject(Src);
5746       return CK_BlockPointerToObjCPointerCast;
5747     case Type::STK_Bool:
5748       return CK_PointerToBoolean;
5749     case Type::STK_Integral:
5750       return CK_PointerToIntegral;
5751     case Type::STK_Floating:
5752     case Type::STK_FloatingComplex:
5753     case Type::STK_IntegralComplex:
5754     case Type::STK_MemberPointer:
5755       llvm_unreachable("illegal cast from pointer");
5756     }
5757     llvm_unreachable("Should have returned before this");
5758
5759   case Type::STK_Bool: // casting from bool is like casting from an integer
5760   case Type::STK_Integral:
5761     switch (DestTy->getScalarTypeKind()) {
5762     case Type::STK_CPointer:
5763     case Type::STK_ObjCObjectPointer:
5764     case Type::STK_BlockPointer:
5765       if (Src.get()->isNullPointerConstant(Context,
5766                                            Expr::NPC_ValueDependentIsNull))
5767         return CK_NullToPointer;
5768       return CK_IntegralToPointer;
5769     case Type::STK_Bool:
5770       return CK_IntegralToBoolean;
5771     case Type::STK_Integral:
5772       return CK_IntegralCast;
5773     case Type::STK_Floating:
5774       return CK_IntegralToFloating;
5775     case Type::STK_IntegralComplex:
5776       Src = ImpCastExprToType(Src.get(),
5777                       DestTy->castAs<ComplexType>()->getElementType(),
5778                       CK_IntegralCast);
5779       return CK_IntegralRealToComplex;
5780     case Type::STK_FloatingComplex:
5781       Src = ImpCastExprToType(Src.get(),
5782                       DestTy->castAs<ComplexType>()->getElementType(),
5783                       CK_IntegralToFloating);
5784       return CK_FloatingRealToComplex;
5785     case Type::STK_MemberPointer:
5786       llvm_unreachable("member pointer type in C");
5787     }
5788     llvm_unreachable("Should have returned before this");
5789
5790   case Type::STK_Floating:
5791     switch (DestTy->getScalarTypeKind()) {
5792     case Type::STK_Floating:
5793       return CK_FloatingCast;
5794     case Type::STK_Bool:
5795       return CK_FloatingToBoolean;
5796     case Type::STK_Integral:
5797       return CK_FloatingToIntegral;
5798     case Type::STK_FloatingComplex:
5799       Src = ImpCastExprToType(Src.get(),
5800                               DestTy->castAs<ComplexType>()->getElementType(),
5801                               CK_FloatingCast);
5802       return CK_FloatingRealToComplex;
5803     case Type::STK_IntegralComplex:
5804       Src = ImpCastExprToType(Src.get(),
5805                               DestTy->castAs<ComplexType>()->getElementType(),
5806                               CK_FloatingToIntegral);
5807       return CK_IntegralRealToComplex;
5808     case Type::STK_CPointer:
5809     case Type::STK_ObjCObjectPointer:
5810     case Type::STK_BlockPointer:
5811       llvm_unreachable("valid float->pointer cast?");
5812     case Type::STK_MemberPointer:
5813       llvm_unreachable("member pointer type in C");
5814     }
5815     llvm_unreachable("Should have returned before this");
5816
5817   case Type::STK_FloatingComplex:
5818     switch (DestTy->getScalarTypeKind()) {
5819     case Type::STK_FloatingComplex:
5820       return CK_FloatingComplexCast;
5821     case Type::STK_IntegralComplex:
5822       return CK_FloatingComplexToIntegralComplex;
5823     case Type::STK_Floating: {
5824       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5825       if (Context.hasSameType(ET, DestTy))
5826         return CK_FloatingComplexToReal;
5827       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5828       return CK_FloatingCast;
5829     }
5830     case Type::STK_Bool:
5831       return CK_FloatingComplexToBoolean;
5832     case Type::STK_Integral:
5833       Src = ImpCastExprToType(Src.get(),
5834                               SrcTy->castAs<ComplexType>()->getElementType(),
5835                               CK_FloatingComplexToReal);
5836       return CK_FloatingToIntegral;
5837     case Type::STK_CPointer:
5838     case Type::STK_ObjCObjectPointer:
5839     case Type::STK_BlockPointer:
5840       llvm_unreachable("valid complex float->pointer cast?");
5841     case Type::STK_MemberPointer:
5842       llvm_unreachable("member pointer type in C");
5843     }
5844     llvm_unreachable("Should have returned before this");
5845
5846   case Type::STK_IntegralComplex:
5847     switch (DestTy->getScalarTypeKind()) {
5848     case Type::STK_FloatingComplex:
5849       return CK_IntegralComplexToFloatingComplex;
5850     case Type::STK_IntegralComplex:
5851       return CK_IntegralComplexCast;
5852     case Type::STK_Integral: {
5853       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5854       if (Context.hasSameType(ET, DestTy))
5855         return CK_IntegralComplexToReal;
5856       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5857       return CK_IntegralCast;
5858     }
5859     case Type::STK_Bool:
5860       return CK_IntegralComplexToBoolean;
5861     case Type::STK_Floating:
5862       Src = ImpCastExprToType(Src.get(),
5863                               SrcTy->castAs<ComplexType>()->getElementType(),
5864                               CK_IntegralComplexToReal);
5865       return CK_IntegralToFloating;
5866     case Type::STK_CPointer:
5867     case Type::STK_ObjCObjectPointer:
5868     case Type::STK_BlockPointer:
5869       llvm_unreachable("valid complex int->pointer cast?");
5870     case Type::STK_MemberPointer:
5871       llvm_unreachable("member pointer type in C");
5872     }
5873     llvm_unreachable("Should have returned before this");
5874   }
5875
5876   llvm_unreachable("Unhandled scalar cast");
5877 }
5878
5879 static bool breakDownVectorType(QualType type, uint64_t &len,
5880                                 QualType &eltType) {
5881   // Vectors are simple.
5882   if (const VectorType *vecType = type->getAs<VectorType>()) {
5883     len = vecType->getNumElements();
5884     eltType = vecType->getElementType();
5885     assert(eltType->isScalarType());
5886     return true;
5887   }
5888   
5889   // We allow lax conversion to and from non-vector types, but only if
5890   // they're real types (i.e. non-complex, non-pointer scalar types).
5891   if (!type->isRealType()) return false;
5892   
5893   len = 1;
5894   eltType = type;
5895   return true;
5896 }
5897
5898 /// Are the two types lax-compatible vector types?  That is, given
5899 /// that one of them is a vector, do they have equal storage sizes,
5900 /// where the storage size is the number of elements times the element
5901 /// size?
5902 ///
5903 /// This will also return false if either of the types is neither a
5904 /// vector nor a real type.
5905 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5906   assert(destTy->isVectorType() || srcTy->isVectorType());
5907   
5908   // Disallow lax conversions between scalars and ExtVectors (these
5909   // conversions are allowed for other vector types because common headers
5910   // depend on them).  Most scalar OP ExtVector cases are handled by the
5911   // splat path anyway, which does what we want (convert, not bitcast).
5912   // What this rules out for ExtVectors is crazy things like char4*float.
5913   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5914   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5915
5916   uint64_t srcLen, destLen;
5917   QualType srcEltTy, destEltTy;
5918   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5919   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5920   
5921   // ASTContext::getTypeSize will return the size rounded up to a
5922   // power of 2, so instead of using that, we need to use the raw
5923   // element size multiplied by the element count.
5924   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5925   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5926   
5927   return (srcLen * srcEltSize == destLen * destEltSize);
5928 }
5929
5930 /// Is this a legal conversion between two types, one of which is
5931 /// known to be a vector type?
5932 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5933   assert(destTy->isVectorType() || srcTy->isVectorType());
5934   
5935   if (!Context.getLangOpts().LaxVectorConversions)
5936     return false;
5937   return areLaxCompatibleVectorTypes(srcTy, destTy);
5938 }
5939
5940 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5941                            CastKind &Kind) {
5942   assert(VectorTy->isVectorType() && "Not a vector type!");
5943
5944   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5945     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5946       return Diag(R.getBegin(),
5947                   Ty->isVectorType() ?
5948                   diag::err_invalid_conversion_between_vectors :
5949                   diag::err_invalid_conversion_between_vector_and_integer)
5950         << VectorTy << Ty << R;
5951   } else
5952     return Diag(R.getBegin(),
5953                 diag::err_invalid_conversion_between_vector_and_scalar)
5954       << VectorTy << Ty << R;
5955
5956   Kind = CK_BitCast;
5957   return false;
5958 }
5959
5960 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5961   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5962
5963   if (DestElemTy == SplattedExpr->getType())
5964     return SplattedExpr;
5965
5966   assert(DestElemTy->isFloatingType() ||
5967          DestElemTy->isIntegralOrEnumerationType());
5968
5969   CastKind CK;
5970   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5971     // OpenCL requires that we convert `true` boolean expressions to -1, but
5972     // only when splatting vectors.
5973     if (DestElemTy->isFloatingType()) {
5974       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5975       // in two steps: boolean to signed integral, then to floating.
5976       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5977                                                  CK_BooleanToSignedIntegral);
5978       SplattedExpr = CastExprRes.get();
5979       CK = CK_IntegralToFloating;
5980     } else {
5981       CK = CK_BooleanToSignedIntegral;
5982     }
5983   } else {
5984     ExprResult CastExprRes = SplattedExpr;
5985     CK = PrepareScalarCast(CastExprRes, DestElemTy);
5986     if (CastExprRes.isInvalid())
5987       return ExprError();
5988     SplattedExpr = CastExprRes.get();
5989   }
5990   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5991 }
5992
5993 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5994                                     Expr *CastExpr, CastKind &Kind) {
5995   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5996
5997   QualType SrcTy = CastExpr->getType();
5998
5999   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6000   // an ExtVectorType.
6001   // In OpenCL, casts between vectors of different types are not allowed.
6002   // (See OpenCL 6.2).
6003   if (SrcTy->isVectorType()) {
6004     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
6005         || (getLangOpts().OpenCL &&
6006             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
6007       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6008         << DestTy << SrcTy << R;
6009       return ExprError();
6010     }
6011     Kind = CK_BitCast;
6012     return CastExpr;
6013   }
6014
6015   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6016   // conversion will take place first from scalar to elt type, and then
6017   // splat from elt type to vector.
6018   if (SrcTy->isPointerType())
6019     return Diag(R.getBegin(),
6020                 diag::err_invalid_conversion_between_vector_and_scalar)
6021       << DestTy << SrcTy << R;
6022
6023   Kind = CK_VectorSplat;
6024   return prepareVectorSplat(DestTy, CastExpr);
6025 }
6026
6027 ExprResult
6028 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6029                     Declarator &D, ParsedType &Ty,
6030                     SourceLocation RParenLoc, Expr *CastExpr) {
6031   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6032          "ActOnCastExpr(): missing type or expr");
6033
6034   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6035   if (D.isInvalidType())
6036     return ExprError();
6037
6038   if (getLangOpts().CPlusPlus) {
6039     // Check that there are no default arguments (C++ only).
6040     CheckExtraCXXDefaultArguments(D);
6041   } else {
6042     // Make sure any TypoExprs have been dealt with.
6043     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6044     if (!Res.isUsable())
6045       return ExprError();
6046     CastExpr = Res.get();
6047   }
6048
6049   checkUnusedDeclAttributes(D);
6050
6051   QualType castType = castTInfo->getType();
6052   Ty = CreateParsedType(castType, castTInfo);
6053
6054   bool isVectorLiteral = false;
6055
6056   // Check for an altivec or OpenCL literal,
6057   // i.e. all the elements are integer constants.
6058   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6059   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6060   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6061        && castType->isVectorType() && (PE || PLE)) {
6062     if (PLE && PLE->getNumExprs() == 0) {
6063       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6064       return ExprError();
6065     }
6066     if (PE || PLE->getNumExprs() == 1) {
6067       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6068       if (!E->getType()->isVectorType())
6069         isVectorLiteral = true;
6070     }
6071     else
6072       isVectorLiteral = true;
6073   }
6074
6075   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6076   // then handle it as such.
6077   if (isVectorLiteral)
6078     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6079
6080   // If the Expr being casted is a ParenListExpr, handle it specially.
6081   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6082   // sequence of BinOp comma operators.
6083   if (isa<ParenListExpr>(CastExpr)) {
6084     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6085     if (Result.isInvalid()) return ExprError();
6086     CastExpr = Result.get();
6087   }
6088
6089   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6090       !getSourceManager().isInSystemMacro(LParenLoc))
6091     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6092   
6093   CheckTollFreeBridgeCast(castType, CastExpr);
6094   
6095   CheckObjCBridgeRelatedCast(castType, CastExpr);
6096
6097   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6098
6099   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6100 }
6101
6102 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6103                                     SourceLocation RParenLoc, Expr *E,
6104                                     TypeSourceInfo *TInfo) {
6105   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6106          "Expected paren or paren list expression");
6107
6108   Expr **exprs;
6109   unsigned numExprs;
6110   Expr *subExpr;
6111   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6112   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6113     LiteralLParenLoc = PE->getLParenLoc();
6114     LiteralRParenLoc = PE->getRParenLoc();
6115     exprs = PE->getExprs();
6116     numExprs = PE->getNumExprs();
6117   } else { // isa<ParenExpr> by assertion at function entrance
6118     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6119     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6120     subExpr = cast<ParenExpr>(E)->getSubExpr();
6121     exprs = &subExpr;
6122     numExprs = 1;
6123   }
6124
6125   QualType Ty = TInfo->getType();
6126   assert(Ty->isVectorType() && "Expected vector type");
6127
6128   SmallVector<Expr *, 8> initExprs;
6129   const VectorType *VTy = Ty->getAs<VectorType>();
6130   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6131   
6132   // '(...)' form of vector initialization in AltiVec: the number of
6133   // initializers must be one or must match the size of the vector.
6134   // If a single value is specified in the initializer then it will be
6135   // replicated to all the components of the vector
6136   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6137     // The number of initializers must be one or must match the size of the
6138     // vector. If a single value is specified in the initializer then it will
6139     // be replicated to all the components of the vector
6140     if (numExprs == 1) {
6141       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6142       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6143       if (Literal.isInvalid())
6144         return ExprError();
6145       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6146                                   PrepareScalarCast(Literal, ElemTy));
6147       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6148     }
6149     else if (numExprs < numElems) {
6150       Diag(E->getExprLoc(),
6151            diag::err_incorrect_number_of_vector_initializers);
6152       return ExprError();
6153     }
6154     else
6155       initExprs.append(exprs, exprs + numExprs);
6156   }
6157   else {
6158     // For OpenCL, when the number of initializers is a single value,
6159     // it will be replicated to all components of the vector.
6160     if (getLangOpts().OpenCL &&
6161         VTy->getVectorKind() == VectorType::GenericVector &&
6162         numExprs == 1) {
6163         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6164         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6165         if (Literal.isInvalid())
6166           return ExprError();
6167         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6168                                     PrepareScalarCast(Literal, ElemTy));
6169         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6170     }
6171     
6172     initExprs.append(exprs, exprs + numExprs);
6173   }
6174   // FIXME: This means that pretty-printing the final AST will produce curly
6175   // braces instead of the original commas.
6176   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6177                                                    initExprs, LiteralRParenLoc);
6178   initE->setType(Ty);
6179   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6180 }
6181
6182 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6183 /// the ParenListExpr into a sequence of comma binary operators.
6184 ExprResult
6185 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6186   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6187   if (!E)
6188     return OrigExpr;
6189
6190   ExprResult Result(E->getExpr(0));
6191
6192   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6193     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6194                         E->getExpr(i));
6195
6196   if (Result.isInvalid()) return ExprError();
6197
6198   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6199 }
6200
6201 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6202                                     SourceLocation R,
6203                                     MultiExprArg Val) {
6204   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6205   return expr;
6206 }
6207
6208 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6209 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6210 /// emitted.
6211 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6212                                       SourceLocation QuestionLoc) {
6213   Expr *NullExpr = LHSExpr;
6214   Expr *NonPointerExpr = RHSExpr;
6215   Expr::NullPointerConstantKind NullKind =
6216       NullExpr->isNullPointerConstant(Context,
6217                                       Expr::NPC_ValueDependentIsNotNull);
6218
6219   if (NullKind == Expr::NPCK_NotNull) {
6220     NullExpr = RHSExpr;
6221     NonPointerExpr = LHSExpr;
6222     NullKind =
6223         NullExpr->isNullPointerConstant(Context,
6224                                         Expr::NPC_ValueDependentIsNotNull);
6225   }
6226
6227   if (NullKind == Expr::NPCK_NotNull)
6228     return false;
6229
6230   if (NullKind == Expr::NPCK_ZeroExpression)
6231     return false;
6232
6233   if (NullKind == Expr::NPCK_ZeroLiteral) {
6234     // In this case, check to make sure that we got here from a "NULL"
6235     // string in the source code.
6236     NullExpr = NullExpr->IgnoreParenImpCasts();
6237     SourceLocation loc = NullExpr->getExprLoc();
6238     if (!findMacroSpelling(loc, "NULL"))
6239       return false;
6240   }
6241
6242   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6243   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6244       << NonPointerExpr->getType() << DiagType
6245       << NonPointerExpr->getSourceRange();
6246   return true;
6247 }
6248
6249 /// \brief Return false if the condition expression is valid, true otherwise.
6250 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6251   QualType CondTy = Cond->getType();
6252
6253   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6254   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6255     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6256       << CondTy << Cond->getSourceRange();
6257     return true;
6258   }
6259
6260   // C99 6.5.15p2
6261   if (CondTy->isScalarType()) return false;
6262
6263   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6264     << CondTy << Cond->getSourceRange();
6265   return true;
6266 }
6267
6268 /// \brief Handle when one or both operands are void type.
6269 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6270                                          ExprResult &RHS) {
6271     Expr *LHSExpr = LHS.get();
6272     Expr *RHSExpr = RHS.get();
6273
6274     if (!LHSExpr->getType()->isVoidType())
6275       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6276         << RHSExpr->getSourceRange();
6277     if (!RHSExpr->getType()->isVoidType())
6278       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6279         << LHSExpr->getSourceRange();
6280     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6281     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6282     return S.Context.VoidTy;
6283 }
6284
6285 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6286 /// true otherwise.
6287 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6288                                         QualType PointerTy) {
6289   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6290       !NullExpr.get()->isNullPointerConstant(S.Context,
6291                                             Expr::NPC_ValueDependentIsNull))
6292     return true;
6293
6294   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6295   return false;
6296 }
6297
6298 /// \brief Checks compatibility between two pointers and return the resulting
6299 /// type.
6300 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6301                                                      ExprResult &RHS,
6302                                                      SourceLocation Loc) {
6303   QualType LHSTy = LHS.get()->getType();
6304   QualType RHSTy = RHS.get()->getType();
6305
6306   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6307     // Two identical pointers types are always compatible.
6308     return LHSTy;
6309   }
6310
6311   QualType lhptee, rhptee;
6312
6313   // Get the pointee types.
6314   bool IsBlockPointer = false;
6315   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6316     lhptee = LHSBTy->getPointeeType();
6317     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6318     IsBlockPointer = true;
6319   } else {
6320     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6321     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6322   }
6323
6324   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6325   // differently qualified versions of compatible types, the result type is
6326   // a pointer to an appropriately qualified version of the composite
6327   // type.
6328
6329   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6330   // clause doesn't make sense for our extensions. E.g. address space 2 should
6331   // be incompatible with address space 3: they may live on different devices or
6332   // anything.
6333   Qualifiers lhQual = lhptee.getQualifiers();
6334   Qualifiers rhQual = rhptee.getQualifiers();
6335
6336   unsigned ResultAddrSpace = 0;
6337   unsigned LAddrSpace = lhQual.getAddressSpace();
6338   unsigned RAddrSpace = rhQual.getAddressSpace();
6339   if (S.getLangOpts().OpenCL) {
6340     // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6341     // spaces is disallowed.
6342     if (lhQual.isAddressSpaceSupersetOf(rhQual))
6343       ResultAddrSpace = LAddrSpace;
6344     else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6345       ResultAddrSpace = RAddrSpace;
6346     else {
6347       S.Diag(Loc,
6348              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6349           << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6350           << RHS.get()->getSourceRange();
6351       return QualType();
6352     }
6353   }
6354
6355   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6356   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6357   lhQual.removeCVRQualifiers();
6358   rhQual.removeCVRQualifiers();
6359
6360   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6361   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6362   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6363   // qual types are compatible iff
6364   //  * corresponded types are compatible
6365   //  * CVR qualifiers are equal
6366   //  * address spaces are equal
6367   // Thus for conditional operator we merge CVR and address space unqualified
6368   // pointees and if there is a composite type we return a pointer to it with
6369   // merged qualifiers.
6370   if (S.getLangOpts().OpenCL) {
6371     LHSCastKind = LAddrSpace == ResultAddrSpace
6372                       ? CK_BitCast
6373                       : CK_AddressSpaceConversion;
6374     RHSCastKind = RAddrSpace == ResultAddrSpace
6375                       ? CK_BitCast
6376                       : CK_AddressSpaceConversion;
6377     lhQual.removeAddressSpace();
6378     rhQual.removeAddressSpace();
6379   }
6380
6381   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6382   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6383
6384   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6385
6386   if (CompositeTy.isNull()) {
6387     // In this situation, we assume void* type. No especially good
6388     // reason, but this is what gcc does, and we do have to pick
6389     // to get a consistent AST.
6390     QualType incompatTy;
6391     incompatTy = S.Context.getPointerType(
6392         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6393     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6394     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6395     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6396     // for casts between types with incompatible address space qualifiers.
6397     // For the following code the compiler produces casts between global and
6398     // local address spaces of the corresponded innermost pointees:
6399     // local int *global *a;
6400     // global int *global *b;
6401     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6402     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6403         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6404         << RHS.get()->getSourceRange();
6405     return incompatTy;
6406   }
6407
6408   // The pointer types are compatible.
6409   // In case of OpenCL ResultTy should have the address space qualifier
6410   // which is a superset of address spaces of both the 2nd and the 3rd
6411   // operands of the conditional operator.
6412   QualType ResultTy = [&, ResultAddrSpace]() {
6413     if (S.getLangOpts().OpenCL) {
6414       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6415       CompositeQuals.setAddressSpace(ResultAddrSpace);
6416       return S.Context
6417           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6418           .withCVRQualifiers(MergedCVRQual);
6419     }
6420     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6421   }();
6422   if (IsBlockPointer)
6423     ResultTy = S.Context.getBlockPointerType(ResultTy);
6424   else
6425     ResultTy = S.Context.getPointerType(ResultTy);
6426
6427   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6428   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6429   return ResultTy;
6430 }
6431
6432 /// \brief Return the resulting type when the operands are both block pointers.
6433 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6434                                                           ExprResult &LHS,
6435                                                           ExprResult &RHS,
6436                                                           SourceLocation Loc) {
6437   QualType LHSTy = LHS.get()->getType();
6438   QualType RHSTy = RHS.get()->getType();
6439
6440   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6441     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6442       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6443       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6444       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6445       return destType;
6446     }
6447     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6448       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6449       << RHS.get()->getSourceRange();
6450     return QualType();
6451   }
6452
6453   // We have 2 block pointer types.
6454   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6455 }
6456
6457 /// \brief Return the resulting type when the operands are both pointers.
6458 static QualType
6459 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6460                                             ExprResult &RHS,
6461                                             SourceLocation Loc) {
6462   // get the pointer types
6463   QualType LHSTy = LHS.get()->getType();
6464   QualType RHSTy = RHS.get()->getType();
6465
6466   // get the "pointed to" types
6467   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6468   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6469
6470   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6471   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6472     // Figure out necessary qualifiers (C99 6.5.15p6)
6473     QualType destPointee
6474       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6475     QualType destType = S.Context.getPointerType(destPointee);
6476     // Add qualifiers if necessary.
6477     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6478     // Promote to void*.
6479     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6480     return destType;
6481   }
6482   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6483     QualType destPointee
6484       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6485     QualType destType = S.Context.getPointerType(destPointee);
6486     // Add qualifiers if necessary.
6487     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6488     // Promote to void*.
6489     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6490     return destType;
6491   }
6492
6493   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6494 }
6495
6496 /// \brief Return false if the first expression is not an integer and the second
6497 /// expression is not a pointer, true otherwise.
6498 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6499                                         Expr* PointerExpr, SourceLocation Loc,
6500                                         bool IsIntFirstExpr) {
6501   if (!PointerExpr->getType()->isPointerType() ||
6502       !Int.get()->getType()->isIntegerType())
6503     return false;
6504
6505   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6506   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6507
6508   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6509     << Expr1->getType() << Expr2->getType()
6510     << Expr1->getSourceRange() << Expr2->getSourceRange();
6511   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6512                             CK_IntegralToPointer);
6513   return true;
6514 }
6515
6516 /// \brief Simple conversion between integer and floating point types.
6517 ///
6518 /// Used when handling the OpenCL conditional operator where the
6519 /// condition is a vector while the other operands are scalar.
6520 ///
6521 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6522 /// types are either integer or floating type. Between the two
6523 /// operands, the type with the higher rank is defined as the "result
6524 /// type". The other operand needs to be promoted to the same type. No
6525 /// other type promotion is allowed. We cannot use
6526 /// UsualArithmeticConversions() for this purpose, since it always
6527 /// promotes promotable types.
6528 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6529                                             ExprResult &RHS,
6530                                             SourceLocation QuestionLoc) {
6531   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6532   if (LHS.isInvalid())
6533     return QualType();
6534   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6535   if (RHS.isInvalid())
6536     return QualType();
6537
6538   // For conversion purposes, we ignore any qualifiers.
6539   // For example, "const float" and "float" are equivalent.
6540   QualType LHSType =
6541     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6542   QualType RHSType =
6543     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6544
6545   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6546     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6547       << LHSType << LHS.get()->getSourceRange();
6548     return QualType();
6549   }
6550
6551   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6552     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6553       << RHSType << RHS.get()->getSourceRange();
6554     return QualType();
6555   }
6556
6557   // If both types are identical, no conversion is needed.
6558   if (LHSType == RHSType)
6559     return LHSType;
6560
6561   // Now handle "real" floating types (i.e. float, double, long double).
6562   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6563     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6564                                  /*IsCompAssign = */ false);
6565
6566   // Finally, we have two differing integer types.
6567   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6568   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6569 }
6570
6571 /// \brief Convert scalar operands to a vector that matches the
6572 ///        condition in length.
6573 ///
6574 /// Used when handling the OpenCL conditional operator where the
6575 /// condition is a vector while the other operands are scalar.
6576 ///
6577 /// We first compute the "result type" for the scalar operands
6578 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6579 /// into a vector of that type where the length matches the condition
6580 /// vector type. s6.11.6 requires that the element types of the result
6581 /// and the condition must have the same number of bits.
6582 static QualType
6583 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6584                               QualType CondTy, SourceLocation QuestionLoc) {
6585   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6586   if (ResTy.isNull()) return QualType();
6587
6588   const VectorType *CV = CondTy->getAs<VectorType>();
6589   assert(CV);
6590
6591   // Determine the vector result type
6592   unsigned NumElements = CV->getNumElements();
6593   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6594
6595   // Ensure that all types have the same number of bits
6596   if (S.Context.getTypeSize(CV->getElementType())
6597       != S.Context.getTypeSize(ResTy)) {
6598     // Since VectorTy is created internally, it does not pretty print
6599     // with an OpenCL name. Instead, we just print a description.
6600     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6601     SmallString<64> Str;
6602     llvm::raw_svector_ostream OS(Str);
6603     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6604     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6605       << CondTy << OS.str();
6606     return QualType();
6607   }
6608
6609   // Convert operands to the vector result type
6610   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6611   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6612
6613   return VectorTy;
6614 }
6615
6616 /// \brief Return false if this is a valid OpenCL condition vector
6617 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6618                                        SourceLocation QuestionLoc) {
6619   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6620   // integral type.
6621   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6622   assert(CondTy);
6623   QualType EleTy = CondTy->getElementType();
6624   if (EleTy->isIntegerType()) return false;
6625
6626   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6627     << Cond->getType() << Cond->getSourceRange();
6628   return true;
6629 }
6630
6631 /// \brief Return false if the vector condition type and the vector
6632 ///        result type are compatible.
6633 ///
6634 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6635 /// number of elements, and their element types have the same number
6636 /// of bits.
6637 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6638                               SourceLocation QuestionLoc) {
6639   const VectorType *CV = CondTy->getAs<VectorType>();
6640   const VectorType *RV = VecResTy->getAs<VectorType>();
6641   assert(CV && RV);
6642
6643   if (CV->getNumElements() != RV->getNumElements()) {
6644     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6645       << CondTy << VecResTy;
6646     return true;
6647   }
6648
6649   QualType CVE = CV->getElementType();
6650   QualType RVE = RV->getElementType();
6651
6652   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6653     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6654       << CondTy << VecResTy;
6655     return true;
6656   }
6657
6658   return false;
6659 }
6660
6661 /// \brief Return the resulting type for the conditional operator in
6662 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6663 ///        s6.3.i) when the condition is a vector type.
6664 static QualType
6665 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6666                              ExprResult &LHS, ExprResult &RHS,
6667                              SourceLocation QuestionLoc) {
6668   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 
6669   if (Cond.isInvalid())
6670     return QualType();
6671   QualType CondTy = Cond.get()->getType();
6672
6673   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6674     return QualType();
6675
6676   // If either operand is a vector then find the vector type of the
6677   // result as specified in OpenCL v1.1 s6.3.i.
6678   if (LHS.get()->getType()->isVectorType() ||
6679       RHS.get()->getType()->isVectorType()) {
6680     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6681                                               /*isCompAssign*/false,
6682                                               /*AllowBothBool*/true,
6683                                               /*AllowBoolConversions*/false);
6684     if (VecResTy.isNull()) return QualType();
6685     // The result type must match the condition type as specified in
6686     // OpenCL v1.1 s6.11.6.
6687     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6688       return QualType();
6689     return VecResTy;
6690   }
6691
6692   // Both operands are scalar.
6693   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6694 }
6695
6696 /// \brief Return true if the Expr is block type
6697 static bool checkBlockType(Sema &S, const Expr *E) {
6698   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6699     QualType Ty = CE->getCallee()->getType();
6700     if (Ty->isBlockPointerType()) {
6701       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6702       return true;
6703     }
6704   }
6705   return false;
6706 }
6707
6708 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6709 /// In that case, LHS = cond.
6710 /// C99 6.5.15
6711 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6712                                         ExprResult &RHS, ExprValueKind &VK,
6713                                         ExprObjectKind &OK,
6714                                         SourceLocation QuestionLoc) {
6715
6716   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6717   if (!LHSResult.isUsable()) return QualType();
6718   LHS = LHSResult;
6719
6720   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6721   if (!RHSResult.isUsable()) return QualType();
6722   RHS = RHSResult;
6723
6724   // C++ is sufficiently different to merit its own checker.
6725   if (getLangOpts().CPlusPlus)
6726     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6727
6728   VK = VK_RValue;
6729   OK = OK_Ordinary;
6730
6731   // The OpenCL operator with a vector condition is sufficiently
6732   // different to merit its own checker.
6733   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6734     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6735
6736   // First, check the condition.
6737   Cond = UsualUnaryConversions(Cond.get());
6738   if (Cond.isInvalid())
6739     return QualType();
6740   if (checkCondition(*this, Cond.get(), QuestionLoc))
6741     return QualType();
6742
6743   // Now check the two expressions.
6744   if (LHS.get()->getType()->isVectorType() ||
6745       RHS.get()->getType()->isVectorType())
6746     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6747                                /*AllowBothBool*/true,
6748                                /*AllowBoolConversions*/false);
6749
6750   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6751   if (LHS.isInvalid() || RHS.isInvalid())
6752     return QualType();
6753
6754   QualType LHSTy = LHS.get()->getType();
6755   QualType RHSTy = RHS.get()->getType();
6756
6757   // Diagnose attempts to convert between __float128 and long double where
6758   // such conversions currently can't be handled.
6759   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6760     Diag(QuestionLoc,
6761          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6762       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6763     return QualType();
6764   }
6765
6766   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6767   // selection operator (?:).
6768   if (getLangOpts().OpenCL &&
6769       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6770     return QualType();
6771   }
6772
6773   // If both operands have arithmetic type, do the usual arithmetic conversions
6774   // to find a common type: C99 6.5.15p3,5.
6775   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6776     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6777     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6778
6779     return ResTy;
6780   }
6781
6782   // If both operands are the same structure or union type, the result is that
6783   // type.
6784   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6785     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6786       if (LHSRT->getDecl() == RHSRT->getDecl())
6787         // "If both the operands have structure or union type, the result has
6788         // that type."  This implies that CV qualifiers are dropped.
6789         return LHSTy.getUnqualifiedType();
6790     // FIXME: Type of conditional expression must be complete in C mode.
6791   }
6792
6793   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6794   // The following || allows only one side to be void (a GCC-ism).
6795   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6796     return checkConditionalVoidType(*this, LHS, RHS);
6797   }
6798
6799   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6800   // the type of the other operand."
6801   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6802   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6803
6804   // All objective-c pointer type analysis is done here.
6805   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6806                                                         QuestionLoc);
6807   if (LHS.isInvalid() || RHS.isInvalid())
6808     return QualType();
6809   if (!compositeType.isNull())
6810     return compositeType;
6811
6812
6813   // Handle block pointer types.
6814   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6815     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6816                                                      QuestionLoc);
6817
6818   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6819   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6820     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6821                                                        QuestionLoc);
6822
6823   // GCC compatibility: soften pointer/integer mismatch.  Note that
6824   // null pointers have been filtered out by this point.
6825   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6826       /*isIntFirstExpr=*/true))
6827     return RHSTy;
6828   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6829       /*isIntFirstExpr=*/false))
6830     return LHSTy;
6831
6832   // Emit a better diagnostic if one of the expressions is a null pointer
6833   // constant and the other is not a pointer type. In this case, the user most
6834   // likely forgot to take the address of the other expression.
6835   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6836     return QualType();
6837
6838   // Otherwise, the operands are not compatible.
6839   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6840     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6841     << RHS.get()->getSourceRange();
6842   return QualType();
6843 }
6844
6845 /// FindCompositeObjCPointerType - Helper method to find composite type of
6846 /// two objective-c pointer types of the two input expressions.
6847 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6848                                             SourceLocation QuestionLoc) {
6849   QualType LHSTy = LHS.get()->getType();
6850   QualType RHSTy = RHS.get()->getType();
6851
6852   // Handle things like Class and struct objc_class*.  Here we case the result
6853   // to the pseudo-builtin, because that will be implicitly cast back to the
6854   // redefinition type if an attempt is made to access its fields.
6855   if (LHSTy->isObjCClassType() &&
6856       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6857     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6858     return LHSTy;
6859   }
6860   if (RHSTy->isObjCClassType() &&
6861       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6862     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6863     return RHSTy;
6864   }
6865   // And the same for struct objc_object* / id
6866   if (LHSTy->isObjCIdType() &&
6867       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6868     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6869     return LHSTy;
6870   }
6871   if (RHSTy->isObjCIdType() &&
6872       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6873     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6874     return RHSTy;
6875   }
6876   // And the same for struct objc_selector* / SEL
6877   if (Context.isObjCSelType(LHSTy) &&
6878       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6879     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6880     return LHSTy;
6881   }
6882   if (Context.isObjCSelType(RHSTy) &&
6883       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6884     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6885     return RHSTy;
6886   }
6887   // Check constraints for Objective-C object pointers types.
6888   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6889
6890     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6891       // Two identical object pointer types are always compatible.
6892       return LHSTy;
6893     }
6894     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6895     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6896     QualType compositeType = LHSTy;
6897
6898     // If both operands are interfaces and either operand can be
6899     // assigned to the other, use that type as the composite
6900     // type. This allows
6901     //   xxx ? (A*) a : (B*) b
6902     // where B is a subclass of A.
6903     //
6904     // Additionally, as for assignment, if either type is 'id'
6905     // allow silent coercion. Finally, if the types are
6906     // incompatible then make sure to use 'id' as the composite
6907     // type so the result is acceptable for sending messages to.
6908
6909     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6910     // It could return the composite type.
6911     if (!(compositeType =
6912           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6913       // Nothing more to do.
6914     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6915       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6916     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6917       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6918     } else if ((LHSTy->isObjCQualifiedIdType() ||
6919                 RHSTy->isObjCQualifiedIdType()) &&
6920                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6921       // Need to handle "id<xx>" explicitly.
6922       // GCC allows qualified id and any Objective-C type to devolve to
6923       // id. Currently localizing to here until clear this should be
6924       // part of ObjCQualifiedIdTypesAreCompatible.
6925       compositeType = Context.getObjCIdType();
6926     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6927       compositeType = Context.getObjCIdType();
6928     } else {
6929       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6930       << LHSTy << RHSTy
6931       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6932       QualType incompatTy = Context.getObjCIdType();
6933       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6934       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6935       return incompatTy;
6936     }
6937     // The object pointer types are compatible.
6938     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6939     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6940     return compositeType;
6941   }
6942   // Check Objective-C object pointer types and 'void *'
6943   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6944     if (getLangOpts().ObjCAutoRefCount) {
6945       // ARC forbids the implicit conversion of object pointers to 'void *',
6946       // so these types are not compatible.
6947       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6948           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6949       LHS = RHS = true;
6950       return QualType();
6951     }
6952     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6953     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6954     QualType destPointee
6955     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6956     QualType destType = Context.getPointerType(destPointee);
6957     // Add qualifiers if necessary.
6958     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6959     // Promote to void*.
6960     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6961     return destType;
6962   }
6963   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6964     if (getLangOpts().ObjCAutoRefCount) {
6965       // ARC forbids the implicit conversion of object pointers to 'void *',
6966       // so these types are not compatible.
6967       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6968           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6969       LHS = RHS = true;
6970       return QualType();
6971     }
6972     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6973     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6974     QualType destPointee
6975     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6976     QualType destType = Context.getPointerType(destPointee);
6977     // Add qualifiers if necessary.
6978     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6979     // Promote to void*.
6980     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6981     return destType;
6982   }
6983   return QualType();
6984 }
6985
6986 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6987 /// ParenRange in parentheses.
6988 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6989                                const PartialDiagnostic &Note,
6990                                SourceRange ParenRange) {
6991   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6992   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6993       EndLoc.isValid()) {
6994     Self.Diag(Loc, Note)
6995       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6996       << FixItHint::CreateInsertion(EndLoc, ")");
6997   } else {
6998     // We can't display the parentheses, so just show the bare note.
6999     Self.Diag(Loc, Note) << ParenRange;
7000   }
7001 }
7002
7003 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7004   return BinaryOperator::isAdditiveOp(Opc) ||
7005          BinaryOperator::isMultiplicativeOp(Opc) ||
7006          BinaryOperator::isShiftOp(Opc);
7007 }
7008
7009 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7010 /// expression, either using a built-in or overloaded operator,
7011 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7012 /// expression.
7013 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7014                                    Expr **RHSExprs) {
7015   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7016   E = E->IgnoreImpCasts();
7017   E = E->IgnoreConversionOperator();
7018   E = E->IgnoreImpCasts();
7019
7020   // Built-in binary operator.
7021   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7022     if (IsArithmeticOp(OP->getOpcode())) {
7023       *Opcode = OP->getOpcode();
7024       *RHSExprs = OP->getRHS();
7025       return true;
7026     }
7027   }
7028
7029   // Overloaded operator.
7030   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7031     if (Call->getNumArgs() != 2)
7032       return false;
7033
7034     // Make sure this is really a binary operator that is safe to pass into
7035     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7036     OverloadedOperatorKind OO = Call->getOperator();
7037     if (OO < OO_Plus || OO > OO_Arrow ||
7038         OO == OO_PlusPlus || OO == OO_MinusMinus)
7039       return false;
7040
7041     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7042     if (IsArithmeticOp(OpKind)) {
7043       *Opcode = OpKind;
7044       *RHSExprs = Call->getArg(1);
7045       return true;
7046     }
7047   }
7048
7049   return false;
7050 }
7051
7052 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7053 /// or is a logical expression such as (x==y) which has int type, but is
7054 /// commonly interpreted as boolean.
7055 static bool ExprLooksBoolean(Expr *E) {
7056   E = E->IgnoreParenImpCasts();
7057
7058   if (E->getType()->isBooleanType())
7059     return true;
7060   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7061     return OP->isComparisonOp() || OP->isLogicalOp();
7062   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7063     return OP->getOpcode() == UO_LNot;
7064   if (E->getType()->isPointerType())
7065     return true;
7066
7067   return false;
7068 }
7069
7070 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7071 /// and binary operator are mixed in a way that suggests the programmer assumed
7072 /// the conditional operator has higher precedence, for example:
7073 /// "int x = a + someBinaryCondition ? 1 : 2".
7074 static void DiagnoseConditionalPrecedence(Sema &Self,
7075                                           SourceLocation OpLoc,
7076                                           Expr *Condition,
7077                                           Expr *LHSExpr,
7078                                           Expr *RHSExpr) {
7079   BinaryOperatorKind CondOpcode;
7080   Expr *CondRHS;
7081
7082   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7083     return;
7084   if (!ExprLooksBoolean(CondRHS))
7085     return;
7086
7087   // The condition is an arithmetic binary expression, with a right-
7088   // hand side that looks boolean, so warn.
7089
7090   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7091       << Condition->getSourceRange()
7092       << BinaryOperator::getOpcodeStr(CondOpcode);
7093
7094   SuggestParentheses(Self, OpLoc,
7095     Self.PDiag(diag::note_precedence_silence)
7096       << BinaryOperator::getOpcodeStr(CondOpcode),
7097     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7098
7099   SuggestParentheses(Self, OpLoc,
7100     Self.PDiag(diag::note_precedence_conditional_first),
7101     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7102 }
7103
7104 /// Compute the nullability of a conditional expression.
7105 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7106                                               QualType LHSTy, QualType RHSTy,
7107                                               ASTContext &Ctx) {
7108   if (!ResTy->isAnyPointerType())
7109     return ResTy;
7110
7111   auto GetNullability = [&Ctx](QualType Ty) {
7112     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7113     if (Kind)
7114       return *Kind;
7115     return NullabilityKind::Unspecified;
7116   };
7117
7118   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7119   NullabilityKind MergedKind;
7120
7121   // Compute nullability of a binary conditional expression.
7122   if (IsBin) {
7123     if (LHSKind == NullabilityKind::NonNull)
7124       MergedKind = NullabilityKind::NonNull;
7125     else
7126       MergedKind = RHSKind;
7127   // Compute nullability of a normal conditional expression.
7128   } else {
7129     if (LHSKind == NullabilityKind::Nullable ||
7130         RHSKind == NullabilityKind::Nullable)
7131       MergedKind = NullabilityKind::Nullable;
7132     else if (LHSKind == NullabilityKind::NonNull)
7133       MergedKind = RHSKind;
7134     else if (RHSKind == NullabilityKind::NonNull)
7135       MergedKind = LHSKind;
7136     else
7137       MergedKind = NullabilityKind::Unspecified;
7138   }
7139
7140   // Return if ResTy already has the correct nullability.
7141   if (GetNullability(ResTy) == MergedKind)
7142     return ResTy;
7143
7144   // Strip all nullability from ResTy.
7145   while (ResTy->getNullability(Ctx))
7146     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7147
7148   // Create a new AttributedType with the new nullability kind.
7149   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7150   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7151 }
7152
7153 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7154 /// in the case of a the GNU conditional expr extension.
7155 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7156                                     SourceLocation ColonLoc,
7157                                     Expr *CondExpr, Expr *LHSExpr,
7158                                     Expr *RHSExpr) {
7159   if (!getLangOpts().CPlusPlus) {
7160     // C cannot handle TypoExpr nodes in the condition because it
7161     // doesn't handle dependent types properly, so make sure any TypoExprs have
7162     // been dealt with before checking the operands.
7163     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7164     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7165     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7166
7167     if (!CondResult.isUsable())
7168       return ExprError();
7169
7170     if (LHSExpr) {
7171       if (!LHSResult.isUsable())
7172         return ExprError();
7173     }
7174
7175     if (!RHSResult.isUsable())
7176       return ExprError();
7177
7178     CondExpr = CondResult.get();
7179     LHSExpr = LHSResult.get();
7180     RHSExpr = RHSResult.get();
7181   }
7182
7183   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7184   // was the condition.
7185   OpaqueValueExpr *opaqueValue = nullptr;
7186   Expr *commonExpr = nullptr;
7187   if (!LHSExpr) {
7188     commonExpr = CondExpr;
7189     // Lower out placeholder types first.  This is important so that we don't
7190     // try to capture a placeholder. This happens in few cases in C++; such
7191     // as Objective-C++'s dictionary subscripting syntax.
7192     if (commonExpr->hasPlaceholderType()) {
7193       ExprResult result = CheckPlaceholderExpr(commonExpr);
7194       if (!result.isUsable()) return ExprError();
7195       commonExpr = result.get();
7196     }
7197     // We usually want to apply unary conversions *before* saving, except
7198     // in the special case of a C++ l-value conditional.
7199     if (!(getLangOpts().CPlusPlus
7200           && !commonExpr->isTypeDependent()
7201           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7202           && commonExpr->isGLValue()
7203           && commonExpr->isOrdinaryOrBitFieldObject()
7204           && RHSExpr->isOrdinaryOrBitFieldObject()
7205           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7206       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7207       if (commonRes.isInvalid())
7208         return ExprError();
7209       commonExpr = commonRes.get();
7210     }
7211
7212     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7213                                                 commonExpr->getType(),
7214                                                 commonExpr->getValueKind(),
7215                                                 commonExpr->getObjectKind(),
7216                                                 commonExpr);
7217     LHSExpr = CondExpr = opaqueValue;
7218   }
7219
7220   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7221   ExprValueKind VK = VK_RValue;
7222   ExprObjectKind OK = OK_Ordinary;
7223   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7224   QualType result = CheckConditionalOperands(Cond, LHS, RHS, 
7225                                              VK, OK, QuestionLoc);
7226   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7227       RHS.isInvalid())
7228     return ExprError();
7229
7230   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7231                                 RHS.get());
7232
7233   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7234
7235   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7236                                          Context);
7237
7238   if (!commonExpr)
7239     return new (Context)
7240         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7241                             RHS.get(), result, VK, OK);
7242
7243   return new (Context) BinaryConditionalOperator(
7244       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7245       ColonLoc, result, VK, OK);
7246 }
7247
7248 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7249 // being closely modeled after the C99 spec:-). The odd characteristic of this
7250 // routine is it effectively iqnores the qualifiers on the top level pointee.
7251 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7252 // FIXME: add a couple examples in this comment.
7253 static Sema::AssignConvertType
7254 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7255   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7256   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7257
7258   // get the "pointed to" type (ignoring qualifiers at the top level)
7259   const Type *lhptee, *rhptee;
7260   Qualifiers lhq, rhq;
7261   std::tie(lhptee, lhq) =
7262       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7263   std::tie(rhptee, rhq) =
7264       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7265
7266   Sema::AssignConvertType ConvTy = Sema::Compatible;
7267
7268   // C99 6.5.16.1p1: This following citation is common to constraints
7269   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7270   // qualifiers of the type *pointed to* by the right;
7271
7272   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7273   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7274       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7275     // Ignore lifetime for further calculation.
7276     lhq.removeObjCLifetime();
7277     rhq.removeObjCLifetime();
7278   }
7279
7280   if (!lhq.compatiblyIncludes(rhq)) {
7281     // Treat address-space mismatches as fatal.  TODO: address subspaces
7282     if (!lhq.isAddressSpaceSupersetOf(rhq))
7283       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7284
7285     // It's okay to add or remove GC or lifetime qualifiers when converting to
7286     // and from void*.
7287     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7288                         .compatiblyIncludes(
7289                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7290              && (lhptee->isVoidType() || rhptee->isVoidType()))
7291       ; // keep old
7292
7293     // Treat lifetime mismatches as fatal.
7294     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7295       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7296     
7297     // For GCC/MS compatibility, other qualifier mismatches are treated
7298     // as still compatible in C.
7299     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7300   }
7301
7302   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7303   // incomplete type and the other is a pointer to a qualified or unqualified
7304   // version of void...
7305   if (lhptee->isVoidType()) {
7306     if (rhptee->isIncompleteOrObjectType())
7307       return ConvTy;
7308
7309     // As an extension, we allow cast to/from void* to function pointer.
7310     assert(rhptee->isFunctionType());
7311     return Sema::FunctionVoidPointer;
7312   }
7313
7314   if (rhptee->isVoidType()) {
7315     if (lhptee->isIncompleteOrObjectType())
7316       return ConvTy;
7317
7318     // As an extension, we allow cast to/from void* to function pointer.
7319     assert(lhptee->isFunctionType());
7320     return Sema::FunctionVoidPointer;
7321   }
7322
7323   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7324   // unqualified versions of compatible types, ...
7325   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7326   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7327     // Check if the pointee types are compatible ignoring the sign.
7328     // We explicitly check for char so that we catch "char" vs
7329     // "unsigned char" on systems where "char" is unsigned.
7330     if (lhptee->isCharType())
7331       ltrans = S.Context.UnsignedCharTy;
7332     else if (lhptee->hasSignedIntegerRepresentation())
7333       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7334
7335     if (rhptee->isCharType())
7336       rtrans = S.Context.UnsignedCharTy;
7337     else if (rhptee->hasSignedIntegerRepresentation())
7338       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7339
7340     if (ltrans == rtrans) {
7341       // Types are compatible ignoring the sign. Qualifier incompatibility
7342       // takes priority over sign incompatibility because the sign
7343       // warning can be disabled.
7344       if (ConvTy != Sema::Compatible)
7345         return ConvTy;
7346
7347       return Sema::IncompatiblePointerSign;
7348     }
7349
7350     // If we are a multi-level pointer, it's possible that our issue is simply
7351     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7352     // the eventual target type is the same and the pointers have the same
7353     // level of indirection, this must be the issue.
7354     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7355       do {
7356         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7357         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7358       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7359
7360       if (lhptee == rhptee)
7361         return Sema::IncompatibleNestedPointerQualifiers;
7362     }
7363
7364     // General pointer incompatibility takes priority over qualifiers.
7365     return Sema::IncompatiblePointer;
7366   }
7367   if (!S.getLangOpts().CPlusPlus &&
7368       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7369     return Sema::IncompatiblePointer;
7370   return ConvTy;
7371 }
7372
7373 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7374 /// block pointer types are compatible or whether a block and normal pointer
7375 /// are compatible. It is more restrict than comparing two function pointer
7376 // types.
7377 static Sema::AssignConvertType
7378 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7379                                     QualType RHSType) {
7380   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7381   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7382
7383   QualType lhptee, rhptee;
7384
7385   // get the "pointed to" type (ignoring qualifiers at the top level)
7386   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7387   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7388
7389   // In C++, the types have to match exactly.
7390   if (S.getLangOpts().CPlusPlus)
7391     return Sema::IncompatibleBlockPointer;
7392
7393   Sema::AssignConvertType ConvTy = Sema::Compatible;
7394
7395   // For blocks we enforce that qualifiers are identical.
7396   Qualifiers LQuals = lhptee.getLocalQualifiers();
7397   Qualifiers RQuals = rhptee.getLocalQualifiers();
7398   if (S.getLangOpts().OpenCL) {
7399     LQuals.removeAddressSpace();
7400     RQuals.removeAddressSpace();
7401   }
7402   if (LQuals != RQuals)
7403     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7404
7405   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7406   // assignment.
7407   // The current behavior is similar to C++ lambdas. A block might be
7408   // assigned to a variable iff its return type and parameters are compatible
7409   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7410   // an assignment. Presumably it should behave in way that a function pointer
7411   // assignment does in C, so for each parameter and return type:
7412   //  * CVR and address space of LHS should be a superset of CVR and address
7413   //  space of RHS.
7414   //  * unqualified types should be compatible.
7415   if (S.getLangOpts().OpenCL) {
7416     if (!S.Context.typesAreBlockPointerCompatible(
7417             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7418             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7419       return Sema::IncompatibleBlockPointer;
7420   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7421     return Sema::IncompatibleBlockPointer;
7422
7423   return ConvTy;
7424 }
7425
7426 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7427 /// for assignment compatibility.
7428 static Sema::AssignConvertType
7429 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7430                                    QualType RHSType) {
7431   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7432   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7433
7434   if (LHSType->isObjCBuiltinType()) {
7435     // Class is not compatible with ObjC object pointers.
7436     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7437         !RHSType->isObjCQualifiedClassType())
7438       return Sema::IncompatiblePointer;
7439     return Sema::Compatible;
7440   }
7441   if (RHSType->isObjCBuiltinType()) {
7442     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7443         !LHSType->isObjCQualifiedClassType())
7444       return Sema::IncompatiblePointer;
7445     return Sema::Compatible;
7446   }
7447   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7448   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7449
7450   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7451       // make an exception for id<P>
7452       !LHSType->isObjCQualifiedIdType())
7453     return Sema::CompatiblePointerDiscardsQualifiers;
7454
7455   if (S.Context.typesAreCompatible(LHSType, RHSType))
7456     return Sema::Compatible;
7457   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7458     return Sema::IncompatibleObjCQualifiedId;
7459   return Sema::IncompatiblePointer;
7460 }
7461
7462 Sema::AssignConvertType
7463 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7464                                  QualType LHSType, QualType RHSType) {
7465   // Fake up an opaque expression.  We don't actually care about what
7466   // cast operations are required, so if CheckAssignmentConstraints
7467   // adds casts to this they'll be wasted, but fortunately that doesn't
7468   // usually happen on valid code.
7469   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7470   ExprResult RHSPtr = &RHSExpr;
7471   CastKind K = CK_Invalid;
7472
7473   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7474 }
7475
7476 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7477 /// has code to accommodate several GCC extensions when type checking
7478 /// pointers. Here are some objectionable examples that GCC considers warnings:
7479 ///
7480 ///  int a, *pint;
7481 ///  short *pshort;
7482 ///  struct foo *pfoo;
7483 ///
7484 ///  pint = pshort; // warning: assignment from incompatible pointer type
7485 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7486 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7487 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7488 ///
7489 /// As a result, the code for dealing with pointers is more complex than the
7490 /// C99 spec dictates.
7491 ///
7492 /// Sets 'Kind' for any result kind except Incompatible.
7493 Sema::AssignConvertType
7494 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7495                                  CastKind &Kind, bool ConvertRHS) {
7496   QualType RHSType = RHS.get()->getType();
7497   QualType OrigLHSType = LHSType;
7498
7499   // Get canonical types.  We're not formatting these types, just comparing
7500   // them.
7501   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7502   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7503
7504   // Common case: no conversion required.
7505   if (LHSType == RHSType) {
7506     Kind = CK_NoOp;
7507     return Compatible;
7508   }
7509
7510   // If we have an atomic type, try a non-atomic assignment, then just add an
7511   // atomic qualification step.
7512   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7513     Sema::AssignConvertType result =
7514       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7515     if (result != Compatible)
7516       return result;
7517     if (Kind != CK_NoOp && ConvertRHS)
7518       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7519     Kind = CK_NonAtomicToAtomic;
7520     return Compatible;
7521   }
7522
7523   // If the left-hand side is a reference type, then we are in a
7524   // (rare!) case where we've allowed the use of references in C,
7525   // e.g., as a parameter type in a built-in function. In this case,
7526   // just make sure that the type referenced is compatible with the
7527   // right-hand side type. The caller is responsible for adjusting
7528   // LHSType so that the resulting expression does not have reference
7529   // type.
7530   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7531     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7532       Kind = CK_LValueBitCast;
7533       return Compatible;
7534     }
7535     return Incompatible;
7536   }
7537
7538   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7539   // to the same ExtVector type.
7540   if (LHSType->isExtVectorType()) {
7541     if (RHSType->isExtVectorType())
7542       return Incompatible;
7543     if (RHSType->isArithmeticType()) {
7544       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7545       if (ConvertRHS)
7546         RHS = prepareVectorSplat(LHSType, RHS.get());
7547       Kind = CK_VectorSplat;
7548       return Compatible;
7549     }
7550   }
7551
7552   // Conversions to or from vector type.
7553   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7554     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7555       // Allow assignments of an AltiVec vector type to an equivalent GCC
7556       // vector type and vice versa
7557       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7558         Kind = CK_BitCast;
7559         return Compatible;
7560       }
7561
7562       // If we are allowing lax vector conversions, and LHS and RHS are both
7563       // vectors, the total size only needs to be the same. This is a bitcast;
7564       // no bits are changed but the result type is different.
7565       if (isLaxVectorConversion(RHSType, LHSType)) {
7566         Kind = CK_BitCast;
7567         return IncompatibleVectors;
7568       }
7569     }
7570
7571     // When the RHS comes from another lax conversion (e.g. binops between
7572     // scalars and vectors) the result is canonicalized as a vector. When the
7573     // LHS is also a vector, the lax is allowed by the condition above. Handle
7574     // the case where LHS is a scalar.
7575     if (LHSType->isScalarType()) {
7576       const VectorType *VecType = RHSType->getAs<VectorType>();
7577       if (VecType && VecType->getNumElements() == 1 &&
7578           isLaxVectorConversion(RHSType, LHSType)) {
7579         ExprResult *VecExpr = &RHS;
7580         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7581         Kind = CK_BitCast;
7582         return Compatible;
7583       }
7584     }
7585
7586     return Incompatible;
7587   }
7588
7589   // Diagnose attempts to convert between __float128 and long double where
7590   // such conversions currently can't be handled.
7591   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7592     return Incompatible;
7593
7594   // Arithmetic conversions.
7595   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7596       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7597     if (ConvertRHS)
7598       Kind = PrepareScalarCast(RHS, LHSType);
7599     return Compatible;
7600   }
7601
7602   // Conversions to normal pointers.
7603   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7604     // U* -> T*
7605     if (isa<PointerType>(RHSType)) {
7606       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7607       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7608       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7609       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7610     }
7611
7612     // int -> T*
7613     if (RHSType->isIntegerType()) {
7614       Kind = CK_IntegralToPointer; // FIXME: null?
7615       return IntToPointer;
7616     }
7617
7618     // C pointers are not compatible with ObjC object pointers,
7619     // with two exceptions:
7620     if (isa<ObjCObjectPointerType>(RHSType)) {
7621       //  - conversions to void*
7622       if (LHSPointer->getPointeeType()->isVoidType()) {
7623         Kind = CK_BitCast;
7624         return Compatible;
7625       }
7626
7627       //  - conversions from 'Class' to the redefinition type
7628       if (RHSType->isObjCClassType() &&
7629           Context.hasSameType(LHSType, 
7630                               Context.getObjCClassRedefinitionType())) {
7631         Kind = CK_BitCast;
7632         return Compatible;
7633       }
7634
7635       Kind = CK_BitCast;
7636       return IncompatiblePointer;
7637     }
7638
7639     // U^ -> void*
7640     if (RHSType->getAs<BlockPointerType>()) {
7641       if (LHSPointer->getPointeeType()->isVoidType()) {
7642         unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7643         unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7644                                   ->getPointeeType()
7645                                   .getAddressSpace();
7646         Kind =
7647             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7648         return Compatible;
7649       }
7650     }
7651
7652     return Incompatible;
7653   }
7654
7655   // Conversions to block pointers.
7656   if (isa<BlockPointerType>(LHSType)) {
7657     // U^ -> T^
7658     if (RHSType->isBlockPointerType()) {
7659       unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>()
7660                                 ->getPointeeType()
7661                                 .getAddressSpace();
7662       unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7663                                 ->getPointeeType()
7664                                 .getAddressSpace();
7665       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7666       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7667     }
7668
7669     // int or null -> T^
7670     if (RHSType->isIntegerType()) {
7671       Kind = CK_IntegralToPointer; // FIXME: null
7672       return IntToBlockPointer;
7673     }
7674
7675     // id -> T^
7676     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7677       Kind = CK_AnyPointerToBlockPointerCast;
7678       return Compatible;
7679     }
7680
7681     // void* -> T^
7682     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7683       if (RHSPT->getPointeeType()->isVoidType()) {
7684         Kind = CK_AnyPointerToBlockPointerCast;
7685         return Compatible;
7686       }
7687
7688     return Incompatible;
7689   }
7690
7691   // Conversions to Objective-C pointers.
7692   if (isa<ObjCObjectPointerType>(LHSType)) {
7693     // A* -> B*
7694     if (RHSType->isObjCObjectPointerType()) {
7695       Kind = CK_BitCast;
7696       Sema::AssignConvertType result = 
7697         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7698       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7699           result == Compatible && 
7700           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7701         result = IncompatibleObjCWeakRef;
7702       return result;
7703     }
7704
7705     // int or null -> A*
7706     if (RHSType->isIntegerType()) {
7707       Kind = CK_IntegralToPointer; // FIXME: null
7708       return IntToPointer;
7709     }
7710
7711     // In general, C pointers are not compatible with ObjC object pointers,
7712     // with two exceptions:
7713     if (isa<PointerType>(RHSType)) {
7714       Kind = CK_CPointerToObjCPointerCast;
7715
7716       //  - conversions from 'void*'
7717       if (RHSType->isVoidPointerType()) {
7718         return Compatible;
7719       }
7720
7721       //  - conversions to 'Class' from its redefinition type
7722       if (LHSType->isObjCClassType() &&
7723           Context.hasSameType(RHSType, 
7724                               Context.getObjCClassRedefinitionType())) {
7725         return Compatible;
7726       }
7727
7728       return IncompatiblePointer;
7729     }
7730
7731     // Only under strict condition T^ is compatible with an Objective-C pointer.
7732     if (RHSType->isBlockPointerType() && 
7733         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7734       if (ConvertRHS)
7735         maybeExtendBlockObject(RHS);
7736       Kind = CK_BlockPointerToObjCPointerCast;
7737       return Compatible;
7738     }
7739
7740     return Incompatible;
7741   }
7742
7743   // Conversions from pointers that are not covered by the above.
7744   if (isa<PointerType>(RHSType)) {
7745     // T* -> _Bool
7746     if (LHSType == Context.BoolTy) {
7747       Kind = CK_PointerToBoolean;
7748       return Compatible;
7749     }
7750
7751     // T* -> int
7752     if (LHSType->isIntegerType()) {
7753       Kind = CK_PointerToIntegral;
7754       return PointerToInt;
7755     }
7756
7757     return Incompatible;
7758   }
7759
7760   // Conversions from Objective-C pointers that are not covered by the above.
7761   if (isa<ObjCObjectPointerType>(RHSType)) {
7762     // T* -> _Bool
7763     if (LHSType == Context.BoolTy) {
7764       Kind = CK_PointerToBoolean;
7765       return Compatible;
7766     }
7767
7768     // T* -> int
7769     if (LHSType->isIntegerType()) {
7770       Kind = CK_PointerToIntegral;
7771       return PointerToInt;
7772     }
7773
7774     return Incompatible;
7775   }
7776
7777   // struct A -> struct B
7778   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7779     if (Context.typesAreCompatible(LHSType, RHSType)) {
7780       Kind = CK_NoOp;
7781       return Compatible;
7782     }
7783   }
7784
7785   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7786     Kind = CK_IntToOCLSampler;
7787     return Compatible;
7788   }
7789
7790   return Incompatible;
7791 }
7792
7793 /// \brief Constructs a transparent union from an expression that is
7794 /// used to initialize the transparent union.
7795 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7796                                       ExprResult &EResult, QualType UnionType,
7797                                       FieldDecl *Field) {
7798   // Build an initializer list that designates the appropriate member
7799   // of the transparent union.
7800   Expr *E = EResult.get();
7801   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7802                                                    E, SourceLocation());
7803   Initializer->setType(UnionType);
7804   Initializer->setInitializedFieldInUnion(Field);
7805
7806   // Build a compound literal constructing a value of the transparent
7807   // union type from this initializer list.
7808   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7809   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7810                                         VK_RValue, Initializer, false);
7811 }
7812
7813 Sema::AssignConvertType
7814 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7815                                                ExprResult &RHS) {
7816   QualType RHSType = RHS.get()->getType();
7817
7818   // If the ArgType is a Union type, we want to handle a potential
7819   // transparent_union GCC extension.
7820   const RecordType *UT = ArgType->getAsUnionType();
7821   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7822     return Incompatible;
7823
7824   // The field to initialize within the transparent union.
7825   RecordDecl *UD = UT->getDecl();
7826   FieldDecl *InitField = nullptr;
7827   // It's compatible if the expression matches any of the fields.
7828   for (auto *it : UD->fields()) {
7829     if (it->getType()->isPointerType()) {
7830       // If the transparent union contains a pointer type, we allow:
7831       // 1) void pointer
7832       // 2) null pointer constant
7833       if (RHSType->isPointerType())
7834         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7835           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7836           InitField = it;
7837           break;
7838         }
7839
7840       if (RHS.get()->isNullPointerConstant(Context,
7841                                            Expr::NPC_ValueDependentIsNull)) {
7842         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7843                                 CK_NullToPointer);
7844         InitField = it;
7845         break;
7846       }
7847     }
7848
7849     CastKind Kind = CK_Invalid;
7850     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7851           == Compatible) {
7852       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7853       InitField = it;
7854       break;
7855     }
7856   }
7857
7858   if (!InitField)
7859     return Incompatible;
7860
7861   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7862   return Compatible;
7863 }
7864
7865 Sema::AssignConvertType
7866 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7867                                        bool Diagnose,
7868                                        bool DiagnoseCFAudited,
7869                                        bool ConvertRHS) {
7870   // We need to be able to tell the caller whether we diagnosed a problem, if
7871   // they ask us to issue diagnostics.
7872   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7873
7874   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7875   // we can't avoid *all* modifications at the moment, so we need some somewhere
7876   // to put the updated value.
7877   ExprResult LocalRHS = CallerRHS;
7878   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7879
7880   if (getLangOpts().CPlusPlus) {
7881     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7882       // C++ 5.17p3: If the left operand is not of class type, the
7883       // expression is implicitly converted (C++ 4) to the
7884       // cv-unqualified type of the left operand.
7885       QualType RHSType = RHS.get()->getType();
7886       if (Diagnose) {
7887         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7888                                         AA_Assigning);
7889       } else {
7890         ImplicitConversionSequence ICS =
7891             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7892                                   /*SuppressUserConversions=*/false,
7893                                   /*AllowExplicit=*/false,
7894                                   /*InOverloadResolution=*/false,
7895                                   /*CStyle=*/false,
7896                                   /*AllowObjCWritebackConversion=*/false);
7897         if (ICS.isFailure())
7898           return Incompatible;
7899         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7900                                         ICS, AA_Assigning);
7901       }
7902       if (RHS.isInvalid())
7903         return Incompatible;
7904       Sema::AssignConvertType result = Compatible;
7905       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7906           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7907         result = IncompatibleObjCWeakRef;
7908       return result;
7909     }
7910
7911     // FIXME: Currently, we fall through and treat C++ classes like C
7912     // structures.
7913     // FIXME: We also fall through for atomics; not sure what should
7914     // happen there, though.
7915   } else if (RHS.get()->getType() == Context.OverloadTy) {
7916     // As a set of extensions to C, we support overloading on functions. These
7917     // functions need to be resolved here.
7918     DeclAccessPair DAP;
7919     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7920             RHS.get(), LHSType, /*Complain=*/false, DAP))
7921       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7922     else
7923       return Incompatible;
7924   }
7925
7926   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7927   // a null pointer constant.
7928   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7929        LHSType->isBlockPointerType()) &&
7930       RHS.get()->isNullPointerConstant(Context,
7931                                        Expr::NPC_ValueDependentIsNull)) {
7932     if (Diagnose || ConvertRHS) {
7933       CastKind Kind;
7934       CXXCastPath Path;
7935       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7936                              /*IgnoreBaseAccess=*/false, Diagnose);
7937       if (ConvertRHS)
7938         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7939     }
7940     return Compatible;
7941   }
7942
7943   // This check seems unnatural, however it is necessary to ensure the proper
7944   // conversion of functions/arrays. If the conversion were done for all
7945   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7946   // expressions that suppress this implicit conversion (&, sizeof).
7947   //
7948   // Suppress this for references: C++ 8.5.3p5.
7949   if (!LHSType->isReferenceType()) {
7950     // FIXME: We potentially allocate here even if ConvertRHS is false.
7951     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7952     if (RHS.isInvalid())
7953       return Incompatible;
7954   }
7955
7956   Expr *PRE = RHS.get()->IgnoreParenCasts();
7957   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7958     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7959     if (PDecl && !PDecl->hasDefinition()) {
7960       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7961       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7962     }
7963   }
7964   
7965   CastKind Kind = CK_Invalid;
7966   Sema::AssignConvertType result =
7967     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7968
7969   // C99 6.5.16.1p2: The value of the right operand is converted to the
7970   // type of the assignment expression.
7971   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7972   // so that we can use references in built-in functions even in C.
7973   // The getNonReferenceType() call makes sure that the resulting expression
7974   // does not have reference type.
7975   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7976     QualType Ty = LHSType.getNonLValueExprType(Context);
7977     Expr *E = RHS.get();
7978
7979     // Check for various Objective-C errors. If we are not reporting
7980     // diagnostics and just checking for errors, e.g., during overload
7981     // resolution, return Incompatible to indicate the failure.
7982     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7983         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7984                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
7985       if (!Diagnose)
7986         return Incompatible;
7987     }
7988     if (getLangOpts().ObjC1 &&
7989         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7990                                            E->getType(), E, Diagnose) ||
7991          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7992       if (!Diagnose)
7993         return Incompatible;
7994       // Replace the expression with a corrected version and continue so we
7995       // can find further errors.
7996       RHS = E;
7997       return Compatible;
7998     }
7999     
8000     if (ConvertRHS)
8001       RHS = ImpCastExprToType(E, Ty, Kind);
8002   }
8003   return result;
8004 }
8005
8006 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8007                                ExprResult &RHS) {
8008   Diag(Loc, diag::err_typecheck_invalid_operands)
8009     << LHS.get()->getType() << RHS.get()->getType()
8010     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8011   return QualType();
8012 }
8013
8014 // Diagnose cases where a scalar was implicitly converted to a vector and
8015 // diagnose the underlying types. Otherwise, diagnose the error
8016 // as invalid vector logical operands for non-C++ cases.
8017 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8018                                             ExprResult &RHS) {
8019   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8020   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8021
8022   bool LHSNatVec = LHSType->isVectorType();
8023   bool RHSNatVec = RHSType->isVectorType();
8024
8025   if (!(LHSNatVec && RHSNatVec)) {
8026     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8027     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8028     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8029         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8030         << Vector->getSourceRange();
8031     return QualType();
8032   }
8033
8034   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8035       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8036       << RHS.get()->getSourceRange();
8037
8038   return QualType();
8039 }
8040
8041 /// Try to convert a value of non-vector type to a vector type by converting
8042 /// the type to the element type of the vector and then performing a splat.
8043 /// If the language is OpenCL, we only use conversions that promote scalar
8044 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8045 /// for float->int.
8046 ///
8047 /// OpenCL V2.0 6.2.6.p2:
8048 /// An error shall occur if any scalar operand type has greater rank
8049 /// than the type of the vector element.
8050 ///
8051 /// \param scalar - if non-null, actually perform the conversions
8052 /// \return true if the operation fails (but without diagnosing the failure)
8053 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8054                                      QualType scalarTy,
8055                                      QualType vectorEltTy,
8056                                      QualType vectorTy,
8057                                      unsigned &DiagID) {
8058   // The conversion to apply to the scalar before splatting it,
8059   // if necessary.
8060   CastKind scalarCast = CK_Invalid;
8061   
8062   if (vectorEltTy->isIntegralType(S.Context)) {
8063     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8064         (scalarTy->isIntegerType() &&
8065          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8066       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8067       return true;
8068     }
8069     if (!scalarTy->isIntegralType(S.Context))
8070       return true;
8071     scalarCast = CK_IntegralCast;
8072   } else if (vectorEltTy->isRealFloatingType()) {
8073     if (scalarTy->isRealFloatingType()) {
8074       if (S.getLangOpts().OpenCL &&
8075           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8076         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8077         return true;
8078       }
8079       scalarCast = CK_FloatingCast;
8080     }
8081     else if (scalarTy->isIntegralType(S.Context))
8082       scalarCast = CK_IntegralToFloating;
8083     else
8084       return true;
8085   } else {
8086     return true;
8087   }
8088
8089   // Adjust scalar if desired.
8090   if (scalar) {
8091     if (scalarCast != CK_Invalid)
8092       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8093     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8094   }
8095   return false;
8096 }
8097
8098 /// Test if a (constant) integer Int can be casted to another integer type
8099 /// IntTy without losing precision.
8100 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8101                                       QualType OtherIntTy) {
8102   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8103
8104   // Reject cases where the value of the Int is unknown as that would
8105   // possibly cause truncation, but accept cases where the scalar can be
8106   // demoted without loss of precision.
8107   llvm::APSInt Result;
8108   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8109   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8110   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8111   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8112
8113   if (CstInt) {
8114     // If the scalar is constant and is of a higher order and has more active
8115     // bits that the vector element type, reject it.
8116     unsigned NumBits = IntSigned
8117                            ? (Result.isNegative() ? Result.getMinSignedBits()
8118                                                   : Result.getActiveBits())
8119                            : Result.getActiveBits();
8120     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8121       return true;
8122
8123     // If the signedness of the scalar type and the vector element type
8124     // differs and the number of bits is greater than that of the vector
8125     // element reject it.
8126     return (IntSigned != OtherIntSigned &&
8127             NumBits > S.Context.getIntWidth(OtherIntTy));
8128   }
8129
8130   // Reject cases where the value of the scalar is not constant and it's
8131   // order is greater than that of the vector element type.
8132   return (Order < 0);
8133 }
8134
8135 /// Test if a (constant) integer Int can be casted to floating point type
8136 /// FloatTy without losing precision.
8137 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8138                                      QualType FloatTy) {
8139   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8140
8141   // Determine if the integer constant can be expressed as a floating point
8142   // number of the appropiate type.
8143   llvm::APSInt Result;
8144   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8145   uint64_t Bits = 0;
8146   if (CstInt) {
8147     // Reject constants that would be truncated if they were converted to
8148     // the floating point type. Test by simple to/from conversion.
8149     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8150     //        could be avoided if there was a convertFromAPInt method
8151     //        which could signal back if implicit truncation occurred.
8152     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8153     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8154                            llvm::APFloat::rmTowardZero);
8155     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8156                              !IntTy->hasSignedIntegerRepresentation());
8157     bool Ignored = false;
8158     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8159                            &Ignored);
8160     if (Result != ConvertBack)
8161       return true;
8162   } else {
8163     // Reject types that cannot be fully encoded into the mantissa of
8164     // the float.
8165     Bits = S.Context.getTypeSize(IntTy);
8166     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8167         S.Context.getFloatTypeSemantics(FloatTy));
8168     if (Bits > FloatPrec)
8169       return true;
8170   }
8171
8172   return false;
8173 }
8174
8175 /// Attempt to convert and splat Scalar into a vector whose types matches
8176 /// Vector following GCC conversion rules. The rule is that implicit
8177 /// conversion can occur when Scalar can be casted to match Vector's element
8178 /// type without causing truncation of Scalar.
8179 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8180                                         ExprResult *Vector) {
8181   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8182   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8183   const VectorType *VT = VectorTy->getAs<VectorType>();
8184
8185   assert(!isa<ExtVectorType>(VT) &&
8186          "ExtVectorTypes should not be handled here!");
8187
8188   QualType VectorEltTy = VT->getElementType();
8189
8190   // Reject cases where the vector element type or the scalar element type are
8191   // not integral or floating point types.
8192   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8193     return true;
8194
8195   // The conversion to apply to the scalar before splatting it,
8196   // if necessary.
8197   CastKind ScalarCast = CK_NoOp;
8198
8199   // Accept cases where the vector elements are integers and the scalar is
8200   // an integer.
8201   // FIXME: Notionally if the scalar was a floating point value with a precise
8202   //        integral representation, we could cast it to an appropriate integer
8203   //        type and then perform the rest of the checks here. GCC will perform
8204   //        this conversion in some cases as determined by the input language.
8205   //        We should accept it on a language independent basis.
8206   if (VectorEltTy->isIntegralType(S.Context) &&
8207       ScalarTy->isIntegralType(S.Context) &&
8208       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8209
8210     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8211       return true;
8212
8213     ScalarCast = CK_IntegralCast;
8214   } else if (VectorEltTy->isRealFloatingType()) {
8215     if (ScalarTy->isRealFloatingType()) {
8216
8217       // Reject cases where the scalar type is not a constant and has a higher
8218       // Order than the vector element type.
8219       llvm::APFloat Result(0.0);
8220       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8221       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8222       if (!CstScalar && Order < 0)
8223         return true;
8224
8225       // If the scalar cannot be safely casted to the vector element type,
8226       // reject it.
8227       if (CstScalar) {
8228         bool Truncated = false;
8229         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8230                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8231         if (Truncated)
8232           return true;
8233       }
8234
8235       ScalarCast = CK_FloatingCast;
8236     } else if (ScalarTy->isIntegralType(S.Context)) {
8237       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8238         return true;
8239
8240       ScalarCast = CK_IntegralToFloating;
8241     } else
8242       return true;
8243   }
8244
8245   // Adjust scalar if desired.
8246   if (Scalar) {
8247     if (ScalarCast != CK_NoOp)
8248       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8249     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8250   }
8251   return false;
8252 }
8253
8254 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8255                                    SourceLocation Loc, bool IsCompAssign,
8256                                    bool AllowBothBool,
8257                                    bool AllowBoolConversions) {
8258   if (!IsCompAssign) {
8259     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8260     if (LHS.isInvalid())
8261       return QualType();
8262   }
8263   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8264   if (RHS.isInvalid())
8265     return QualType();
8266
8267   // For conversion purposes, we ignore any qualifiers.
8268   // For example, "const float" and "float" are equivalent.
8269   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8270   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8271
8272   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8273   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8274   assert(LHSVecType || RHSVecType);
8275
8276   // AltiVec-style "vector bool op vector bool" combinations are allowed
8277   // for some operators but not others.
8278   if (!AllowBothBool &&
8279       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8280       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8281     return InvalidOperands(Loc, LHS, RHS);
8282
8283   // If the vector types are identical, return.
8284   if (Context.hasSameType(LHSType, RHSType))
8285     return LHSType;
8286
8287   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8288   if (LHSVecType && RHSVecType &&
8289       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8290     if (isa<ExtVectorType>(LHSVecType)) {
8291       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8292       return LHSType;
8293     }
8294
8295     if (!IsCompAssign)
8296       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8297     return RHSType;
8298   }
8299
8300   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8301   // can be mixed, with the result being the non-bool type.  The non-bool
8302   // operand must have integer element type.
8303   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8304       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8305       (Context.getTypeSize(LHSVecType->getElementType()) ==
8306        Context.getTypeSize(RHSVecType->getElementType()))) {
8307     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8308         LHSVecType->getElementType()->isIntegerType() &&
8309         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8310       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8311       return LHSType;
8312     }
8313     if (!IsCompAssign &&
8314         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8315         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8316         RHSVecType->getElementType()->isIntegerType()) {
8317       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8318       return RHSType;
8319     }
8320   }
8321
8322   // If there's a vector type and a scalar, try to convert the scalar to
8323   // the vector element type and splat.
8324   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8325   if (!RHSVecType) {
8326     if (isa<ExtVectorType>(LHSVecType)) {
8327       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8328                                     LHSVecType->getElementType(), LHSType,
8329                                     DiagID))
8330         return LHSType;
8331     } else {
8332       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8333         return LHSType;
8334     }
8335   }
8336   if (!LHSVecType) {
8337     if (isa<ExtVectorType>(RHSVecType)) {
8338       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8339                                     LHSType, RHSVecType->getElementType(),
8340                                     RHSType, DiagID))
8341         return RHSType;
8342     } else {
8343       if (LHS.get()->getValueKind() == VK_LValue ||
8344           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8345         return RHSType;
8346     }
8347   }
8348
8349   // FIXME: The code below also handles conversion between vectors and
8350   // non-scalars, we should break this down into fine grained specific checks
8351   // and emit proper diagnostics.
8352   QualType VecType = LHSVecType ? LHSType : RHSType;
8353   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8354   QualType OtherType = LHSVecType ? RHSType : LHSType;
8355   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8356   if (isLaxVectorConversion(OtherType, VecType)) {
8357     // If we're allowing lax vector conversions, only the total (data) size
8358     // needs to be the same. For non compound assignment, if one of the types is
8359     // scalar, the result is always the vector type.
8360     if (!IsCompAssign) {
8361       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8362       return VecType;
8363     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8364     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8365     // type. Note that this is already done by non-compound assignments in
8366     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8367     // <1 x T> -> T. The result is also a vector type.
8368     } else if (OtherType->isExtVectorType() ||
8369                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8370       ExprResult *RHSExpr = &RHS;
8371       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8372       return VecType;
8373     }
8374   }
8375
8376   // Okay, the expression is invalid.
8377
8378   // If there's a non-vector, non-real operand, diagnose that.
8379   if ((!RHSVecType && !RHSType->isRealType()) ||
8380       (!LHSVecType && !LHSType->isRealType())) {
8381     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8382       << LHSType << RHSType
8383       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8384     return QualType();
8385   }
8386
8387   // OpenCL V1.1 6.2.6.p1:
8388   // If the operands are of more than one vector type, then an error shall
8389   // occur. Implicit conversions between vector types are not permitted, per
8390   // section 6.2.1.
8391   if (getLangOpts().OpenCL &&
8392       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8393       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8394     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8395                                                            << RHSType;
8396     return QualType();
8397   }
8398
8399
8400   // If there is a vector type that is not a ExtVector and a scalar, we reach
8401   // this point if scalar could not be converted to the vector's element type
8402   // without truncation.
8403   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8404       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8405     QualType Scalar = LHSVecType ? RHSType : LHSType;
8406     QualType Vector = LHSVecType ? LHSType : RHSType;
8407     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8408     Diag(Loc,
8409          diag::err_typecheck_vector_not_convertable_implict_truncation)
8410         << ScalarOrVector << Scalar << Vector;
8411
8412     return QualType();
8413   }
8414
8415   // Otherwise, use the generic diagnostic.
8416   Diag(Loc, DiagID)
8417     << LHSType << RHSType
8418     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8419   return QualType();
8420 }
8421
8422 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8423 // expression.  These are mainly cases where the null pointer is used as an
8424 // integer instead of a pointer.
8425 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8426                                 SourceLocation Loc, bool IsCompare) {
8427   // The canonical way to check for a GNU null is with isNullPointerConstant,
8428   // but we use a bit of a hack here for speed; this is a relatively
8429   // hot path, and isNullPointerConstant is slow.
8430   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8431   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8432
8433   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8434
8435   // Avoid analyzing cases where the result will either be invalid (and
8436   // diagnosed as such) or entirely valid and not something to warn about.
8437   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8438       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8439     return;
8440
8441   // Comparison operations would not make sense with a null pointer no matter
8442   // what the other expression is.
8443   if (!IsCompare) {
8444     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8445         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8446         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8447     return;
8448   }
8449
8450   // The rest of the operations only make sense with a null pointer
8451   // if the other expression is a pointer.
8452   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8453       NonNullType->canDecayToPointerType())
8454     return;
8455
8456   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8457       << LHSNull /* LHS is NULL */ << NonNullType
8458       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8459 }
8460
8461 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8462                                                ExprResult &RHS,
8463                                                SourceLocation Loc, bool IsDiv) {
8464   // Check for division/remainder by zero.
8465   llvm::APSInt RHSValue;
8466   if (!RHS.get()->isValueDependent() &&
8467       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8468     S.DiagRuntimeBehavior(Loc, RHS.get(),
8469                           S.PDiag(diag::warn_remainder_division_by_zero)
8470                             << IsDiv << RHS.get()->getSourceRange());
8471 }
8472
8473 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8474                                            SourceLocation Loc,
8475                                            bool IsCompAssign, bool IsDiv) {
8476   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8477
8478   if (LHS.get()->getType()->isVectorType() ||
8479       RHS.get()->getType()->isVectorType())
8480     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8481                                /*AllowBothBool*/getLangOpts().AltiVec,
8482                                /*AllowBoolConversions*/false);
8483
8484   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8485   if (LHS.isInvalid() || RHS.isInvalid())
8486     return QualType();
8487
8488
8489   if (compType.isNull() || !compType->isArithmeticType())
8490     return InvalidOperands(Loc, LHS, RHS);
8491   if (IsDiv)
8492     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8493   return compType;
8494 }
8495
8496 QualType Sema::CheckRemainderOperands(
8497   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8498   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8499
8500   if (LHS.get()->getType()->isVectorType() ||
8501       RHS.get()->getType()->isVectorType()) {
8502     if (LHS.get()->getType()->hasIntegerRepresentation() && 
8503         RHS.get()->getType()->hasIntegerRepresentation())
8504       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8505                                  /*AllowBothBool*/getLangOpts().AltiVec,
8506                                  /*AllowBoolConversions*/false);
8507     return InvalidOperands(Loc, LHS, RHS);
8508   }
8509
8510   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8511   if (LHS.isInvalid() || RHS.isInvalid())
8512     return QualType();
8513
8514   if (compType.isNull() || !compType->isIntegerType())
8515     return InvalidOperands(Loc, LHS, RHS);
8516   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8517   return compType;
8518 }
8519
8520 /// \brief Diagnose invalid arithmetic on two void pointers.
8521 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8522                                                 Expr *LHSExpr, Expr *RHSExpr) {
8523   S.Diag(Loc, S.getLangOpts().CPlusPlus
8524                 ? diag::err_typecheck_pointer_arith_void_type
8525                 : diag::ext_gnu_void_ptr)
8526     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8527                             << RHSExpr->getSourceRange();
8528 }
8529
8530 /// \brief Diagnose invalid arithmetic on a void pointer.
8531 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8532                                             Expr *Pointer) {
8533   S.Diag(Loc, S.getLangOpts().CPlusPlus
8534                 ? diag::err_typecheck_pointer_arith_void_type
8535                 : diag::ext_gnu_void_ptr)
8536     << 0 /* one pointer */ << Pointer->getSourceRange();
8537 }
8538
8539 /// \brief Diagnose invalid arithmetic on two function pointers.
8540 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8541                                                     Expr *LHS, Expr *RHS) {
8542   assert(LHS->getType()->isAnyPointerType());
8543   assert(RHS->getType()->isAnyPointerType());
8544   S.Diag(Loc, S.getLangOpts().CPlusPlus
8545                 ? diag::err_typecheck_pointer_arith_function_type
8546                 : diag::ext_gnu_ptr_func_arith)
8547     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8548     // We only show the second type if it differs from the first.
8549     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8550                                                    RHS->getType())
8551     << RHS->getType()->getPointeeType()
8552     << LHS->getSourceRange() << RHS->getSourceRange();
8553 }
8554
8555 /// \brief Diagnose invalid arithmetic on a function pointer.
8556 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8557                                                 Expr *Pointer) {
8558   assert(Pointer->getType()->isAnyPointerType());
8559   S.Diag(Loc, S.getLangOpts().CPlusPlus
8560                 ? diag::err_typecheck_pointer_arith_function_type
8561                 : diag::ext_gnu_ptr_func_arith)
8562     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8563     << 0 /* one pointer, so only one type */
8564     << Pointer->getSourceRange();
8565 }
8566
8567 /// \brief Emit error if Operand is incomplete pointer type
8568 ///
8569 /// \returns True if pointer has incomplete type
8570 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8571                                                  Expr *Operand) {
8572   QualType ResType = Operand->getType();
8573   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8574     ResType = ResAtomicType->getValueType();
8575
8576   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8577   QualType PointeeTy = ResType->getPointeeType();
8578   return S.RequireCompleteType(Loc, PointeeTy,
8579                                diag::err_typecheck_arithmetic_incomplete_type,
8580                                PointeeTy, Operand->getSourceRange());
8581 }
8582
8583 /// \brief Check the validity of an arithmetic pointer operand.
8584 ///
8585 /// If the operand has pointer type, this code will check for pointer types
8586 /// which are invalid in arithmetic operations. These will be diagnosed
8587 /// appropriately, including whether or not the use is supported as an
8588 /// extension.
8589 ///
8590 /// \returns True when the operand is valid to use (even if as an extension).
8591 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8592                                             Expr *Operand) {
8593   QualType ResType = Operand->getType();
8594   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8595     ResType = ResAtomicType->getValueType();
8596
8597   if (!ResType->isAnyPointerType()) return true;
8598
8599   QualType PointeeTy = ResType->getPointeeType();
8600   if (PointeeTy->isVoidType()) {
8601     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8602     return !S.getLangOpts().CPlusPlus;
8603   }
8604   if (PointeeTy->isFunctionType()) {
8605     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8606     return !S.getLangOpts().CPlusPlus;
8607   }
8608
8609   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8610
8611   return true;
8612 }
8613
8614 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8615 /// operands.
8616 ///
8617 /// This routine will diagnose any invalid arithmetic on pointer operands much
8618 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8619 /// for emitting a single diagnostic even for operations where both LHS and RHS
8620 /// are (potentially problematic) pointers.
8621 ///
8622 /// \returns True when the operand is valid to use (even if as an extension).
8623 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8624                                                 Expr *LHSExpr, Expr *RHSExpr) {
8625   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8626   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8627   if (!isLHSPointer && !isRHSPointer) return true;
8628
8629   QualType LHSPointeeTy, RHSPointeeTy;
8630   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8631   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8632
8633   // if both are pointers check if operation is valid wrt address spaces
8634   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8635     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8636     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8637     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8638       S.Diag(Loc,
8639              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8640           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8641           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8642       return false;
8643     }
8644   }
8645
8646   // Check for arithmetic on pointers to incomplete types.
8647   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8648   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8649   if (isLHSVoidPtr || isRHSVoidPtr) {
8650     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8651     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8652     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8653
8654     return !S.getLangOpts().CPlusPlus;
8655   }
8656
8657   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8658   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8659   if (isLHSFuncPtr || isRHSFuncPtr) {
8660     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8661     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8662                                                                 RHSExpr);
8663     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8664
8665     return !S.getLangOpts().CPlusPlus;
8666   }
8667
8668   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8669     return false;
8670   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8671     return false;
8672
8673   return true;
8674 }
8675
8676 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8677 /// literal.
8678 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8679                                   Expr *LHSExpr, Expr *RHSExpr) {
8680   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8681   Expr* IndexExpr = RHSExpr;
8682   if (!StrExpr) {
8683     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8684     IndexExpr = LHSExpr;
8685   }
8686
8687   bool IsStringPlusInt = StrExpr &&
8688       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8689   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8690     return;
8691
8692   llvm::APSInt index;
8693   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8694     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8695     if (index.isNonNegative() &&
8696         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8697                               index.isUnsigned()))
8698       return;
8699   }
8700
8701   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8702   Self.Diag(OpLoc, diag::warn_string_plus_int)
8703       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8704
8705   // Only print a fixit for "str" + int, not for int + "str".
8706   if (IndexExpr == RHSExpr) {
8707     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8708     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8709         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8710         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8711         << FixItHint::CreateInsertion(EndLoc, "]");
8712   } else
8713     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8714 }
8715
8716 /// \brief Emit a warning when adding a char literal to a string.
8717 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8718                                    Expr *LHSExpr, Expr *RHSExpr) {
8719   const Expr *StringRefExpr = LHSExpr;
8720   const CharacterLiteral *CharExpr =
8721       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8722
8723   if (!CharExpr) {
8724     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8725     StringRefExpr = RHSExpr;
8726   }
8727
8728   if (!CharExpr || !StringRefExpr)
8729     return;
8730
8731   const QualType StringType = StringRefExpr->getType();
8732
8733   // Return if not a PointerType.
8734   if (!StringType->isAnyPointerType())
8735     return;
8736
8737   // Return if not a CharacterType.
8738   if (!StringType->getPointeeType()->isAnyCharacterType())
8739     return;
8740
8741   ASTContext &Ctx = Self.getASTContext();
8742   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8743
8744   const QualType CharType = CharExpr->getType();
8745   if (!CharType->isAnyCharacterType() &&
8746       CharType->isIntegerType() &&
8747       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8748     Self.Diag(OpLoc, diag::warn_string_plus_char)
8749         << DiagRange << Ctx.CharTy;
8750   } else {
8751     Self.Diag(OpLoc, diag::warn_string_plus_char)
8752         << DiagRange << CharExpr->getType();
8753   }
8754
8755   // Only print a fixit for str + char, not for char + str.
8756   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8757     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8758     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8759         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8760         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8761         << FixItHint::CreateInsertion(EndLoc, "]");
8762   } else {
8763     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8764   }
8765 }
8766
8767 /// \brief Emit error when two pointers are incompatible.
8768 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8769                                            Expr *LHSExpr, Expr *RHSExpr) {
8770   assert(LHSExpr->getType()->isAnyPointerType());
8771   assert(RHSExpr->getType()->isAnyPointerType());
8772   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8773     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8774     << RHSExpr->getSourceRange();
8775 }
8776
8777 // C99 6.5.6
8778 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8779                                      SourceLocation Loc, BinaryOperatorKind Opc,
8780                                      QualType* CompLHSTy) {
8781   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8782
8783   if (LHS.get()->getType()->isVectorType() ||
8784       RHS.get()->getType()->isVectorType()) {
8785     QualType compType = CheckVectorOperands(
8786         LHS, RHS, Loc, CompLHSTy,
8787         /*AllowBothBool*/getLangOpts().AltiVec,
8788         /*AllowBoolConversions*/getLangOpts().ZVector);
8789     if (CompLHSTy) *CompLHSTy = compType;
8790     return compType;
8791   }
8792
8793   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8794   if (LHS.isInvalid() || RHS.isInvalid())
8795     return QualType();
8796
8797   // Diagnose "string literal" '+' int and string '+' "char literal".
8798   if (Opc == BO_Add) {
8799     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8800     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8801   }
8802
8803   // handle the common case first (both operands are arithmetic).
8804   if (!compType.isNull() && compType->isArithmeticType()) {
8805     if (CompLHSTy) *CompLHSTy = compType;
8806     return compType;
8807   }
8808
8809   // Type-checking.  Ultimately the pointer's going to be in PExp;
8810   // note that we bias towards the LHS being the pointer.
8811   Expr *PExp = LHS.get(), *IExp = RHS.get();
8812
8813   bool isObjCPointer;
8814   if (PExp->getType()->isPointerType()) {
8815     isObjCPointer = false;
8816   } else if (PExp->getType()->isObjCObjectPointerType()) {
8817     isObjCPointer = true;
8818   } else {
8819     std::swap(PExp, IExp);
8820     if (PExp->getType()->isPointerType()) {
8821       isObjCPointer = false;
8822     } else if (PExp->getType()->isObjCObjectPointerType()) {
8823       isObjCPointer = true;
8824     } else {
8825       return InvalidOperands(Loc, LHS, RHS);
8826     }
8827   }
8828   assert(PExp->getType()->isAnyPointerType());
8829
8830   if (!IExp->getType()->isIntegerType())
8831     return InvalidOperands(Loc, LHS, RHS);
8832
8833   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8834     return QualType();
8835
8836   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8837     return QualType();
8838
8839   // Check array bounds for pointer arithemtic
8840   CheckArrayAccess(PExp, IExp);
8841
8842   if (CompLHSTy) {
8843     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8844     if (LHSTy.isNull()) {
8845       LHSTy = LHS.get()->getType();
8846       if (LHSTy->isPromotableIntegerType())
8847         LHSTy = Context.getPromotedIntegerType(LHSTy);
8848     }
8849     *CompLHSTy = LHSTy;
8850   }
8851
8852   return PExp->getType();
8853 }
8854
8855 // C99 6.5.6
8856 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8857                                         SourceLocation Loc,
8858                                         QualType* CompLHSTy) {
8859   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8860
8861   if (LHS.get()->getType()->isVectorType() ||
8862       RHS.get()->getType()->isVectorType()) {
8863     QualType compType = CheckVectorOperands(
8864         LHS, RHS, Loc, CompLHSTy,
8865         /*AllowBothBool*/getLangOpts().AltiVec,
8866         /*AllowBoolConversions*/getLangOpts().ZVector);
8867     if (CompLHSTy) *CompLHSTy = compType;
8868     return compType;
8869   }
8870
8871   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8872   if (LHS.isInvalid() || RHS.isInvalid())
8873     return QualType();
8874
8875   // Enforce type constraints: C99 6.5.6p3.
8876
8877   // Handle the common case first (both operands are arithmetic).
8878   if (!compType.isNull() && compType->isArithmeticType()) {
8879     if (CompLHSTy) *CompLHSTy = compType;
8880     return compType;
8881   }
8882
8883   // Either ptr - int   or   ptr - ptr.
8884   if (LHS.get()->getType()->isAnyPointerType()) {
8885     QualType lpointee = LHS.get()->getType()->getPointeeType();
8886
8887     // Diagnose bad cases where we step over interface counts.
8888     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8889         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8890       return QualType();
8891
8892     // The result type of a pointer-int computation is the pointer type.
8893     if (RHS.get()->getType()->isIntegerType()) {
8894       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8895         return QualType();
8896
8897       // Check array bounds for pointer arithemtic
8898       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8899                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8900
8901       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8902       return LHS.get()->getType();
8903     }
8904
8905     // Handle pointer-pointer subtractions.
8906     if (const PointerType *RHSPTy
8907           = RHS.get()->getType()->getAs<PointerType>()) {
8908       QualType rpointee = RHSPTy->getPointeeType();
8909
8910       if (getLangOpts().CPlusPlus) {
8911         // Pointee types must be the same: C++ [expr.add]
8912         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8913           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8914         }
8915       } else {
8916         // Pointee types must be compatible C99 6.5.6p3
8917         if (!Context.typesAreCompatible(
8918                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8919                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8920           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8921           return QualType();
8922         }
8923       }
8924
8925       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8926                                                LHS.get(), RHS.get()))
8927         return QualType();
8928
8929       // The pointee type may have zero size.  As an extension, a structure or
8930       // union may have zero size or an array may have zero length.  In this
8931       // case subtraction does not make sense.
8932       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8933         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8934         if (ElementSize.isZero()) {
8935           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8936             << rpointee.getUnqualifiedType()
8937             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8938         }
8939       }
8940
8941       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8942       return Context.getPointerDiffType();
8943     }
8944   }
8945
8946   return InvalidOperands(Loc, LHS, RHS);
8947 }
8948
8949 static bool isScopedEnumerationType(QualType T) {
8950   if (const EnumType *ET = T->getAs<EnumType>())
8951     return ET->getDecl()->isScoped();
8952   return false;
8953 }
8954
8955 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8956                                    SourceLocation Loc, BinaryOperatorKind Opc,
8957                                    QualType LHSType) {
8958   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8959   // so skip remaining warnings as we don't want to modify values within Sema.
8960   if (S.getLangOpts().OpenCL)
8961     return;
8962
8963   llvm::APSInt Right;
8964   // Check right/shifter operand
8965   if (RHS.get()->isValueDependent() ||
8966       !RHS.get()->EvaluateAsInt(Right, S.Context))
8967     return;
8968
8969   if (Right.isNegative()) {
8970     S.DiagRuntimeBehavior(Loc, RHS.get(),
8971                           S.PDiag(diag::warn_shift_negative)
8972                             << RHS.get()->getSourceRange());
8973     return;
8974   }
8975   llvm::APInt LeftBits(Right.getBitWidth(),
8976                        S.Context.getTypeSize(LHS.get()->getType()));
8977   if (Right.uge(LeftBits)) {
8978     S.DiagRuntimeBehavior(Loc, RHS.get(),
8979                           S.PDiag(diag::warn_shift_gt_typewidth)
8980                             << RHS.get()->getSourceRange());
8981     return;
8982   }
8983   if (Opc != BO_Shl)
8984     return;
8985
8986   // When left shifting an ICE which is signed, we can check for overflow which
8987   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8988   // integers have defined behavior modulo one more than the maximum value
8989   // representable in the result type, so never warn for those.
8990   llvm::APSInt Left;
8991   if (LHS.get()->isValueDependent() ||
8992       LHSType->hasUnsignedIntegerRepresentation() ||
8993       !LHS.get()->EvaluateAsInt(Left, S.Context))
8994     return;
8995
8996   // If LHS does not have a signed type and non-negative value
8997   // then, the behavior is undefined. Warn about it.
8998   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8999     S.DiagRuntimeBehavior(Loc, LHS.get(),
9000                           S.PDiag(diag::warn_shift_lhs_negative)
9001                             << LHS.get()->getSourceRange());
9002     return;
9003   }
9004
9005   llvm::APInt ResultBits =
9006       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9007   if (LeftBits.uge(ResultBits))
9008     return;
9009   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9010   Result = Result.shl(Right);
9011
9012   // Print the bit representation of the signed integer as an unsigned
9013   // hexadecimal number.
9014   SmallString<40> HexResult;
9015   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9016
9017   // If we are only missing a sign bit, this is less likely to result in actual
9018   // bugs -- if the result is cast back to an unsigned type, it will have the
9019   // expected value. Thus we place this behind a different warning that can be
9020   // turned off separately if needed.
9021   if (LeftBits == ResultBits - 1) {
9022     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9023         << HexResult << LHSType
9024         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9025     return;
9026   }
9027
9028   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9029     << HexResult.str() << Result.getMinSignedBits() << LHSType
9030     << Left.getBitWidth() << LHS.get()->getSourceRange()
9031     << RHS.get()->getSourceRange();
9032 }
9033
9034 /// \brief Return the resulting type when a vector is shifted
9035 ///        by a scalar or vector shift amount.
9036 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9037                                  SourceLocation Loc, bool IsCompAssign) {
9038   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9039   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9040       !LHS.get()->getType()->isVectorType()) {
9041     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9042       << RHS.get()->getType() << LHS.get()->getType()
9043       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9044     return QualType();
9045   }
9046
9047   if (!IsCompAssign) {
9048     LHS = S.UsualUnaryConversions(LHS.get());
9049     if (LHS.isInvalid()) return QualType();
9050   }
9051
9052   RHS = S.UsualUnaryConversions(RHS.get());
9053   if (RHS.isInvalid()) return QualType();
9054
9055   QualType LHSType = LHS.get()->getType();
9056   // Note that LHS might be a scalar because the routine calls not only in
9057   // OpenCL case.
9058   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9059   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9060
9061   // Note that RHS might not be a vector.
9062   QualType RHSType = RHS.get()->getType();
9063   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9064   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9065
9066   // The operands need to be integers.
9067   if (!LHSEleType->isIntegerType()) {
9068     S.Diag(Loc, diag::err_typecheck_expect_int)
9069       << LHS.get()->getType() << LHS.get()->getSourceRange();
9070     return QualType();
9071   }
9072
9073   if (!RHSEleType->isIntegerType()) {
9074     S.Diag(Loc, diag::err_typecheck_expect_int)
9075       << RHS.get()->getType() << RHS.get()->getSourceRange();
9076     return QualType();
9077   }
9078
9079   if (!LHSVecTy) {
9080     assert(RHSVecTy);
9081     if (IsCompAssign)
9082       return RHSType;
9083     if (LHSEleType != RHSEleType) {
9084       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9085       LHSEleType = RHSEleType;
9086     }
9087     QualType VecTy =
9088         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9089     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9090     LHSType = VecTy;
9091   } else if (RHSVecTy) {
9092     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9093     // are applied component-wise. So if RHS is a vector, then ensure
9094     // that the number of elements is the same as LHS...
9095     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9096       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9097         << LHS.get()->getType() << RHS.get()->getType()
9098         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9099       return QualType();
9100     }
9101     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9102       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9103       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9104       if (LHSBT != RHSBT &&
9105           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9106         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9107             << LHS.get()->getType() << RHS.get()->getType()
9108             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9109       }
9110     }
9111   } else {
9112     // ...else expand RHS to match the number of elements in LHS.
9113     QualType VecTy =
9114       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9115     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9116   }
9117
9118   return LHSType;
9119 }
9120
9121 // C99 6.5.7
9122 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9123                                   SourceLocation Loc, BinaryOperatorKind Opc,
9124                                   bool IsCompAssign) {
9125   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9126
9127   // Vector shifts promote their scalar inputs to vector type.
9128   if (LHS.get()->getType()->isVectorType() ||
9129       RHS.get()->getType()->isVectorType()) {
9130     if (LangOpts.ZVector) {
9131       // The shift operators for the z vector extensions work basically
9132       // like general shifts, except that neither the LHS nor the RHS is
9133       // allowed to be a "vector bool".
9134       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9135         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9136           return InvalidOperands(Loc, LHS, RHS);
9137       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9138         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9139           return InvalidOperands(Loc, LHS, RHS);
9140     }
9141     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9142   }
9143
9144   // Shifts don't perform usual arithmetic conversions, they just do integer
9145   // promotions on each operand. C99 6.5.7p3
9146
9147   // For the LHS, do usual unary conversions, but then reset them away
9148   // if this is a compound assignment.
9149   ExprResult OldLHS = LHS;
9150   LHS = UsualUnaryConversions(LHS.get());
9151   if (LHS.isInvalid())
9152     return QualType();
9153   QualType LHSType = LHS.get()->getType();
9154   if (IsCompAssign) LHS = OldLHS;
9155
9156   // The RHS is simpler.
9157   RHS = UsualUnaryConversions(RHS.get());
9158   if (RHS.isInvalid())
9159     return QualType();
9160   QualType RHSType = RHS.get()->getType();
9161
9162   // C99 6.5.7p2: Each of the operands shall have integer type.
9163   if (!LHSType->hasIntegerRepresentation() ||
9164       !RHSType->hasIntegerRepresentation())
9165     return InvalidOperands(Loc, LHS, RHS);
9166
9167   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9168   // hasIntegerRepresentation() above instead of this.
9169   if (isScopedEnumerationType(LHSType) ||
9170       isScopedEnumerationType(RHSType)) {
9171     return InvalidOperands(Loc, LHS, RHS);
9172   }
9173   // Sanity-check shift operands
9174   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9175
9176   // "The type of the result is that of the promoted left operand."
9177   return LHSType;
9178 }
9179
9180 static bool IsWithinTemplateSpecialization(Decl *D) {
9181   if (DeclContext *DC = D->getDeclContext()) {
9182     if (isa<ClassTemplateSpecializationDecl>(DC))
9183       return true;
9184     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
9185       return FD->isFunctionTemplateSpecialization();
9186   }
9187   return false;
9188 }
9189
9190 /// If two different enums are compared, raise a warning.
9191 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9192                                 Expr *RHS) {
9193   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9194   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9195
9196   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9197   if (!LHSEnumType)
9198     return;
9199   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9200   if (!RHSEnumType)
9201     return;
9202
9203   // Ignore anonymous enums.
9204   if (!LHSEnumType->getDecl()->getIdentifier())
9205     return;
9206   if (!RHSEnumType->getDecl()->getIdentifier())
9207     return;
9208
9209   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9210     return;
9211
9212   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9213       << LHSStrippedType << RHSStrippedType
9214       << LHS->getSourceRange() << RHS->getSourceRange();
9215 }
9216
9217 /// \brief Diagnose bad pointer comparisons.
9218 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9219                                               ExprResult &LHS, ExprResult &RHS,
9220                                               bool IsError) {
9221   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9222                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9223     << LHS.get()->getType() << RHS.get()->getType()
9224     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9225 }
9226
9227 /// \brief Returns false if the pointers are converted to a composite type,
9228 /// true otherwise.
9229 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9230                                            ExprResult &LHS, ExprResult &RHS) {
9231   // C++ [expr.rel]p2:
9232   //   [...] Pointer conversions (4.10) and qualification
9233   //   conversions (4.4) are performed on pointer operands (or on
9234   //   a pointer operand and a null pointer constant) to bring
9235   //   them to their composite pointer type. [...]
9236   //
9237   // C++ [expr.eq]p1 uses the same notion for (in)equality
9238   // comparisons of pointers.
9239
9240   QualType LHSType = LHS.get()->getType();
9241   QualType RHSType = RHS.get()->getType();
9242   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9243          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9244
9245   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9246   if (T.isNull()) {
9247     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9248         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9249       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9250     else
9251       S.InvalidOperands(Loc, LHS, RHS);
9252     return true;
9253   }
9254
9255   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9256   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9257   return false;
9258 }
9259
9260 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9261                                                     ExprResult &LHS,
9262                                                     ExprResult &RHS,
9263                                                     bool IsError) {
9264   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9265                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9266     << LHS.get()->getType() << RHS.get()->getType()
9267     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9268 }
9269
9270 static bool isObjCObjectLiteral(ExprResult &E) {
9271   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9272   case Stmt::ObjCArrayLiteralClass:
9273   case Stmt::ObjCDictionaryLiteralClass:
9274   case Stmt::ObjCStringLiteralClass:
9275   case Stmt::ObjCBoxedExprClass:
9276     return true;
9277   default:
9278     // Note that ObjCBoolLiteral is NOT an object literal!
9279     return false;
9280   }
9281 }
9282
9283 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9284   const ObjCObjectPointerType *Type =
9285     LHS->getType()->getAs<ObjCObjectPointerType>();
9286
9287   // If this is not actually an Objective-C object, bail out.
9288   if (!Type)
9289     return false;
9290
9291   // Get the LHS object's interface type.
9292   QualType InterfaceType = Type->getPointeeType();
9293
9294   // If the RHS isn't an Objective-C object, bail out.
9295   if (!RHS->getType()->isObjCObjectPointerType())
9296     return false;
9297
9298   // Try to find the -isEqual: method.
9299   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9300   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9301                                                       InterfaceType,
9302                                                       /*instance=*/true);
9303   if (!Method) {
9304     if (Type->isObjCIdType()) {
9305       // For 'id', just check the global pool.
9306       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9307                                                   /*receiverId=*/true);
9308     } else {
9309       // Check protocols.
9310       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9311                                              /*instance=*/true);
9312     }
9313   }
9314
9315   if (!Method)
9316     return false;
9317
9318   QualType T = Method->parameters()[0]->getType();
9319   if (!T->isObjCObjectPointerType())
9320     return false;
9321
9322   QualType R = Method->getReturnType();
9323   if (!R->isScalarType())
9324     return false;
9325
9326   return true;
9327 }
9328
9329 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9330   FromE = FromE->IgnoreParenImpCasts();
9331   switch (FromE->getStmtClass()) {
9332     default:
9333       break;
9334     case Stmt::ObjCStringLiteralClass:
9335       // "string literal"
9336       return LK_String;
9337     case Stmt::ObjCArrayLiteralClass:
9338       // "array literal"
9339       return LK_Array;
9340     case Stmt::ObjCDictionaryLiteralClass:
9341       // "dictionary literal"
9342       return LK_Dictionary;
9343     case Stmt::BlockExprClass:
9344       return LK_Block;
9345     case Stmt::ObjCBoxedExprClass: {
9346       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9347       switch (Inner->getStmtClass()) {
9348         case Stmt::IntegerLiteralClass:
9349         case Stmt::FloatingLiteralClass:
9350         case Stmt::CharacterLiteralClass:
9351         case Stmt::ObjCBoolLiteralExprClass:
9352         case Stmt::CXXBoolLiteralExprClass:
9353           // "numeric literal"
9354           return LK_Numeric;
9355         case Stmt::ImplicitCastExprClass: {
9356           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9357           // Boolean literals can be represented by implicit casts.
9358           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9359             return LK_Numeric;
9360           break;
9361         }
9362         default:
9363           break;
9364       }
9365       return LK_Boxed;
9366     }
9367   }
9368   return LK_None;
9369 }
9370
9371 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9372                                           ExprResult &LHS, ExprResult &RHS,
9373                                           BinaryOperator::Opcode Opc){
9374   Expr *Literal;
9375   Expr *Other;
9376   if (isObjCObjectLiteral(LHS)) {
9377     Literal = LHS.get();
9378     Other = RHS.get();
9379   } else {
9380     Literal = RHS.get();
9381     Other = LHS.get();
9382   }
9383
9384   // Don't warn on comparisons against nil.
9385   Other = Other->IgnoreParenCasts();
9386   if (Other->isNullPointerConstant(S.getASTContext(),
9387                                    Expr::NPC_ValueDependentIsNotNull))
9388     return;
9389
9390   // This should be kept in sync with warn_objc_literal_comparison.
9391   // LK_String should always be after the other literals, since it has its own
9392   // warning flag.
9393   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9394   assert(LiteralKind != Sema::LK_Block);
9395   if (LiteralKind == Sema::LK_None) {
9396     llvm_unreachable("Unknown Objective-C object literal kind");
9397   }
9398
9399   if (LiteralKind == Sema::LK_String)
9400     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9401       << Literal->getSourceRange();
9402   else
9403     S.Diag(Loc, diag::warn_objc_literal_comparison)
9404       << LiteralKind << Literal->getSourceRange();
9405
9406   if (BinaryOperator::isEqualityOp(Opc) &&
9407       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9408     SourceLocation Start = LHS.get()->getLocStart();
9409     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9410     CharSourceRange OpRange =
9411       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9412
9413     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9414       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9415       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9416       << FixItHint::CreateInsertion(End, "]");
9417   }
9418 }
9419
9420 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9421 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9422                                            ExprResult &RHS, SourceLocation Loc,
9423                                            BinaryOperatorKind Opc) {
9424   // Check that left hand side is !something.
9425   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9426   if (!UO || UO->getOpcode() != UO_LNot) return;
9427
9428   // Only check if the right hand side is non-bool arithmetic type.
9429   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9430
9431   // Make sure that the something in !something is not bool.
9432   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9433   if (SubExpr->isKnownToHaveBooleanValue()) return;
9434
9435   // Emit warning.
9436   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9437   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9438       << Loc << IsBitwiseOp;
9439
9440   // First note suggest !(x < y)
9441   SourceLocation FirstOpen = SubExpr->getLocStart();
9442   SourceLocation FirstClose = RHS.get()->getLocEnd();
9443   FirstClose = S.getLocForEndOfToken(FirstClose);
9444   if (FirstClose.isInvalid())
9445     FirstOpen = SourceLocation();
9446   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9447       << IsBitwiseOp
9448       << FixItHint::CreateInsertion(FirstOpen, "(")
9449       << FixItHint::CreateInsertion(FirstClose, ")");
9450
9451   // Second note suggests (!x) < y
9452   SourceLocation SecondOpen = LHS.get()->getLocStart();
9453   SourceLocation SecondClose = LHS.get()->getLocEnd();
9454   SecondClose = S.getLocForEndOfToken(SecondClose);
9455   if (SecondClose.isInvalid())
9456     SecondOpen = SourceLocation();
9457   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9458       << FixItHint::CreateInsertion(SecondOpen, "(")
9459       << FixItHint::CreateInsertion(SecondClose, ")");
9460 }
9461
9462 // Get the decl for a simple expression: a reference to a variable,
9463 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9464 static ValueDecl *getCompareDecl(Expr *E) {
9465   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9466     return DR->getDecl();
9467   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9468     if (Ivar->isFreeIvar())
9469       return Ivar->getDecl();
9470   }
9471   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9472     if (Mem->isImplicitAccess())
9473       return Mem->getMemberDecl();
9474   }
9475   return nullptr;
9476 }
9477
9478 // C99 6.5.8, C++ [expr.rel]
9479 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9480                                     SourceLocation Loc, BinaryOperatorKind Opc,
9481                                     bool IsRelational) {
9482   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9483
9484   // Handle vector comparisons separately.
9485   if (LHS.get()->getType()->isVectorType() ||
9486       RHS.get()->getType()->isVectorType())
9487     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9488
9489   QualType LHSType = LHS.get()->getType();
9490   QualType RHSType = RHS.get()->getType();
9491
9492   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9493   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9494
9495   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9496   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9497
9498   if (!LHSType->hasFloatingRepresentation() &&
9499       !(LHSType->isBlockPointerType() && IsRelational) &&
9500       !LHS.get()->getLocStart().isMacroID() &&
9501       !RHS.get()->getLocStart().isMacroID() &&
9502       !inTemplateInstantiation()) {
9503     // For non-floating point types, check for self-comparisons of the form
9504     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9505     // often indicate logic errors in the program.
9506     //
9507     // NOTE: Don't warn about comparison expressions resulting from macro
9508     // expansion. Also don't warn about comparisons which are only self
9509     // comparisons within a template specialization. The warnings should catch
9510     // obvious cases in the definition of the template anyways. The idea is to
9511     // warn when the typed comparison operator will always evaluate to the same
9512     // result.
9513     ValueDecl *DL = getCompareDecl(LHSStripped);
9514     ValueDecl *DR = getCompareDecl(RHSStripped);
9515     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9516       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9517                           << 0 // self-
9518                           << (Opc == BO_EQ
9519                               || Opc == BO_LE
9520                               || Opc == BO_GE));
9521     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9522                !DL->getType()->isReferenceType() &&
9523                !DR->getType()->isReferenceType()) {
9524         // what is it always going to eval to?
9525         char always_evals_to;
9526         switch(Opc) {
9527         case BO_EQ: // e.g. array1 == array2
9528           always_evals_to = 0; // false
9529           break;
9530         case BO_NE: // e.g. array1 != array2
9531           always_evals_to = 1; // true
9532           break;
9533         default:
9534           // best we can say is 'a constant'
9535           always_evals_to = 2; // e.g. array1 <= array2
9536           break;
9537         }
9538         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9539                             << 1 // array
9540                             << always_evals_to);
9541     }
9542
9543     if (isa<CastExpr>(LHSStripped))
9544       LHSStripped = LHSStripped->IgnoreParenCasts();
9545     if (isa<CastExpr>(RHSStripped))
9546       RHSStripped = RHSStripped->IgnoreParenCasts();
9547
9548     // Warn about comparisons against a string constant (unless the other
9549     // operand is null), the user probably wants strcmp.
9550     Expr *literalString = nullptr;
9551     Expr *literalStringStripped = nullptr;
9552     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9553         !RHSStripped->isNullPointerConstant(Context,
9554                                             Expr::NPC_ValueDependentIsNull)) {
9555       literalString = LHS.get();
9556       literalStringStripped = LHSStripped;
9557     } else if ((isa<StringLiteral>(RHSStripped) ||
9558                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9559                !LHSStripped->isNullPointerConstant(Context,
9560                                             Expr::NPC_ValueDependentIsNull)) {
9561       literalString = RHS.get();
9562       literalStringStripped = RHSStripped;
9563     }
9564
9565     if (literalString) {
9566       DiagRuntimeBehavior(Loc, nullptr,
9567         PDiag(diag::warn_stringcompare)
9568           << isa<ObjCEncodeExpr>(literalStringStripped)
9569           << literalString->getSourceRange());
9570     }
9571   }
9572
9573   // C99 6.5.8p3 / C99 6.5.9p4
9574   UsualArithmeticConversions(LHS, RHS);
9575   if (LHS.isInvalid() || RHS.isInvalid())
9576     return QualType();
9577
9578   LHSType = LHS.get()->getType();
9579   RHSType = RHS.get()->getType();
9580
9581   // The result of comparisons is 'bool' in C++, 'int' in C.
9582   QualType ResultTy = Context.getLogicalOperationType();
9583
9584   if (IsRelational) {
9585     if (LHSType->isRealType() && RHSType->isRealType())
9586       return ResultTy;
9587   } else {
9588     // Check for comparisons of floating point operands using != and ==.
9589     if (LHSType->hasFloatingRepresentation())
9590       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9591
9592     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9593       return ResultTy;
9594   }
9595
9596   const Expr::NullPointerConstantKind LHSNullKind =
9597       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9598   const Expr::NullPointerConstantKind RHSNullKind =
9599       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9600   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9601   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9602
9603   if (!IsRelational && LHSIsNull != RHSIsNull) {
9604     bool IsEquality = Opc == BO_EQ;
9605     if (RHSIsNull)
9606       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9607                                    RHS.get()->getSourceRange());
9608     else
9609       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9610                                    LHS.get()->getSourceRange());
9611   }
9612
9613   if ((LHSType->isIntegerType() && !LHSIsNull) ||
9614       (RHSType->isIntegerType() && !RHSIsNull)) {
9615     // Skip normal pointer conversion checks in this case; we have better
9616     // diagnostics for this below.
9617   } else if (getLangOpts().CPlusPlus) {
9618     // Equality comparison of a function pointer to a void pointer is invalid,
9619     // but we allow it as an extension.
9620     // FIXME: If we really want to allow this, should it be part of composite
9621     // pointer type computation so it works in conditionals too?
9622     if (!IsRelational &&
9623         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9624          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9625       // This is a gcc extension compatibility comparison.
9626       // In a SFINAE context, we treat this as a hard error to maintain
9627       // conformance with the C++ standard.
9628       diagnoseFunctionPointerToVoidComparison(
9629           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9630       
9631       if (isSFINAEContext())
9632         return QualType();
9633       
9634       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9635       return ResultTy;
9636     }
9637
9638     // C++ [expr.eq]p2:
9639     //   If at least one operand is a pointer [...] bring them to their
9640     //   composite pointer type.
9641     // C++ [expr.rel]p2:
9642     //   If both operands are pointers, [...] bring them to their composite
9643     //   pointer type.
9644     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9645             (IsRelational ? 2 : 1) &&
9646         (!LangOpts.ObjCAutoRefCount ||
9647          !(LHSType->isObjCObjectPointerType() ||
9648            RHSType->isObjCObjectPointerType()))) {
9649       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9650         return QualType();
9651       else
9652         return ResultTy;
9653     }
9654   } else if (LHSType->isPointerType() &&
9655              RHSType->isPointerType()) { // C99 6.5.8p2
9656     // All of the following pointer-related warnings are GCC extensions, except
9657     // when handling null pointer constants.
9658     QualType LCanPointeeTy =
9659       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9660     QualType RCanPointeeTy =
9661       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9662
9663     // C99 6.5.9p2 and C99 6.5.8p2
9664     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9665                                    RCanPointeeTy.getUnqualifiedType())) {
9666       // Valid unless a relational comparison of function pointers
9667       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9668         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9669           << LHSType << RHSType << LHS.get()->getSourceRange()
9670           << RHS.get()->getSourceRange();
9671       }
9672     } else if (!IsRelational &&
9673                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9674       // Valid unless comparison between non-null pointer and function pointer
9675       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9676           && !LHSIsNull && !RHSIsNull)
9677         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9678                                                 /*isError*/false);
9679     } else {
9680       // Invalid
9681       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9682     }
9683     if (LCanPointeeTy != RCanPointeeTy) {
9684       // Treat NULL constant as a special case in OpenCL.
9685       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9686         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9687         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9688           Diag(Loc,
9689                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9690               << LHSType << RHSType << 0 /* comparison */
9691               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9692         }
9693       }
9694       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9695       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9696       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9697                                                : CK_BitCast;
9698       if (LHSIsNull && !RHSIsNull)
9699         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9700       else
9701         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9702     }
9703     return ResultTy;
9704   }
9705
9706   if (getLangOpts().CPlusPlus) {
9707     // C++ [expr.eq]p4:
9708     //   Two operands of type std::nullptr_t or one operand of type
9709     //   std::nullptr_t and the other a null pointer constant compare equal.
9710     if (!IsRelational && LHSIsNull && RHSIsNull) {
9711       if (LHSType->isNullPtrType()) {
9712         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9713         return ResultTy;
9714       }
9715       if (RHSType->isNullPtrType()) {
9716         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9717         return ResultTy;
9718       }
9719     }
9720
9721     // Comparison of Objective-C pointers and block pointers against nullptr_t.
9722     // These aren't covered by the composite pointer type rules.
9723     if (!IsRelational && RHSType->isNullPtrType() &&
9724         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9725       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9726       return ResultTy;
9727     }
9728     if (!IsRelational && LHSType->isNullPtrType() &&
9729         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9730       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9731       return ResultTy;
9732     }
9733
9734     if (IsRelational &&
9735         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9736          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9737       // HACK: Relational comparison of nullptr_t against a pointer type is
9738       // invalid per DR583, but we allow it within std::less<> and friends,
9739       // since otherwise common uses of it break.
9740       // FIXME: Consider removing this hack once LWG fixes std::less<> and
9741       // friends to have std::nullptr_t overload candidates.
9742       DeclContext *DC = CurContext;
9743       if (isa<FunctionDecl>(DC))
9744         DC = DC->getParent();
9745       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9746         if (CTSD->isInStdNamespace() &&
9747             llvm::StringSwitch<bool>(CTSD->getName())
9748                 .Cases("less", "less_equal", "greater", "greater_equal", true)
9749                 .Default(false)) {
9750           if (RHSType->isNullPtrType())
9751             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9752           else
9753             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9754           return ResultTy;
9755         }
9756       }
9757     }
9758
9759     // C++ [expr.eq]p2:
9760     //   If at least one operand is a pointer to member, [...] bring them to
9761     //   their composite pointer type.
9762     if (!IsRelational &&
9763         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9764       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9765         return QualType();
9766       else
9767         return ResultTy;
9768     }
9769
9770     // Handle scoped enumeration types specifically, since they don't promote
9771     // to integers.
9772     if (LHS.get()->getType()->isEnumeralType() &&
9773         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9774                                        RHS.get()->getType()))
9775       return ResultTy;
9776   }
9777
9778   // Handle block pointer types.
9779   if (!IsRelational && LHSType->isBlockPointerType() &&
9780       RHSType->isBlockPointerType()) {
9781     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9782     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9783
9784     if (!LHSIsNull && !RHSIsNull &&
9785         !Context.typesAreCompatible(lpointee, rpointee)) {
9786       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9787         << LHSType << RHSType << LHS.get()->getSourceRange()
9788         << RHS.get()->getSourceRange();
9789     }
9790     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9791     return ResultTy;
9792   }
9793
9794   // Allow block pointers to be compared with null pointer constants.
9795   if (!IsRelational
9796       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9797           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9798     if (!LHSIsNull && !RHSIsNull) {
9799       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9800              ->getPointeeType()->isVoidType())
9801             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9802                 ->getPointeeType()->isVoidType())))
9803         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9804           << LHSType << RHSType << LHS.get()->getSourceRange()
9805           << RHS.get()->getSourceRange();
9806     }
9807     if (LHSIsNull && !RHSIsNull)
9808       LHS = ImpCastExprToType(LHS.get(), RHSType,
9809                               RHSType->isPointerType() ? CK_BitCast
9810                                 : CK_AnyPointerToBlockPointerCast);
9811     else
9812       RHS = ImpCastExprToType(RHS.get(), LHSType,
9813                               LHSType->isPointerType() ? CK_BitCast
9814                                 : CK_AnyPointerToBlockPointerCast);
9815     return ResultTy;
9816   }
9817
9818   if (LHSType->isObjCObjectPointerType() ||
9819       RHSType->isObjCObjectPointerType()) {
9820     const PointerType *LPT = LHSType->getAs<PointerType>();
9821     const PointerType *RPT = RHSType->getAs<PointerType>();
9822     if (LPT || RPT) {
9823       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9824       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9825
9826       if (!LPtrToVoid && !RPtrToVoid &&
9827           !Context.typesAreCompatible(LHSType, RHSType)) {
9828         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9829                                           /*isError*/false);
9830       }
9831       if (LHSIsNull && !RHSIsNull) {
9832         Expr *E = LHS.get();
9833         if (getLangOpts().ObjCAutoRefCount)
9834           CheckObjCConversion(SourceRange(), RHSType, E,
9835                               CCK_ImplicitConversion);
9836         LHS = ImpCastExprToType(E, RHSType,
9837                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9838       }
9839       else {
9840         Expr *E = RHS.get();
9841         if (getLangOpts().ObjCAutoRefCount)
9842           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
9843                               /*Diagnose=*/true,
9844                               /*DiagnoseCFAudited=*/false, Opc);
9845         RHS = ImpCastExprToType(E, LHSType,
9846                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9847       }
9848       return ResultTy;
9849     }
9850     if (LHSType->isObjCObjectPointerType() &&
9851         RHSType->isObjCObjectPointerType()) {
9852       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9853         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9854                                           /*isError*/false);
9855       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9856         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9857
9858       if (LHSIsNull && !RHSIsNull)
9859         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9860       else
9861         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9862       return ResultTy;
9863     }
9864   }
9865   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9866       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9867     unsigned DiagID = 0;
9868     bool isError = false;
9869     if (LangOpts.DebuggerSupport) {
9870       // Under a debugger, allow the comparison of pointers to integers,
9871       // since users tend to want to compare addresses.
9872     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9873                (RHSIsNull && RHSType->isIntegerType())) {
9874       if (IsRelational) {
9875         isError = getLangOpts().CPlusPlus;
9876         DiagID =
9877           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9878                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9879       }
9880     } else if (getLangOpts().CPlusPlus) {
9881       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9882       isError = true;
9883     } else if (IsRelational)
9884       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9885     else
9886       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9887
9888     if (DiagID) {
9889       Diag(Loc, DiagID)
9890         << LHSType << RHSType << LHS.get()->getSourceRange()
9891         << RHS.get()->getSourceRange();
9892       if (isError)
9893         return QualType();
9894     }
9895     
9896     if (LHSType->isIntegerType())
9897       LHS = ImpCastExprToType(LHS.get(), RHSType,
9898                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9899     else
9900       RHS = ImpCastExprToType(RHS.get(), LHSType,
9901                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9902     return ResultTy;
9903   }
9904   
9905   // Handle block pointers.
9906   if (!IsRelational && RHSIsNull
9907       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9908     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9909     return ResultTy;
9910   }
9911   if (!IsRelational && LHSIsNull
9912       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9913     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9914     return ResultTy;
9915   }
9916
9917   if (getLangOpts().OpenCLVersion >= 200) {
9918     if (LHSIsNull && RHSType->isQueueT()) {
9919       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9920       return ResultTy;
9921     }
9922
9923     if (LHSType->isQueueT() && RHSIsNull) {
9924       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9925       return ResultTy;
9926     }
9927   }
9928
9929   return InvalidOperands(Loc, LHS, RHS);
9930 }
9931
9932 // Return a signed ext_vector_type that is of identical size and number of
9933 // elements. For floating point vectors, return an integer type of identical
9934 // size and number of elements. In the non ext_vector_type case, search from
9935 // the largest type to the smallest type to avoid cases where long long == long,
9936 // where long gets picked over long long.
9937 QualType Sema::GetSignedVectorType(QualType V) {
9938   const VectorType *VTy = V->getAs<VectorType>();
9939   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9940
9941   if (isa<ExtVectorType>(VTy)) {
9942     if (TypeSize == Context.getTypeSize(Context.CharTy))
9943       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9944     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9945       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9946     else if (TypeSize == Context.getTypeSize(Context.IntTy))
9947       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9948     else if (TypeSize == Context.getTypeSize(Context.LongTy))
9949       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9950     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9951            "Unhandled vector element size in vector compare");
9952     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9953   }
9954
9955   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
9956     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
9957                                  VectorType::GenericVector);
9958   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9959     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
9960                                  VectorType::GenericVector);
9961   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9962     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
9963                                  VectorType::GenericVector);
9964   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9965     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
9966                                  VectorType::GenericVector);
9967   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
9968          "Unhandled vector element size in vector compare");
9969   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
9970                                VectorType::GenericVector);
9971 }
9972
9973 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9974 /// operates on extended vector types.  Instead of producing an IntTy result,
9975 /// like a scalar comparison, a vector comparison produces a vector of integer
9976 /// types.
9977 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9978                                           SourceLocation Loc,
9979                                           bool IsRelational) {
9980   // Check to make sure we're operating on vectors of the same type and width,
9981   // Allowing one side to be a scalar of element type.
9982   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9983                               /*AllowBothBool*/true,
9984                               /*AllowBoolConversions*/getLangOpts().ZVector);
9985   if (vType.isNull())
9986     return vType;
9987
9988   QualType LHSType = LHS.get()->getType();
9989
9990   // If AltiVec, the comparison results in a numeric type, i.e.
9991   // bool for C++, int for C
9992   if (getLangOpts().AltiVec &&
9993       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9994     return Context.getLogicalOperationType();
9995
9996   // For non-floating point types, check for self-comparisons of the form
9997   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9998   // often indicate logic errors in the program.
9999   if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) {
10000     if (DeclRefExpr* DRL
10001           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
10002       if (DeclRefExpr* DRR
10003             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
10004         if (DRL->getDecl() == DRR->getDecl())
10005           DiagRuntimeBehavior(Loc, nullptr,
10006                               PDiag(diag::warn_comparison_always)
10007                                 << 0 // self-
10008                                 << 2 // "a constant"
10009                               );
10010   }
10011
10012   // Check for comparisons of floating point operands using != and ==.
10013   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
10014     assert (RHS.get()->getType()->hasFloatingRepresentation());
10015     CheckFloatComparison(Loc, LHS.get(), RHS.get());
10016   }
10017
10018   // Return a signed type for the vector.
10019   return GetSignedVectorType(vType);
10020 }
10021
10022 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10023                                           SourceLocation Loc) {
10024   // Ensure that either both operands are of the same vector type, or
10025   // one operand is of a vector type and the other is of its element type.
10026   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10027                                        /*AllowBothBool*/true,
10028                                        /*AllowBoolConversions*/false);
10029   if (vType.isNull())
10030     return InvalidOperands(Loc, LHS, RHS);
10031   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10032       vType->hasFloatingRepresentation())
10033     return InvalidOperands(Loc, LHS, RHS);
10034   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10035   //        usage of the logical operators && and || with vectors in C. This
10036   //        check could be notionally dropped.
10037   if (!getLangOpts().CPlusPlus &&
10038       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10039     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10040
10041   return GetSignedVectorType(LHS.get()->getType());
10042 }
10043
10044 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10045                                            SourceLocation Loc,
10046                                            BinaryOperatorKind Opc) {
10047   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10048
10049   bool IsCompAssign =
10050       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10051
10052   if (LHS.get()->getType()->isVectorType() ||
10053       RHS.get()->getType()->isVectorType()) {
10054     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10055         RHS.get()->getType()->hasIntegerRepresentation())
10056       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10057                         /*AllowBothBool*/true,
10058                         /*AllowBoolConversions*/getLangOpts().ZVector);
10059     return InvalidOperands(Loc, LHS, RHS);
10060   }
10061
10062   if (Opc == BO_And)
10063     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10064
10065   ExprResult LHSResult = LHS, RHSResult = RHS;
10066   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10067                                                  IsCompAssign);
10068   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10069     return QualType();
10070   LHS = LHSResult.get();
10071   RHS = RHSResult.get();
10072
10073   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10074     return compType;
10075   return InvalidOperands(Loc, LHS, RHS);
10076 }
10077
10078 // C99 6.5.[13,14]
10079 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10080                                            SourceLocation Loc,
10081                                            BinaryOperatorKind Opc) {
10082   // Check vector operands differently.
10083   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10084     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10085   
10086   // Diagnose cases where the user write a logical and/or but probably meant a
10087   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10088   // is a constant.
10089   if (LHS.get()->getType()->isIntegerType() &&
10090       !LHS.get()->getType()->isBooleanType() &&
10091       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10092       // Don't warn in macros or template instantiations.
10093       !Loc.isMacroID() && !inTemplateInstantiation()) {
10094     // If the RHS can be constant folded, and if it constant folds to something
10095     // that isn't 0 or 1 (which indicate a potential logical operation that
10096     // happened to fold to true/false) then warn.
10097     // Parens on the RHS are ignored.
10098     llvm::APSInt Result;
10099     if (RHS.get()->EvaluateAsInt(Result, Context))
10100       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10101            !RHS.get()->getExprLoc().isMacroID()) ||
10102           (Result != 0 && Result != 1)) {
10103         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10104           << RHS.get()->getSourceRange()
10105           << (Opc == BO_LAnd ? "&&" : "||");
10106         // Suggest replacing the logical operator with the bitwise version
10107         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10108             << (Opc == BO_LAnd ? "&" : "|")
10109             << FixItHint::CreateReplacement(SourceRange(
10110                                                  Loc, getLocForEndOfToken(Loc)),
10111                                             Opc == BO_LAnd ? "&" : "|");
10112         if (Opc == BO_LAnd)
10113           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10114           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10115               << FixItHint::CreateRemoval(
10116                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
10117                               RHS.get()->getLocEnd()));
10118       }
10119   }
10120
10121   if (!Context.getLangOpts().CPlusPlus) {
10122     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10123     // not operate on the built-in scalar and vector float types.
10124     if (Context.getLangOpts().OpenCL &&
10125         Context.getLangOpts().OpenCLVersion < 120) {
10126       if (LHS.get()->getType()->isFloatingType() ||
10127           RHS.get()->getType()->isFloatingType())
10128         return InvalidOperands(Loc, LHS, RHS);
10129     }
10130
10131     LHS = UsualUnaryConversions(LHS.get());
10132     if (LHS.isInvalid())
10133       return QualType();
10134
10135     RHS = UsualUnaryConversions(RHS.get());
10136     if (RHS.isInvalid())
10137       return QualType();
10138
10139     if (!LHS.get()->getType()->isScalarType() ||
10140         !RHS.get()->getType()->isScalarType())
10141       return InvalidOperands(Loc, LHS, RHS);
10142
10143     return Context.IntTy;
10144   }
10145
10146   // The following is safe because we only use this method for
10147   // non-overloadable operands.
10148
10149   // C++ [expr.log.and]p1
10150   // C++ [expr.log.or]p1
10151   // The operands are both contextually converted to type bool.
10152   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10153   if (LHSRes.isInvalid())
10154     return InvalidOperands(Loc, LHS, RHS);
10155   LHS = LHSRes;
10156
10157   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10158   if (RHSRes.isInvalid())
10159     return InvalidOperands(Loc, LHS, RHS);
10160   RHS = RHSRes;
10161
10162   // C++ [expr.log.and]p2
10163   // C++ [expr.log.or]p2
10164   // The result is a bool.
10165   return Context.BoolTy;
10166 }
10167
10168 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10169   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10170   if (!ME) return false;
10171   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10172   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10173       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
10174   if (!Base) return false;
10175   return Base->getMethodDecl() != nullptr;
10176 }
10177
10178 /// Is the given expression (which must be 'const') a reference to a
10179 /// variable which was originally non-const, but which has become
10180 /// 'const' due to being captured within a block?
10181 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
10182 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
10183   assert(E->isLValue() && E->getType().isConstQualified());
10184   E = E->IgnoreParens();
10185
10186   // Must be a reference to a declaration from an enclosing scope.
10187   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10188   if (!DRE) return NCCK_None;
10189   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10190
10191   // The declaration must be a variable which is not declared 'const'.
10192   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10193   if (!var) return NCCK_None;
10194   if (var->getType().isConstQualified()) return NCCK_None;
10195   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10196
10197   // Decide whether the first capture was for a block or a lambda.
10198   DeclContext *DC = S.CurContext, *Prev = nullptr;
10199   // Decide whether the first capture was for a block or a lambda.
10200   while (DC) {
10201     // For init-capture, it is possible that the variable belongs to the
10202     // template pattern of the current context.
10203     if (auto *FD = dyn_cast<FunctionDecl>(DC))
10204       if (var->isInitCapture() &&
10205           FD->getTemplateInstantiationPattern() == var->getDeclContext())
10206         break;
10207     if (DC == var->getDeclContext())
10208       break;
10209     Prev = DC;
10210     DC = DC->getParent();
10211   }
10212   // Unless we have an init-capture, we've gone one step too far.
10213   if (!var->isInitCapture())
10214     DC = Prev;
10215   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10216 }
10217
10218 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10219   Ty = Ty.getNonReferenceType();
10220   if (IsDereference && Ty->isPointerType())
10221     Ty = Ty->getPointeeType();
10222   return !Ty.isConstQualified();
10223 }
10224
10225 /// Emit the "read-only variable not assignable" error and print notes to give
10226 /// more information about why the variable is not assignable, such as pointing
10227 /// to the declaration of a const variable, showing that a method is const, or
10228 /// that the function is returning a const reference.
10229 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10230                                     SourceLocation Loc) {
10231   // Update err_typecheck_assign_const and note_typecheck_assign_const
10232   // when this enum is changed.
10233   enum {
10234     ConstFunction,
10235     ConstVariable,
10236     ConstMember,
10237     ConstMethod,
10238     ConstUnknown,  // Keep as last element
10239   };
10240
10241   SourceRange ExprRange = E->getSourceRange();
10242
10243   // Only emit one error on the first const found.  All other consts will emit
10244   // a note to the error.
10245   bool DiagnosticEmitted = false;
10246
10247   // Track if the current expression is the result of a dereference, and if the
10248   // next checked expression is the result of a dereference.
10249   bool IsDereference = false;
10250   bool NextIsDereference = false;
10251
10252   // Loop to process MemberExpr chains.
10253   while (true) {
10254     IsDereference = NextIsDereference;
10255
10256     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10257     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10258       NextIsDereference = ME->isArrow();
10259       const ValueDecl *VD = ME->getMemberDecl();
10260       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10261         // Mutable fields can be modified even if the class is const.
10262         if (Field->isMutable()) {
10263           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10264           break;
10265         }
10266
10267         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10268           if (!DiagnosticEmitted) {
10269             S.Diag(Loc, diag::err_typecheck_assign_const)
10270                 << ExprRange << ConstMember << false /*static*/ << Field
10271                 << Field->getType();
10272             DiagnosticEmitted = true;
10273           }
10274           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10275               << ConstMember << false /*static*/ << Field << Field->getType()
10276               << Field->getSourceRange();
10277         }
10278         E = ME->getBase();
10279         continue;
10280       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10281         if (VDecl->getType().isConstQualified()) {
10282           if (!DiagnosticEmitted) {
10283             S.Diag(Loc, diag::err_typecheck_assign_const)
10284                 << ExprRange << ConstMember << true /*static*/ << VDecl
10285                 << VDecl->getType();
10286             DiagnosticEmitted = true;
10287           }
10288           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10289               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10290               << VDecl->getSourceRange();
10291         }
10292         // Static fields do not inherit constness from parents.
10293         break;
10294       }
10295       break;
10296     } // End MemberExpr
10297     break;
10298   }
10299
10300   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10301     // Function calls
10302     const FunctionDecl *FD = CE->getDirectCallee();
10303     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10304       if (!DiagnosticEmitted) {
10305         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10306                                                       << ConstFunction << FD;
10307         DiagnosticEmitted = true;
10308       }
10309       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10310              diag::note_typecheck_assign_const)
10311           << ConstFunction << FD << FD->getReturnType()
10312           << FD->getReturnTypeSourceRange();
10313     }
10314   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10315     // Point to variable declaration.
10316     if (const ValueDecl *VD = DRE->getDecl()) {
10317       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10318         if (!DiagnosticEmitted) {
10319           S.Diag(Loc, diag::err_typecheck_assign_const)
10320               << ExprRange << ConstVariable << VD << VD->getType();
10321           DiagnosticEmitted = true;
10322         }
10323         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10324             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10325       }
10326     }
10327   } else if (isa<CXXThisExpr>(E)) {
10328     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10329       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10330         if (MD->isConst()) {
10331           if (!DiagnosticEmitted) {
10332             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10333                                                           << ConstMethod << MD;
10334             DiagnosticEmitted = true;
10335           }
10336           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10337               << ConstMethod << MD << MD->getSourceRange();
10338         }
10339       }
10340     }
10341   }
10342
10343   if (DiagnosticEmitted)
10344     return;
10345
10346   // Can't determine a more specific message, so display the generic error.
10347   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10348 }
10349
10350 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10351 /// emit an error and return true.  If so, return false.
10352 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10353   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10354
10355   S.CheckShadowingDeclModification(E, Loc);
10356
10357   SourceLocation OrigLoc = Loc;
10358   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10359                                                               &Loc);
10360   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10361     IsLV = Expr::MLV_InvalidMessageExpression;
10362   if (IsLV == Expr::MLV_Valid)
10363     return false;
10364
10365   unsigned DiagID = 0;
10366   bool NeedType = false;
10367   switch (IsLV) { // C99 6.5.16p2
10368   case Expr::MLV_ConstQualified:
10369     // Use a specialized diagnostic when we're assigning to an object
10370     // from an enclosing function or block.
10371     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10372       if (NCCK == NCCK_Block)
10373         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10374       else
10375         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10376       break;
10377     }
10378
10379     // In ARC, use some specialized diagnostics for occasions where we
10380     // infer 'const'.  These are always pseudo-strong variables.
10381     if (S.getLangOpts().ObjCAutoRefCount) {
10382       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10383       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10384         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10385
10386         // Use the normal diagnostic if it's pseudo-__strong but the
10387         // user actually wrote 'const'.
10388         if (var->isARCPseudoStrong() &&
10389             (!var->getTypeSourceInfo() ||
10390              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10391           // There are two pseudo-strong cases:
10392           //  - self
10393           ObjCMethodDecl *method = S.getCurMethodDecl();
10394           if (method && var == method->getSelfDecl())
10395             DiagID = method->isClassMethod()
10396               ? diag::err_typecheck_arc_assign_self_class_method
10397               : diag::err_typecheck_arc_assign_self;
10398
10399           //  - fast enumeration variables
10400           else
10401             DiagID = diag::err_typecheck_arr_assign_enumeration;
10402
10403           SourceRange Assign;
10404           if (Loc != OrigLoc)
10405             Assign = SourceRange(OrigLoc, OrigLoc);
10406           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10407           // We need to preserve the AST regardless, so migration tool
10408           // can do its job.
10409           return false;
10410         }
10411       }
10412     }
10413
10414     // If none of the special cases above are triggered, then this is a
10415     // simple const assignment.
10416     if (DiagID == 0) {
10417       DiagnoseConstAssignment(S, E, Loc);
10418       return true;
10419     }
10420
10421     break;
10422   case Expr::MLV_ConstAddrSpace:
10423     DiagnoseConstAssignment(S, E, Loc);
10424     return true;
10425   case Expr::MLV_ArrayType:
10426   case Expr::MLV_ArrayTemporary:
10427     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10428     NeedType = true;
10429     break;
10430   case Expr::MLV_NotObjectType:
10431     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10432     NeedType = true;
10433     break;
10434   case Expr::MLV_LValueCast:
10435     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10436     break;
10437   case Expr::MLV_Valid:
10438     llvm_unreachable("did not take early return for MLV_Valid");
10439   case Expr::MLV_InvalidExpression:
10440   case Expr::MLV_MemberFunction:
10441   case Expr::MLV_ClassTemporary:
10442     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10443     break;
10444   case Expr::MLV_IncompleteType:
10445   case Expr::MLV_IncompleteVoidType:
10446     return S.RequireCompleteType(Loc, E->getType(),
10447              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10448   case Expr::MLV_DuplicateVectorComponents:
10449     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10450     break;
10451   case Expr::MLV_NoSetterProperty:
10452     llvm_unreachable("readonly properties should be processed differently");
10453   case Expr::MLV_InvalidMessageExpression:
10454     DiagID = diag::err_readonly_message_assignment;
10455     break;
10456   case Expr::MLV_SubObjCPropertySetting:
10457     DiagID = diag::err_no_subobject_property_setting;
10458     break;
10459   }
10460
10461   SourceRange Assign;
10462   if (Loc != OrigLoc)
10463     Assign = SourceRange(OrigLoc, OrigLoc);
10464   if (NeedType)
10465     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10466   else
10467     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10468   return true;
10469 }
10470
10471 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10472                                          SourceLocation Loc,
10473                                          Sema &Sema) {
10474   // C / C++ fields
10475   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10476   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10477   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10478     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10479       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10480   }
10481
10482   // Objective-C instance variables
10483   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10484   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10485   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10486     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10487     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10488     if (RL && RR && RL->getDecl() == RR->getDecl())
10489       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10490   }
10491 }
10492
10493 // C99 6.5.16.1
10494 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10495                                        SourceLocation Loc,
10496                                        QualType CompoundType) {
10497   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10498
10499   // Verify that LHS is a modifiable lvalue, and emit error if not.
10500   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10501     return QualType();
10502
10503   QualType LHSType = LHSExpr->getType();
10504   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10505                                              CompoundType;
10506   // OpenCL v1.2 s6.1.1.1 p2:
10507   // The half data type can only be used to declare a pointer to a buffer that
10508   // contains half values
10509   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10510     LHSType->isHalfType()) {
10511     Diag(Loc, diag::err_opencl_half_load_store) << 1
10512         << LHSType.getUnqualifiedType();
10513     return QualType();
10514   }
10515     
10516   AssignConvertType ConvTy;
10517   if (CompoundType.isNull()) {
10518     Expr *RHSCheck = RHS.get();
10519
10520     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10521
10522     QualType LHSTy(LHSType);
10523     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10524     if (RHS.isInvalid())
10525       return QualType();
10526     // Special case of NSObject attributes on c-style pointer types.
10527     if (ConvTy == IncompatiblePointer &&
10528         ((Context.isObjCNSObjectType(LHSType) &&
10529           RHSType->isObjCObjectPointerType()) ||
10530          (Context.isObjCNSObjectType(RHSType) &&
10531           LHSType->isObjCObjectPointerType())))
10532       ConvTy = Compatible;
10533
10534     if (ConvTy == Compatible &&
10535         LHSType->isObjCObjectType())
10536         Diag(Loc, diag::err_objc_object_assignment)
10537           << LHSType;
10538
10539     // If the RHS is a unary plus or minus, check to see if they = and + are
10540     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10541     // instead of "x += 4".
10542     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10543       RHSCheck = ICE->getSubExpr();
10544     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10545       if ((UO->getOpcode() == UO_Plus ||
10546            UO->getOpcode() == UO_Minus) &&
10547           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10548           // Only if the two operators are exactly adjacent.
10549           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10550           // And there is a space or other character before the subexpr of the
10551           // unary +/-.  We don't want to warn on "x=-1".
10552           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10553           UO->getSubExpr()->getLocStart().isFileID()) {
10554         Diag(Loc, diag::warn_not_compound_assign)
10555           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10556           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10557       }
10558     }
10559
10560     if (ConvTy == Compatible) {
10561       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10562         // Warn about retain cycles where a block captures the LHS, but
10563         // not if the LHS is a simple variable into which the block is
10564         // being stored...unless that variable can be captured by reference!
10565         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10566         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10567         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10568           checkRetainCycles(LHSExpr, RHS.get());
10569       }
10570
10571       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
10572           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
10573         // It is safe to assign a weak reference into a strong variable.
10574         // Although this code can still have problems:
10575         //   id x = self.weakProp;
10576         //   id y = self.weakProp;
10577         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10578         // paths through the function. This should be revisited if
10579         // -Wrepeated-use-of-weak is made flow-sensitive.
10580         // For ObjCWeak only, we do not warn if the assign is to a non-weak
10581         // variable, which will be valid for the current autorelease scope.
10582         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10583                              RHS.get()->getLocStart()))
10584           getCurFunction()->markSafeWeakUse(RHS.get());
10585
10586       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
10587         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10588       }
10589     }
10590   } else {
10591     // Compound assignment "x += y"
10592     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10593   }
10594
10595   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10596                                RHS.get(), AA_Assigning))
10597     return QualType();
10598
10599   CheckForNullPointerDereference(*this, LHSExpr);
10600
10601   // C99 6.5.16p3: The type of an assignment expression is the type of the
10602   // left operand unless the left operand has qualified type, in which case
10603   // it is the unqualified version of the type of the left operand.
10604   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10605   // is converted to the type of the assignment expression (above).
10606   // C++ 5.17p1: the type of the assignment expression is that of its left
10607   // operand.
10608   return (getLangOpts().CPlusPlus
10609           ? LHSType : LHSType.getUnqualifiedType());
10610 }
10611
10612 // Only ignore explicit casts to void.
10613 static bool IgnoreCommaOperand(const Expr *E) {
10614   E = E->IgnoreParens();
10615
10616   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10617     if (CE->getCastKind() == CK_ToVoid) {
10618       return true;
10619     }
10620   }
10621
10622   return false;
10623 }
10624
10625 // Look for instances where it is likely the comma operator is confused with
10626 // another operator.  There is a whitelist of acceptable expressions for the
10627 // left hand side of the comma operator, otherwise emit a warning.
10628 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10629   // No warnings in macros
10630   if (Loc.isMacroID())
10631     return;
10632
10633   // Don't warn in template instantiations.
10634   if (inTemplateInstantiation())
10635     return;
10636
10637   // Scope isn't fine-grained enough to whitelist the specific cases, so
10638   // instead, skip more than needed, then call back into here with the
10639   // CommaVisitor in SemaStmt.cpp.
10640   // The whitelisted locations are the initialization and increment portions
10641   // of a for loop.  The additional checks are on the condition of
10642   // if statements, do/while loops, and for loops.
10643   const unsigned ForIncrementFlags =
10644       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10645   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10646   const unsigned ScopeFlags = getCurScope()->getFlags();
10647   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10648       (ScopeFlags & ForInitFlags) == ForInitFlags)
10649     return;
10650
10651   // If there are multiple comma operators used together, get the RHS of the
10652   // of the comma operator as the LHS.
10653   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10654     if (BO->getOpcode() != BO_Comma)
10655       break;
10656     LHS = BO->getRHS();
10657   }
10658
10659   // Only allow some expressions on LHS to not warn.
10660   if (IgnoreCommaOperand(LHS))
10661     return;
10662
10663   Diag(Loc, diag::warn_comma_operator);
10664   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10665       << LHS->getSourceRange()
10666       << FixItHint::CreateInsertion(LHS->getLocStart(),
10667                                     LangOpts.CPlusPlus ? "static_cast<void>("
10668                                                        : "(void)(")
10669       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10670                                     ")");
10671 }
10672
10673 // C99 6.5.17
10674 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10675                                    SourceLocation Loc) {
10676   LHS = S.CheckPlaceholderExpr(LHS.get());
10677   RHS = S.CheckPlaceholderExpr(RHS.get());
10678   if (LHS.isInvalid() || RHS.isInvalid())
10679     return QualType();
10680
10681   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10682   // operands, but not unary promotions.
10683   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10684
10685   // So we treat the LHS as a ignored value, and in C++ we allow the
10686   // containing site to determine what should be done with the RHS.
10687   LHS = S.IgnoredValueConversions(LHS.get());
10688   if (LHS.isInvalid())
10689     return QualType();
10690
10691   S.DiagnoseUnusedExprResult(LHS.get());
10692
10693   if (!S.getLangOpts().CPlusPlus) {
10694     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10695     if (RHS.isInvalid())
10696       return QualType();
10697     if (!RHS.get()->getType()->isVoidType())
10698       S.RequireCompleteType(Loc, RHS.get()->getType(),
10699                             diag::err_incomplete_type);
10700   }
10701
10702   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10703     S.DiagnoseCommaOperator(LHS.get(), Loc);
10704
10705   return RHS.get()->getType();
10706 }
10707
10708 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10709 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10710 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10711                                                ExprValueKind &VK,
10712                                                ExprObjectKind &OK,
10713                                                SourceLocation OpLoc,
10714                                                bool IsInc, bool IsPrefix) {
10715   if (Op->isTypeDependent())
10716     return S.Context.DependentTy;
10717
10718   QualType ResType = Op->getType();
10719   // Atomic types can be used for increment / decrement where the non-atomic
10720   // versions can, so ignore the _Atomic() specifier for the purpose of
10721   // checking.
10722   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10723     ResType = ResAtomicType->getValueType();
10724
10725   assert(!ResType.isNull() && "no type for increment/decrement expression");
10726
10727   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10728     // Decrement of bool is not allowed.
10729     if (!IsInc) {
10730       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10731       return QualType();
10732     }
10733     // Increment of bool sets it to true, but is deprecated.
10734     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10735                                               : diag::warn_increment_bool)
10736       << Op->getSourceRange();
10737   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10738     // Error on enum increments and decrements in C++ mode
10739     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10740     return QualType();
10741   } else if (ResType->isRealType()) {
10742     // OK!
10743   } else if (ResType->isPointerType()) {
10744     // C99 6.5.2.4p2, 6.5.6p2
10745     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10746       return QualType();
10747   } else if (ResType->isObjCObjectPointerType()) {
10748     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10749     // Otherwise, we just need a complete type.
10750     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10751         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10752       return QualType();    
10753   } else if (ResType->isAnyComplexType()) {
10754     // C99 does not support ++/-- on complex types, we allow as an extension.
10755     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10756       << ResType << Op->getSourceRange();
10757   } else if (ResType->isPlaceholderType()) {
10758     ExprResult PR = S.CheckPlaceholderExpr(Op);
10759     if (PR.isInvalid()) return QualType();
10760     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10761                                           IsInc, IsPrefix);
10762   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10763     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10764   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10765              (ResType->getAs<VectorType>()->getVectorKind() !=
10766               VectorType::AltiVecBool)) {
10767     // The z vector extensions allow ++ and -- for non-bool vectors.
10768   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10769             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10770     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10771   } else {
10772     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10773       << ResType << int(IsInc) << Op->getSourceRange();
10774     return QualType();
10775   }
10776   // At this point, we know we have a real, complex or pointer type.
10777   // Now make sure the operand is a modifiable lvalue.
10778   if (CheckForModifiableLvalue(Op, OpLoc, S))
10779     return QualType();
10780   // In C++, a prefix increment is the same type as the operand. Otherwise
10781   // (in C or with postfix), the increment is the unqualified type of the
10782   // operand.
10783   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10784     VK = VK_LValue;
10785     OK = Op->getObjectKind();
10786     return ResType;
10787   } else {
10788     VK = VK_RValue;
10789     return ResType.getUnqualifiedType();
10790   }
10791 }
10792   
10793
10794 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10795 /// This routine allows us to typecheck complex/recursive expressions
10796 /// where the declaration is needed for type checking. We only need to
10797 /// handle cases when the expression references a function designator
10798 /// or is an lvalue. Here are some examples:
10799 ///  - &(x) => x
10800 ///  - &*****f => f for f a function designator.
10801 ///  - &s.xx => s
10802 ///  - &s.zz[1].yy -> s, if zz is an array
10803 ///  - *(x + 1) -> x, if x is an array
10804 ///  - &"123"[2] -> 0
10805 ///  - & __real__ x -> x
10806 static ValueDecl *getPrimaryDecl(Expr *E) {
10807   switch (E->getStmtClass()) {
10808   case Stmt::DeclRefExprClass:
10809     return cast<DeclRefExpr>(E)->getDecl();
10810   case Stmt::MemberExprClass:
10811     // If this is an arrow operator, the address is an offset from
10812     // the base's value, so the object the base refers to is
10813     // irrelevant.
10814     if (cast<MemberExpr>(E)->isArrow())
10815       return nullptr;
10816     // Otherwise, the expression refers to a part of the base
10817     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10818   case Stmt::ArraySubscriptExprClass: {
10819     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10820     // promotion of register arrays earlier.
10821     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10822     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10823       if (ICE->getSubExpr()->getType()->isArrayType())
10824         return getPrimaryDecl(ICE->getSubExpr());
10825     }
10826     return nullptr;
10827   }
10828   case Stmt::UnaryOperatorClass: {
10829     UnaryOperator *UO = cast<UnaryOperator>(E);
10830
10831     switch(UO->getOpcode()) {
10832     case UO_Real:
10833     case UO_Imag:
10834     case UO_Extension:
10835       return getPrimaryDecl(UO->getSubExpr());
10836     default:
10837       return nullptr;
10838     }
10839   }
10840   case Stmt::ParenExprClass:
10841     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10842   case Stmt::ImplicitCastExprClass:
10843     // If the result of an implicit cast is an l-value, we care about
10844     // the sub-expression; otherwise, the result here doesn't matter.
10845     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10846   default:
10847     return nullptr;
10848   }
10849 }
10850
10851 namespace {
10852   enum {
10853     AO_Bit_Field = 0,
10854     AO_Vector_Element = 1,
10855     AO_Property_Expansion = 2,
10856     AO_Register_Variable = 3,
10857     AO_No_Error = 4
10858   };
10859 }
10860 /// \brief Diagnose invalid operand for address of operations.
10861 ///
10862 /// \param Type The type of operand which cannot have its address taken.
10863 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10864                                          Expr *E, unsigned Type) {
10865   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10866 }
10867
10868 /// CheckAddressOfOperand - The operand of & must be either a function
10869 /// designator or an lvalue designating an object. If it is an lvalue, the
10870 /// object cannot be declared with storage class register or be a bit field.
10871 /// Note: The usual conversions are *not* applied to the operand of the &
10872 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10873 /// In C++, the operand might be an overloaded function name, in which case
10874 /// we allow the '&' but retain the overloaded-function type.
10875 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10876   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10877     if (PTy->getKind() == BuiltinType::Overload) {
10878       Expr *E = OrigOp.get()->IgnoreParens();
10879       if (!isa<OverloadExpr>(E)) {
10880         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10881         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10882           << OrigOp.get()->getSourceRange();
10883         return QualType();
10884       }
10885
10886       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10887       if (isa<UnresolvedMemberExpr>(Ovl))
10888         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10889           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10890             << OrigOp.get()->getSourceRange();
10891           return QualType();
10892         }
10893
10894       return Context.OverloadTy;
10895     }
10896
10897     if (PTy->getKind() == BuiltinType::UnknownAny)
10898       return Context.UnknownAnyTy;
10899
10900     if (PTy->getKind() == BuiltinType::BoundMember) {
10901       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10902         << OrigOp.get()->getSourceRange();
10903       return QualType();
10904     }
10905
10906     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10907     if (OrigOp.isInvalid()) return QualType();
10908   }
10909
10910   if (OrigOp.get()->isTypeDependent())
10911     return Context.DependentTy;
10912
10913   assert(!OrigOp.get()->getType()->isPlaceholderType());
10914
10915   // Make sure to ignore parentheses in subsequent checks
10916   Expr *op = OrigOp.get()->IgnoreParens();
10917
10918   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10919   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10920     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10921     return QualType();
10922   }
10923
10924   if (getLangOpts().C99) {
10925     // Implement C99-only parts of addressof rules.
10926     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10927       if (uOp->getOpcode() == UO_Deref)
10928         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10929         // (assuming the deref expression is valid).
10930         return uOp->getSubExpr()->getType();
10931     }
10932     // Technically, there should be a check for array subscript
10933     // expressions here, but the result of one is always an lvalue anyway.
10934   }
10935   ValueDecl *dcl = getPrimaryDecl(op);
10936
10937   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10938     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10939                                            op->getLocStart()))
10940       return QualType();
10941
10942   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10943   unsigned AddressOfError = AO_No_Error;
10944
10945   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 
10946     bool sfinae = (bool)isSFINAEContext();
10947     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10948                                   : diag::ext_typecheck_addrof_temporary)
10949       << op->getType() << op->getSourceRange();
10950     if (sfinae)
10951       return QualType();
10952     // Materialize the temporary as an lvalue so that we can take its address.
10953     OrigOp = op =
10954         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10955   } else if (isa<ObjCSelectorExpr>(op)) {
10956     return Context.getPointerType(op->getType());
10957   } else if (lval == Expr::LV_MemberFunction) {
10958     // If it's an instance method, make a member pointer.
10959     // The expression must have exactly the form &A::foo.
10960
10961     // If the underlying expression isn't a decl ref, give up.
10962     if (!isa<DeclRefExpr>(op)) {
10963       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10964         << OrigOp.get()->getSourceRange();
10965       return QualType();
10966     }
10967     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10968     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10969
10970     // The id-expression was parenthesized.
10971     if (OrigOp.get() != DRE) {
10972       Diag(OpLoc, diag::err_parens_pointer_member_function)
10973         << OrigOp.get()->getSourceRange();
10974
10975     // The method was named without a qualifier.
10976     } else if (!DRE->getQualifier()) {
10977       if (MD->getParent()->getName().empty())
10978         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10979           << op->getSourceRange();
10980       else {
10981         SmallString<32> Str;
10982         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10983         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10984           << op->getSourceRange()
10985           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10986       }
10987     }
10988
10989     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10990     if (isa<CXXDestructorDecl>(MD))
10991       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10992
10993     QualType MPTy = Context.getMemberPointerType(
10994         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10995     // Under the MS ABI, lock down the inheritance model now.
10996     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10997       (void)isCompleteType(OpLoc, MPTy);
10998     return MPTy;
10999   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11000     // C99 6.5.3.2p1
11001     // The operand must be either an l-value or a function designator
11002     if (!op->getType()->isFunctionType()) {
11003       // Use a special diagnostic for loads from property references.
11004       if (isa<PseudoObjectExpr>(op)) {
11005         AddressOfError = AO_Property_Expansion;
11006       } else {
11007         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11008           << op->getType() << op->getSourceRange();
11009         return QualType();
11010       }
11011     }
11012   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
11013     // The operand cannot be a bit-field
11014     AddressOfError = AO_Bit_Field;
11015   } else if (op->getObjectKind() == OK_VectorComponent) {
11016     // The operand cannot be an element of a vector
11017     AddressOfError = AO_Vector_Element;
11018   } else if (dcl) { // C99 6.5.3.2p1
11019     // We have an lvalue with a decl. Make sure the decl is not declared
11020     // with the register storage-class specifier.
11021     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
11022       // in C++ it is not error to take address of a register
11023       // variable (c++03 7.1.1P3)
11024       if (vd->getStorageClass() == SC_Register &&
11025           !getLangOpts().CPlusPlus) {
11026         AddressOfError = AO_Register_Variable;
11027       }
11028     } else if (isa<MSPropertyDecl>(dcl)) {
11029       AddressOfError = AO_Property_Expansion;
11030     } else if (isa<FunctionTemplateDecl>(dcl)) {
11031       return Context.OverloadTy;
11032     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
11033       // Okay: we can take the address of a field.
11034       // Could be a pointer to member, though, if there is an explicit
11035       // scope qualifier for the class.
11036       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
11037         DeclContext *Ctx = dcl->getDeclContext();
11038         if (Ctx && Ctx->isRecord()) {
11039           if (dcl->getType()->isReferenceType()) {
11040             Diag(OpLoc,
11041                  diag::err_cannot_form_pointer_to_member_of_reference_type)
11042               << dcl->getDeclName() << dcl->getType();
11043             return QualType();
11044           }
11045
11046           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
11047             Ctx = Ctx->getParent();
11048
11049           QualType MPTy = Context.getMemberPointerType(
11050               op->getType(),
11051               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
11052           // Under the MS ABI, lock down the inheritance model now.
11053           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11054             (void)isCompleteType(OpLoc, MPTy);
11055           return MPTy;
11056         }
11057       }
11058     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
11059                !isa<BindingDecl>(dcl))
11060       llvm_unreachable("Unknown/unexpected decl type");
11061   }
11062
11063   if (AddressOfError != AO_No_Error) {
11064     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
11065     return QualType();
11066   }
11067
11068   if (lval == Expr::LV_IncompleteVoidType) {
11069     // Taking the address of a void variable is technically illegal, but we
11070     // allow it in cases which are otherwise valid.
11071     // Example: "extern void x; void* y = &x;".
11072     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
11073   }
11074
11075   // If the operand has type "type", the result has type "pointer to type".
11076   if (op->getType()->isObjCObjectType())
11077     return Context.getObjCObjectPointerType(op->getType());
11078
11079   CheckAddressOfPackedMember(op);
11080
11081   return Context.getPointerType(op->getType());
11082 }
11083
11084 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11085   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11086   if (!DRE)
11087     return;
11088   const Decl *D = DRE->getDecl();
11089   if (!D)
11090     return;
11091   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11092   if (!Param)
11093     return;
11094   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11095     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11096       return;
11097   if (FunctionScopeInfo *FD = S.getCurFunction())
11098     if (!FD->ModifiedNonNullParams.count(Param))
11099       FD->ModifiedNonNullParams.insert(Param);
11100 }
11101
11102 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11103 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
11104                                         SourceLocation OpLoc) {
11105   if (Op->isTypeDependent())
11106     return S.Context.DependentTy;
11107
11108   ExprResult ConvResult = S.UsualUnaryConversions(Op);
11109   if (ConvResult.isInvalid())
11110     return QualType();
11111   Op = ConvResult.get();
11112   QualType OpTy = Op->getType();
11113   QualType Result;
11114
11115   if (isa<CXXReinterpretCastExpr>(Op)) {
11116     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11117     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11118                                      Op->getSourceRange());
11119   }
11120
11121   if (const PointerType *PT = OpTy->getAs<PointerType>())
11122   {
11123     Result = PT->getPointeeType();
11124   }
11125   else if (const ObjCObjectPointerType *OPT =
11126              OpTy->getAs<ObjCObjectPointerType>())
11127     Result = OPT->getPointeeType();
11128   else {
11129     ExprResult PR = S.CheckPlaceholderExpr(Op);
11130     if (PR.isInvalid()) return QualType();
11131     if (PR.get() != Op)
11132       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
11133   }
11134
11135   if (Result.isNull()) {
11136     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
11137       << OpTy << Op->getSourceRange();
11138     return QualType();
11139   }
11140
11141   // Note that per both C89 and C99, indirection is always legal, even if Result
11142   // is an incomplete type or void.  It would be possible to warn about
11143   // dereferencing a void pointer, but it's completely well-defined, and such a
11144   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
11145   // for pointers to 'void' but is fine for any other pointer type:
11146   //
11147   // C++ [expr.unary.op]p1:
11148   //   [...] the expression to which [the unary * operator] is applied shall
11149   //   be a pointer to an object type, or a pointer to a function type
11150   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
11151     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
11152       << OpTy << Op->getSourceRange();
11153
11154   // Dereferences are usually l-values...
11155   VK = VK_LValue;
11156
11157   // ...except that certain expressions are never l-values in C.
11158   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
11159     VK = VK_RValue;
11160   
11161   return Result;
11162 }
11163
11164 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
11165   BinaryOperatorKind Opc;
11166   switch (Kind) {
11167   default: llvm_unreachable("Unknown binop!");
11168   case tok::periodstar:           Opc = BO_PtrMemD; break;
11169   case tok::arrowstar:            Opc = BO_PtrMemI; break;
11170   case tok::star:                 Opc = BO_Mul; break;
11171   case tok::slash:                Opc = BO_Div; break;
11172   case tok::percent:              Opc = BO_Rem; break;
11173   case tok::plus:                 Opc = BO_Add; break;
11174   case tok::minus:                Opc = BO_Sub; break;
11175   case tok::lessless:             Opc = BO_Shl; break;
11176   case tok::greatergreater:       Opc = BO_Shr; break;
11177   case tok::lessequal:            Opc = BO_LE; break;
11178   case tok::less:                 Opc = BO_LT; break;
11179   case tok::greaterequal:         Opc = BO_GE; break;
11180   case tok::greater:              Opc = BO_GT; break;
11181   case tok::exclaimequal:         Opc = BO_NE; break;
11182   case tok::equalequal:           Opc = BO_EQ; break;
11183   case tok::amp:                  Opc = BO_And; break;
11184   case tok::caret:                Opc = BO_Xor; break;
11185   case tok::pipe:                 Opc = BO_Or; break;
11186   case tok::ampamp:               Opc = BO_LAnd; break;
11187   case tok::pipepipe:             Opc = BO_LOr; break;
11188   case tok::equal:                Opc = BO_Assign; break;
11189   case tok::starequal:            Opc = BO_MulAssign; break;
11190   case tok::slashequal:           Opc = BO_DivAssign; break;
11191   case tok::percentequal:         Opc = BO_RemAssign; break;
11192   case tok::plusequal:            Opc = BO_AddAssign; break;
11193   case tok::minusequal:           Opc = BO_SubAssign; break;
11194   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
11195   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
11196   case tok::ampequal:             Opc = BO_AndAssign; break;
11197   case tok::caretequal:           Opc = BO_XorAssign; break;
11198   case tok::pipeequal:            Opc = BO_OrAssign; break;
11199   case tok::comma:                Opc = BO_Comma; break;
11200   }
11201   return Opc;
11202 }
11203
11204 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
11205   tok::TokenKind Kind) {
11206   UnaryOperatorKind Opc;
11207   switch (Kind) {
11208   default: llvm_unreachable("Unknown unary op!");
11209   case tok::plusplus:     Opc = UO_PreInc; break;
11210   case tok::minusminus:   Opc = UO_PreDec; break;
11211   case tok::amp:          Opc = UO_AddrOf; break;
11212   case tok::star:         Opc = UO_Deref; break;
11213   case tok::plus:         Opc = UO_Plus; break;
11214   case tok::minus:        Opc = UO_Minus; break;
11215   case tok::tilde:        Opc = UO_Not; break;
11216   case tok::exclaim:      Opc = UO_LNot; break;
11217   case tok::kw___real:    Opc = UO_Real; break;
11218   case tok::kw___imag:    Opc = UO_Imag; break;
11219   case tok::kw___extension__: Opc = UO_Extension; break;
11220   }
11221   return Opc;
11222 }
11223
11224 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11225 /// This warning is only emitted for builtin assignment operations. It is also
11226 /// suppressed in the event of macro expansions.
11227 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11228                                    SourceLocation OpLoc) {
11229   if (S.inTemplateInstantiation())
11230     return;
11231   if (OpLoc.isInvalid() || OpLoc.isMacroID())
11232     return;
11233   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11234   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11235   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11236   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11237   if (!LHSDeclRef || !RHSDeclRef ||
11238       LHSDeclRef->getLocation().isMacroID() ||
11239       RHSDeclRef->getLocation().isMacroID())
11240     return;
11241   const ValueDecl *LHSDecl =
11242     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11243   const ValueDecl *RHSDecl =
11244     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11245   if (LHSDecl != RHSDecl)
11246     return;
11247   if (LHSDecl->getType().isVolatileQualified())
11248     return;
11249   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11250     if (RefTy->getPointeeType().isVolatileQualified())
11251       return;
11252
11253   S.Diag(OpLoc, diag::warn_self_assignment)
11254       << LHSDeclRef->getType()
11255       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11256 }
11257
11258 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
11259 /// is usually indicative of introspection within the Objective-C pointer.
11260 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11261                                           SourceLocation OpLoc) {
11262   if (!S.getLangOpts().ObjC1)
11263     return;
11264
11265   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11266   const Expr *LHS = L.get();
11267   const Expr *RHS = R.get();
11268
11269   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11270     ObjCPointerExpr = LHS;
11271     OtherExpr = RHS;
11272   }
11273   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11274     ObjCPointerExpr = RHS;
11275     OtherExpr = LHS;
11276   }
11277
11278   // This warning is deliberately made very specific to reduce false
11279   // positives with logic that uses '&' for hashing.  This logic mainly
11280   // looks for code trying to introspect into tagged pointers, which
11281   // code should generally never do.
11282   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11283     unsigned Diag = diag::warn_objc_pointer_masking;
11284     // Determine if we are introspecting the result of performSelectorXXX.
11285     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11286     // Special case messages to -performSelector and friends, which
11287     // can return non-pointer values boxed in a pointer value.
11288     // Some clients may wish to silence warnings in this subcase.
11289     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11290       Selector S = ME->getSelector();
11291       StringRef SelArg0 = S.getNameForSlot(0);
11292       if (SelArg0.startswith("performSelector"))
11293         Diag = diag::warn_objc_pointer_masking_performSelector;
11294     }
11295     
11296     S.Diag(OpLoc, Diag)
11297       << ObjCPointerExpr->getSourceRange();
11298   }
11299 }
11300
11301 static NamedDecl *getDeclFromExpr(Expr *E) {
11302   if (!E)
11303     return nullptr;
11304   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11305     return DRE->getDecl();
11306   if (auto *ME = dyn_cast<MemberExpr>(E))
11307     return ME->getMemberDecl();
11308   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11309     return IRE->getDecl();
11310   return nullptr;
11311 }
11312
11313 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11314 /// operator @p Opc at location @c TokLoc. This routine only supports
11315 /// built-in operations; ActOnBinOp handles overloaded operators.
11316 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11317                                     BinaryOperatorKind Opc,
11318                                     Expr *LHSExpr, Expr *RHSExpr) {
11319   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11320     // The syntax only allows initializer lists on the RHS of assignment,
11321     // so we don't need to worry about accepting invalid code for
11322     // non-assignment operators.
11323     // C++11 5.17p9:
11324     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11325     //   of x = {} is x = T().
11326     InitializationKind Kind =
11327         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
11328     InitializedEntity Entity =
11329         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11330     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11331     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11332     if (Init.isInvalid())
11333       return Init;
11334     RHSExpr = Init.get();
11335   }
11336
11337   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11338   QualType ResultTy;     // Result type of the binary operator.
11339   // The following two variables are used for compound assignment operators
11340   QualType CompLHSTy;    // Type of LHS after promotions for computation
11341   QualType CompResultTy; // Type of computation result
11342   ExprValueKind VK = VK_RValue;
11343   ExprObjectKind OK = OK_Ordinary;
11344
11345   if (!getLangOpts().CPlusPlus) {
11346     // C cannot handle TypoExpr nodes on either side of a binop because it
11347     // doesn't handle dependent types properly, so make sure any TypoExprs have
11348     // been dealt with before checking the operands.
11349     LHS = CorrectDelayedTyposInExpr(LHSExpr);
11350     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
11351       if (Opc != BO_Assign)
11352         return ExprResult(E);
11353       // Avoid correcting the RHS to the same Expr as the LHS.
11354       Decl *D = getDeclFromExpr(E);
11355       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11356     });
11357     if (!LHS.isUsable() || !RHS.isUsable())
11358       return ExprError();
11359   }
11360
11361   if (getLangOpts().OpenCL) {
11362     QualType LHSTy = LHSExpr->getType();
11363     QualType RHSTy = RHSExpr->getType();
11364     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11365     // the ATOMIC_VAR_INIT macro.
11366     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11367       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11368       if (BO_Assign == Opc)
11369         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
11370       else
11371         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11372       return ExprError();
11373     }
11374
11375     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11376     // only with a builtin functions and therefore should be disallowed here.
11377     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11378         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11379         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11380         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11381       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11382       return ExprError();
11383     }
11384   }
11385
11386   switch (Opc) {
11387   case BO_Assign:
11388     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11389     if (getLangOpts().CPlusPlus &&
11390         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11391       VK = LHS.get()->getValueKind();
11392       OK = LHS.get()->getObjectKind();
11393     }
11394     if (!ResultTy.isNull()) {
11395       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11396       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11397     }
11398     RecordModifiableNonNullParam(*this, LHS.get());
11399     break;
11400   case BO_PtrMemD:
11401   case BO_PtrMemI:
11402     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11403                                             Opc == BO_PtrMemI);
11404     break;
11405   case BO_Mul:
11406   case BO_Div:
11407     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11408                                            Opc == BO_Div);
11409     break;
11410   case BO_Rem:
11411     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11412     break;
11413   case BO_Add:
11414     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11415     break;
11416   case BO_Sub:
11417     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11418     break;
11419   case BO_Shl:
11420   case BO_Shr:
11421     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11422     break;
11423   case BO_LE:
11424   case BO_LT:
11425   case BO_GE:
11426   case BO_GT:
11427     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11428     break;
11429   case BO_EQ:
11430   case BO_NE:
11431     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11432     break;
11433   case BO_And:
11434     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11435     LLVM_FALLTHROUGH;
11436   case BO_Xor:
11437   case BO_Or:
11438     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11439     break;
11440   case BO_LAnd:
11441   case BO_LOr:
11442     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11443     break;
11444   case BO_MulAssign:
11445   case BO_DivAssign:
11446     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11447                                                Opc == BO_DivAssign);
11448     CompLHSTy = CompResultTy;
11449     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11450       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11451     break;
11452   case BO_RemAssign:
11453     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11454     CompLHSTy = CompResultTy;
11455     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11456       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11457     break;
11458   case BO_AddAssign:
11459     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11460     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11461       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11462     break;
11463   case BO_SubAssign:
11464     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11465     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11466       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11467     break;
11468   case BO_ShlAssign:
11469   case BO_ShrAssign:
11470     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, 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_AndAssign:
11476   case BO_OrAssign: // fallthrough
11477     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11478     LLVM_FALLTHROUGH;
11479   case BO_XorAssign:
11480     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11481     CompLHSTy = CompResultTy;
11482     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11483       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11484     break;
11485   case BO_Comma:
11486     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11487     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11488       VK = RHS.get()->getValueKind();
11489       OK = RHS.get()->getObjectKind();
11490     }
11491     break;
11492   }
11493   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11494     return ExprError();
11495
11496   // Check for array bounds violations for both sides of the BinaryOperator
11497   CheckArrayAccess(LHS.get());
11498   CheckArrayAccess(RHS.get());
11499
11500   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11501     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11502                                                  &Context.Idents.get("object_setClass"),
11503                                                  SourceLocation(), LookupOrdinaryName);
11504     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11505       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11506       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11507       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11508       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11509       FixItHint::CreateInsertion(RHSLocEnd, ")");
11510     }
11511     else
11512       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11513   }
11514   else if (const ObjCIvarRefExpr *OIRE =
11515            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11516     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11517   
11518   if (CompResultTy.isNull())
11519     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11520                                         OK, OpLoc, FPFeatures);
11521   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11522       OK_ObjCProperty) {
11523     VK = VK_LValue;
11524     OK = LHS.get()->getObjectKind();
11525   }
11526   return new (Context) CompoundAssignOperator(
11527       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11528       OpLoc, FPFeatures);
11529 }
11530
11531 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11532 /// operators are mixed in a way that suggests that the programmer forgot that
11533 /// comparison operators have higher precedence. The most typical example of
11534 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11535 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11536                                       SourceLocation OpLoc, Expr *LHSExpr,
11537                                       Expr *RHSExpr) {
11538   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11539   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11540
11541   // Check that one of the sides is a comparison operator and the other isn't.
11542   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11543   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11544   if (isLeftComp == isRightComp)
11545     return;
11546
11547   // Bitwise operations are sometimes used as eager logical ops.
11548   // Don't diagnose this.
11549   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11550   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11551   if (isLeftBitwise || isRightBitwise)
11552     return;
11553
11554   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11555                                                    OpLoc)
11556                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11557   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11558   SourceRange ParensRange = isLeftComp ?
11559       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11560     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11561
11562   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11563     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11564   SuggestParentheses(Self, OpLoc,
11565     Self.PDiag(diag::note_precedence_silence) << OpStr,
11566     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11567   SuggestParentheses(Self, OpLoc,
11568     Self.PDiag(diag::note_precedence_bitwise_first)
11569       << BinaryOperator::getOpcodeStr(Opc),
11570     ParensRange);
11571 }
11572
11573 /// \brief It accepts a '&&' expr that is inside a '||' one.
11574 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11575 /// in parentheses.
11576 static void
11577 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11578                                        BinaryOperator *Bop) {
11579   assert(Bop->getOpcode() == BO_LAnd);
11580   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11581       << Bop->getSourceRange() << OpLoc;
11582   SuggestParentheses(Self, Bop->getOperatorLoc(),
11583     Self.PDiag(diag::note_precedence_silence)
11584       << Bop->getOpcodeStr(),
11585     Bop->getSourceRange());
11586 }
11587
11588 /// \brief Returns true if the given expression can be evaluated as a constant
11589 /// 'true'.
11590 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11591   bool Res;
11592   return !E->isValueDependent() &&
11593          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11594 }
11595
11596 /// \brief Returns true if the given expression can be evaluated as a constant
11597 /// 'false'.
11598 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11599   bool Res;
11600   return !E->isValueDependent() &&
11601          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11602 }
11603
11604 /// \brief Look for '&&' in the left hand of a '||' expr.
11605 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11606                                              Expr *LHSExpr, Expr *RHSExpr) {
11607   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11608     if (Bop->getOpcode() == BO_LAnd) {
11609       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11610       if (EvaluatesAsFalse(S, RHSExpr))
11611         return;
11612       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11613       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11614         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11615     } else if (Bop->getOpcode() == BO_LOr) {
11616       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11617         // If it's "a || b && 1 || c" we didn't warn earlier for
11618         // "a || b && 1", but warn now.
11619         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11620           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11621       }
11622     }
11623   }
11624 }
11625
11626 /// \brief Look for '&&' in the right hand of a '||' expr.
11627 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11628                                              Expr *LHSExpr, Expr *RHSExpr) {
11629   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11630     if (Bop->getOpcode() == BO_LAnd) {
11631       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11632       if (EvaluatesAsFalse(S, LHSExpr))
11633         return;
11634       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11635       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11636         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11637     }
11638   }
11639 }
11640
11641 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11642 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11643 /// the '&' expression in parentheses.
11644 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11645                                          SourceLocation OpLoc, Expr *SubExpr) {
11646   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11647     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11648       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11649         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11650         << Bop->getSourceRange() << OpLoc;
11651       SuggestParentheses(S, Bop->getOperatorLoc(),
11652         S.PDiag(diag::note_precedence_silence)
11653           << Bop->getOpcodeStr(),
11654         Bop->getSourceRange());
11655     }
11656   }
11657 }
11658
11659 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11660                                     Expr *SubExpr, StringRef Shift) {
11661   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11662     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11663       StringRef Op = Bop->getOpcodeStr();
11664       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11665           << Bop->getSourceRange() << OpLoc << Shift << Op;
11666       SuggestParentheses(S, Bop->getOperatorLoc(),
11667           S.PDiag(diag::note_precedence_silence) << Op,
11668           Bop->getSourceRange());
11669     }
11670   }
11671 }
11672
11673 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11674                                  Expr *LHSExpr, Expr *RHSExpr) {
11675   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11676   if (!OCE)
11677     return;
11678
11679   FunctionDecl *FD = OCE->getDirectCallee();
11680   if (!FD || !FD->isOverloadedOperator())
11681     return;
11682
11683   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11684   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11685     return;
11686
11687   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11688       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11689       << (Kind == OO_LessLess);
11690   SuggestParentheses(S, OCE->getOperatorLoc(),
11691                      S.PDiag(diag::note_precedence_silence)
11692                          << (Kind == OO_LessLess ? "<<" : ">>"),
11693                      OCE->getSourceRange());
11694   SuggestParentheses(S, OpLoc,
11695                      S.PDiag(diag::note_evaluate_comparison_first),
11696                      SourceRange(OCE->getArg(1)->getLocStart(),
11697                                  RHSExpr->getLocEnd()));
11698 }
11699
11700 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11701 /// precedence.
11702 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11703                                     SourceLocation OpLoc, Expr *LHSExpr,
11704                                     Expr *RHSExpr){
11705   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11706   if (BinaryOperator::isBitwiseOp(Opc))
11707     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11708
11709   // Diagnose "arg1 & arg2 | arg3"
11710   if ((Opc == BO_Or || Opc == BO_Xor) &&
11711       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11712     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11713     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11714   }
11715
11716   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11717   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11718   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11719     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11720     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11721   }
11722
11723   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11724       || Opc == BO_Shr) {
11725     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11726     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11727     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11728   }
11729
11730   // Warn on overloaded shift operators and comparisons, such as:
11731   // cout << 5 == 4;
11732   if (BinaryOperator::isComparisonOp(Opc))
11733     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11734 }
11735
11736 // Binary Operators.  'Tok' is the token for the operator.
11737 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11738                             tok::TokenKind Kind,
11739                             Expr *LHSExpr, Expr *RHSExpr) {
11740   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11741   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11742   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11743
11744   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11745   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11746
11747   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11748 }
11749
11750 /// Build an overloaded binary operator expression in the given scope.
11751 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11752                                        BinaryOperatorKind Opc,
11753                                        Expr *LHS, Expr *RHS) {
11754   // Find all of the overloaded operators visible from this
11755   // point. We perform both an operator-name lookup from the local
11756   // scope and an argument-dependent lookup based on the types of
11757   // the arguments.
11758   UnresolvedSet<16> Functions;
11759   OverloadedOperatorKind OverOp
11760     = BinaryOperator::getOverloadedOperator(Opc);
11761   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11762     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11763                                    RHS->getType(), Functions);
11764
11765   // Build the (potentially-overloaded, potentially-dependent)
11766   // binary operation.
11767   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11768 }
11769
11770 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11771                             BinaryOperatorKind Opc,
11772                             Expr *LHSExpr, Expr *RHSExpr) {
11773   // We want to end up calling one of checkPseudoObjectAssignment
11774   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11775   // both expressions are overloadable or either is type-dependent),
11776   // or CreateBuiltinBinOp (in any other case).  We also want to get
11777   // any placeholder types out of the way.
11778
11779   // Handle pseudo-objects in the LHS.
11780   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11781     // Assignments with a pseudo-object l-value need special analysis.
11782     if (pty->getKind() == BuiltinType::PseudoObject &&
11783         BinaryOperator::isAssignmentOp(Opc))
11784       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11785
11786     // Don't resolve overloads if the other type is overloadable.
11787     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
11788       // We can't actually test that if we still have a placeholder,
11789       // though.  Fortunately, none of the exceptions we see in that
11790       // code below are valid when the LHS is an overload set.  Note
11791       // that an overload set can be dependently-typed, but it never
11792       // instantiates to having an overloadable type.
11793       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11794       if (resolvedRHS.isInvalid()) return ExprError();
11795       RHSExpr = resolvedRHS.get();
11796
11797       if (RHSExpr->isTypeDependent() ||
11798           RHSExpr->getType()->isOverloadableType())
11799         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11800     }
11801
11802     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
11803     // template, diagnose the missing 'template' keyword instead of diagnosing
11804     // an invalid use of a bound member function.
11805     //
11806     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
11807     // to C++1z [over.over]/1.4, but we already checked for that case above.
11808     if (Opc == BO_LT && inTemplateInstantiation() &&
11809         (pty->getKind() == BuiltinType::BoundMember ||
11810          pty->getKind() == BuiltinType::Overload)) {
11811       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
11812       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
11813           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
11814             return isa<FunctionTemplateDecl>(ND);
11815           })) {
11816         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
11817                                 : OE->getNameLoc(),
11818              diag::err_template_kw_missing)
11819           << OE->getName().getAsString() << "";
11820         return ExprError();
11821       }
11822     }
11823         
11824     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11825     if (LHS.isInvalid()) return ExprError();
11826     LHSExpr = LHS.get();
11827   }
11828
11829   // Handle pseudo-objects in the RHS.
11830   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11831     // An overload in the RHS can potentially be resolved by the type
11832     // being assigned to.
11833     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11834       if (getLangOpts().CPlusPlus &&
11835           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
11836            LHSExpr->getType()->isOverloadableType()))
11837         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11838
11839       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11840     }
11841
11842     // Don't resolve overloads if the other type is overloadable.
11843     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
11844         LHSExpr->getType()->isOverloadableType())
11845       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11846
11847     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11848     if (!resolvedRHS.isUsable()) return ExprError();
11849     RHSExpr = resolvedRHS.get();
11850   }
11851
11852   if (getLangOpts().CPlusPlus) {
11853     // If either expression is type-dependent, always build an
11854     // overloaded op.
11855     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11856       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11857
11858     // Otherwise, build an overloaded op if either expression has an
11859     // overloadable type.
11860     if (LHSExpr->getType()->isOverloadableType() ||
11861         RHSExpr->getType()->isOverloadableType())
11862       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11863   }
11864
11865   // Build a built-in binary operation.
11866   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11867 }
11868
11869 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11870                                       UnaryOperatorKind Opc,
11871                                       Expr *InputExpr) {
11872   ExprResult Input = InputExpr;
11873   ExprValueKind VK = VK_RValue;
11874   ExprObjectKind OK = OK_Ordinary;
11875   QualType resultType;
11876   if (getLangOpts().OpenCL) {
11877     QualType Ty = InputExpr->getType();
11878     // The only legal unary operation for atomics is '&'.
11879     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11880     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11881     // only with a builtin functions and therefore should be disallowed here.
11882         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11883         || Ty->isBlockPointerType())) {
11884       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11885                        << InputExpr->getType()
11886                        << Input.get()->getSourceRange());
11887     }
11888   }
11889   switch (Opc) {
11890   case UO_PreInc:
11891   case UO_PreDec:
11892   case UO_PostInc:
11893   case UO_PostDec:
11894     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11895                                                 OpLoc,
11896                                                 Opc == UO_PreInc ||
11897                                                 Opc == UO_PostInc,
11898                                                 Opc == UO_PreInc ||
11899                                                 Opc == UO_PreDec);
11900     break;
11901   case UO_AddrOf:
11902     resultType = CheckAddressOfOperand(Input, OpLoc);
11903     RecordModifiableNonNullParam(*this, InputExpr);
11904     break;
11905   case UO_Deref: {
11906     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11907     if (Input.isInvalid()) return ExprError();
11908     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11909     break;
11910   }
11911   case UO_Plus:
11912   case UO_Minus:
11913     Input = UsualUnaryConversions(Input.get());
11914     if (Input.isInvalid()) return ExprError();
11915     resultType = Input.get()->getType();
11916     if (resultType->isDependentType())
11917       break;
11918     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11919       break;
11920     else if (resultType->isVectorType() &&
11921              // The z vector extensions don't allow + or - with bool vectors.
11922              (!Context.getLangOpts().ZVector ||
11923               resultType->getAs<VectorType>()->getVectorKind() !=
11924               VectorType::AltiVecBool))
11925       break;
11926     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11927              Opc == UO_Plus &&
11928              resultType->isPointerType())
11929       break;
11930
11931     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11932       << resultType << Input.get()->getSourceRange());
11933
11934   case UO_Not: // bitwise complement
11935     Input = UsualUnaryConversions(Input.get());
11936     if (Input.isInvalid())
11937       return ExprError();
11938     resultType = Input.get()->getType();
11939     if (resultType->isDependentType())
11940       break;
11941     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11942     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11943       // C99 does not support '~' for complex conjugation.
11944       Diag(OpLoc, diag::ext_integer_complement_complex)
11945           << resultType << Input.get()->getSourceRange();
11946     else if (resultType->hasIntegerRepresentation())
11947       break;
11948     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
11949       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11950       // on vector float types.
11951       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11952       if (!T->isIntegerType())
11953         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11954                           << resultType << Input.get()->getSourceRange());
11955     } else {
11956       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11957                        << resultType << Input.get()->getSourceRange());
11958     }
11959     break;
11960
11961   case UO_LNot: // logical negation
11962     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11963     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11964     if (Input.isInvalid()) return ExprError();
11965     resultType = Input.get()->getType();
11966
11967     // Though we still have to promote half FP to float...
11968     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11969       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11970       resultType = Context.FloatTy;
11971     }
11972
11973     if (resultType->isDependentType())
11974       break;
11975     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11976       // C99 6.5.3.3p1: ok, fallthrough;
11977       if (Context.getLangOpts().CPlusPlus) {
11978         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11979         // operand contextually converted to bool.
11980         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11981                                   ScalarTypeToBooleanCastKind(resultType));
11982       } else if (Context.getLangOpts().OpenCL &&
11983                  Context.getLangOpts().OpenCLVersion < 120) {
11984         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11985         // operate on scalar float types.
11986         if (!resultType->isIntegerType() && !resultType->isPointerType())
11987           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11988                            << resultType << Input.get()->getSourceRange());
11989       }
11990     } else if (resultType->isExtVectorType()) {
11991       if (Context.getLangOpts().OpenCL &&
11992           Context.getLangOpts().OpenCLVersion < 120) {
11993         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11994         // operate on vector float types.
11995         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11996         if (!T->isIntegerType())
11997           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11998                            << resultType << Input.get()->getSourceRange());
11999       }
12000       // Vector logical not returns the signed variant of the operand type.
12001       resultType = GetSignedVectorType(resultType);
12002       break;
12003     } else {
12004       // FIXME: GCC's vector extension permits the usage of '!' with a vector
12005       //        type in C++. We should allow that here too.
12006       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12007         << resultType << Input.get()->getSourceRange());
12008     }
12009     
12010     // LNot always has type int. C99 6.5.3.3p5.
12011     // In C++, it's bool. C++ 5.3.1p8
12012     resultType = Context.getLogicalOperationType();
12013     break;
12014   case UO_Real:
12015   case UO_Imag:
12016     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
12017     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
12018     // complex l-values to ordinary l-values and all other values to r-values.
12019     if (Input.isInvalid()) return ExprError();
12020     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
12021       if (Input.get()->getValueKind() != VK_RValue &&
12022           Input.get()->getObjectKind() == OK_Ordinary)
12023         VK = Input.get()->getValueKind();
12024     } else if (!getLangOpts().CPlusPlus) {
12025       // In C, a volatile scalar is read by __imag. In C++, it is not.
12026       Input = DefaultLvalueConversion(Input.get());
12027     }
12028     break;
12029   case UO_Extension:
12030     resultType = Input.get()->getType();
12031     VK = Input.get()->getValueKind();
12032     OK = Input.get()->getObjectKind();
12033     break;
12034   case UO_Coawait:
12035     // It's unnessesary to represent the pass-through operator co_await in the
12036     // AST; just return the input expression instead.
12037     assert(!Input.get()->getType()->isDependentType() &&
12038                    "the co_await expression must be non-dependant before "
12039                    "building operator co_await");
12040     return Input;
12041   }
12042   if (resultType.isNull() || Input.isInvalid())
12043     return ExprError();
12044
12045   // Check for array bounds violations in the operand of the UnaryOperator,
12046   // except for the '*' and '&' operators that have to be handled specially
12047   // by CheckArrayAccess (as there are special cases like &array[arraysize]
12048   // that are explicitly defined as valid by the standard).
12049   if (Opc != UO_AddrOf && Opc != UO_Deref)
12050     CheckArrayAccess(Input.get());
12051
12052   return new (Context)
12053       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
12054 }
12055
12056 /// \brief Determine whether the given expression is a qualified member
12057 /// access expression, of a form that could be turned into a pointer to member
12058 /// with the address-of operator.
12059 static bool isQualifiedMemberAccess(Expr *E) {
12060   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12061     if (!DRE->getQualifier())
12062       return false;
12063     
12064     ValueDecl *VD = DRE->getDecl();
12065     if (!VD->isCXXClassMember())
12066       return false;
12067     
12068     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
12069       return true;
12070     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
12071       return Method->isInstance();
12072       
12073     return false;
12074   }
12075   
12076   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12077     if (!ULE->getQualifier())
12078       return false;
12079     
12080     for (NamedDecl *D : ULE->decls()) {
12081       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
12082         if (Method->isInstance())
12083           return true;
12084       } else {
12085         // Overload set does not contain methods.
12086         break;
12087       }
12088     }
12089     
12090     return false;
12091   }
12092   
12093   return false;
12094 }
12095
12096 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
12097                               UnaryOperatorKind Opc, Expr *Input) {
12098   // First things first: handle placeholders so that the
12099   // overloaded-operator check considers the right type.
12100   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
12101     // Increment and decrement of pseudo-object references.
12102     if (pty->getKind() == BuiltinType::PseudoObject &&
12103         UnaryOperator::isIncrementDecrementOp(Opc))
12104       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
12105
12106     // extension is always a builtin operator.
12107     if (Opc == UO_Extension)
12108       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12109
12110     // & gets special logic for several kinds of placeholder.
12111     // The builtin code knows what to do.
12112     if (Opc == UO_AddrOf &&
12113         (pty->getKind() == BuiltinType::Overload ||
12114          pty->getKind() == BuiltinType::UnknownAny ||
12115          pty->getKind() == BuiltinType::BoundMember))
12116       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12117
12118     // Anything else needs to be handled now.
12119     ExprResult Result = CheckPlaceholderExpr(Input);
12120     if (Result.isInvalid()) return ExprError();
12121     Input = Result.get();
12122   }
12123
12124   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
12125       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
12126       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
12127     // Find all of the overloaded operators visible from this
12128     // point. We perform both an operator-name lookup from the local
12129     // scope and an argument-dependent lookup based on the types of
12130     // the arguments.
12131     UnresolvedSet<16> Functions;
12132     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
12133     if (S && OverOp != OO_None)
12134       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
12135                                    Functions);
12136
12137     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
12138   }
12139
12140   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12141 }
12142
12143 // Unary Operators.  'Tok' is the token for the operator.
12144 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
12145                               tok::TokenKind Op, Expr *Input) {
12146   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
12147 }
12148
12149 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
12150 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
12151                                 LabelDecl *TheDecl) {
12152   TheDecl->markUsed(Context);
12153   // Create the AST node.  The address of a label always has type 'void*'.
12154   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
12155                                      Context.getPointerType(Context.VoidTy));
12156 }
12157
12158 /// Given the last statement in a statement-expression, check whether
12159 /// the result is a producing expression (like a call to an
12160 /// ns_returns_retained function) and, if so, rebuild it to hoist the
12161 /// release out of the full-expression.  Otherwise, return null.
12162 /// Cannot fail.
12163 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
12164   // Should always be wrapped with one of these.
12165   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
12166   if (!cleanups) return nullptr;
12167
12168   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
12169   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
12170     return nullptr;
12171
12172   // Splice out the cast.  This shouldn't modify any interesting
12173   // features of the statement.
12174   Expr *producer = cast->getSubExpr();
12175   assert(producer->getType() == cast->getType());
12176   assert(producer->getValueKind() == cast->getValueKind());
12177   cleanups->setSubExpr(producer);
12178   return cleanups;
12179 }
12180
12181 void Sema::ActOnStartStmtExpr() {
12182   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12183 }
12184
12185 void Sema::ActOnStmtExprError() {
12186   // Note that function is also called by TreeTransform when leaving a
12187   // StmtExpr scope without rebuilding anything.
12188
12189   DiscardCleanupsInEvaluationContext();
12190   PopExpressionEvaluationContext();
12191 }
12192
12193 ExprResult
12194 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
12195                     SourceLocation RPLoc) { // "({..})"
12196   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
12197   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
12198
12199   if (hasAnyUnrecoverableErrorsInThisFunction())
12200     DiscardCleanupsInEvaluationContext();
12201   assert(!Cleanup.exprNeedsCleanups() &&
12202          "cleanups within StmtExpr not correctly bound!");
12203   PopExpressionEvaluationContext();
12204
12205   // FIXME: there are a variety of strange constraints to enforce here, for
12206   // example, it is not possible to goto into a stmt expression apparently.
12207   // More semantic analysis is needed.
12208
12209   // If there are sub-stmts in the compound stmt, take the type of the last one
12210   // as the type of the stmtexpr.
12211   QualType Ty = Context.VoidTy;
12212   bool StmtExprMayBindToTemp = false;
12213   if (!Compound->body_empty()) {
12214     Stmt *LastStmt = Compound->body_back();
12215     LabelStmt *LastLabelStmt = nullptr;
12216     // If LastStmt is a label, skip down through into the body.
12217     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
12218       LastLabelStmt = Label;
12219       LastStmt = Label->getSubStmt();
12220     }
12221
12222     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
12223       // Do function/array conversion on the last expression, but not
12224       // lvalue-to-rvalue.  However, initialize an unqualified type.
12225       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
12226       if (LastExpr.isInvalid())
12227         return ExprError();
12228       Ty = LastExpr.get()->getType().getUnqualifiedType();
12229
12230       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
12231         // In ARC, if the final expression ends in a consume, splice
12232         // the consume out and bind it later.  In the alternate case
12233         // (when dealing with a retainable type), the result
12234         // initialization will create a produce.  In both cases the
12235         // result will be +1, and we'll need to balance that out with
12236         // a bind.
12237         if (Expr *rebuiltLastStmt
12238               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
12239           LastExpr = rebuiltLastStmt;
12240         } else {
12241           LastExpr = PerformCopyInitialization(
12242                             InitializedEntity::InitializeResult(LPLoc, 
12243                                                                 Ty,
12244                                                                 false),
12245                                                    SourceLocation(),
12246                                                LastExpr);
12247         }
12248
12249         if (LastExpr.isInvalid())
12250           return ExprError();
12251         if (LastExpr.get() != nullptr) {
12252           if (!LastLabelStmt)
12253             Compound->setLastStmt(LastExpr.get());
12254           else
12255             LastLabelStmt->setSubStmt(LastExpr.get());
12256           StmtExprMayBindToTemp = true;
12257         }
12258       }
12259     }
12260   }
12261
12262   // FIXME: Check that expression type is complete/non-abstract; statement
12263   // expressions are not lvalues.
12264   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
12265   if (StmtExprMayBindToTemp)
12266     return MaybeBindToTemporary(ResStmtExpr);
12267   return ResStmtExpr;
12268 }
12269
12270 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
12271                                       TypeSourceInfo *TInfo,
12272                                       ArrayRef<OffsetOfComponent> Components,
12273                                       SourceLocation RParenLoc) {
12274   QualType ArgTy = TInfo->getType();
12275   bool Dependent = ArgTy->isDependentType();
12276   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
12277   
12278   // We must have at least one component that refers to the type, and the first
12279   // one is known to be a field designator.  Verify that the ArgTy represents
12280   // a struct/union/class.
12281   if (!Dependent && !ArgTy->isRecordType())
12282     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 
12283                        << ArgTy << TypeRange);
12284   
12285   // Type must be complete per C99 7.17p3 because a declaring a variable
12286   // with an incomplete type would be ill-formed.
12287   if (!Dependent 
12288       && RequireCompleteType(BuiltinLoc, ArgTy,
12289                              diag::err_offsetof_incomplete_type, TypeRange))
12290     return ExprError();
12291   
12292   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
12293   // GCC extension, diagnose them.
12294   // FIXME: This diagnostic isn't actually visible because the location is in
12295   // a system header!
12296   if (Components.size() != 1)
12297     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
12298       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
12299   
12300   bool DidWarnAboutNonPOD = false;
12301   QualType CurrentType = ArgTy;
12302   SmallVector<OffsetOfNode, 4> Comps;
12303   SmallVector<Expr*, 4> Exprs;
12304   for (const OffsetOfComponent &OC : Components) {
12305     if (OC.isBrackets) {
12306       // Offset of an array sub-field.  TODO: Should we allow vector elements?
12307       if (!CurrentType->isDependentType()) {
12308         const ArrayType *AT = Context.getAsArrayType(CurrentType);
12309         if(!AT)
12310           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
12311                            << CurrentType);
12312         CurrentType = AT->getElementType();
12313       } else
12314         CurrentType = Context.DependentTy;
12315       
12316       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
12317       if (IdxRval.isInvalid())
12318         return ExprError();
12319       Expr *Idx = IdxRval.get();
12320
12321       // The expression must be an integral expression.
12322       // FIXME: An integral constant expression?
12323       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
12324           !Idx->getType()->isIntegerType())
12325         return ExprError(Diag(Idx->getLocStart(),
12326                               diag::err_typecheck_subscript_not_integer)
12327                          << Idx->getSourceRange());
12328
12329       // Record this array index.
12330       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
12331       Exprs.push_back(Idx);
12332       continue;
12333     }
12334     
12335     // Offset of a field.
12336     if (CurrentType->isDependentType()) {
12337       // We have the offset of a field, but we can't look into the dependent
12338       // type. Just record the identifier of the field.
12339       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12340       CurrentType = Context.DependentTy;
12341       continue;
12342     }
12343     
12344     // We need to have a complete type to look into.
12345     if (RequireCompleteType(OC.LocStart, CurrentType,
12346                             diag::err_offsetof_incomplete_type))
12347       return ExprError();
12348     
12349     // Look for the designated field.
12350     const RecordType *RC = CurrentType->getAs<RecordType>();
12351     if (!RC) 
12352       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12353                        << CurrentType);
12354     RecordDecl *RD = RC->getDecl();
12355     
12356     // C++ [lib.support.types]p5:
12357     //   The macro offsetof accepts a restricted set of type arguments in this
12358     //   International Standard. type shall be a POD structure or a POD union
12359     //   (clause 9).
12360     // C++11 [support.types]p4:
12361     //   If type is not a standard-layout class (Clause 9), the results are
12362     //   undefined.
12363     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12364       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12365       unsigned DiagID =
12366         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12367                             : diag::ext_offsetof_non_pod_type;
12368
12369       if (!IsSafe && !DidWarnAboutNonPOD &&
12370           DiagRuntimeBehavior(BuiltinLoc, nullptr,
12371                               PDiag(DiagID)
12372                               << SourceRange(Components[0].LocStart, OC.LocEnd)
12373                               << CurrentType))
12374         DidWarnAboutNonPOD = true;
12375     }
12376     
12377     // Look for the field.
12378     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12379     LookupQualifiedName(R, RD);
12380     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12381     IndirectFieldDecl *IndirectMemberDecl = nullptr;
12382     if (!MemberDecl) {
12383       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12384         MemberDecl = IndirectMemberDecl->getAnonField();
12385     }
12386
12387     if (!MemberDecl)
12388       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12389                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 
12390                                                               OC.LocEnd));
12391     
12392     // C99 7.17p3:
12393     //   (If the specified member is a bit-field, the behavior is undefined.)
12394     //
12395     // We diagnose this as an error.
12396     if (MemberDecl->isBitField()) {
12397       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12398         << MemberDecl->getDeclName()
12399         << SourceRange(BuiltinLoc, RParenLoc);
12400       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12401       return ExprError();
12402     }
12403
12404     RecordDecl *Parent = MemberDecl->getParent();
12405     if (IndirectMemberDecl)
12406       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12407
12408     // If the member was found in a base class, introduce OffsetOfNodes for
12409     // the base class indirections.
12410     CXXBasePaths Paths;
12411     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12412                       Paths)) {
12413       if (Paths.getDetectedVirtual()) {
12414         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12415           << MemberDecl->getDeclName()
12416           << SourceRange(BuiltinLoc, RParenLoc);
12417         return ExprError();
12418       }
12419
12420       CXXBasePath &Path = Paths.front();
12421       for (const CXXBasePathElement &B : Path)
12422         Comps.push_back(OffsetOfNode(B.Base));
12423     }
12424
12425     if (IndirectMemberDecl) {
12426       for (auto *FI : IndirectMemberDecl->chain()) {
12427         assert(isa<FieldDecl>(FI));
12428         Comps.push_back(OffsetOfNode(OC.LocStart,
12429                                      cast<FieldDecl>(FI), OC.LocEnd));
12430       }
12431     } else
12432       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12433
12434     CurrentType = MemberDecl->getType().getNonReferenceType(); 
12435   }
12436   
12437   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12438                               Comps, Exprs, RParenLoc);
12439 }
12440
12441 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12442                                       SourceLocation BuiltinLoc,
12443                                       SourceLocation TypeLoc,
12444                                       ParsedType ParsedArgTy,
12445                                       ArrayRef<OffsetOfComponent> Components,
12446                                       SourceLocation RParenLoc) {
12447   
12448   TypeSourceInfo *ArgTInfo;
12449   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12450   if (ArgTy.isNull())
12451     return ExprError();
12452
12453   if (!ArgTInfo)
12454     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12455
12456   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12457 }
12458
12459
12460 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12461                                  Expr *CondExpr,
12462                                  Expr *LHSExpr, Expr *RHSExpr,
12463                                  SourceLocation RPLoc) {
12464   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12465
12466   ExprValueKind VK = VK_RValue;
12467   ExprObjectKind OK = OK_Ordinary;
12468   QualType resType;
12469   bool ValueDependent = false;
12470   bool CondIsTrue = false;
12471   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12472     resType = Context.DependentTy;
12473     ValueDependent = true;
12474   } else {
12475     // The conditional expression is required to be a constant expression.
12476     llvm::APSInt condEval(32);
12477     ExprResult CondICE
12478       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12479           diag::err_typecheck_choose_expr_requires_constant, false);
12480     if (CondICE.isInvalid())
12481       return ExprError();
12482     CondExpr = CondICE.get();
12483     CondIsTrue = condEval.getZExtValue();
12484
12485     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12486     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12487
12488     resType = ActiveExpr->getType();
12489     ValueDependent = ActiveExpr->isValueDependent();
12490     VK = ActiveExpr->getValueKind();
12491     OK = ActiveExpr->getObjectKind();
12492   }
12493
12494   return new (Context)
12495       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12496                  CondIsTrue, resType->isDependentType(), ValueDependent);
12497 }
12498
12499 //===----------------------------------------------------------------------===//
12500 // Clang Extensions.
12501 //===----------------------------------------------------------------------===//
12502
12503 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12504 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12505   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12506
12507   if (LangOpts.CPlusPlus) {
12508     Decl *ManglingContextDecl;
12509     if (MangleNumberingContext *MCtx =
12510             getCurrentMangleNumberContext(Block->getDeclContext(),
12511                                           ManglingContextDecl)) {
12512       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12513       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12514     }
12515   }
12516
12517   PushBlockScope(CurScope, Block);
12518   CurContext->addDecl(Block);
12519   if (CurScope)
12520     PushDeclContext(CurScope, Block);
12521   else
12522     CurContext = Block;
12523
12524   getCurBlock()->HasImplicitReturnType = true;
12525
12526   // Enter a new evaluation context to insulate the block from any
12527   // cleanups from the enclosing full-expression.
12528   PushExpressionEvaluationContext(
12529       ExpressionEvaluationContext::PotentiallyEvaluated);
12530 }
12531
12532 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12533                                Scope *CurScope) {
12534   assert(ParamInfo.getIdentifier() == nullptr &&
12535          "block-id should have no identifier!");
12536   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12537   BlockScopeInfo *CurBlock = getCurBlock();
12538
12539   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12540   QualType T = Sig->getType();
12541
12542   // FIXME: We should allow unexpanded parameter packs here, but that would,
12543   // in turn, make the block expression contain unexpanded parameter packs.
12544   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12545     // Drop the parameters.
12546     FunctionProtoType::ExtProtoInfo EPI;
12547     EPI.HasTrailingReturn = false;
12548     EPI.TypeQuals |= DeclSpec::TQ_const;
12549     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12550     Sig = Context.getTrivialTypeSourceInfo(T);
12551   }
12552   
12553   // GetTypeForDeclarator always produces a function type for a block
12554   // literal signature.  Furthermore, it is always a FunctionProtoType
12555   // unless the function was written with a typedef.
12556   assert(T->isFunctionType() &&
12557          "GetTypeForDeclarator made a non-function block signature");
12558
12559   // Look for an explicit signature in that function type.
12560   FunctionProtoTypeLoc ExplicitSignature;
12561
12562   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12563   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12564
12565     // Check whether that explicit signature was synthesized by
12566     // GetTypeForDeclarator.  If so, don't save that as part of the
12567     // written signature.
12568     if (ExplicitSignature.getLocalRangeBegin() ==
12569         ExplicitSignature.getLocalRangeEnd()) {
12570       // This would be much cheaper if we stored TypeLocs instead of
12571       // TypeSourceInfos.
12572       TypeLoc Result = ExplicitSignature.getReturnLoc();
12573       unsigned Size = Result.getFullDataSize();
12574       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12575       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12576
12577       ExplicitSignature = FunctionProtoTypeLoc();
12578     }
12579   }
12580
12581   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12582   CurBlock->FunctionType = T;
12583
12584   const FunctionType *Fn = T->getAs<FunctionType>();
12585   QualType RetTy = Fn->getReturnType();
12586   bool isVariadic =
12587     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12588
12589   CurBlock->TheDecl->setIsVariadic(isVariadic);
12590
12591   // Context.DependentTy is used as a placeholder for a missing block
12592   // return type.  TODO:  what should we do with declarators like:
12593   //   ^ * { ... }
12594   // If the answer is "apply template argument deduction"....
12595   if (RetTy != Context.DependentTy) {
12596     CurBlock->ReturnType = RetTy;
12597     CurBlock->TheDecl->setBlockMissingReturnType(false);
12598     CurBlock->HasImplicitReturnType = false;
12599   }
12600
12601   // Push block parameters from the declarator if we had them.
12602   SmallVector<ParmVarDecl*, 8> Params;
12603   if (ExplicitSignature) {
12604     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12605       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12606       if (Param->getIdentifier() == nullptr &&
12607           !Param->isImplicit() &&
12608           !Param->isInvalidDecl() &&
12609           !getLangOpts().CPlusPlus)
12610         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12611       Params.push_back(Param);
12612     }
12613
12614   // Fake up parameter variables if we have a typedef, like
12615   //   ^ fntype { ... }
12616   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12617     for (const auto &I : Fn->param_types()) {
12618       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12619           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12620       Params.push_back(Param);
12621     }
12622   }
12623
12624   // Set the parameters on the block decl.
12625   if (!Params.empty()) {
12626     CurBlock->TheDecl->setParams(Params);
12627     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12628                              /*CheckParameterNames=*/false);
12629   }
12630   
12631   // Finally we can process decl attributes.
12632   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12633
12634   // Put the parameter variables in scope.
12635   for (auto AI : CurBlock->TheDecl->parameters()) {
12636     AI->setOwningFunction(CurBlock->TheDecl);
12637
12638     // If this has an identifier, add it to the scope stack.
12639     if (AI->getIdentifier()) {
12640       CheckShadow(CurBlock->TheScope, AI);
12641
12642       PushOnScopeChains(AI, CurBlock->TheScope);
12643     }
12644   }
12645 }
12646
12647 /// ActOnBlockError - If there is an error parsing a block, this callback
12648 /// is invoked to pop the information about the block from the action impl.
12649 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12650   // Leave the expression-evaluation context.
12651   DiscardCleanupsInEvaluationContext();
12652   PopExpressionEvaluationContext();
12653
12654   // Pop off CurBlock, handle nested blocks.
12655   PopDeclContext();
12656   PopFunctionScopeInfo();
12657 }
12658
12659 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12660 /// literal was successfully completed.  ^(int x){...}
12661 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12662                                     Stmt *Body, Scope *CurScope) {
12663   // If blocks are disabled, emit an error.
12664   if (!LangOpts.Blocks)
12665     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12666
12667   // Leave the expression-evaluation context.
12668   if (hasAnyUnrecoverableErrorsInThisFunction())
12669     DiscardCleanupsInEvaluationContext();
12670   assert(!Cleanup.exprNeedsCleanups() &&
12671          "cleanups within block not correctly bound!");
12672   PopExpressionEvaluationContext();
12673
12674   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12675
12676   if (BSI->HasImplicitReturnType)
12677     deduceClosureReturnType(*BSI);
12678
12679   PopDeclContext();
12680
12681   QualType RetTy = Context.VoidTy;
12682   if (!BSI->ReturnType.isNull())
12683     RetTy = BSI->ReturnType;
12684
12685   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12686   QualType BlockTy;
12687
12688   // Set the captured variables on the block.
12689   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12690   SmallVector<BlockDecl::Capture, 4> Captures;
12691   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12692     if (Cap.isThisCapture())
12693       continue;
12694     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12695                               Cap.isNested(), Cap.getInitExpr());
12696     Captures.push_back(NewCap);
12697   }
12698   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12699
12700   // If the user wrote a function type in some form, try to use that.
12701   if (!BSI->FunctionType.isNull()) {
12702     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12703
12704     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12705     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12706     
12707     // Turn protoless block types into nullary block types.
12708     if (isa<FunctionNoProtoType>(FTy)) {
12709       FunctionProtoType::ExtProtoInfo EPI;
12710       EPI.ExtInfo = Ext;
12711       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12712
12713     // Otherwise, if we don't need to change anything about the function type,
12714     // preserve its sugar structure.
12715     } else if (FTy->getReturnType() == RetTy &&
12716                (!NoReturn || FTy->getNoReturnAttr())) {
12717       BlockTy = BSI->FunctionType;
12718
12719     // Otherwise, make the minimal modifications to the function type.
12720     } else {
12721       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12722       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12723       EPI.TypeQuals = 0; // FIXME: silently?
12724       EPI.ExtInfo = Ext;
12725       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12726     }
12727
12728   // If we don't have a function type, just build one from nothing.
12729   } else {
12730     FunctionProtoType::ExtProtoInfo EPI;
12731     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12732     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12733   }
12734
12735   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12736   BlockTy = Context.getBlockPointerType(BlockTy);
12737
12738   // If needed, diagnose invalid gotos and switches in the block.
12739   if (getCurFunction()->NeedsScopeChecking() &&
12740       !PP.isCodeCompletionEnabled())
12741     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12742
12743   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12744
12745   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12746     DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl);
12747
12748   // Try to apply the named return value optimization. We have to check again
12749   // if we can do this, though, because blocks keep return statements around
12750   // to deduce an implicit return type.
12751   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12752       !BSI->TheDecl->isDependentContext())
12753     computeNRVO(Body, BSI);
12754   
12755   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12756   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12757   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12758
12759   // If the block isn't obviously global, i.e. it captures anything at
12760   // all, then we need to do a few things in the surrounding context:
12761   if (Result->getBlockDecl()->hasCaptures()) {
12762     // First, this expression has a new cleanup object.
12763     ExprCleanupObjects.push_back(Result->getBlockDecl());
12764     Cleanup.setExprNeedsCleanups(true);
12765
12766     // It also gets a branch-protected scope if any of the captured
12767     // variables needs destruction.
12768     for (const auto &CI : Result->getBlockDecl()->captures()) {
12769       const VarDecl *var = CI.getVariable();
12770       if (var->getType().isDestructedType() != QualType::DK_none) {
12771         getCurFunction()->setHasBranchProtectedScope();
12772         break;
12773       }
12774     }
12775   }
12776
12777   return Result;
12778 }
12779
12780 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12781                             SourceLocation RPLoc) {
12782   TypeSourceInfo *TInfo;
12783   GetTypeFromParser(Ty, &TInfo);
12784   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12785 }
12786
12787 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12788                                 Expr *E, TypeSourceInfo *TInfo,
12789                                 SourceLocation RPLoc) {
12790   Expr *OrigExpr = E;
12791   bool IsMS = false;
12792
12793   // CUDA device code does not support varargs.
12794   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12795     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12796       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12797       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12798         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12799     }
12800   }
12801
12802   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12803   // as Microsoft ABI on an actual Microsoft platform, where
12804   // __builtin_ms_va_list and __builtin_va_list are the same.)
12805   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12806       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12807     QualType MSVaListType = Context.getBuiltinMSVaListType();
12808     if (Context.hasSameType(MSVaListType, E->getType())) {
12809       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12810         return ExprError();
12811       IsMS = true;
12812     }
12813   }
12814
12815   // Get the va_list type
12816   QualType VaListType = Context.getBuiltinVaListType();
12817   if (!IsMS) {
12818     if (VaListType->isArrayType()) {
12819       // Deal with implicit array decay; for example, on x86-64,
12820       // va_list is an array, but it's supposed to decay to
12821       // a pointer for va_arg.
12822       VaListType = Context.getArrayDecayedType(VaListType);
12823       // Make sure the input expression also decays appropriately.
12824       ExprResult Result = UsualUnaryConversions(E);
12825       if (Result.isInvalid())
12826         return ExprError();
12827       E = Result.get();
12828     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12829       // If va_list is a record type and we are compiling in C++ mode,
12830       // check the argument using reference binding.
12831       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12832           Context, Context.getLValueReferenceType(VaListType), false);
12833       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12834       if (Init.isInvalid())
12835         return ExprError();
12836       E = Init.getAs<Expr>();
12837     } else {
12838       // Otherwise, the va_list argument must be an l-value because
12839       // it is modified by va_arg.
12840       if (!E->isTypeDependent() &&
12841           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12842         return ExprError();
12843     }
12844   }
12845
12846   if (!IsMS && !E->isTypeDependent() &&
12847       !Context.hasSameType(VaListType, E->getType()))
12848     return ExprError(Diag(E->getLocStart(),
12849                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12850       << OrigExpr->getType() << E->getSourceRange());
12851
12852   if (!TInfo->getType()->isDependentType()) {
12853     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12854                             diag::err_second_parameter_to_va_arg_incomplete,
12855                             TInfo->getTypeLoc()))
12856       return ExprError();
12857
12858     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12859                                TInfo->getType(),
12860                                diag::err_second_parameter_to_va_arg_abstract,
12861                                TInfo->getTypeLoc()))
12862       return ExprError();
12863
12864     if (!TInfo->getType().isPODType(Context)) {
12865       Diag(TInfo->getTypeLoc().getBeginLoc(),
12866            TInfo->getType()->isObjCLifetimeType()
12867              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12868              : diag::warn_second_parameter_to_va_arg_not_pod)
12869         << TInfo->getType()
12870         << TInfo->getTypeLoc().getSourceRange();
12871     }
12872
12873     // Check for va_arg where arguments of the given type will be promoted
12874     // (i.e. this va_arg is guaranteed to have undefined behavior).
12875     QualType PromoteType;
12876     if (TInfo->getType()->isPromotableIntegerType()) {
12877       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12878       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12879         PromoteType = QualType();
12880     }
12881     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12882       PromoteType = Context.DoubleTy;
12883     if (!PromoteType.isNull())
12884       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12885                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12886                           << TInfo->getType()
12887                           << PromoteType
12888                           << TInfo->getTypeLoc().getSourceRange());
12889   }
12890
12891   QualType T = TInfo->getType().getNonLValueExprType(Context);
12892   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12893 }
12894
12895 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12896   // The type of __null will be int or long, depending on the size of
12897   // pointers on the target.
12898   QualType Ty;
12899   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12900   if (pw == Context.getTargetInfo().getIntWidth())
12901     Ty = Context.IntTy;
12902   else if (pw == Context.getTargetInfo().getLongWidth())
12903     Ty = Context.LongTy;
12904   else if (pw == Context.getTargetInfo().getLongLongWidth())
12905     Ty = Context.LongLongTy;
12906   else {
12907     llvm_unreachable("I don't know size of pointer!");
12908   }
12909
12910   return new (Context) GNUNullExpr(Ty, TokenLoc);
12911 }
12912
12913 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12914                                               bool Diagnose) {
12915   if (!getLangOpts().ObjC1)
12916     return false;
12917
12918   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12919   if (!PT)
12920     return false;
12921
12922   if (!PT->isObjCIdType()) {
12923     // Check if the destination is the 'NSString' interface.
12924     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12925     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12926       return false;
12927   }
12928   
12929   // Ignore any parens, implicit casts (should only be
12930   // array-to-pointer decays), and not-so-opaque values.  The last is
12931   // important for making this trigger for property assignments.
12932   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12933   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12934     if (OV->getSourceExpr())
12935       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12936
12937   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12938   if (!SL || !SL->isAscii())
12939     return false;
12940   if (Diagnose) {
12941     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12942       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12943     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12944   }
12945   return true;
12946 }
12947
12948 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12949                                               const Expr *SrcExpr) {
12950   if (!DstType->isFunctionPointerType() ||
12951       !SrcExpr->getType()->isFunctionType())
12952     return false;
12953
12954   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12955   if (!DRE)
12956     return false;
12957
12958   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12959   if (!FD)
12960     return false;
12961
12962   return !S.checkAddressOfFunctionIsAvailable(FD,
12963                                               /*Complain=*/true,
12964                                               SrcExpr->getLocStart());
12965 }
12966
12967 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12968                                     SourceLocation Loc,
12969                                     QualType DstType, QualType SrcType,
12970                                     Expr *SrcExpr, AssignmentAction Action,
12971                                     bool *Complained) {
12972   if (Complained)
12973     *Complained = false;
12974
12975   // Decode the result (notice that AST's are still created for extensions).
12976   bool CheckInferredResultType = false;
12977   bool isInvalid = false;
12978   unsigned DiagKind = 0;
12979   FixItHint Hint;
12980   ConversionFixItGenerator ConvHints;
12981   bool MayHaveConvFixit = false;
12982   bool MayHaveFunctionDiff = false;
12983   const ObjCInterfaceDecl *IFace = nullptr;
12984   const ObjCProtocolDecl *PDecl = nullptr;
12985
12986   switch (ConvTy) {
12987   case Compatible:
12988       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12989       return false;
12990
12991   case PointerToInt:
12992     DiagKind = diag::ext_typecheck_convert_pointer_int;
12993     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12994     MayHaveConvFixit = true;
12995     break;
12996   case IntToPointer:
12997     DiagKind = diag::ext_typecheck_convert_int_pointer;
12998     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12999     MayHaveConvFixit = true;
13000     break;
13001   case IncompatiblePointer:
13002     if (Action == AA_Passing_CFAudited)
13003       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
13004     else if (SrcType->isFunctionPointerType() &&
13005              DstType->isFunctionPointerType())
13006       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
13007     else
13008       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
13009
13010     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
13011       SrcType->isObjCObjectPointerType();
13012     if (Hint.isNull() && !CheckInferredResultType) {
13013       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13014     }
13015     else if (CheckInferredResultType) {
13016       SrcType = SrcType.getUnqualifiedType();
13017       DstType = DstType.getUnqualifiedType();
13018     }
13019     MayHaveConvFixit = true;
13020     break;
13021   case IncompatiblePointerSign:
13022     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
13023     break;
13024   case FunctionVoidPointer:
13025     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
13026     break;
13027   case IncompatiblePointerDiscardsQualifiers: {
13028     // Perform array-to-pointer decay if necessary.
13029     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
13030
13031     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
13032     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
13033     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
13034       DiagKind = diag::err_typecheck_incompatible_address_space;
13035       break;
13036
13037
13038     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
13039       DiagKind = diag::err_typecheck_incompatible_ownership;
13040       break;
13041     }
13042
13043     llvm_unreachable("unknown error case for discarding qualifiers!");
13044     // fallthrough
13045   }
13046   case CompatiblePointerDiscardsQualifiers:
13047     // If the qualifiers lost were because we were applying the
13048     // (deprecated) C++ conversion from a string literal to a char*
13049     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
13050     // Ideally, this check would be performed in
13051     // checkPointerTypesForAssignment. However, that would require a
13052     // bit of refactoring (so that the second argument is an
13053     // expression, rather than a type), which should be done as part
13054     // of a larger effort to fix checkPointerTypesForAssignment for
13055     // C++ semantics.
13056     if (getLangOpts().CPlusPlus &&
13057         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
13058       return false;
13059     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
13060     break;
13061   case IncompatibleNestedPointerQualifiers:
13062     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
13063     break;
13064   case IntToBlockPointer:
13065     DiagKind = diag::err_int_to_block_pointer;
13066     break;
13067   case IncompatibleBlockPointer:
13068     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
13069     break;
13070   case IncompatibleObjCQualifiedId: {
13071     if (SrcType->isObjCQualifiedIdType()) {
13072       const ObjCObjectPointerType *srcOPT =
13073                 SrcType->getAs<ObjCObjectPointerType>();
13074       for (auto *srcProto : srcOPT->quals()) {
13075         PDecl = srcProto;
13076         break;
13077       }
13078       if (const ObjCInterfaceType *IFaceT =
13079             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13080         IFace = IFaceT->getDecl();
13081     }
13082     else if (DstType->isObjCQualifiedIdType()) {
13083       const ObjCObjectPointerType *dstOPT =
13084         DstType->getAs<ObjCObjectPointerType>();
13085       for (auto *dstProto : dstOPT->quals()) {
13086         PDecl = dstProto;
13087         break;
13088       }
13089       if (const ObjCInterfaceType *IFaceT =
13090             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13091         IFace = IFaceT->getDecl();
13092     }
13093     DiagKind = diag::warn_incompatible_qualified_id;
13094     break;
13095   }
13096   case IncompatibleVectors:
13097     DiagKind = diag::warn_incompatible_vectors;
13098     break;
13099   case IncompatibleObjCWeakRef:
13100     DiagKind = diag::err_arc_weak_unavailable_assign;
13101     break;
13102   case Incompatible:
13103     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
13104       if (Complained)
13105         *Complained = true;
13106       return true;
13107     }
13108
13109     DiagKind = diag::err_typecheck_convert_incompatible;
13110     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13111     MayHaveConvFixit = true;
13112     isInvalid = true;
13113     MayHaveFunctionDiff = true;
13114     break;
13115   }
13116
13117   QualType FirstType, SecondType;
13118   switch (Action) {
13119   case AA_Assigning:
13120   case AA_Initializing:
13121     // The destination type comes first.
13122     FirstType = DstType;
13123     SecondType = SrcType;
13124     break;
13125
13126   case AA_Returning:
13127   case AA_Passing:
13128   case AA_Passing_CFAudited:
13129   case AA_Converting:
13130   case AA_Sending:
13131   case AA_Casting:
13132     // The source type comes first.
13133     FirstType = SrcType;
13134     SecondType = DstType;
13135     break;
13136   }
13137
13138   PartialDiagnostic FDiag = PDiag(DiagKind);
13139   if (Action == AA_Passing_CFAudited)
13140     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
13141   else
13142     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
13143
13144   // If we can fix the conversion, suggest the FixIts.
13145   assert(ConvHints.isNull() || Hint.isNull());
13146   if (!ConvHints.isNull()) {
13147     for (FixItHint &H : ConvHints.Hints)
13148       FDiag << H;
13149   } else {
13150     FDiag << Hint;
13151   }
13152   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
13153
13154   if (MayHaveFunctionDiff)
13155     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
13156
13157   Diag(Loc, FDiag);
13158   if (DiagKind == diag::warn_incompatible_qualified_id &&
13159       PDecl && IFace && !IFace->hasDefinition())
13160       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
13161         << IFace->getName() << PDecl->getName();
13162     
13163   if (SecondType == Context.OverloadTy)
13164     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
13165                               FirstType, /*TakingAddress=*/true);
13166
13167   if (CheckInferredResultType)
13168     EmitRelatedResultTypeNote(SrcExpr);
13169
13170   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
13171     EmitRelatedResultTypeNoteForReturn(DstType);
13172   
13173   if (Complained)
13174     *Complained = true;
13175   return isInvalid;
13176 }
13177
13178 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13179                                                  llvm::APSInt *Result) {
13180   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
13181   public:
13182     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13183       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
13184     }
13185   } Diagnoser;
13186   
13187   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
13188 }
13189
13190 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13191                                                  llvm::APSInt *Result,
13192                                                  unsigned DiagID,
13193                                                  bool AllowFold) {
13194   class IDDiagnoser : public VerifyICEDiagnoser {
13195     unsigned DiagID;
13196     
13197   public:
13198     IDDiagnoser(unsigned DiagID)
13199       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
13200     
13201     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13202       S.Diag(Loc, DiagID) << SR;
13203     }
13204   } Diagnoser(DiagID);
13205   
13206   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
13207 }
13208
13209 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
13210                                             SourceRange SR) {
13211   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
13212 }
13213
13214 ExprResult
13215 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
13216                                       VerifyICEDiagnoser &Diagnoser,
13217                                       bool AllowFold) {
13218   SourceLocation DiagLoc = E->getLocStart();
13219
13220   if (getLangOpts().CPlusPlus11) {
13221     // C++11 [expr.const]p5:
13222     //   If an expression of literal class type is used in a context where an
13223     //   integral constant expression is required, then that class type shall
13224     //   have a single non-explicit conversion function to an integral or
13225     //   unscoped enumeration type
13226     ExprResult Converted;
13227     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
13228     public:
13229       CXX11ConvertDiagnoser(bool Silent)
13230           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
13231                                 Silent, true) {}
13232
13233       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
13234                                            QualType T) override {
13235         return S.Diag(Loc, diag::err_ice_not_integral) << T;
13236       }
13237
13238       SemaDiagnosticBuilder diagnoseIncomplete(
13239           Sema &S, SourceLocation Loc, QualType T) override {
13240         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
13241       }
13242
13243       SemaDiagnosticBuilder diagnoseExplicitConv(
13244           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13245         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
13246       }
13247
13248       SemaDiagnosticBuilder noteExplicitConv(
13249           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13250         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13251                  << ConvTy->isEnumeralType() << ConvTy;
13252       }
13253
13254       SemaDiagnosticBuilder diagnoseAmbiguous(
13255           Sema &S, SourceLocation Loc, QualType T) override {
13256         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
13257       }
13258
13259       SemaDiagnosticBuilder noteAmbiguous(
13260           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13261         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13262                  << ConvTy->isEnumeralType() << ConvTy;
13263       }
13264
13265       SemaDiagnosticBuilder diagnoseConversion(
13266           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13267         llvm_unreachable("conversion functions are permitted");
13268       }
13269     } ConvertDiagnoser(Diagnoser.Suppress);
13270
13271     Converted = PerformContextualImplicitConversion(DiagLoc, E,
13272                                                     ConvertDiagnoser);
13273     if (Converted.isInvalid())
13274       return Converted;
13275     E = Converted.get();
13276     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
13277       return ExprError();
13278   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13279     // An ICE must be of integral or unscoped enumeration type.
13280     if (!Diagnoser.Suppress)
13281       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13282     return ExprError();
13283   }
13284
13285   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
13286   // in the non-ICE case.
13287   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
13288     if (Result)
13289       *Result = E->EvaluateKnownConstInt(Context);
13290     return E;
13291   }
13292
13293   Expr::EvalResult EvalResult;
13294   SmallVector<PartialDiagnosticAt, 8> Notes;
13295   EvalResult.Diag = &Notes;
13296
13297   // Try to evaluate the expression, and produce diagnostics explaining why it's
13298   // not a constant expression as a side-effect.
13299   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
13300                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
13301
13302   // In C++11, we can rely on diagnostics being produced for any expression
13303   // which is not a constant expression. If no diagnostics were produced, then
13304   // this is a constant expression.
13305   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
13306     if (Result)
13307       *Result = EvalResult.Val.getInt();
13308     return E;
13309   }
13310
13311   // If our only note is the usual "invalid subexpression" note, just point
13312   // the caret at its location rather than producing an essentially
13313   // redundant note.
13314   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13315         diag::note_invalid_subexpr_in_const_expr) {
13316     DiagLoc = Notes[0].first;
13317     Notes.clear();
13318   }
13319
13320   if (!Folded || !AllowFold) {
13321     if (!Diagnoser.Suppress) {
13322       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13323       for (const PartialDiagnosticAt &Note : Notes)
13324         Diag(Note.first, Note.second);
13325     }
13326
13327     return ExprError();
13328   }
13329
13330   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
13331   for (const PartialDiagnosticAt &Note : Notes)
13332     Diag(Note.first, Note.second);
13333
13334   if (Result)
13335     *Result = EvalResult.Val.getInt();
13336   return E;
13337 }
13338
13339 namespace {
13340   // Handle the case where we conclude a expression which we speculatively
13341   // considered to be unevaluated is actually evaluated.
13342   class TransformToPE : public TreeTransform<TransformToPE> {
13343     typedef TreeTransform<TransformToPE> BaseTransform;
13344
13345   public:
13346     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13347
13348     // Make sure we redo semantic analysis
13349     bool AlwaysRebuild() { return true; }
13350
13351     // Make sure we handle LabelStmts correctly.
13352     // FIXME: This does the right thing, but maybe we need a more general
13353     // fix to TreeTransform?
13354     StmtResult TransformLabelStmt(LabelStmt *S) {
13355       S->getDecl()->setStmt(nullptr);
13356       return BaseTransform::TransformLabelStmt(S);
13357     }
13358
13359     // We need to special-case DeclRefExprs referring to FieldDecls which
13360     // are not part of a member pointer formation; normal TreeTransforming
13361     // doesn't catch this case because of the way we represent them in the AST.
13362     // FIXME: This is a bit ugly; is it really the best way to handle this
13363     // case?
13364     //
13365     // Error on DeclRefExprs referring to FieldDecls.
13366     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13367       if (isa<FieldDecl>(E->getDecl()) &&
13368           !SemaRef.isUnevaluatedContext())
13369         return SemaRef.Diag(E->getLocation(),
13370                             diag::err_invalid_non_static_member_use)
13371             << E->getDecl() << E->getSourceRange();
13372
13373       return BaseTransform::TransformDeclRefExpr(E);
13374     }
13375
13376     // Exception: filter out member pointer formation
13377     ExprResult TransformUnaryOperator(UnaryOperator *E) {
13378       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13379         return E;
13380
13381       return BaseTransform::TransformUnaryOperator(E);
13382     }
13383
13384     ExprResult TransformLambdaExpr(LambdaExpr *E) {
13385       // Lambdas never need to be transformed.
13386       return E;
13387     }
13388   };
13389 }
13390
13391 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13392   assert(isUnevaluatedContext() &&
13393          "Should only transform unevaluated expressions");
13394   ExprEvalContexts.back().Context =
13395       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13396   if (isUnevaluatedContext())
13397     return E;
13398   return TransformToPE(*this).TransformExpr(E);
13399 }
13400
13401 void
13402 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13403                                       Decl *LambdaContextDecl,
13404                                       bool IsDecltype) {
13405   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13406                                 LambdaContextDecl, IsDecltype);
13407   Cleanup.reset();
13408   if (!MaybeODRUseExprs.empty())
13409     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13410 }
13411
13412 void
13413 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13414                                       ReuseLambdaContextDecl_t,
13415                                       bool IsDecltype) {
13416   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13417   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13418 }
13419
13420 void Sema::PopExpressionEvaluationContext() {
13421   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13422   unsigned NumTypos = Rec.NumTypos;
13423
13424   if (!Rec.Lambdas.empty()) {
13425     if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13426       unsigned D;
13427       if (Rec.isUnevaluated()) {
13428         // C++11 [expr.prim.lambda]p2:
13429         //   A lambda-expression shall not appear in an unevaluated operand
13430         //   (Clause 5).
13431         D = diag::err_lambda_unevaluated_operand;
13432       } else {
13433         // C++1y [expr.const]p2:
13434         //   A conditional-expression e is a core constant expression unless the
13435         //   evaluation of e, following the rules of the abstract machine, would
13436         //   evaluate [...] a lambda-expression.
13437         D = diag::err_lambda_in_constant_expression;
13438       }
13439
13440       // C++1z allows lambda expressions as core constant expressions.
13441       // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
13442       // 1607) from appearing within template-arguments and array-bounds that
13443       // are part of function-signatures.  Be mindful that P0315 (Lambdas in
13444       // unevaluated contexts) might lift some of these restrictions in a 
13445       // future version.
13446       if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus1z)
13447         for (const auto *L : Rec.Lambdas)
13448           Diag(L->getLocStart(), D);
13449     } else {
13450       // Mark the capture expressions odr-used. This was deferred
13451       // during lambda expression creation.
13452       for (auto *Lambda : Rec.Lambdas) {
13453         for (auto *C : Lambda->capture_inits())
13454           MarkDeclarationsReferencedInExpr(C);
13455       }
13456     }
13457   }
13458
13459   // When are coming out of an unevaluated context, clear out any
13460   // temporaries that we may have created as part of the evaluation of
13461   // the expression in that context: they aren't relevant because they
13462   // will never be constructed.
13463   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13464     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13465                              ExprCleanupObjects.end());
13466     Cleanup = Rec.ParentCleanup;
13467     CleanupVarDeclMarking();
13468     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13469   // Otherwise, merge the contexts together.
13470   } else {
13471     Cleanup.mergeFrom(Rec.ParentCleanup);
13472     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13473                             Rec.SavedMaybeODRUseExprs.end());
13474   }
13475
13476   // Pop the current expression evaluation context off the stack.
13477   ExprEvalContexts.pop_back();
13478
13479   if (!ExprEvalContexts.empty())
13480     ExprEvalContexts.back().NumTypos += NumTypos;
13481   else
13482     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13483                             "last ExpressionEvaluationContextRecord");
13484 }
13485
13486 void Sema::DiscardCleanupsInEvaluationContext() {
13487   ExprCleanupObjects.erase(
13488          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13489          ExprCleanupObjects.end());
13490   Cleanup.reset();
13491   MaybeODRUseExprs.clear();
13492 }
13493
13494 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13495   if (!E->getType()->isVariablyModifiedType())
13496     return E;
13497   return TransformToPotentiallyEvaluated(E);
13498 }
13499
13500 /// Are we within a context in which some evaluation could be performed (be it
13501 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
13502 /// captured by C++'s idea of an "unevaluated context".
13503 static bool isEvaluatableContext(Sema &SemaRef) {
13504   switch (SemaRef.ExprEvalContexts.back().Context) {
13505     case Sema::ExpressionEvaluationContext::Unevaluated:
13506     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13507     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13508       // Expressions in this context are never evaluated.
13509       return false;
13510
13511     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13512     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13513     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13514       // Expressions in this context could be evaluated.
13515       return true;
13516
13517     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13518       // Referenced declarations will only be used if the construct in the
13519       // containing expression is used, at which point we'll be given another
13520       // turn to mark them.
13521       return false;
13522   }
13523   llvm_unreachable("Invalid context");
13524 }
13525
13526 /// Are we within a context in which references to resolved functions or to
13527 /// variables result in odr-use?
13528 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
13529   // An expression in a template is not really an expression until it's been
13530   // instantiated, so it doesn't trigger odr-use.
13531   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
13532     return false;
13533
13534   switch (SemaRef.ExprEvalContexts.back().Context) {
13535     case Sema::ExpressionEvaluationContext::Unevaluated:
13536     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13537     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13538     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13539       return false;
13540
13541     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13542     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13543       return true;
13544
13545     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13546       return false;
13547   }
13548   llvm_unreachable("Invalid context");
13549 }
13550
13551 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
13552   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13553   return Func->isConstexpr() &&
13554          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
13555 }
13556
13557 /// \brief Mark a function referenced, and check whether it is odr-used
13558 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13559 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13560                                   bool MightBeOdrUse) {
13561   assert(Func && "No function?");
13562
13563   Func->setReferenced();
13564
13565   // C++11 [basic.def.odr]p3:
13566   //   A function whose name appears as a potentially-evaluated expression is
13567   //   odr-used if it is the unique lookup result or the selected member of a
13568   //   set of overloaded functions [...].
13569   //
13570   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13571   // can just check that here.
13572   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
13573
13574   // Determine whether we require a function definition to exist, per
13575   // C++11 [temp.inst]p3:
13576   //   Unless a function template specialization has been explicitly
13577   //   instantiated or explicitly specialized, the function template
13578   //   specialization is implicitly instantiated when the specialization is
13579   //   referenced in a context that requires a function definition to exist.
13580   //
13581   // That is either when this is an odr-use, or when a usage of a constexpr
13582   // function occurs within an evaluatable context.
13583   bool NeedDefinition =
13584       OdrUse || (isEvaluatableContext(*this) &&
13585                  isImplicitlyDefinableConstexprFunction(Func));
13586
13587   // C++14 [temp.expl.spec]p6:
13588   //   If a template [...] is explicitly specialized then that specialization
13589   //   shall be declared before the first use of that specialization that would
13590   //   cause an implicit instantiation to take place, in every translation unit
13591   //   in which such a use occurs
13592   if (NeedDefinition &&
13593       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13594        Func->getMemberSpecializationInfo()))
13595     checkSpecializationVisibility(Loc, Func);
13596
13597   // C++14 [except.spec]p17:
13598   //   An exception-specification is considered to be needed when:
13599   //   - the function is odr-used or, if it appears in an unevaluated operand,
13600   //     would be odr-used if the expression were potentially-evaluated;
13601   //
13602   // Note, we do this even if MightBeOdrUse is false. That indicates that the
13603   // function is a pure virtual function we're calling, and in that case the
13604   // function was selected by overload resolution and we need to resolve its
13605   // exception specification for a different reason.
13606   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13607   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13608     ResolveExceptionSpec(Loc, FPT);
13609
13610   // If we don't need to mark the function as used, and we don't need to
13611   // try to provide a definition, there's nothing more to do.
13612   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13613       (!NeedDefinition || Func->getBody()))
13614     return;
13615
13616   // Note that this declaration has been used.
13617   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13618     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13619     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13620       if (Constructor->isDefaultConstructor()) {
13621         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13622           return;
13623         DefineImplicitDefaultConstructor(Loc, Constructor);
13624       } else if (Constructor->isCopyConstructor()) {
13625         DefineImplicitCopyConstructor(Loc, Constructor);
13626       } else if (Constructor->isMoveConstructor()) {
13627         DefineImplicitMoveConstructor(Loc, Constructor);
13628       }
13629     } else if (Constructor->getInheritedConstructor()) {
13630       DefineInheritingConstructor(Loc, Constructor);
13631     }
13632   } else if (CXXDestructorDecl *Destructor =
13633                  dyn_cast<CXXDestructorDecl>(Func)) {
13634     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13635     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13636       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13637         return;
13638       DefineImplicitDestructor(Loc, Destructor);
13639     }
13640     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13641       MarkVTableUsed(Loc, Destructor->getParent());
13642   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13643     if (MethodDecl->isOverloadedOperator() &&
13644         MethodDecl->getOverloadedOperator() == OO_Equal) {
13645       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13646       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13647         if (MethodDecl->isCopyAssignmentOperator())
13648           DefineImplicitCopyAssignment(Loc, MethodDecl);
13649         else if (MethodDecl->isMoveAssignmentOperator())
13650           DefineImplicitMoveAssignment(Loc, MethodDecl);
13651       }
13652     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13653                MethodDecl->getParent()->isLambda()) {
13654       CXXConversionDecl *Conversion =
13655           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13656       if (Conversion->isLambdaToBlockPointerConversion())
13657         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13658       else
13659         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13660     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13661       MarkVTableUsed(Loc, MethodDecl->getParent());
13662   }
13663
13664   // Recursive functions should be marked when used from another function.
13665   // FIXME: Is this really right?
13666   if (CurContext == Func) return;
13667
13668   // Implicit instantiation of function templates and member functions of
13669   // class templates.
13670   if (Func->isImplicitlyInstantiable()) {
13671     bool AlreadyInstantiated = false;
13672     SourceLocation PointOfInstantiation = Loc;
13673     if (FunctionTemplateSpecializationInfo *SpecInfo
13674                               = Func->getTemplateSpecializationInfo()) {
13675       if (SpecInfo->getPointOfInstantiation().isInvalid())
13676         SpecInfo->setPointOfInstantiation(Loc);
13677       else if (SpecInfo->getTemplateSpecializationKind()
13678                  == TSK_ImplicitInstantiation) {
13679         AlreadyInstantiated = true;
13680         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13681       }
13682     } else if (MemberSpecializationInfo *MSInfo
13683                                 = Func->getMemberSpecializationInfo()) {
13684       if (MSInfo->getPointOfInstantiation().isInvalid())
13685         MSInfo->setPointOfInstantiation(Loc);
13686       else if (MSInfo->getTemplateSpecializationKind()
13687                  == TSK_ImplicitInstantiation) {
13688         AlreadyInstantiated = true;
13689         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13690       }
13691     }
13692
13693     if (!AlreadyInstantiated || Func->isConstexpr()) {
13694       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13695           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13696           CodeSynthesisContexts.size())
13697         PendingLocalImplicitInstantiations.push_back(
13698             std::make_pair(Func, PointOfInstantiation));
13699       else if (Func->isConstexpr())
13700         // Do not defer instantiations of constexpr functions, to avoid the
13701         // expression evaluator needing to call back into Sema if it sees a
13702         // call to such a function.
13703         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13704       else {
13705         Func->setInstantiationIsPending(true);
13706         PendingInstantiations.push_back(std::make_pair(Func,
13707                                                        PointOfInstantiation));
13708         // Notify the consumer that a function was implicitly instantiated.
13709         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13710       }
13711     }
13712   } else {
13713     // Walk redefinitions, as some of them may be instantiable.
13714     for (auto i : Func->redecls()) {
13715       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13716         MarkFunctionReferenced(Loc, i, OdrUse);
13717     }
13718   }
13719
13720   if (!OdrUse) return;
13721
13722   // Keep track of used but undefined functions.
13723   if (!Func->isDefined()) {
13724     if (mightHaveNonExternalLinkage(Func))
13725       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13726     else if (Func->getMostRecentDecl()->isInlined() &&
13727              !LangOpts.GNUInline &&
13728              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13729       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13730   }
13731
13732   Func->markUsed(Context);
13733 }
13734
13735 static void
13736 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13737                                    ValueDecl *var, DeclContext *DC) {
13738   DeclContext *VarDC = var->getDeclContext();
13739
13740   //  If the parameter still belongs to the translation unit, then
13741   //  we're actually just using one parameter in the declaration of
13742   //  the next.
13743   if (isa<ParmVarDecl>(var) &&
13744       isa<TranslationUnitDecl>(VarDC))
13745     return;
13746
13747   // For C code, don't diagnose about capture if we're not actually in code
13748   // right now; it's impossible to write a non-constant expression outside of
13749   // function context, so we'll get other (more useful) diagnostics later.
13750   //
13751   // For C++, things get a bit more nasty... it would be nice to suppress this
13752   // diagnostic for certain cases like using a local variable in an array bound
13753   // for a member of a local class, but the correct predicate is not obvious.
13754   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13755     return;
13756
13757   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13758   unsigned ContextKind = 3; // unknown
13759   if (isa<CXXMethodDecl>(VarDC) &&
13760       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13761     ContextKind = 2;
13762   } else if (isa<FunctionDecl>(VarDC)) {
13763     ContextKind = 0;
13764   } else if (isa<BlockDecl>(VarDC)) {
13765     ContextKind = 1;
13766   }
13767
13768   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13769     << var << ValueKind << ContextKind << VarDC;
13770   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13771       << var;
13772
13773   // FIXME: Add additional diagnostic info about class etc. which prevents
13774   // capture.
13775 }
13776
13777  
13778 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 
13779                                       bool &SubCapturesAreNested,
13780                                       QualType &CaptureType, 
13781                                       QualType &DeclRefType) {
13782    // Check whether we've already captured it.
13783   if (CSI->CaptureMap.count(Var)) {
13784     // If we found a capture, any subcaptures are nested.
13785     SubCapturesAreNested = true;
13786       
13787     // Retrieve the capture type for this variable.
13788     CaptureType = CSI->getCapture(Var).getCaptureType();
13789       
13790     // Compute the type of an expression that refers to this variable.
13791     DeclRefType = CaptureType.getNonReferenceType();
13792
13793     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13794     // are mutable in the sense that user can change their value - they are
13795     // private instances of the captured declarations.
13796     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13797     if (Cap.isCopyCapture() &&
13798         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13799         !(isa<CapturedRegionScopeInfo>(CSI) &&
13800           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13801       DeclRefType.addConst();
13802     return true;
13803   }
13804   return false;
13805 }
13806
13807 // Only block literals, captured statements, and lambda expressions can
13808 // capture; other scopes don't work.
13809 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 
13810                                  SourceLocation Loc, 
13811                                  const bool Diagnose, Sema &S) {
13812   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13813     return getLambdaAwareParentOfDeclContext(DC);
13814   else if (Var->hasLocalStorage()) {
13815     if (Diagnose)
13816        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13817   }
13818   return nullptr;
13819 }
13820
13821 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 
13822 // certain types of variables (unnamed, variably modified types etc.)
13823 // so check for eligibility.
13824 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 
13825                                  SourceLocation Loc, 
13826                                  const bool Diagnose, Sema &S) {
13827
13828   bool IsBlock = isa<BlockScopeInfo>(CSI);
13829   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13830
13831   // Lambdas are not allowed to capture unnamed variables
13832   // (e.g. anonymous unions).
13833   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13834   // assuming that's the intent.
13835   if (IsLambda && !Var->getDeclName()) {
13836     if (Diagnose) {
13837       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13838       S.Diag(Var->getLocation(), diag::note_declared_at);
13839     }
13840     return false;
13841   }
13842
13843   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13844   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13845     if (Diagnose) {
13846       S.Diag(Loc, diag::err_ref_vm_type);
13847       S.Diag(Var->getLocation(), diag::note_previous_decl) 
13848         << Var->getDeclName();
13849     }
13850     return false;
13851   }
13852   // Prohibit structs with flexible array members too.
13853   // We cannot capture what is in the tail end of the struct.
13854   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13855     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13856       if (Diagnose) {
13857         if (IsBlock)
13858           S.Diag(Loc, diag::err_ref_flexarray_type);
13859         else
13860           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13861             << Var->getDeclName();
13862         S.Diag(Var->getLocation(), diag::note_previous_decl)
13863           << Var->getDeclName();
13864       }
13865       return false;
13866     }
13867   }
13868   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13869   // Lambdas and captured statements are not allowed to capture __block
13870   // variables; they don't support the expected semantics.
13871   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13872     if (Diagnose) {
13873       S.Diag(Loc, diag::err_capture_block_variable)
13874         << Var->getDeclName() << !IsLambda;
13875       S.Diag(Var->getLocation(), diag::note_previous_decl)
13876         << Var->getDeclName();
13877     }
13878     return false;
13879   }
13880   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
13881   if (S.getLangOpts().OpenCL && IsBlock &&
13882       Var->getType()->isBlockPointerType()) {
13883     if (Diagnose)
13884       S.Diag(Loc, diag::err_opencl_block_ref_block);
13885     return false;
13886   }
13887
13888   return true;
13889 }
13890
13891 // Returns true if the capture by block was successful.
13892 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 
13893                                  SourceLocation Loc, 
13894                                  const bool BuildAndDiagnose, 
13895                                  QualType &CaptureType,
13896                                  QualType &DeclRefType, 
13897                                  const bool Nested,
13898                                  Sema &S) {
13899   Expr *CopyExpr = nullptr;
13900   bool ByRef = false;
13901       
13902   // Blocks are not allowed to capture arrays.
13903   if (CaptureType->isArrayType()) {
13904     if (BuildAndDiagnose) {
13905       S.Diag(Loc, diag::err_ref_array_type);
13906       S.Diag(Var->getLocation(), diag::note_previous_decl) 
13907       << Var->getDeclName();
13908     }
13909     return false;
13910   }
13911
13912   // Forbid the block-capture of autoreleasing variables.
13913   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13914     if (BuildAndDiagnose) {
13915       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13916         << /*block*/ 0;
13917       S.Diag(Var->getLocation(), diag::note_previous_decl)
13918         << Var->getDeclName();
13919     }
13920     return false;
13921   }
13922
13923   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13924   if (const auto *PT = CaptureType->getAs<PointerType>()) {
13925     // This function finds out whether there is an AttributedType of kind
13926     // attr_objc_ownership in Ty. The existence of AttributedType of kind
13927     // attr_objc_ownership implies __autoreleasing was explicitly specified
13928     // rather than being added implicitly by the compiler.
13929     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
13930       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
13931         if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
13932           return true;
13933
13934         // Peel off AttributedTypes that are not of kind objc_ownership.
13935         Ty = AttrTy->getModifiedType();
13936       }
13937
13938       return false;
13939     };
13940
13941     QualType PointeeTy = PT->getPointeeType();
13942
13943     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
13944         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13945         !IsObjCOwnershipAttributedType(PointeeTy)) {
13946       if (BuildAndDiagnose) {
13947         SourceLocation VarLoc = Var->getLocation();
13948         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13949         {
13950           auto AddAutoreleaseNote =
13951               S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing);
13952           // Provide a fix-it for the '__autoreleasing' keyword at the
13953           // appropriate location in the variable's type.
13954           if (const auto *TSI = Var->getTypeSourceInfo()) {
13955             PointerTypeLoc PTL =
13956                 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>();
13957             if (PTL) {
13958               SourceLocation Loc = PTL.getPointeeLoc().getEndLoc();
13959               Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(),
13960                                                S.getLangOpts());
13961               if (Loc.isValid()) {
13962                 StringRef CharAtLoc = Lexer::getSourceText(
13963                     CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)),
13964                     S.getSourceManager(), S.getLangOpts());
13965                 AddAutoreleaseNote << FixItHint::CreateInsertion(
13966                     Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0])
13967                              ? " __autoreleasing "
13968                              : " __autoreleasing");
13969               }
13970             }
13971           }
13972         }
13973         S.Diag(VarLoc, diag::note_declare_parameter_strong);
13974       }
13975     }
13976   }
13977
13978   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13979   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13980       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13981     // Block capture by reference does not change the capture or
13982     // declaration reference types.
13983     ByRef = true;
13984   } else {
13985     // Block capture by copy introduces 'const'.
13986     CaptureType = CaptureType.getNonReferenceType().withConst();
13987     DeclRefType = CaptureType;
13988                 
13989     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13990       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13991         // The capture logic needs the destructor, so make sure we mark it.
13992         // Usually this is unnecessary because most local variables have
13993         // their destructors marked at declaration time, but parameters are
13994         // an exception because it's technically only the call site that
13995         // actually requires the destructor.
13996         if (isa<ParmVarDecl>(Var))
13997           S.FinalizeVarWithDestructor(Var, Record);
13998
13999         // Enter a new evaluation context to insulate the copy
14000         // full-expression.
14001         EnterExpressionEvaluationContext scope(
14002             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
14003
14004         // According to the blocks spec, the capture of a variable from
14005         // the stack requires a const copy constructor.  This is not true
14006         // of the copy/move done to move a __block variable to the heap.
14007         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
14008                                                   DeclRefType.withConst(), 
14009                                                   VK_LValue, Loc);
14010             
14011         ExprResult Result
14012           = S.PerformCopyInitialization(
14013               InitializedEntity::InitializeBlock(Var->getLocation(),
14014                                                   CaptureType, false),
14015               Loc, DeclRef);
14016             
14017         // Build a full-expression copy expression if initialization
14018         // succeeded and used a non-trivial constructor.  Recover from
14019         // errors by pretending that the copy isn't necessary.
14020         if (!Result.isInvalid() &&
14021             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14022                 ->isTrivial()) {
14023           Result = S.MaybeCreateExprWithCleanups(Result);
14024           CopyExpr = Result.get();
14025         }
14026       }
14027     }
14028   }
14029
14030   // Actually capture the variable.
14031   if (BuildAndDiagnose)
14032     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 
14033                     SourceLocation(), CaptureType, CopyExpr);
14034
14035   return true;
14036
14037 }
14038
14039
14040 /// \brief Capture the given variable in the captured region.
14041 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
14042                                     VarDecl *Var, 
14043                                     SourceLocation Loc, 
14044                                     const bool BuildAndDiagnose, 
14045                                     QualType &CaptureType,
14046                                     QualType &DeclRefType, 
14047                                     const bool RefersToCapturedVariable,
14048                                     Sema &S) {
14049   // By default, capture variables by reference.
14050   bool ByRef = true;
14051   // Using an LValue reference type is consistent with Lambdas (see below).
14052   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
14053     if (S.IsOpenMPCapturedDecl(Var))
14054       DeclRefType = DeclRefType.getUnqualifiedType();
14055     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
14056   }
14057
14058   if (ByRef)
14059     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14060   else
14061     CaptureType = DeclRefType;
14062
14063   Expr *CopyExpr = nullptr;
14064   if (BuildAndDiagnose) {
14065     // The current implementation assumes that all variables are captured
14066     // by references. Since there is no capture by copy, no expression
14067     // evaluation will be needed.
14068     RecordDecl *RD = RSI->TheRecordDecl;
14069
14070     FieldDecl *Field
14071       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
14072                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
14073                           nullptr, false, ICIS_NoInit);
14074     Field->setImplicit(true);
14075     Field->setAccess(AS_private);
14076     RD->addDecl(Field);
14077  
14078     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
14079                                             DeclRefType, VK_LValue, Loc);
14080     Var->setReferenced(true);
14081     Var->markUsed(S.Context);
14082   }
14083
14084   // Actually capture the variable.
14085   if (BuildAndDiagnose)
14086     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
14087                     SourceLocation(), CaptureType, CopyExpr);
14088   
14089   
14090   return true;
14091 }
14092
14093 /// \brief Create a field within the lambda class for the variable
14094 /// being captured.
14095 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 
14096                                     QualType FieldType, QualType DeclRefType,
14097                                     SourceLocation Loc,
14098                                     bool RefersToCapturedVariable) {
14099   CXXRecordDecl *Lambda = LSI->Lambda;
14100
14101   // Build the non-static data member.
14102   FieldDecl *Field
14103     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
14104                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
14105                         nullptr, false, ICIS_NoInit);
14106   Field->setImplicit(true);
14107   Field->setAccess(AS_private);
14108   Lambda->addDecl(Field);
14109 }
14110
14111 /// \brief Capture the given variable in the lambda.
14112 static bool captureInLambda(LambdaScopeInfo *LSI,
14113                             VarDecl *Var, 
14114                             SourceLocation Loc, 
14115                             const bool BuildAndDiagnose, 
14116                             QualType &CaptureType,
14117                             QualType &DeclRefType, 
14118                             const bool RefersToCapturedVariable,
14119                             const Sema::TryCaptureKind Kind, 
14120                             SourceLocation EllipsisLoc,
14121                             const bool IsTopScope,
14122                             Sema &S) {
14123
14124   // Determine whether we are capturing by reference or by value.
14125   bool ByRef = false;
14126   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
14127     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
14128   } else {
14129     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
14130   }
14131     
14132   // Compute the type of the field that will capture this variable.
14133   if (ByRef) {
14134     // C++11 [expr.prim.lambda]p15:
14135     //   An entity is captured by reference if it is implicitly or
14136     //   explicitly captured but not captured by copy. It is
14137     //   unspecified whether additional unnamed non-static data
14138     //   members are declared in the closure type for entities
14139     //   captured by reference.
14140     //
14141     // FIXME: It is not clear whether we want to build an lvalue reference
14142     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
14143     // to do the former, while EDG does the latter. Core issue 1249 will 
14144     // clarify, but for now we follow GCC because it's a more permissive and
14145     // easily defensible position.
14146     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14147   } else {
14148     // C++11 [expr.prim.lambda]p14:
14149     //   For each entity captured by copy, an unnamed non-static
14150     //   data member is declared in the closure type. The
14151     //   declaration order of these members is unspecified. The type
14152     //   of such a data member is the type of the corresponding
14153     //   captured entity if the entity is not a reference to an
14154     //   object, or the referenced type otherwise. [Note: If the
14155     //   captured entity is a reference to a function, the
14156     //   corresponding data member is also a reference to a
14157     //   function. - end note ]
14158     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
14159       if (!RefType->getPointeeType()->isFunctionType())
14160         CaptureType = RefType->getPointeeType();
14161     }
14162
14163     // Forbid the lambda copy-capture of autoreleasing variables.
14164     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14165       if (BuildAndDiagnose) {
14166         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
14167         S.Diag(Var->getLocation(), diag::note_previous_decl)
14168           << Var->getDeclName();
14169       }
14170       return false;
14171     }
14172
14173     // Make sure that by-copy captures are of a complete and non-abstract type.
14174     if (BuildAndDiagnose) {
14175       if (!CaptureType->isDependentType() &&
14176           S.RequireCompleteType(Loc, CaptureType,
14177                                 diag::err_capture_of_incomplete_type,
14178                                 Var->getDeclName()))
14179         return false;
14180
14181       if (S.RequireNonAbstractType(Loc, CaptureType,
14182                                    diag::err_capture_of_abstract_type))
14183         return false;
14184     }
14185   }
14186
14187   // Capture this variable in the lambda.
14188   if (BuildAndDiagnose)
14189     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
14190                             RefersToCapturedVariable);
14191     
14192   // Compute the type of a reference to this captured variable.
14193   if (ByRef)
14194     DeclRefType = CaptureType.getNonReferenceType();
14195   else {
14196     // C++ [expr.prim.lambda]p5:
14197     //   The closure type for a lambda-expression has a public inline 
14198     //   function call operator [...]. This function call operator is 
14199     //   declared const (9.3.1) if and only if the lambda-expression's 
14200     //   parameter-declaration-clause is not followed by mutable.
14201     DeclRefType = CaptureType.getNonReferenceType();
14202     if (!LSI->Mutable && !CaptureType->isReferenceType())
14203       DeclRefType.addConst();      
14204   }
14205     
14206   // Add the capture.
14207   if (BuildAndDiagnose)
14208     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 
14209                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
14210       
14211   return true;
14212 }
14213
14214 bool Sema::tryCaptureVariable(
14215     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
14216     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
14217     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
14218   // An init-capture is notionally from the context surrounding its
14219   // declaration, but its parent DC is the lambda class.
14220   DeclContext *VarDC = Var->getDeclContext();
14221   if (Var->isInitCapture())
14222     VarDC = VarDC->getParent();
14223   
14224   DeclContext *DC = CurContext;
14225   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 
14226       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;  
14227   // We need to sync up the Declaration Context with the
14228   // FunctionScopeIndexToStopAt
14229   if (FunctionScopeIndexToStopAt) {
14230     unsigned FSIndex = FunctionScopes.size() - 1;
14231     while (FSIndex != MaxFunctionScopesIndex) {
14232       DC = getLambdaAwareParentOfDeclContext(DC);
14233       --FSIndex;
14234     }
14235   }
14236
14237   
14238   // If the variable is declared in the current context, there is no need to
14239   // capture it.
14240   if (VarDC == DC) return true;
14241
14242   // Capture global variables if it is required to use private copy of this
14243   // variable.
14244   bool IsGlobal = !Var->hasLocalStorage();
14245   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
14246     return true;
14247
14248   // Walk up the stack to determine whether we can capture the variable,
14249   // performing the "simple" checks that don't depend on type. We stop when
14250   // we've either hit the declared scope of the variable or find an existing
14251   // capture of that variable.  We start from the innermost capturing-entity
14252   // (the DC) and ensure that all intervening capturing-entities 
14253   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
14254   // declcontext can either capture the variable or have already captured
14255   // the variable.
14256   CaptureType = Var->getType();
14257   DeclRefType = CaptureType.getNonReferenceType();
14258   bool Nested = false;
14259   bool Explicit = (Kind != TryCapture_Implicit);
14260   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
14261   do {
14262     // Only block literals, captured statements, and lambda expressions can
14263     // capture; other scopes don't work.
14264     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 
14265                                                               ExprLoc, 
14266                                                               BuildAndDiagnose,
14267                                                               *this);
14268     // We need to check for the parent *first* because, if we *have*
14269     // private-captured a global variable, we need to recursively capture it in
14270     // intermediate blocks, lambdas, etc.
14271     if (!ParentDC) {
14272       if (IsGlobal) {
14273         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
14274         break;
14275       }
14276       return true;
14277     }
14278
14279     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
14280     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
14281
14282
14283     // Check whether we've already captured it.
14284     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 
14285                                              DeclRefType)) {
14286       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
14287       break;
14288     }
14289     // If we are instantiating a generic lambda call operator body, 
14290     // we do not want to capture new variables.  What was captured
14291     // during either a lambdas transformation or initial parsing
14292     // should be used. 
14293     if (isGenericLambdaCallOperatorSpecialization(DC)) {
14294       if (BuildAndDiagnose) {
14295         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);   
14296         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
14297           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14298           Diag(Var->getLocation(), diag::note_previous_decl) 
14299              << Var->getDeclName();
14300           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);          
14301         } else
14302           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
14303       }
14304       return true;
14305     }
14306     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 
14307     // certain types of variables (unnamed, variably modified types etc.)
14308     // so check for eligibility.
14309     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
14310        return true;
14311
14312     // Try to capture variable-length arrays types.
14313     if (Var->getType()->isVariablyModifiedType()) {
14314       // We're going to walk down into the type and look for VLA
14315       // expressions.
14316       QualType QTy = Var->getType();
14317       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
14318         QTy = PVD->getOriginalType();
14319       captureVariablyModifiedType(Context, QTy, CSI);
14320     }
14321
14322     if (getLangOpts().OpenMP) {
14323       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14324         // OpenMP private variables should not be captured in outer scope, so
14325         // just break here. Similarly, global variables that are captured in a
14326         // target region should not be captured outside the scope of the region.
14327         if (RSI->CapRegionKind == CR_OpenMP) {
14328           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
14329           // When we detect target captures we are looking from inside the
14330           // target region, therefore we need to propagate the capture from the
14331           // enclosing region. Therefore, the capture is not initially nested.
14332           if (IsTargetCap)
14333             FunctionScopesIndex--;
14334
14335           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
14336             Nested = !IsTargetCap;
14337             DeclRefType = DeclRefType.getUnqualifiedType();
14338             CaptureType = Context.getLValueReferenceType(DeclRefType);
14339             break;
14340           }
14341         }
14342       }
14343     }
14344     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
14345       // No capture-default, and this is not an explicit capture 
14346       // so cannot capture this variable.  
14347       if (BuildAndDiagnose) {
14348         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14349         Diag(Var->getLocation(), diag::note_previous_decl) 
14350           << Var->getDeclName();
14351         if (cast<LambdaScopeInfo>(CSI)->Lambda)
14352           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
14353                diag::note_lambda_decl);
14354         // FIXME: If we error out because an outer lambda can not implicitly
14355         // capture a variable that an inner lambda explicitly captures, we
14356         // should have the inner lambda do the explicit capture - because
14357         // it makes for cleaner diagnostics later.  This would purely be done
14358         // so that the diagnostic does not misleadingly claim that a variable 
14359         // can not be captured by a lambda implicitly even though it is captured 
14360         // explicitly.  Suggestion:
14361         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit 
14362         //    at the function head
14363         //  - cache the StartingDeclContext - this must be a lambda 
14364         //  - captureInLambda in the innermost lambda the variable.
14365       }
14366       return true;
14367     }
14368
14369     FunctionScopesIndex--;
14370     DC = ParentDC;
14371     Explicit = false;
14372   } while (!VarDC->Equals(DC));
14373
14374   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
14375   // computing the type of the capture at each step, checking type-specific 
14376   // requirements, and adding captures if requested. 
14377   // If the variable had already been captured previously, we start capturing 
14378   // at the lambda nested within that one.   
14379   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 
14380        ++I) {
14381     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
14382     
14383     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
14384       if (!captureInBlock(BSI, Var, ExprLoc, 
14385                           BuildAndDiagnose, CaptureType, 
14386                           DeclRefType, Nested, *this))
14387         return true;
14388       Nested = true;
14389     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14390       if (!captureInCapturedRegion(RSI, Var, ExprLoc, 
14391                                    BuildAndDiagnose, CaptureType, 
14392                                    DeclRefType, Nested, *this))
14393         return true;
14394       Nested = true;
14395     } else {
14396       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14397       if (!captureInLambda(LSI, Var, ExprLoc, 
14398                            BuildAndDiagnose, CaptureType, 
14399                            DeclRefType, Nested, Kind, EllipsisLoc, 
14400                             /*IsTopScope*/I == N - 1, *this))
14401         return true;
14402       Nested = true;
14403     }
14404   }
14405   return false;
14406 }
14407
14408 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14409                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {  
14410   QualType CaptureType;
14411   QualType DeclRefType;
14412   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14413                             /*BuildAndDiagnose=*/true, CaptureType,
14414                             DeclRefType, nullptr);
14415 }
14416
14417 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14418   QualType CaptureType;
14419   QualType DeclRefType;
14420   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14421                              /*BuildAndDiagnose=*/false, CaptureType,
14422                              DeclRefType, nullptr);
14423 }
14424
14425 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14426   QualType CaptureType;
14427   QualType DeclRefType;
14428   
14429   // Determine whether we can capture this variable.
14430   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14431                          /*BuildAndDiagnose=*/false, CaptureType, 
14432                          DeclRefType, nullptr))
14433     return QualType();
14434
14435   return DeclRefType;
14436 }
14437
14438
14439
14440 // If either the type of the variable or the initializer is dependent, 
14441 // return false. Otherwise, determine whether the variable is a constant
14442 // expression. Use this if you need to know if a variable that might or
14443 // might not be dependent is truly a constant expression.
14444 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 
14445     ASTContext &Context) {
14446  
14447   if (Var->getType()->isDependentType()) 
14448     return false;
14449   const VarDecl *DefVD = nullptr;
14450   Var->getAnyInitializer(DefVD);
14451   if (!DefVD) 
14452     return false;
14453   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14454   Expr *Init = cast<Expr>(Eval->Value);
14455   if (Init->isValueDependent()) 
14456     return false;
14457   return IsVariableAConstantExpression(Var, Context); 
14458 }
14459
14460
14461 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14462   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 
14463   // an object that satisfies the requirements for appearing in a
14464   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14465   // is immediately applied."  This function handles the lvalue-to-rvalue
14466   // conversion part.
14467   MaybeODRUseExprs.erase(E->IgnoreParens());
14468   
14469   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14470   // to a variable that is a constant expression, and if so, identify it as
14471   // a reference to a variable that does not involve an odr-use of that 
14472   // variable. 
14473   if (LambdaScopeInfo *LSI = getCurLambda()) {
14474     Expr *SansParensExpr = E->IgnoreParens();
14475     VarDecl *Var = nullptr;
14476     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 
14477       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14478     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14479       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14480     
14481     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 
14482       LSI->markVariableExprAsNonODRUsed(SansParensExpr);    
14483   }
14484 }
14485
14486 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14487   Res = CorrectDelayedTyposInExpr(Res);
14488
14489   if (!Res.isUsable())
14490     return Res;
14491
14492   // If a constant-expression is a reference to a variable where we delay
14493   // deciding whether it is an odr-use, just assume we will apply the
14494   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
14495   // (a non-type template argument), we have special handling anyway.
14496   UpdateMarkingForLValueToRValue(Res.get());
14497   return Res;
14498 }
14499
14500 void Sema::CleanupVarDeclMarking() {
14501   for (Expr *E : MaybeODRUseExprs) {
14502     VarDecl *Var;
14503     SourceLocation Loc;
14504     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14505       Var = cast<VarDecl>(DRE->getDecl());
14506       Loc = DRE->getLocation();
14507     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14508       Var = cast<VarDecl>(ME->getMemberDecl());
14509       Loc = ME->getMemberLoc();
14510     } else {
14511       llvm_unreachable("Unexpected expression");
14512     }
14513
14514     MarkVarDeclODRUsed(Var, Loc, *this,
14515                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
14516   }
14517
14518   MaybeODRUseExprs.clear();
14519 }
14520
14521
14522 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14523                                     VarDecl *Var, Expr *E) {
14524   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14525          "Invalid Expr argument to DoMarkVarDeclReferenced");
14526   Var->setReferenced();
14527
14528   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14529
14530   bool OdrUseContext = isOdrUseContext(SemaRef);
14531   bool NeedDefinition =
14532       OdrUseContext || (isEvaluatableContext(SemaRef) &&
14533                         Var->isUsableInConstantExpressions(SemaRef.Context));
14534
14535   VarTemplateSpecializationDecl *VarSpec =
14536       dyn_cast<VarTemplateSpecializationDecl>(Var);
14537   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14538          "Can't instantiate a partial template specialization.");
14539
14540   // If this might be a member specialization of a static data member, check
14541   // the specialization is visible. We already did the checks for variable
14542   // template specializations when we created them.
14543   if (NeedDefinition && TSK != TSK_Undeclared &&
14544       !isa<VarTemplateSpecializationDecl>(Var))
14545     SemaRef.checkSpecializationVisibility(Loc, Var);
14546
14547   // Perform implicit instantiation of static data members, static data member
14548   // templates of class templates, and variable template specializations. Delay
14549   // instantiations of variable templates, except for those that could be used
14550   // in a constant expression.
14551   if (NeedDefinition && isTemplateInstantiation(TSK)) {
14552     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14553
14554     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14555       if (Var->getPointOfInstantiation().isInvalid()) {
14556         // This is a modification of an existing AST node. Notify listeners.
14557         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14558           L->StaticDataMemberInstantiated(Var);
14559       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14560         // Don't bother trying to instantiate it again, unless we might need
14561         // its initializer before we get to the end of the TU.
14562         TryInstantiating = false;
14563     }
14564
14565     if (Var->getPointOfInstantiation().isInvalid())
14566       Var->setTemplateSpecializationKind(TSK, Loc);
14567
14568     if (TryInstantiating) {
14569       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14570       bool InstantiationDependent = false;
14571       bool IsNonDependent =
14572           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14573                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14574                   : true;
14575
14576       // Do not instantiate specializations that are still type-dependent.
14577       if (IsNonDependent) {
14578         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14579           // Do not defer instantiations of variables which could be used in a
14580           // constant expression.
14581           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14582         } else {
14583           SemaRef.PendingInstantiations
14584               .push_back(std::make_pair(Var, PointOfInstantiation));
14585         }
14586       }
14587     }
14588   }
14589
14590   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14591   // the requirements for appearing in a constant expression (5.19) and, if
14592   // it is an object, the lvalue-to-rvalue conversion (4.1)
14593   // is immediately applied."  We check the first part here, and
14594   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14595   // Note that we use the C++11 definition everywhere because nothing in
14596   // C++03 depends on whether we get the C++03 version correct. The second
14597   // part does not apply to references, since they are not objects.
14598   if (OdrUseContext && E &&
14599       IsVariableAConstantExpression(Var, SemaRef.Context)) {
14600     // A reference initialized by a constant expression can never be
14601     // odr-used, so simply ignore it.
14602     if (!Var->getType()->isReferenceType())
14603       SemaRef.MaybeODRUseExprs.insert(E);
14604   } else if (OdrUseContext) {
14605     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14606                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14607   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
14608     // If this is a dependent context, we don't need to mark variables as
14609     // odr-used, but we may still need to track them for lambda capture.
14610     // FIXME: Do we also need to do this inside dependent typeid expressions
14611     // (which are modeled as unevaluated at this point)?
14612     const bool RefersToEnclosingScope =
14613         (SemaRef.CurContext != Var->getDeclContext() &&
14614          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14615     if (RefersToEnclosingScope) {
14616       LambdaScopeInfo *const LSI =
14617           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
14618       if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) {
14619         // If a variable could potentially be odr-used, defer marking it so
14620         // until we finish analyzing the full expression for any
14621         // lvalue-to-rvalue
14622         // or discarded value conversions that would obviate odr-use.
14623         // Add it to the list of potential captures that will be analyzed
14624         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14625         // unless the variable is a reference that was initialized by a constant
14626         // expression (this will never need to be captured or odr-used).
14627         assert(E && "Capture variable should be used in an expression.");
14628         if (!Var->getType()->isReferenceType() ||
14629             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14630           LSI->addPotentialCapture(E->IgnoreParens());
14631       }
14632     }
14633   }
14634 }
14635
14636 /// \brief Mark a variable referenced, and check whether it is odr-used
14637 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
14638 /// used directly for normal expressions referring to VarDecl.
14639 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14640   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14641 }
14642
14643 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14644                                Decl *D, Expr *E, bool MightBeOdrUse) {
14645   if (SemaRef.isInOpenMPDeclareTargetContext())
14646     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14647
14648   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14649     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14650     return;
14651   }
14652
14653   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14654
14655   // If this is a call to a method via a cast, also mark the method in the
14656   // derived class used in case codegen can devirtualize the call.
14657   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14658   if (!ME)
14659     return;
14660   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14661   if (!MD)
14662     return;
14663   // Only attempt to devirtualize if this is truly a virtual call.
14664   bool IsVirtualCall = MD->isVirtual() &&
14665                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14666   if (!IsVirtualCall)
14667     return;
14668
14669   // If it's possible to devirtualize the call, mark the called function
14670   // referenced.
14671   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
14672       ME->getBase(), SemaRef.getLangOpts().AppleKext);
14673   if (DM)
14674     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14675
14676
14677 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14678 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
14679   // TODO: update this with DR# once a defect report is filed.
14680   // C++11 defect. The address of a pure member should not be an ODR use, even
14681   // if it's a qualified reference.
14682   bool OdrUse = true;
14683   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14684     if (Method->isVirtual() &&
14685         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
14686       OdrUse = false;
14687   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14688 }
14689
14690 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14691 void Sema::MarkMemberReferenced(MemberExpr *E) {
14692   // C++11 [basic.def.odr]p2:
14693   //   A non-overloaded function whose name appears as a potentially-evaluated
14694   //   expression or a member of a set of candidate functions, if selected by
14695   //   overload resolution when referred to from a potentially-evaluated
14696   //   expression, is odr-used, unless it is a pure virtual function and its
14697   //   name is not explicitly qualified.
14698   bool MightBeOdrUse = true;
14699   if (E->performsVirtualDispatch(getLangOpts())) {
14700     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14701       if (Method->isPure())
14702         MightBeOdrUse = false;
14703   }
14704   SourceLocation Loc = E->getMemberLoc().isValid() ?
14705                             E->getMemberLoc() : E->getLocStart();
14706   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14707 }
14708
14709 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14710 /// marks the declaration referenced, and performs odr-use checking for
14711 /// functions and variables. This method should not be used when building a
14712 /// normal expression which refers to a variable.
14713 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14714                                  bool MightBeOdrUse) {
14715   if (MightBeOdrUse) {
14716     if (auto *VD = dyn_cast<VarDecl>(D)) {
14717       MarkVariableReferenced(Loc, VD);
14718       return;
14719     }
14720   }
14721   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14722     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14723     return;
14724   }
14725   D->setReferenced();
14726 }
14727
14728 namespace {
14729   // Mark all of the declarations used by a type as referenced.
14730   // FIXME: Not fully implemented yet! We need to have a better understanding
14731   // of when we're entering a context we should not recurse into.
14732   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
14733   // TreeTransforms rebuilding the type in a new context. Rather than
14734   // duplicating the TreeTransform logic, we should consider reusing it here.
14735   // Currently that causes problems when rebuilding LambdaExprs.
14736   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14737     Sema &S;
14738     SourceLocation Loc;
14739
14740   public:
14741     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14742
14743     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14744
14745     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14746   };
14747 }
14748
14749 bool MarkReferencedDecls::TraverseTemplateArgument(
14750     const TemplateArgument &Arg) {
14751   {
14752     // A non-type template argument is a constant-evaluated context.
14753     EnterExpressionEvaluationContext Evaluated(
14754         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
14755     if (Arg.getKind() == TemplateArgument::Declaration) {
14756       if (Decl *D = Arg.getAsDecl())
14757         S.MarkAnyDeclReferenced(Loc, D, true);
14758     } else if (Arg.getKind() == TemplateArgument::Expression) {
14759       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
14760     }
14761   }
14762
14763   return Inherited::TraverseTemplateArgument(Arg);
14764 }
14765
14766 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14767   MarkReferencedDecls Marker(*this, Loc);
14768   Marker.TraverseType(T);
14769 }
14770
14771 namespace {
14772   /// \brief Helper class that marks all of the declarations referenced by
14773   /// potentially-evaluated subexpressions as "referenced".
14774   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14775     Sema &S;
14776     bool SkipLocalVariables;
14777     
14778   public:
14779     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14780     
14781     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 
14782       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14783     
14784     void VisitDeclRefExpr(DeclRefExpr *E) {
14785       // If we were asked not to visit local variables, don't.
14786       if (SkipLocalVariables) {
14787         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14788           if (VD->hasLocalStorage())
14789             return;
14790       }
14791       
14792       S.MarkDeclRefReferenced(E);
14793     }
14794
14795     void VisitMemberExpr(MemberExpr *E) {
14796       S.MarkMemberReferenced(E);
14797       Inherited::VisitMemberExpr(E);
14798     }
14799     
14800     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14801       S.MarkFunctionReferenced(E->getLocStart(),
14802             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14803       Visit(E->getSubExpr());
14804     }
14805     
14806     void VisitCXXNewExpr(CXXNewExpr *E) {
14807       if (E->getOperatorNew())
14808         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14809       if (E->getOperatorDelete())
14810         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14811       Inherited::VisitCXXNewExpr(E);
14812     }
14813
14814     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14815       if (E->getOperatorDelete())
14816         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14817       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14818       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14819         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14820         S.MarkFunctionReferenced(E->getLocStart(), 
14821                                     S.LookupDestructor(Record));
14822       }
14823       
14824       Inherited::VisitCXXDeleteExpr(E);
14825     }
14826     
14827     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14828       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14829       Inherited::VisitCXXConstructExpr(E);
14830     }
14831     
14832     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14833       Visit(E->getExpr());
14834     }
14835
14836     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14837       Inherited::VisitImplicitCastExpr(E);
14838
14839       if (E->getCastKind() == CK_LValueToRValue)
14840         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14841     }
14842   };
14843 }
14844
14845 /// \brief Mark any declarations that appear within this expression or any
14846 /// potentially-evaluated subexpressions as "referenced".
14847 ///
14848 /// \param SkipLocalVariables If true, don't mark local variables as 
14849 /// 'referenced'.
14850 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 
14851                                             bool SkipLocalVariables) {
14852   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14853 }
14854
14855 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14856 /// of the program being compiled.
14857 ///
14858 /// This routine emits the given diagnostic when the code currently being
14859 /// type-checked is "potentially evaluated", meaning that there is a
14860 /// possibility that the code will actually be executable. Code in sizeof()
14861 /// expressions, code used only during overload resolution, etc., are not
14862 /// potentially evaluated. This routine will suppress such diagnostics or,
14863 /// in the absolutely nutty case of potentially potentially evaluated
14864 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14865 /// later.
14866 ///
14867 /// This routine should be used for all diagnostics that describe the run-time
14868 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14869 /// Failure to do so will likely result in spurious diagnostics or failures
14870 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14871 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14872                                const PartialDiagnostic &PD) {
14873   switch (ExprEvalContexts.back().Context) {
14874   case ExpressionEvaluationContext::Unevaluated:
14875   case ExpressionEvaluationContext::UnevaluatedList:
14876   case ExpressionEvaluationContext::UnevaluatedAbstract:
14877   case ExpressionEvaluationContext::DiscardedStatement:
14878     // The argument will never be evaluated, so don't complain.
14879     break;
14880
14881   case ExpressionEvaluationContext::ConstantEvaluated:
14882     // Relevant diagnostics should be produced by constant evaluation.
14883     break;
14884
14885   case ExpressionEvaluationContext::PotentiallyEvaluated:
14886   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14887     if (Statement && getCurFunctionOrMethodDecl()) {
14888       FunctionScopes.back()->PossiblyUnreachableDiags.
14889         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14890     }
14891     else
14892       Diag(Loc, PD);
14893       
14894     return true;
14895   }
14896
14897   return false;
14898 }
14899
14900 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14901                                CallExpr *CE, FunctionDecl *FD) {
14902   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14903     return false;
14904
14905   // If we're inside a decltype's expression, don't check for a valid return
14906   // type or construct temporaries until we know whether this is the last call.
14907   if (ExprEvalContexts.back().IsDecltype) {
14908     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14909     return false;
14910   }
14911
14912   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14913     FunctionDecl *FD;
14914     CallExpr *CE;
14915     
14916   public:
14917     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14918       : FD(FD), CE(CE) { }
14919
14920     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14921       if (!FD) {
14922         S.Diag(Loc, diag::err_call_incomplete_return)
14923           << T << CE->getSourceRange();
14924         return;
14925       }
14926       
14927       S.Diag(Loc, diag::err_call_function_incomplete_return)
14928         << CE->getSourceRange() << FD->getDeclName() << T;
14929       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14930           << FD->getDeclName();
14931     }
14932   } Diagnoser(FD, CE);
14933   
14934   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14935     return true;
14936
14937   return false;
14938 }
14939
14940 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14941 // will prevent this condition from triggering, which is what we want.
14942 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14943   SourceLocation Loc;
14944
14945   unsigned diagnostic = diag::warn_condition_is_assignment;
14946   bool IsOrAssign = false;
14947
14948   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14949     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14950       return;
14951
14952     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14953
14954     // Greylist some idioms by putting them into a warning subcategory.
14955     if (ObjCMessageExpr *ME
14956           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14957       Selector Sel = ME->getSelector();
14958
14959       // self = [<foo> init...]
14960       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14961         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14962
14963       // <foo> = [<bar> nextObject]
14964       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14965         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14966     }
14967
14968     Loc = Op->getOperatorLoc();
14969   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14970     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14971       return;
14972
14973     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14974     Loc = Op->getOperatorLoc();
14975   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14976     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14977   else {
14978     // Not an assignment.
14979     return;
14980   }
14981
14982   Diag(Loc, diagnostic) << E->getSourceRange();
14983
14984   SourceLocation Open = E->getLocStart();
14985   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14986   Diag(Loc, diag::note_condition_assign_silence)
14987         << FixItHint::CreateInsertion(Open, "(")
14988         << FixItHint::CreateInsertion(Close, ")");
14989
14990   if (IsOrAssign)
14991     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14992       << FixItHint::CreateReplacement(Loc, "!=");
14993   else
14994     Diag(Loc, diag::note_condition_assign_to_comparison)
14995       << FixItHint::CreateReplacement(Loc, "==");
14996 }
14997
14998 /// \brief Redundant parentheses over an equality comparison can indicate
14999 /// that the user intended an assignment used as condition.
15000 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
15001   // Don't warn if the parens came from a macro.
15002   SourceLocation parenLoc = ParenE->getLocStart();
15003   if (parenLoc.isInvalid() || parenLoc.isMacroID())
15004     return;
15005   // Don't warn for dependent expressions.
15006   if (ParenE->isTypeDependent())
15007     return;
15008
15009   Expr *E = ParenE->IgnoreParens();
15010
15011   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
15012     if (opE->getOpcode() == BO_EQ &&
15013         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
15014                                                            == Expr::MLV_Valid) {
15015       SourceLocation Loc = opE->getOperatorLoc();
15016       
15017       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
15018       SourceRange ParenERange = ParenE->getSourceRange();
15019       Diag(Loc, diag::note_equality_comparison_silence)
15020         << FixItHint::CreateRemoval(ParenERange.getBegin())
15021         << FixItHint::CreateRemoval(ParenERange.getEnd());
15022       Diag(Loc, diag::note_equality_comparison_to_assign)
15023         << FixItHint::CreateReplacement(Loc, "=");
15024     }
15025 }
15026
15027 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
15028                                        bool IsConstexpr) {
15029   DiagnoseAssignmentAsCondition(E);
15030   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
15031     DiagnoseEqualityWithExtraParens(parenE);
15032
15033   ExprResult result = CheckPlaceholderExpr(E);
15034   if (result.isInvalid()) return ExprError();
15035   E = result.get();
15036
15037   if (!E->isTypeDependent()) {
15038     if (getLangOpts().CPlusPlus)
15039       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
15040
15041     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
15042     if (ERes.isInvalid())
15043       return ExprError();
15044     E = ERes.get();
15045
15046     QualType T = E->getType();
15047     if (!T->isScalarType()) { // C99 6.8.4.1p1
15048       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
15049         << T << E->getSourceRange();
15050       return ExprError();
15051     }
15052     CheckBoolLikeConversion(E, Loc);
15053   }
15054
15055   return E;
15056 }
15057
15058 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
15059                                            Expr *SubExpr, ConditionKind CK) {
15060   // Empty conditions are valid in for-statements.
15061   if (!SubExpr)
15062     return ConditionResult();
15063
15064   ExprResult Cond;
15065   switch (CK) {
15066   case ConditionKind::Boolean:
15067     Cond = CheckBooleanCondition(Loc, SubExpr);
15068     break;
15069
15070   case ConditionKind::ConstexprIf:
15071     Cond = CheckBooleanCondition(Loc, SubExpr, true);
15072     break;
15073
15074   case ConditionKind::Switch:
15075     Cond = CheckSwitchCondition(Loc, SubExpr);
15076     break;
15077   }
15078   if (Cond.isInvalid())
15079     return ConditionError();
15080
15081   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
15082   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
15083   if (!FullExpr.get())
15084     return ConditionError();
15085
15086   return ConditionResult(*this, nullptr, FullExpr,
15087                          CK == ConditionKind::ConstexprIf);
15088 }
15089
15090 namespace {
15091   /// A visitor for rebuilding a call to an __unknown_any expression
15092   /// to have an appropriate type.
15093   struct RebuildUnknownAnyFunction
15094     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
15095
15096     Sema &S;
15097
15098     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
15099
15100     ExprResult VisitStmt(Stmt *S) {
15101       llvm_unreachable("unexpected statement!");
15102     }
15103
15104     ExprResult VisitExpr(Expr *E) {
15105       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
15106         << E->getSourceRange();
15107       return ExprError();
15108     }
15109
15110     /// Rebuild an expression which simply semantically wraps another
15111     /// expression which it shares the type and value kind of.
15112     template <class T> ExprResult rebuildSugarExpr(T *E) {
15113       ExprResult SubResult = Visit(E->getSubExpr());
15114       if (SubResult.isInvalid()) return ExprError();
15115
15116       Expr *SubExpr = SubResult.get();
15117       E->setSubExpr(SubExpr);
15118       E->setType(SubExpr->getType());
15119       E->setValueKind(SubExpr->getValueKind());
15120       assert(E->getObjectKind() == OK_Ordinary);
15121       return E;
15122     }
15123
15124     ExprResult VisitParenExpr(ParenExpr *E) {
15125       return rebuildSugarExpr(E);
15126     }
15127
15128     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15129       return rebuildSugarExpr(E);
15130     }
15131
15132     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15133       ExprResult SubResult = Visit(E->getSubExpr());
15134       if (SubResult.isInvalid()) return ExprError();
15135
15136       Expr *SubExpr = SubResult.get();
15137       E->setSubExpr(SubExpr);
15138       E->setType(S.Context.getPointerType(SubExpr->getType()));
15139       assert(E->getValueKind() == VK_RValue);
15140       assert(E->getObjectKind() == OK_Ordinary);
15141       return E;
15142     }
15143
15144     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
15145       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
15146
15147       E->setType(VD->getType());
15148
15149       assert(E->getValueKind() == VK_RValue);
15150       if (S.getLangOpts().CPlusPlus &&
15151           !(isa<CXXMethodDecl>(VD) &&
15152             cast<CXXMethodDecl>(VD)->isInstance()))
15153         E->setValueKind(VK_LValue);
15154
15155       return E;
15156     }
15157
15158     ExprResult VisitMemberExpr(MemberExpr *E) {
15159       return resolveDecl(E, E->getMemberDecl());
15160     }
15161
15162     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15163       return resolveDecl(E, E->getDecl());
15164     }
15165   };
15166 }
15167
15168 /// Given a function expression of unknown-any type, try to rebuild it
15169 /// to have a function type.
15170 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
15171   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
15172   if (Result.isInvalid()) return ExprError();
15173   return S.DefaultFunctionArrayConversion(Result.get());
15174 }
15175
15176 namespace {
15177   /// A visitor for rebuilding an expression of type __unknown_anytype
15178   /// into one which resolves the type directly on the referring
15179   /// expression.  Strict preservation of the original source
15180   /// structure is not a goal.
15181   struct RebuildUnknownAnyExpr
15182     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
15183
15184     Sema &S;
15185
15186     /// The current destination type.
15187     QualType DestType;
15188
15189     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
15190       : S(S), DestType(CastType) {}
15191
15192     ExprResult VisitStmt(Stmt *S) {
15193       llvm_unreachable("unexpected statement!");
15194     }
15195
15196     ExprResult VisitExpr(Expr *E) {
15197       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15198         << E->getSourceRange();
15199       return ExprError();
15200     }
15201
15202     ExprResult VisitCallExpr(CallExpr *E);
15203     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
15204
15205     /// Rebuild an expression which simply semantically wraps another
15206     /// expression which it shares the type and value kind of.
15207     template <class T> ExprResult rebuildSugarExpr(T *E) {
15208       ExprResult SubResult = Visit(E->getSubExpr());
15209       if (SubResult.isInvalid()) return ExprError();
15210       Expr *SubExpr = SubResult.get();
15211       E->setSubExpr(SubExpr);
15212       E->setType(SubExpr->getType());
15213       E->setValueKind(SubExpr->getValueKind());
15214       assert(E->getObjectKind() == OK_Ordinary);
15215       return E;
15216     }
15217
15218     ExprResult VisitParenExpr(ParenExpr *E) {
15219       return rebuildSugarExpr(E);
15220     }
15221
15222     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15223       return rebuildSugarExpr(E);
15224     }
15225
15226     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15227       const PointerType *Ptr = DestType->getAs<PointerType>();
15228       if (!Ptr) {
15229         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
15230           << E->getSourceRange();
15231         return ExprError();
15232       }
15233
15234       if (isa<CallExpr>(E->getSubExpr())) {
15235         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
15236           << E->getSourceRange();
15237         return ExprError();
15238       }
15239
15240       assert(E->getValueKind() == VK_RValue);
15241       assert(E->getObjectKind() == OK_Ordinary);
15242       E->setType(DestType);
15243
15244       // Build the sub-expression as if it were an object of the pointee type.
15245       DestType = Ptr->getPointeeType();
15246       ExprResult SubResult = Visit(E->getSubExpr());
15247       if (SubResult.isInvalid()) return ExprError();
15248       E->setSubExpr(SubResult.get());
15249       return E;
15250     }
15251
15252     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
15253
15254     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
15255
15256     ExprResult VisitMemberExpr(MemberExpr *E) {
15257       return resolveDecl(E, E->getMemberDecl());
15258     }
15259
15260     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15261       return resolveDecl(E, E->getDecl());
15262     }
15263   };
15264 }
15265
15266 /// Rebuilds a call expression which yielded __unknown_anytype.
15267 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
15268   Expr *CalleeExpr = E->getCallee();
15269
15270   enum FnKind {
15271     FK_MemberFunction,
15272     FK_FunctionPointer,
15273     FK_BlockPointer
15274   };
15275
15276   FnKind Kind;
15277   QualType CalleeType = CalleeExpr->getType();
15278   if (CalleeType == S.Context.BoundMemberTy) {
15279     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
15280     Kind = FK_MemberFunction;
15281     CalleeType = Expr::findBoundMemberType(CalleeExpr);
15282   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
15283     CalleeType = Ptr->getPointeeType();
15284     Kind = FK_FunctionPointer;
15285   } else {
15286     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
15287     Kind = FK_BlockPointer;
15288   }
15289   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
15290
15291   // Verify that this is a legal result type of a function.
15292   if (DestType->isArrayType() || DestType->isFunctionType()) {
15293     unsigned diagID = diag::err_func_returning_array_function;
15294     if (Kind == FK_BlockPointer)
15295       diagID = diag::err_block_returning_array_function;
15296
15297     S.Diag(E->getExprLoc(), diagID)
15298       << DestType->isFunctionType() << DestType;
15299     return ExprError();
15300   }
15301
15302   // Otherwise, go ahead and set DestType as the call's result.
15303   E->setType(DestType.getNonLValueExprType(S.Context));
15304   E->setValueKind(Expr::getValueKindForType(DestType));
15305   assert(E->getObjectKind() == OK_Ordinary);
15306
15307   // Rebuild the function type, replacing the result type with DestType.
15308   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
15309   if (Proto) {
15310     // __unknown_anytype(...) is a special case used by the debugger when
15311     // it has no idea what a function's signature is.
15312     //
15313     // We want to build this call essentially under the K&R
15314     // unprototyped rules, but making a FunctionNoProtoType in C++
15315     // would foul up all sorts of assumptions.  However, we cannot
15316     // simply pass all arguments as variadic arguments, nor can we
15317     // portably just call the function under a non-variadic type; see
15318     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
15319     // However, it turns out that in practice it is generally safe to
15320     // call a function declared as "A foo(B,C,D);" under the prototype
15321     // "A foo(B,C,D,...);".  The only known exception is with the
15322     // Windows ABI, where any variadic function is implicitly cdecl
15323     // regardless of its normal CC.  Therefore we change the parameter
15324     // types to match the types of the arguments.
15325     //
15326     // This is a hack, but it is far superior to moving the
15327     // corresponding target-specific code from IR-gen to Sema/AST.
15328
15329     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
15330     SmallVector<QualType, 8> ArgTypes;
15331     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
15332       ArgTypes.reserve(E->getNumArgs());
15333       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
15334         Expr *Arg = E->getArg(i);
15335         QualType ArgType = Arg->getType();
15336         if (E->isLValue()) {
15337           ArgType = S.Context.getLValueReferenceType(ArgType);
15338         } else if (E->isXValue()) {
15339           ArgType = S.Context.getRValueReferenceType(ArgType);
15340         }
15341         ArgTypes.push_back(ArgType);
15342       }
15343       ParamTypes = ArgTypes;
15344     }
15345     DestType = S.Context.getFunctionType(DestType, ParamTypes,
15346                                          Proto->getExtProtoInfo());
15347   } else {
15348     DestType = S.Context.getFunctionNoProtoType(DestType,
15349                                                 FnType->getExtInfo());
15350   }
15351
15352   // Rebuild the appropriate pointer-to-function type.
15353   switch (Kind) { 
15354   case FK_MemberFunction:
15355     // Nothing to do.
15356     break;
15357
15358   case FK_FunctionPointer:
15359     DestType = S.Context.getPointerType(DestType);
15360     break;
15361
15362   case FK_BlockPointer:
15363     DestType = S.Context.getBlockPointerType(DestType);
15364     break;
15365   }
15366
15367   // Finally, we can recurse.
15368   ExprResult CalleeResult = Visit(CalleeExpr);
15369   if (!CalleeResult.isUsable()) return ExprError();
15370   E->setCallee(CalleeResult.get());
15371
15372   // Bind a temporary if necessary.
15373   return S.MaybeBindToTemporary(E);
15374 }
15375
15376 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
15377   // Verify that this is a legal result type of a call.
15378   if (DestType->isArrayType() || DestType->isFunctionType()) {
15379     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
15380       << DestType->isFunctionType() << DestType;
15381     return ExprError();
15382   }
15383
15384   // Rewrite the method result type if available.
15385   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
15386     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
15387     Method->setReturnType(DestType);
15388   }
15389
15390   // Change the type of the message.
15391   E->setType(DestType.getNonReferenceType());
15392   E->setValueKind(Expr::getValueKindForType(DestType));
15393
15394   return S.MaybeBindToTemporary(E);
15395 }
15396
15397 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15398   // The only case we should ever see here is a function-to-pointer decay.
15399   if (E->getCastKind() == CK_FunctionToPointerDecay) {
15400     assert(E->getValueKind() == VK_RValue);
15401     assert(E->getObjectKind() == OK_Ordinary);
15402   
15403     E->setType(DestType);
15404   
15405     // Rebuild the sub-expression as the pointee (function) type.
15406     DestType = DestType->castAs<PointerType>()->getPointeeType();
15407   
15408     ExprResult Result = Visit(E->getSubExpr());
15409     if (!Result.isUsable()) return ExprError();
15410   
15411     E->setSubExpr(Result.get());
15412     return E;
15413   } else if (E->getCastKind() == CK_LValueToRValue) {
15414     assert(E->getValueKind() == VK_RValue);
15415     assert(E->getObjectKind() == OK_Ordinary);
15416
15417     assert(isa<BlockPointerType>(E->getType()));
15418
15419     E->setType(DestType);
15420
15421     // The sub-expression has to be a lvalue reference, so rebuild it as such.
15422     DestType = S.Context.getLValueReferenceType(DestType);
15423
15424     ExprResult Result = Visit(E->getSubExpr());
15425     if (!Result.isUsable()) return ExprError();
15426
15427     E->setSubExpr(Result.get());
15428     return E;
15429   } else {
15430     llvm_unreachable("Unhandled cast type!");
15431   }
15432 }
15433
15434 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15435   ExprValueKind ValueKind = VK_LValue;
15436   QualType Type = DestType;
15437
15438   // We know how to make this work for certain kinds of decls:
15439
15440   //  - functions
15441   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15442     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15443       DestType = Ptr->getPointeeType();
15444       ExprResult Result = resolveDecl(E, VD);
15445       if (Result.isInvalid()) return ExprError();
15446       return S.ImpCastExprToType(Result.get(), Type,
15447                                  CK_FunctionToPointerDecay, VK_RValue);
15448     }
15449
15450     if (!Type->isFunctionType()) {
15451       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15452         << VD << E->getSourceRange();
15453       return ExprError();
15454     }
15455     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15456       // We must match the FunctionDecl's type to the hack introduced in
15457       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15458       // type. See the lengthy commentary in that routine.
15459       QualType FDT = FD->getType();
15460       const FunctionType *FnType = FDT->castAs<FunctionType>();
15461       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15462       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15463       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15464         SourceLocation Loc = FD->getLocation();
15465         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15466                                       FD->getDeclContext(),
15467                                       Loc, Loc, FD->getNameInfo().getName(),
15468                                       DestType, FD->getTypeSourceInfo(),
15469                                       SC_None, false/*isInlineSpecified*/,
15470                                       FD->hasPrototype(),
15471                                       false/*isConstexprSpecified*/);
15472           
15473         if (FD->getQualifier())
15474           NewFD->setQualifierInfo(FD->getQualifierLoc());
15475
15476         SmallVector<ParmVarDecl*, 16> Params;
15477         for (const auto &AI : FT->param_types()) {
15478           ParmVarDecl *Param =
15479             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15480           Param->setScopeInfo(0, Params.size());
15481           Params.push_back(Param);
15482         }
15483         NewFD->setParams(Params);
15484         DRE->setDecl(NewFD);
15485         VD = DRE->getDecl();
15486       }
15487     }
15488
15489     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15490       if (MD->isInstance()) {
15491         ValueKind = VK_RValue;
15492         Type = S.Context.BoundMemberTy;
15493       }
15494
15495     // Function references aren't l-values in C.
15496     if (!S.getLangOpts().CPlusPlus)
15497       ValueKind = VK_RValue;
15498
15499   //  - variables
15500   } else if (isa<VarDecl>(VD)) {
15501     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15502       Type = RefTy->getPointeeType();
15503     } else if (Type->isFunctionType()) {
15504       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15505         << VD << E->getSourceRange();
15506       return ExprError();
15507     }
15508
15509   //  - nothing else
15510   } else {
15511     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15512       << VD << E->getSourceRange();
15513     return ExprError();
15514   }
15515
15516   // Modifying the declaration like this is friendly to IR-gen but
15517   // also really dangerous.
15518   VD->setType(DestType);
15519   E->setType(Type);
15520   E->setValueKind(ValueKind);
15521   return E;
15522 }
15523
15524 /// Check a cast of an unknown-any type.  We intentionally only
15525 /// trigger this for C-style casts.
15526 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15527                                      Expr *CastExpr, CastKind &CastKind,
15528                                      ExprValueKind &VK, CXXCastPath &Path) {
15529   // The type we're casting to must be either void or complete.
15530   if (!CastType->isVoidType() &&
15531       RequireCompleteType(TypeRange.getBegin(), CastType,
15532                           diag::err_typecheck_cast_to_incomplete))
15533     return ExprError();
15534
15535   // Rewrite the casted expression from scratch.
15536   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15537   if (!result.isUsable()) return ExprError();
15538
15539   CastExpr = result.get();
15540   VK = CastExpr->getValueKind();
15541   CastKind = CK_NoOp;
15542
15543   return CastExpr;
15544 }
15545
15546 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15547   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15548 }
15549
15550 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15551                                     Expr *arg, QualType &paramType) {
15552   // If the syntactic form of the argument is not an explicit cast of
15553   // any sort, just do default argument promotion.
15554   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15555   if (!castArg) {
15556     ExprResult result = DefaultArgumentPromotion(arg);
15557     if (result.isInvalid()) return ExprError();
15558     paramType = result.get()->getType();
15559     return result;
15560   }
15561
15562   // Otherwise, use the type that was written in the explicit cast.
15563   assert(!arg->hasPlaceholderType());
15564   paramType = castArg->getTypeAsWritten();
15565
15566   // Copy-initialize a parameter of that type.
15567   InitializedEntity entity =
15568     InitializedEntity::InitializeParameter(Context, paramType,
15569                                            /*consumed*/ false);
15570   return PerformCopyInitialization(entity, callLoc, arg);
15571 }
15572
15573 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15574   Expr *orig = E;
15575   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15576   while (true) {
15577     E = E->IgnoreParenImpCasts();
15578     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15579       E = call->getCallee();
15580       diagID = diag::err_uncasted_call_of_unknown_any;
15581     } else {
15582       break;
15583     }
15584   }
15585
15586   SourceLocation loc;
15587   NamedDecl *d;
15588   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15589     loc = ref->getLocation();
15590     d = ref->getDecl();
15591   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15592     loc = mem->getMemberLoc();
15593     d = mem->getMemberDecl();
15594   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15595     diagID = diag::err_uncasted_call_of_unknown_any;
15596     loc = msg->getSelectorStartLoc();
15597     d = msg->getMethodDecl();
15598     if (!d) {
15599       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15600         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15601         << orig->getSourceRange();
15602       return ExprError();
15603     }
15604   } else {
15605     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15606       << E->getSourceRange();
15607     return ExprError();
15608   }
15609
15610   S.Diag(loc, diagID) << d << orig->getSourceRange();
15611
15612   // Never recoverable.
15613   return ExprError();
15614 }
15615
15616 /// Check for operands with placeholder types and complain if found.
15617 /// Returns ExprError() if there was an error and no recovery was possible.
15618 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15619   if (!getLangOpts().CPlusPlus) {
15620     // C cannot handle TypoExpr nodes on either side of a binop because it
15621     // doesn't handle dependent types properly, so make sure any TypoExprs have
15622     // been dealt with before checking the operands.
15623     ExprResult Result = CorrectDelayedTyposInExpr(E);
15624     if (!Result.isUsable()) return ExprError();
15625     E = Result.get();
15626   }
15627
15628   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15629   if (!placeholderType) return E;
15630
15631   switch (placeholderType->getKind()) {
15632
15633   // Overloaded expressions.
15634   case BuiltinType::Overload: {
15635     // Try to resolve a single function template specialization.
15636     // This is obligatory.
15637     ExprResult Result = E;
15638     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15639       return Result;
15640
15641     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15642     // leaves Result unchanged on failure.
15643     Result = E;
15644     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15645       return Result;
15646
15647     // If that failed, try to recover with a call.
15648     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15649                          /*complain*/ true);
15650     return Result;
15651   }
15652
15653   // Bound member functions.
15654   case BuiltinType::BoundMember: {
15655     ExprResult result = E;
15656     const Expr *BME = E->IgnoreParens();
15657     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15658     // Try to give a nicer diagnostic if it is a bound member that we recognize.
15659     if (isa<CXXPseudoDestructorExpr>(BME)) {
15660       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15661     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15662       if (ME->getMemberNameInfo().getName().getNameKind() ==
15663           DeclarationName::CXXDestructorName)
15664         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15665     }
15666     tryToRecoverWithCall(result, PD,
15667                          /*complain*/ true);
15668     return result;
15669   }
15670
15671   // ARC unbridged casts.
15672   case BuiltinType::ARCUnbridgedCast: {
15673     Expr *realCast = stripARCUnbridgedCast(E);
15674     diagnoseARCUnbridgedCast(realCast);
15675     return realCast;
15676   }
15677
15678   // Expressions of unknown type.
15679   case BuiltinType::UnknownAny:
15680     return diagnoseUnknownAnyExpr(*this, E);
15681
15682   // Pseudo-objects.
15683   case BuiltinType::PseudoObject:
15684     return checkPseudoObjectRValue(E);
15685
15686   case BuiltinType::BuiltinFn: {
15687     // Accept __noop without parens by implicitly converting it to a call expr.
15688     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15689     if (DRE) {
15690       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15691       if (FD->getBuiltinID() == Builtin::BI__noop) {
15692         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15693                               CK_BuiltinFnToFnPtr).get();
15694         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15695                                       VK_RValue, SourceLocation());
15696       }
15697     }
15698
15699     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15700     return ExprError();
15701   }
15702
15703   // Expressions of unknown type.
15704   case BuiltinType::OMPArraySection:
15705     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15706     return ExprError();
15707
15708   // Everything else should be impossible.
15709 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15710   case BuiltinType::Id:
15711 #include "clang/Basic/OpenCLImageTypes.def"
15712 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15713 #define PLACEHOLDER_TYPE(Id, SingletonId)
15714 #include "clang/AST/BuiltinTypes.def"
15715     break;
15716   }
15717
15718   llvm_unreachable("invalid placeholder type!");
15719 }
15720
15721 bool Sema::CheckCaseExpression(Expr *E) {
15722   if (E->isTypeDependent())
15723     return true;
15724   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15725     return E->getType()->isIntegralOrEnumerationType();
15726   return false;
15727 }
15728
15729 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15730 ExprResult
15731 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15732   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15733          "Unknown Objective-C Boolean value!");
15734   QualType BoolT = Context.ObjCBuiltinBoolTy;
15735   if (!Context.getBOOLDecl()) {
15736     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15737                         Sema::LookupOrdinaryName);
15738     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15739       NamedDecl *ND = Result.getFoundDecl();
15740       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 
15741         Context.setBOOLDecl(TD);
15742     }
15743   }
15744   if (Context.getBOOLDecl())
15745     BoolT = Context.getBOOLType();
15746   return new (Context)
15747       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15748 }
15749
15750 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15751     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15752     SourceLocation RParen) {
15753
15754   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15755
15756   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15757                            [&](const AvailabilitySpec &Spec) {
15758                              return Spec.getPlatform() == Platform;
15759                            });
15760
15761   VersionTuple Version;
15762   if (Spec != AvailSpecs.end())
15763     Version = Spec->getVersion();
15764
15765   // The use of `@available` in the enclosing function should be analyzed to
15766   // warn when it's used inappropriately (i.e. not if(@available)).
15767   if (getCurFunctionOrMethodDecl())
15768     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
15769   else if (getCurBlock() || getCurLambda())
15770     getCurFunction()->HasPotentialAvailabilityViolations = true;
15771
15772   return new (Context)
15773       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15774 }