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 /// \brief Emit a note explaining that this function is deleted.
91 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
92   assert(Decl->isDeleted());
93 
94   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
95 
96   if (Method && Method->isDeleted() && Method->isDefaulted()) {
97     // If the method was explicitly defaulted, point at that declaration.
98     if (!Method->isImplicit())
99       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
100 
101     // Try to diagnose why this special member function was implicitly
102     // deleted. This might fail, if that reason no longer applies.
103     CXXSpecialMember CSM = getSpecialMember(Method);
104     if (CSM != CXXInvalid)
105       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
106 
107     return;
108   }
109 
110   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
111   if (Ctor && Ctor->isInheritingConstructor())
112     return NoteDeletedInheritingConstructor(Ctor);
113 
114   Diag(Decl->getLocation(), diag::note_availability_specified_here)
115     << Decl << true;
116 }
117 
118 /// \brief Determine whether a FunctionDecl was ever declared with an
119 /// explicit storage class.
120 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
121   for (auto I : D->redecls()) {
122     if (I->getStorageClass() != SC_None)
123       return true;
124   }
125   return false;
126 }
127 
128 /// \brief Check whether we're in an extern inline function and referring to a
129 /// variable or function with internal linkage (C11 6.7.4p3).
130 ///
131 /// This is only a warning because we used to silently accept this code, but
132 /// in many cases it will not behave correctly. This is not enabled in C++ mode
133 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
134 /// and so while there may still be user mistakes, most of the time we can't
135 /// prove that there are errors.
136 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
137                                                       const NamedDecl *D,
138                                                       SourceLocation Loc) {
139   // This is disabled under C++; there are too many ways for this to fire in
140   // contexts where the warning is a false positive, or where it is technically
141   // correct but benign.
142   if (S.getLangOpts().CPlusPlus)
143     return;
144 
145   // Check if this is an inlined function or method.
146   FunctionDecl *Current = S.getCurFunctionDecl();
147   if (!Current)
148     return;
149   if (!Current->isInlined())
150     return;
151   if (!Current->isExternallyVisible())
152     return;
153 
154   // Check if the decl has internal linkage.
155   if (D->getFormalLinkage() != InternalLinkage)
156     return;
157 
158   // Downgrade from ExtWarn to Extension if
159   //  (1) the supposedly external inline function is in the main file,
160   //      and probably won't be included anywhere else.
161   //  (2) the thing we're referencing is a pure function.
162   //  (3) the thing we're referencing is another inline function.
163   // This last can give us false negatives, but it's better than warning on
164   // wrappers for simple C library functions.
165   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
166   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
167   if (!DowngradeWarning && UsedFn)
168     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
169 
170   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
171                                : diag::ext_internal_in_extern_inline)
172     << /*IsVar=*/!UsedFn << D;
173 
174   S.MaybeSuggestAddingStaticToDecl(Current);
175 
176   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
177       << D;
178 }
179 
180 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
181   const FunctionDecl *First = Cur->getFirstDecl();
182 
183   // Suggest "static" on the function, if possible.
184   if (!hasAnyExplicitStorageClass(First)) {
185     SourceLocation DeclBegin = First->getSourceRange().getBegin();
186     Diag(DeclBegin, diag::note_convert_inline_to_static)
187       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
188   }
189 }
190 
191 /// \brief Determine whether the use of this declaration is valid, and
192 /// emit any corresponding diagnostics.
193 ///
194 /// This routine diagnoses various problems with referencing
195 /// declarations that can occur when using a declaration. For example,
196 /// it might warn if a deprecated or unavailable declaration is being
197 /// used, or produce an error (and return true) if a C++0x deleted
198 /// function is being used.
199 ///
200 /// \returns true if there was an error (this declaration cannot be
201 /// referenced), false otherwise.
202 ///
203 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
204                              const ObjCInterfaceDecl *UnknownObjCClass,
205                              bool ObjCPropertyAccess,
206                              bool AvoidPartialAvailabilityChecks) {
207   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
208     // If there were any diagnostics suppressed by template argument deduction,
209     // emit them now.
210     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
211     if (Pos != SuppressedDiagnostics.end()) {
212       for (const PartialDiagnosticAt &Suppressed : Pos->second)
213         Diag(Suppressed.first, Suppressed.second);
214 
215       // Clear out the list of suppressed diagnostics, so that we don't emit
216       // them again for this specialization. However, we don't obsolete this
217       // entry from the table, because we want to avoid ever emitting these
218       // diagnostics again.
219       Pos->second.clear();
220     }
221 
222     // C++ [basic.start.main]p3:
223     //   The function 'main' shall not be used within a program.
224     if (cast<FunctionDecl>(D)->isMain())
225       Diag(Loc, diag::ext_main_used);
226   }
227 
228   // See if this is an auto-typed variable whose initializer we are parsing.
229   if (ParsingInitForAutoVars.count(D)) {
230     if (isa<BindingDecl>(D)) {
231       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
232         << D->getDeclName();
233     } else {
234       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
235         << D->getDeclName() << cast<VarDecl>(D)->getType();
236     }
237     return true;
238   }
239 
240   // See if this is a deleted function.
241   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
242     if (FD->isDeleted()) {
243       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
244       if (Ctor && Ctor->isInheritingConstructor())
245         Diag(Loc, diag::err_deleted_inherited_ctor_use)
246             << Ctor->getParent()
247             << Ctor->getInheritedConstructor().getConstructor()->getParent();
248       else
249         Diag(Loc, diag::err_deleted_function_use);
250       NoteDeletedFunction(FD);
251       return true;
252     }
253 
254     // If the function has a deduced return type, and we can't deduce it,
255     // then we can't use it either.
256     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
257         DeduceReturnType(FD, Loc))
258       return true;
259 
260     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
261       return true;
262   }
263 
264   auto getReferencedObjCProp = [](const NamedDecl *D) ->
265                                       const ObjCPropertyDecl * {
266     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
267       return MD->findPropertyDecl();
268     return nullptr;
269   };
270   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
271     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
272       return true;
273   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
274       return true;
275   }
276 
277   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
278   // Only the variables omp_in and omp_out are allowed in the combiner.
279   // Only the variables omp_priv and omp_orig are allowed in the
280   // initializer-clause.
281   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
282   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
283       isa<VarDecl>(D)) {
284     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
285         << getCurFunction()->HasOMPDeclareReductionCombiner;
286     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
287     return true;
288   }
289 
290   DiagnoseAvailabilityOfDecl(D, Loc, UnknownObjCClass, ObjCPropertyAccess,
291                              AvoidPartialAvailabilityChecks);
292 
293   DiagnoseUnusedOfDecl(*this, D, Loc);
294 
295   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
296 
297   return false;
298 }
299 
300 /// \brief Retrieve the message suffix that should be added to a
301 /// diagnostic complaining about the given function being deleted or
302 /// unavailable.
303 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
304   std::string Message;
305   if (FD->getAvailability(&Message))
306     return ": " + Message;
307 
308   return std::string();
309 }
310 
311 /// DiagnoseSentinelCalls - This routine checks whether a call or
312 /// message-send is to a declaration with the sentinel attribute, and
313 /// if so, it checks that the requirements of the sentinel are
314 /// satisfied.
315 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
316                                  ArrayRef<Expr *> Args) {
317   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
318   if (!attr)
319     return;
320 
321   // The number of formal parameters of the declaration.
322   unsigned numFormalParams;
323 
324   // The kind of declaration.  This is also an index into a %select in
325   // the diagnostic.
326   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
327 
328   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
329     numFormalParams = MD->param_size();
330     calleeType = CT_Method;
331   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
332     numFormalParams = FD->param_size();
333     calleeType = CT_Function;
334   } else if (isa<VarDecl>(D)) {
335     QualType type = cast<ValueDecl>(D)->getType();
336     const FunctionType *fn = nullptr;
337     if (const PointerType *ptr = type->getAs<PointerType>()) {
338       fn = ptr->getPointeeType()->getAs<FunctionType>();
339       if (!fn) return;
340       calleeType = CT_Function;
341     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
342       fn = ptr->getPointeeType()->castAs<FunctionType>();
343       calleeType = CT_Block;
344     } else {
345       return;
346     }
347 
348     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
349       numFormalParams = proto->getNumParams();
350     } else {
351       numFormalParams = 0;
352     }
353   } else {
354     return;
355   }
356 
357   // "nullPos" is the number of formal parameters at the end which
358   // effectively count as part of the variadic arguments.  This is
359   // useful if you would prefer to not have *any* formal parameters,
360   // but the language forces you to have at least one.
361   unsigned nullPos = attr->getNullPos();
362   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
363   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
364 
365   // The number of arguments which should follow the sentinel.
366   unsigned numArgsAfterSentinel = attr->getSentinel();
367 
368   // If there aren't enough arguments for all the formal parameters,
369   // the sentinel, and the args after the sentinel, complain.
370   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
371     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
372     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
373     return;
374   }
375 
376   // Otherwise, find the sentinel expression.
377   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
378   if (!sentinelExpr) return;
379   if (sentinelExpr->isValueDependent()) return;
380   if (Context.isSentinelNullExpr(sentinelExpr)) return;
381 
382   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
383   // or 'NULL' if those are actually defined in the context.  Only use
384   // 'nil' for ObjC methods, where it's much more likely that the
385   // variadic arguments form a list of object pointers.
386   SourceLocation MissingNilLoc
387     = getLocForEndOfToken(sentinelExpr->getLocEnd());
388   std::string NullValue;
389   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
390     NullValue = "nil";
391   else if (getLangOpts().CPlusPlus11)
392     NullValue = "nullptr";
393   else if (PP.isMacroDefined("NULL"))
394     NullValue = "NULL";
395   else
396     NullValue = "(void*) 0";
397 
398   if (MissingNilLoc.isInvalid())
399     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
400   else
401     Diag(MissingNilLoc, diag::warn_missing_sentinel)
402       << int(calleeType)
403       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
404   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
405 }
406 
407 SourceRange Sema::getExprRange(Expr *E) const {
408   return E ? E->getSourceRange() : SourceRange();
409 }
410 
411 //===----------------------------------------------------------------------===//
412 //  Standard Promotions and Conversions
413 //===----------------------------------------------------------------------===//
414 
415 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
416 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
417   // Handle any placeholder expressions which made it here.
418   if (E->getType()->isPlaceholderType()) {
419     ExprResult result = CheckPlaceholderExpr(E);
420     if (result.isInvalid()) return ExprError();
421     E = result.get();
422   }
423 
424   QualType Ty = E->getType();
425   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
426 
427   if (Ty->isFunctionType()) {
428     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
429       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
430         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
431           return ExprError();
432 
433     E = ImpCastExprToType(E, Context.getPointerType(Ty),
434                           CK_FunctionToPointerDecay).get();
435   } else if (Ty->isArrayType()) {
436     // In C90 mode, arrays only promote to pointers if the array expression is
437     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
438     // type 'array of type' is converted to an expression that has type 'pointer
439     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
440     // that has type 'array of type' ...".  The relevant change is "an lvalue"
441     // (C90) to "an expression" (C99).
442     //
443     // C++ 4.2p1:
444     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
445     // T" can be converted to an rvalue of type "pointer to T".
446     //
447     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
448       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
449                             CK_ArrayToPointerDecay).get();
450   }
451   return E;
452 }
453 
454 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
455   // Check to see if we are dereferencing a null pointer.  If so,
456   // and if not volatile-qualified, this is undefined behavior that the
457   // optimizer will delete, so warn about it.  People sometimes try to use this
458   // to get a deterministic trap and are surprised by clang's behavior.  This
459   // only handles the pattern "*null", which is a very syntactic check.
460   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
461     if (UO->getOpcode() == UO_Deref &&
462         UO->getSubExpr()->IgnoreParenCasts()->
463           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
464         !UO->getType().isVolatileQualified()) {
465     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
466                           S.PDiag(diag::warn_indirection_through_null)
467                             << UO->getSubExpr()->getSourceRange());
468     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
469                         S.PDiag(diag::note_indirection_through_null));
470   }
471 }
472 
473 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
474                                     SourceLocation AssignLoc,
475                                     const Expr* RHS) {
476   const ObjCIvarDecl *IV = OIRE->getDecl();
477   if (!IV)
478     return;
479 
480   DeclarationName MemberName = IV->getDeclName();
481   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
482   if (!Member || !Member->isStr("isa"))
483     return;
484 
485   const Expr *Base = OIRE->getBase();
486   QualType BaseType = Base->getType();
487   if (OIRE->isArrow())
488     BaseType = BaseType->getPointeeType();
489   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
490     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
491       ObjCInterfaceDecl *ClassDeclared = nullptr;
492       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
493       if (!ClassDeclared->getSuperClass()
494           && (*ClassDeclared->ivar_begin()) == IV) {
495         if (RHS) {
496           NamedDecl *ObjectSetClass =
497             S.LookupSingleName(S.TUScope,
498                                &S.Context.Idents.get("object_setClass"),
499                                SourceLocation(), S.LookupOrdinaryName);
500           if (ObjectSetClass) {
501             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
502             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
503             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
504             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
505                                                      AssignLoc), ",") <<
506             FixItHint::CreateInsertion(RHSLocEnd, ")");
507           }
508           else
509             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
510         } else {
511           NamedDecl *ObjectGetClass =
512             S.LookupSingleName(S.TUScope,
513                                &S.Context.Idents.get("object_getClass"),
514                                SourceLocation(), S.LookupOrdinaryName);
515           if (ObjectGetClass)
516             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
517             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
518             FixItHint::CreateReplacement(
519                                          SourceRange(OIRE->getOpLoc(),
520                                                      OIRE->getLocEnd()), ")");
521           else
522             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
523         }
524         S.Diag(IV->getLocation(), diag::note_ivar_decl);
525       }
526     }
527 }
528 
529 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
530   // Handle any placeholder expressions which made it here.
531   if (E->getType()->isPlaceholderType()) {
532     ExprResult result = CheckPlaceholderExpr(E);
533     if (result.isInvalid()) return ExprError();
534     E = result.get();
535   }
536 
537   // C++ [conv.lval]p1:
538   //   A glvalue of a non-function, non-array type T can be
539   //   converted to a prvalue.
540   if (!E->isGLValue()) return E;
541 
542   QualType T = E->getType();
543   assert(!T.isNull() && "r-value conversion on typeless expression?");
544 
545   // We don't want to throw lvalue-to-rvalue casts on top of
546   // expressions of certain types in C++.
547   if (getLangOpts().CPlusPlus &&
548       (E->getType() == Context.OverloadTy ||
549        T->isDependentType() ||
550        T->isRecordType()))
551     return E;
552 
553   // The C standard is actually really unclear on this point, and
554   // DR106 tells us what the result should be but not why.  It's
555   // generally best to say that void types just doesn't undergo
556   // lvalue-to-rvalue at all.  Note that expressions of unqualified
557   // 'void' type are never l-values, but qualified void can be.
558   if (T->isVoidType())
559     return E;
560 
561   // OpenCL usually rejects direct accesses to values of 'half' type.
562   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
563       T->isHalfType()) {
564     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
565       << 0 << T;
566     return ExprError();
567   }
568 
569   CheckForNullPointerDereference(*this, E);
570   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
571     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
572                                      &Context.Idents.get("object_getClass"),
573                                      SourceLocation(), LookupOrdinaryName);
574     if (ObjectGetClass)
575       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
576         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
577         FixItHint::CreateReplacement(
578                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
579     else
580       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
581   }
582   else if (const ObjCIvarRefExpr *OIRE =
583             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
584     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
585 
586   // C++ [conv.lval]p1:
587   //   [...] If T is a non-class type, the type of the prvalue is the
588   //   cv-unqualified version of T. Otherwise, the type of the
589   //   rvalue is T.
590   //
591   // C99 6.3.2.1p2:
592   //   If the lvalue has qualified type, the value has the unqualified
593   //   version of the type of the lvalue; otherwise, the value has the
594   //   type of the lvalue.
595   if (T.hasQualifiers())
596     T = T.getUnqualifiedType();
597 
598   // Under the MS ABI, lock down the inheritance model now.
599   if (T->isMemberPointerType() &&
600       Context.getTargetInfo().getCXXABI().isMicrosoft())
601     (void)isCompleteType(E->getExprLoc(), T);
602 
603   UpdateMarkingForLValueToRValue(E);
604 
605   // Loading a __weak object implicitly retains the value, so we need a cleanup to
606   // balance that.
607   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
608     Cleanup.setExprNeedsCleanups(true);
609 
610   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
611                                             nullptr, VK_RValue);
612 
613   // C11 6.3.2.1p2:
614   //   ... if the lvalue has atomic type, the value has the non-atomic version
615   //   of the type of the lvalue ...
616   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
617     T = Atomic->getValueType().getUnqualifiedType();
618     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
619                                    nullptr, VK_RValue);
620   }
621 
622   return Res;
623 }
624 
625 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
626   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
627   if (Res.isInvalid())
628     return ExprError();
629   Res = DefaultLvalueConversion(Res.get());
630   if (Res.isInvalid())
631     return ExprError();
632   return Res;
633 }
634 
635 /// CallExprUnaryConversions - a special case of an unary conversion
636 /// performed on a function designator of a call expression.
637 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
638   QualType Ty = E->getType();
639   ExprResult Res = E;
640   // Only do implicit cast for a function type, but not for a pointer
641   // to function type.
642   if (Ty->isFunctionType()) {
643     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
644                             CK_FunctionToPointerDecay).get();
645     if (Res.isInvalid())
646       return ExprError();
647   }
648   Res = DefaultLvalueConversion(Res.get());
649   if (Res.isInvalid())
650     return ExprError();
651   return Res.get();
652 }
653 
654 /// UsualUnaryConversions - Performs various conversions that are common to most
655 /// operators (C99 6.3). The conversions of array and function types are
656 /// sometimes suppressed. For example, the array->pointer conversion doesn't
657 /// apply if the array is an argument to the sizeof or address (&) operators.
658 /// In these instances, this routine should *not* be called.
659 ExprResult Sema::UsualUnaryConversions(Expr *E) {
660   // First, convert to an r-value.
661   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
662   if (Res.isInvalid())
663     return ExprError();
664   E = Res.get();
665 
666   QualType Ty = E->getType();
667   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
668 
669   // Half FP have to be promoted to float unless it is natively supported
670   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
671     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
672 
673   // Try to perform integral promotions if the object has a theoretically
674   // promotable type.
675   if (Ty->isIntegralOrUnscopedEnumerationType()) {
676     // C99 6.3.1.1p2:
677     //
678     //   The following may be used in an expression wherever an int or
679     //   unsigned int may be used:
680     //     - an object or expression with an integer type whose integer
681     //       conversion rank is less than or equal to the rank of int
682     //       and unsigned int.
683     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
684     //
685     //   If an int can represent all values of the original type, the
686     //   value is converted to an int; otherwise, it is converted to an
687     //   unsigned int. These are called the integer promotions. All
688     //   other types are unchanged by the integer promotions.
689 
690     QualType PTy = Context.isPromotableBitField(E);
691     if (!PTy.isNull()) {
692       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
693       return E;
694     }
695     if (Ty->isPromotableIntegerType()) {
696       QualType PT = Context.getPromotedIntegerType(Ty);
697       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
698       return E;
699     }
700   }
701   return E;
702 }
703 
704 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
705 /// do not have a prototype. Arguments that have type float or __fp16
706 /// are promoted to double. All other argument types are converted by
707 /// UsualUnaryConversions().
708 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
709   QualType Ty = E->getType();
710   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
711 
712   ExprResult Res = UsualUnaryConversions(E);
713   if (Res.isInvalid())
714     return ExprError();
715   E = Res.get();
716 
717   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
718   // promote to double.
719   // Note that default argument promotion applies only to float (and
720   // half/fp16); it does not apply to _Float16.
721   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
722   if (BTy && (BTy->getKind() == BuiltinType::Half ||
723               BTy->getKind() == BuiltinType::Float)) {
724     if (getLangOpts().OpenCL &&
725         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
726         if (BTy->getKind() == BuiltinType::Half) {
727             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
728         }
729     } else {
730       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
731     }
732   }
733 
734   // C++ performs lvalue-to-rvalue conversion as a default argument
735   // promotion, even on class types, but note:
736   //   C++11 [conv.lval]p2:
737   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
738   //     operand or a subexpression thereof the value contained in the
739   //     referenced object is not accessed. Otherwise, if the glvalue
740   //     has a class type, the conversion copy-initializes a temporary
741   //     of type T from the glvalue and the result of the conversion
742   //     is a prvalue for the temporary.
743   // FIXME: add some way to gate this entire thing for correctness in
744   // potentially potentially evaluated contexts.
745   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
746     ExprResult Temp = PerformCopyInitialization(
747                        InitializedEntity::InitializeTemporary(E->getType()),
748                                                 E->getExprLoc(), E);
749     if (Temp.isInvalid())
750       return ExprError();
751     E = Temp.get();
752   }
753 
754   return E;
755 }
756 
757 /// Determine the degree of POD-ness for an expression.
758 /// Incomplete types are considered POD, since this check can be performed
759 /// when we're in an unevaluated context.
760 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
761   if (Ty->isIncompleteType()) {
762     // C++11 [expr.call]p7:
763     //   After these conversions, if the argument does not have arithmetic,
764     //   enumeration, pointer, pointer to member, or class type, the program
765     //   is ill-formed.
766     //
767     // Since we've already performed array-to-pointer and function-to-pointer
768     // decay, the only such type in C++ is cv void. This also handles
769     // initializer lists as variadic arguments.
770     if (Ty->isVoidType())
771       return VAK_Invalid;
772 
773     if (Ty->isObjCObjectType())
774       return VAK_Invalid;
775     return VAK_Valid;
776   }
777 
778   if (Ty.isCXX98PODType(Context))
779     return VAK_Valid;
780 
781   // C++11 [expr.call]p7:
782   //   Passing a potentially-evaluated argument of class type (Clause 9)
783   //   having a non-trivial copy constructor, a non-trivial move constructor,
784   //   or a non-trivial destructor, with no corresponding parameter,
785   //   is conditionally-supported with implementation-defined semantics.
786   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
787     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
788       if (!Record->hasNonTrivialCopyConstructor() &&
789           !Record->hasNonTrivialMoveConstructor() &&
790           !Record->hasNonTrivialDestructor())
791         return VAK_ValidInCXX11;
792 
793   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
794     return VAK_Valid;
795 
796   if (Ty->isObjCObjectType())
797     return VAK_Invalid;
798 
799   if (getLangOpts().MSVCCompat)
800     return VAK_MSVCUndefined;
801 
802   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
803   // permitted to reject them. We should consider doing so.
804   return VAK_Undefined;
805 }
806 
807 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
808   // Don't allow one to pass an Objective-C interface to a vararg.
809   const QualType &Ty = E->getType();
810   VarArgKind VAK = isValidVarArgType(Ty);
811 
812   // Complain about passing non-POD types through varargs.
813   switch (VAK) {
814   case VAK_ValidInCXX11:
815     DiagRuntimeBehavior(
816         E->getLocStart(), nullptr,
817         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
818           << Ty << CT);
819     // Fall through.
820   case VAK_Valid:
821     if (Ty->isRecordType()) {
822       // This is unlikely to be what the user intended. If the class has a
823       // 'c_str' member function, the user probably meant to call that.
824       DiagRuntimeBehavior(E->getLocStart(), nullptr,
825                           PDiag(diag::warn_pass_class_arg_to_vararg)
826                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
827     }
828     break;
829 
830   case VAK_Undefined:
831   case VAK_MSVCUndefined:
832     DiagRuntimeBehavior(
833         E->getLocStart(), nullptr,
834         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
835           << getLangOpts().CPlusPlus11 << Ty << CT);
836     break;
837 
838   case VAK_Invalid:
839     if (Ty->isObjCObjectType())
840       DiagRuntimeBehavior(
841           E->getLocStart(), nullptr,
842           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
843             << Ty << CT);
844     else
845       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
846         << isa<InitListExpr>(E) << Ty << CT;
847     break;
848   }
849 }
850 
851 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
852 /// will create a trap if the resulting type is not a POD type.
853 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
854                                                   FunctionDecl *FDecl) {
855   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
856     // Strip the unbridged-cast placeholder expression off, if applicable.
857     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
858         (CT == VariadicMethod ||
859          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
860       E = stripARCUnbridgedCast(E);
861 
862     // Otherwise, do normal placeholder checking.
863     } else {
864       ExprResult ExprRes = CheckPlaceholderExpr(E);
865       if (ExprRes.isInvalid())
866         return ExprError();
867       E = ExprRes.get();
868     }
869   }
870 
871   ExprResult ExprRes = DefaultArgumentPromotion(E);
872   if (ExprRes.isInvalid())
873     return ExprError();
874   E = ExprRes.get();
875 
876   // Diagnostics regarding non-POD argument types are
877   // emitted along with format string checking in Sema::CheckFunctionCall().
878   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
879     // Turn this into a trap.
880     CXXScopeSpec SS;
881     SourceLocation TemplateKWLoc;
882     UnqualifiedId Name;
883     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
884                        E->getLocStart());
885     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
886                                           Name, true, false);
887     if (TrapFn.isInvalid())
888       return ExprError();
889 
890     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
891                                     E->getLocStart(), None,
892                                     E->getLocEnd());
893     if (Call.isInvalid())
894       return ExprError();
895 
896     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
897                                   Call.get(), E);
898     if (Comma.isInvalid())
899       return ExprError();
900     return Comma.get();
901   }
902 
903   if (!getLangOpts().CPlusPlus &&
904       RequireCompleteType(E->getExprLoc(), E->getType(),
905                           diag::err_call_incomplete_argument))
906     return ExprError();
907 
908   return E;
909 }
910 
911 /// \brief Converts an integer to complex float type.  Helper function of
912 /// UsualArithmeticConversions()
913 ///
914 /// \return false if the integer expression is an integer type and is
915 /// successfully converted to the complex type.
916 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
917                                                   ExprResult &ComplexExpr,
918                                                   QualType IntTy,
919                                                   QualType ComplexTy,
920                                                   bool SkipCast) {
921   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
922   if (SkipCast) return false;
923   if (IntTy->isIntegerType()) {
924     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
925     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
926     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
927                                   CK_FloatingRealToComplex);
928   } else {
929     assert(IntTy->isComplexIntegerType());
930     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
931                                   CK_IntegralComplexToFloatingComplex);
932   }
933   return false;
934 }
935 
936 /// \brief Handle arithmetic conversion with complex types.  Helper function of
937 /// UsualArithmeticConversions()
938 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
939                                              ExprResult &RHS, QualType LHSType,
940                                              QualType RHSType,
941                                              bool IsCompAssign) {
942   // if we have an integer operand, the result is the complex type.
943   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
944                                              /*skipCast*/false))
945     return LHSType;
946   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
947                                              /*skipCast*/IsCompAssign))
948     return RHSType;
949 
950   // This handles complex/complex, complex/float, or float/complex.
951   // When both operands are complex, the shorter operand is converted to the
952   // type of the longer, and that is the type of the result. This corresponds
953   // to what is done when combining two real floating-point operands.
954   // The fun begins when size promotion occur across type domains.
955   // From H&S 6.3.4: When one operand is complex and the other is a real
956   // floating-point type, the less precise type is converted, within it's
957   // real or complex domain, to the precision of the other type. For example,
958   // when combining a "long double" with a "double _Complex", the
959   // "double _Complex" is promoted to "long double _Complex".
960 
961   // Compute the rank of the two types, regardless of whether they are complex.
962   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
963 
964   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
965   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
966   QualType LHSElementType =
967       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
968   QualType RHSElementType =
969       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
970 
971   QualType ResultType = S.Context.getComplexType(LHSElementType);
972   if (Order < 0) {
973     // Promote the precision of the LHS if not an assignment.
974     ResultType = S.Context.getComplexType(RHSElementType);
975     if (!IsCompAssign) {
976       if (LHSComplexType)
977         LHS =
978             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
979       else
980         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
981     }
982   } else if (Order > 0) {
983     // Promote the precision of the RHS.
984     if (RHSComplexType)
985       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
986     else
987       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
988   }
989   return ResultType;
990 }
991 
992 /// \brief Handle arithmetic conversion from integer to float.  Helper function
993 /// of UsualArithmeticConversions()
994 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
995                                            ExprResult &IntExpr,
996                                            QualType FloatTy, QualType IntTy,
997                                            bool ConvertFloat, bool ConvertInt) {
998   if (IntTy->isIntegerType()) {
999     if (ConvertInt)
1000       // Convert intExpr to the lhs floating point type.
1001       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1002                                     CK_IntegralToFloating);
1003     return FloatTy;
1004   }
1005 
1006   // Convert both sides to the appropriate complex float.
1007   assert(IntTy->isComplexIntegerType());
1008   QualType result = S.Context.getComplexType(FloatTy);
1009 
1010   // _Complex int -> _Complex float
1011   if (ConvertInt)
1012     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1013                                   CK_IntegralComplexToFloatingComplex);
1014 
1015   // float -> _Complex float
1016   if (ConvertFloat)
1017     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1018                                     CK_FloatingRealToComplex);
1019 
1020   return result;
1021 }
1022 
1023 /// \brief Handle arithmethic conversion with floating point types.  Helper
1024 /// function of UsualArithmeticConversions()
1025 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1026                                       ExprResult &RHS, QualType LHSType,
1027                                       QualType RHSType, bool IsCompAssign) {
1028   bool LHSFloat = LHSType->isRealFloatingType();
1029   bool RHSFloat = RHSType->isRealFloatingType();
1030 
1031   // If we have two real floating types, convert the smaller operand
1032   // to the bigger result.
1033   if (LHSFloat && RHSFloat) {
1034     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1035     if (order > 0) {
1036       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1037       return LHSType;
1038     }
1039 
1040     assert(order < 0 && "illegal float comparison");
1041     if (!IsCompAssign)
1042       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1043     return RHSType;
1044   }
1045 
1046   if (LHSFloat) {
1047     // Half FP has to be promoted to float unless it is natively supported
1048     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1049       LHSType = S.Context.FloatTy;
1050 
1051     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1052                                       /*convertFloat=*/!IsCompAssign,
1053                                       /*convertInt=*/ true);
1054   }
1055   assert(RHSFloat);
1056   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1057                                     /*convertInt=*/ true,
1058                                     /*convertFloat=*/!IsCompAssign);
1059 }
1060 
1061 /// \brief Diagnose attempts to convert between __float128 and long double if
1062 /// there is no support for such conversion. Helper function of
1063 /// UsualArithmeticConversions().
1064 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1065                                       QualType RHSType) {
1066   /*  No issue converting if at least one of the types is not a floating point
1067       type or the two types have the same rank.
1068   */
1069   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1070       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1071     return false;
1072 
1073   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1074          "The remaining types must be floating point types.");
1075 
1076   auto *LHSComplex = LHSType->getAs<ComplexType>();
1077   auto *RHSComplex = RHSType->getAs<ComplexType>();
1078 
1079   QualType LHSElemType = LHSComplex ?
1080     LHSComplex->getElementType() : LHSType;
1081   QualType RHSElemType = RHSComplex ?
1082     RHSComplex->getElementType() : RHSType;
1083 
1084   // No issue if the two types have the same representation
1085   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1086       &S.Context.getFloatTypeSemantics(RHSElemType))
1087     return false;
1088 
1089   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1090                                 RHSElemType == S.Context.LongDoubleTy);
1091   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1092                             RHSElemType == S.Context.Float128Ty);
1093 
1094   /* We've handled the situation where __float128 and long double have the same
1095      representation. The only other allowable conversion is if long double is
1096      really just double.
1097   */
1098   return Float128AndLongDouble &&
1099     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1100      &llvm::APFloat::IEEEdouble());
1101 }
1102 
1103 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1104 
1105 namespace {
1106 /// These helper callbacks are placed in an anonymous namespace to
1107 /// permit their use as function template parameters.
1108 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1109   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1110 }
1111 
1112 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1113   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1114                              CK_IntegralComplexCast);
1115 }
1116 }
1117 
1118 /// \brief Handle integer arithmetic conversions.  Helper function of
1119 /// UsualArithmeticConversions()
1120 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1121 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1122                                         ExprResult &RHS, QualType LHSType,
1123                                         QualType RHSType, bool IsCompAssign) {
1124   // The rules for this case are in C99 6.3.1.8
1125   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1126   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1127   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1128   if (LHSSigned == RHSSigned) {
1129     // Same signedness; use the higher-ranked type
1130     if (order >= 0) {
1131       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1132       return LHSType;
1133     } else if (!IsCompAssign)
1134       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1135     return RHSType;
1136   } else if (order != (LHSSigned ? 1 : -1)) {
1137     // The unsigned type has greater than or equal rank to the
1138     // signed type, so use the unsigned type
1139     if (RHSSigned) {
1140       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1141       return LHSType;
1142     } else if (!IsCompAssign)
1143       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1144     return RHSType;
1145   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1146     // The two types are different widths; if we are here, that
1147     // means the signed type is larger than the unsigned type, so
1148     // use the signed type.
1149     if (LHSSigned) {
1150       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1151       return LHSType;
1152     } else if (!IsCompAssign)
1153       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1154     return RHSType;
1155   } else {
1156     // The signed type is higher-ranked than the unsigned type,
1157     // but isn't actually any bigger (like unsigned int and long
1158     // on most 32-bit systems).  Use the unsigned type corresponding
1159     // to the signed type.
1160     QualType result =
1161       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1162     RHS = (*doRHSCast)(S, RHS.get(), result);
1163     if (!IsCompAssign)
1164       LHS = (*doLHSCast)(S, LHS.get(), result);
1165     return result;
1166   }
1167 }
1168 
1169 /// \brief Handle conversions with GCC complex int extension.  Helper function
1170 /// of UsualArithmeticConversions()
1171 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1172                                            ExprResult &RHS, QualType LHSType,
1173                                            QualType RHSType,
1174                                            bool IsCompAssign) {
1175   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1176   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1177 
1178   if (LHSComplexInt && RHSComplexInt) {
1179     QualType LHSEltType = LHSComplexInt->getElementType();
1180     QualType RHSEltType = RHSComplexInt->getElementType();
1181     QualType ScalarType =
1182       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1183         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1184 
1185     return S.Context.getComplexType(ScalarType);
1186   }
1187 
1188   if (LHSComplexInt) {
1189     QualType LHSEltType = LHSComplexInt->getElementType();
1190     QualType ScalarType =
1191       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1192         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1193     QualType ComplexType = S.Context.getComplexType(ScalarType);
1194     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1195                               CK_IntegralRealToComplex);
1196 
1197     return ComplexType;
1198   }
1199 
1200   assert(RHSComplexInt);
1201 
1202   QualType RHSEltType = RHSComplexInt->getElementType();
1203   QualType ScalarType =
1204     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1205       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1206   QualType ComplexType = S.Context.getComplexType(ScalarType);
1207 
1208   if (!IsCompAssign)
1209     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1210                               CK_IntegralRealToComplex);
1211   return ComplexType;
1212 }
1213 
1214 /// UsualArithmeticConversions - Performs various conversions that are common to
1215 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1216 /// routine returns the first non-arithmetic type found. The client is
1217 /// responsible for emitting appropriate error diagnostics.
1218 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1219                                           bool IsCompAssign) {
1220   if (!IsCompAssign) {
1221     LHS = UsualUnaryConversions(LHS.get());
1222     if (LHS.isInvalid())
1223       return QualType();
1224   }
1225 
1226   RHS = UsualUnaryConversions(RHS.get());
1227   if (RHS.isInvalid())
1228     return QualType();
1229 
1230   // For conversion purposes, we ignore any qualifiers.
1231   // For example, "const float" and "float" are equivalent.
1232   QualType LHSType =
1233     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1234   QualType RHSType =
1235     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1236 
1237   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1238   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1239     LHSType = AtomicLHS->getValueType();
1240 
1241   // If both types are identical, no conversion is needed.
1242   if (LHSType == RHSType)
1243     return LHSType;
1244 
1245   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1246   // The caller can deal with this (e.g. pointer + int).
1247   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1248     return QualType();
1249 
1250   // Apply unary and bitfield promotions to the LHS's type.
1251   QualType LHSUnpromotedType = LHSType;
1252   if (LHSType->isPromotableIntegerType())
1253     LHSType = Context.getPromotedIntegerType(LHSType);
1254   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1255   if (!LHSBitfieldPromoteTy.isNull())
1256     LHSType = LHSBitfieldPromoteTy;
1257   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1258     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1259 
1260   // If both types are identical, no conversion is needed.
1261   if (LHSType == RHSType)
1262     return LHSType;
1263 
1264   // At this point, we have two different arithmetic types.
1265 
1266   // Diagnose attempts to convert between __float128 and long double where
1267   // such conversions currently can't be handled.
1268   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1269     return QualType();
1270 
1271   // Handle complex types first (C99 6.3.1.8p1).
1272   if (LHSType->isComplexType() || RHSType->isComplexType())
1273     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1274                                         IsCompAssign);
1275 
1276   // Now handle "real" floating types (i.e. float, double, long double).
1277   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1278     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1279                                  IsCompAssign);
1280 
1281   // Handle GCC complex int extension.
1282   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1283     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1284                                       IsCompAssign);
1285 
1286   // Finally, we have two differing integer types.
1287   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1288            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1289 }
1290 
1291 
1292 //===----------------------------------------------------------------------===//
1293 //  Semantic Analysis for various Expression Types
1294 //===----------------------------------------------------------------------===//
1295 
1296 
1297 ExprResult
1298 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1299                                 SourceLocation DefaultLoc,
1300                                 SourceLocation RParenLoc,
1301                                 Expr *ControllingExpr,
1302                                 ArrayRef<ParsedType> ArgTypes,
1303                                 ArrayRef<Expr *> ArgExprs) {
1304   unsigned NumAssocs = ArgTypes.size();
1305   assert(NumAssocs == ArgExprs.size());
1306 
1307   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1308   for (unsigned i = 0; i < NumAssocs; ++i) {
1309     if (ArgTypes[i])
1310       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1311     else
1312       Types[i] = nullptr;
1313   }
1314 
1315   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1316                                              ControllingExpr,
1317                                              llvm::makeArrayRef(Types, NumAssocs),
1318                                              ArgExprs);
1319   delete [] Types;
1320   return ER;
1321 }
1322 
1323 ExprResult
1324 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1325                                  SourceLocation DefaultLoc,
1326                                  SourceLocation RParenLoc,
1327                                  Expr *ControllingExpr,
1328                                  ArrayRef<TypeSourceInfo *> Types,
1329                                  ArrayRef<Expr *> Exprs) {
1330   unsigned NumAssocs = Types.size();
1331   assert(NumAssocs == Exprs.size());
1332 
1333   // Decay and strip qualifiers for the controlling expression type, and handle
1334   // placeholder type replacement. See committee discussion from WG14 DR423.
1335   {
1336     EnterExpressionEvaluationContext Unevaluated(
1337         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1338     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1339     if (R.isInvalid())
1340       return ExprError();
1341     ControllingExpr = R.get();
1342   }
1343 
1344   // The controlling expression is an unevaluated operand, so side effects are
1345   // likely unintended.
1346   if (!inTemplateInstantiation() &&
1347       ControllingExpr->HasSideEffects(Context, false))
1348     Diag(ControllingExpr->getExprLoc(),
1349          diag::warn_side_effects_unevaluated_context);
1350 
1351   bool TypeErrorFound = false,
1352        IsResultDependent = ControllingExpr->isTypeDependent(),
1353        ContainsUnexpandedParameterPack
1354          = ControllingExpr->containsUnexpandedParameterPack();
1355 
1356   for (unsigned i = 0; i < NumAssocs; ++i) {
1357     if (Exprs[i]->containsUnexpandedParameterPack())
1358       ContainsUnexpandedParameterPack = true;
1359 
1360     if (Types[i]) {
1361       if (Types[i]->getType()->containsUnexpandedParameterPack())
1362         ContainsUnexpandedParameterPack = true;
1363 
1364       if (Types[i]->getType()->isDependentType()) {
1365         IsResultDependent = true;
1366       } else {
1367         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1368         // complete object type other than a variably modified type."
1369         unsigned D = 0;
1370         if (Types[i]->getType()->isIncompleteType())
1371           D = diag::err_assoc_type_incomplete;
1372         else if (!Types[i]->getType()->isObjectType())
1373           D = diag::err_assoc_type_nonobject;
1374         else if (Types[i]->getType()->isVariablyModifiedType())
1375           D = diag::err_assoc_type_variably_modified;
1376 
1377         if (D != 0) {
1378           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1379             << Types[i]->getTypeLoc().getSourceRange()
1380             << Types[i]->getType();
1381           TypeErrorFound = true;
1382         }
1383 
1384         // C11 6.5.1.1p2 "No two generic associations in the same generic
1385         // selection shall specify compatible types."
1386         for (unsigned j = i+1; j < NumAssocs; ++j)
1387           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1388               Context.typesAreCompatible(Types[i]->getType(),
1389                                          Types[j]->getType())) {
1390             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1391                  diag::err_assoc_compatible_types)
1392               << Types[j]->getTypeLoc().getSourceRange()
1393               << Types[j]->getType()
1394               << Types[i]->getType();
1395             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1396                  diag::note_compat_assoc)
1397               << Types[i]->getTypeLoc().getSourceRange()
1398               << Types[i]->getType();
1399             TypeErrorFound = true;
1400           }
1401       }
1402     }
1403   }
1404   if (TypeErrorFound)
1405     return ExprError();
1406 
1407   // If we determined that the generic selection is result-dependent, don't
1408   // try to compute the result expression.
1409   if (IsResultDependent)
1410     return new (Context) GenericSelectionExpr(
1411         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1412         ContainsUnexpandedParameterPack);
1413 
1414   SmallVector<unsigned, 1> CompatIndices;
1415   unsigned DefaultIndex = -1U;
1416   for (unsigned i = 0; i < NumAssocs; ++i) {
1417     if (!Types[i])
1418       DefaultIndex = i;
1419     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1420                                         Types[i]->getType()))
1421       CompatIndices.push_back(i);
1422   }
1423 
1424   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1425   // type compatible with at most one of the types named in its generic
1426   // association list."
1427   if (CompatIndices.size() > 1) {
1428     // We strip parens here because the controlling expression is typically
1429     // parenthesized in macro definitions.
1430     ControllingExpr = ControllingExpr->IgnoreParens();
1431     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1432       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1433       << (unsigned) CompatIndices.size();
1434     for (unsigned I : CompatIndices) {
1435       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1436            diag::note_compat_assoc)
1437         << Types[I]->getTypeLoc().getSourceRange()
1438         << Types[I]->getType();
1439     }
1440     return ExprError();
1441   }
1442 
1443   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1444   // its controlling expression shall have type compatible with exactly one of
1445   // the types named in its generic association list."
1446   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1447     // We strip parens here because the controlling expression is typically
1448     // parenthesized in macro definitions.
1449     ControllingExpr = ControllingExpr->IgnoreParens();
1450     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1451       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1452     return ExprError();
1453   }
1454 
1455   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1456   // type name that is compatible with the type of the controlling expression,
1457   // then the result expression of the generic selection is the expression
1458   // in that generic association. Otherwise, the result expression of the
1459   // generic selection is the expression in the default generic association."
1460   unsigned ResultIndex =
1461     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1462 
1463   return new (Context) GenericSelectionExpr(
1464       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1465       ContainsUnexpandedParameterPack, ResultIndex);
1466 }
1467 
1468 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1469 /// location of the token and the offset of the ud-suffix within it.
1470 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1471                                      unsigned Offset) {
1472   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1473                                         S.getLangOpts());
1474 }
1475 
1476 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1477 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1478 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1479                                                  IdentifierInfo *UDSuffix,
1480                                                  SourceLocation UDSuffixLoc,
1481                                                  ArrayRef<Expr*> Args,
1482                                                  SourceLocation LitEndLoc) {
1483   assert(Args.size() <= 2 && "too many arguments for literal operator");
1484 
1485   QualType ArgTy[2];
1486   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1487     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1488     if (ArgTy[ArgIdx]->isArrayType())
1489       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1490   }
1491 
1492   DeclarationName OpName =
1493     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1494   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1495   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1496 
1497   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1498   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1499                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1500                               /*AllowStringTemplate*/ false,
1501                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1502     return ExprError();
1503 
1504   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1505 }
1506 
1507 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1508 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1509 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1510 /// multiple tokens.  However, the common case is that StringToks points to one
1511 /// string.
1512 ///
1513 ExprResult
1514 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1515   assert(!StringToks.empty() && "Must have at least one string!");
1516 
1517   StringLiteralParser Literal(StringToks, PP);
1518   if (Literal.hadError)
1519     return ExprError();
1520 
1521   SmallVector<SourceLocation, 4> StringTokLocs;
1522   for (const Token &Tok : StringToks)
1523     StringTokLocs.push_back(Tok.getLocation());
1524 
1525   QualType CharTy = Context.CharTy;
1526   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1527   if (Literal.isWide()) {
1528     CharTy = Context.getWideCharType();
1529     Kind = StringLiteral::Wide;
1530   } else if (Literal.isUTF8()) {
1531     Kind = StringLiteral::UTF8;
1532   } else if (Literal.isUTF16()) {
1533     CharTy = Context.Char16Ty;
1534     Kind = StringLiteral::UTF16;
1535   } else if (Literal.isUTF32()) {
1536     CharTy = Context.Char32Ty;
1537     Kind = StringLiteral::UTF32;
1538   } else if (Literal.isPascal()) {
1539     CharTy = Context.UnsignedCharTy;
1540   }
1541 
1542   QualType CharTyConst = CharTy;
1543   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1544   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1545     CharTyConst.addConst();
1546 
1547   // Get an array type for the string, according to C99 6.4.5.  This includes
1548   // the nul terminator character as well as the string length for pascal
1549   // strings.
1550   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1551                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1552                                  ArrayType::Normal, 0);
1553 
1554   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1555   if (getLangOpts().OpenCL) {
1556     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1557   }
1558 
1559   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1560   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1561                                              Kind, Literal.Pascal, StrTy,
1562                                              &StringTokLocs[0],
1563                                              StringTokLocs.size());
1564   if (Literal.getUDSuffix().empty())
1565     return Lit;
1566 
1567   // We're building a user-defined literal.
1568   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1569   SourceLocation UDSuffixLoc =
1570     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1571                    Literal.getUDSuffixOffset());
1572 
1573   // Make sure we're allowed user-defined literals here.
1574   if (!UDLScope)
1575     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1576 
1577   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1578   //   operator "" X (str, len)
1579   QualType SizeType = Context.getSizeType();
1580 
1581   DeclarationName OpName =
1582     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1583   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1584   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1585 
1586   QualType ArgTy[] = {
1587     Context.getArrayDecayedType(StrTy), SizeType
1588   };
1589 
1590   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1591   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1592                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1593                                 /*AllowStringTemplate*/ true,
1594                                 /*DiagnoseMissing*/ true)) {
1595 
1596   case LOLR_Cooked: {
1597     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1598     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1599                                                     StringTokLocs[0]);
1600     Expr *Args[] = { Lit, LenArg };
1601 
1602     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1603   }
1604 
1605   case LOLR_StringTemplate: {
1606     TemplateArgumentListInfo ExplicitArgs;
1607 
1608     unsigned CharBits = Context.getIntWidth(CharTy);
1609     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1610     llvm::APSInt Value(CharBits, CharIsUnsigned);
1611 
1612     TemplateArgument TypeArg(CharTy);
1613     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1614     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1615 
1616     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1617       Value = Lit->getCodeUnit(I);
1618       TemplateArgument Arg(Context, Value, CharTy);
1619       TemplateArgumentLocInfo ArgInfo;
1620       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1621     }
1622     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1623                                     &ExplicitArgs);
1624   }
1625   case LOLR_Raw:
1626   case LOLR_Template:
1627   case LOLR_ErrorNoDiagnostic:
1628     llvm_unreachable("unexpected literal operator lookup result");
1629   case LOLR_Error:
1630     return ExprError();
1631   }
1632   llvm_unreachable("unexpected literal operator lookup result");
1633 }
1634 
1635 ExprResult
1636 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1637                        SourceLocation Loc,
1638                        const CXXScopeSpec *SS) {
1639   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1640   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1641 }
1642 
1643 /// BuildDeclRefExpr - Build an expression that references a
1644 /// declaration that does not require a closure capture.
1645 ExprResult
1646 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1647                        const DeclarationNameInfo &NameInfo,
1648                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1649                        const TemplateArgumentListInfo *TemplateArgs) {
1650   bool RefersToCapturedVariable =
1651       isa<VarDecl>(D) &&
1652       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1653 
1654   DeclRefExpr *E;
1655   if (isa<VarTemplateSpecializationDecl>(D)) {
1656     VarTemplateSpecializationDecl *VarSpec =
1657         cast<VarTemplateSpecializationDecl>(D);
1658 
1659     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1660                                         : NestedNameSpecifierLoc(),
1661                             VarSpec->getTemplateKeywordLoc(), D,
1662                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1663                             FoundD, TemplateArgs);
1664   } else {
1665     assert(!TemplateArgs && "No template arguments for non-variable"
1666                             " template specialization references");
1667     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1668                                         : NestedNameSpecifierLoc(),
1669                             SourceLocation(), D, RefersToCapturedVariable,
1670                             NameInfo, Ty, VK, FoundD);
1671   }
1672 
1673   MarkDeclRefReferenced(E);
1674 
1675   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1676       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1677       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1678       recordUseOfEvaluatedWeak(E);
1679 
1680   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1681   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1682     FD = IFD->getAnonField();
1683   if (FD) {
1684     UnusedPrivateFields.remove(FD);
1685     // Just in case we're building an illegal pointer-to-member.
1686     if (FD->isBitField())
1687       E->setObjectKind(OK_BitField);
1688   }
1689 
1690   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1691   // designates a bit-field.
1692   if (auto *BD = dyn_cast<BindingDecl>(D))
1693     if (auto *BE = BD->getBinding())
1694       E->setObjectKind(BE->getObjectKind());
1695 
1696   return E;
1697 }
1698 
1699 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1700 /// possibly a list of template arguments.
1701 ///
1702 /// If this produces template arguments, it is permitted to call
1703 /// DecomposeTemplateName.
1704 ///
1705 /// This actually loses a lot of source location information for
1706 /// non-standard name kinds; we should consider preserving that in
1707 /// some way.
1708 void
1709 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1710                              TemplateArgumentListInfo &Buffer,
1711                              DeclarationNameInfo &NameInfo,
1712                              const TemplateArgumentListInfo *&TemplateArgs) {
1713   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1714     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1715     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1716 
1717     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1718                                        Id.TemplateId->NumArgs);
1719     translateTemplateArguments(TemplateArgsPtr, Buffer);
1720 
1721     TemplateName TName = Id.TemplateId->Template.get();
1722     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1723     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1724     TemplateArgs = &Buffer;
1725   } else {
1726     NameInfo = GetNameFromUnqualifiedId(Id);
1727     TemplateArgs = nullptr;
1728   }
1729 }
1730 
1731 static void emitEmptyLookupTypoDiagnostic(
1732     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1733     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1734     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1735   DeclContext *Ctx =
1736       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1737   if (!TC) {
1738     // Emit a special diagnostic for failed member lookups.
1739     // FIXME: computing the declaration context might fail here (?)
1740     if (Ctx)
1741       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1742                                                  << SS.getRange();
1743     else
1744       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1745     return;
1746   }
1747 
1748   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1749   bool DroppedSpecifier =
1750       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1751   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1752                         ? diag::note_implicit_param_decl
1753                         : diag::note_previous_decl;
1754   if (!Ctx)
1755     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1756                          SemaRef.PDiag(NoteID));
1757   else
1758     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1759                                  << Typo << Ctx << DroppedSpecifier
1760                                  << SS.getRange(),
1761                          SemaRef.PDiag(NoteID));
1762 }
1763 
1764 /// Diagnose an empty lookup.
1765 ///
1766 /// \return false if new lookup candidates were found
1767 bool
1768 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1769                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1770                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1771                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1772   DeclarationName Name = R.getLookupName();
1773 
1774   unsigned diagnostic = diag::err_undeclared_var_use;
1775   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1776   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1777       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1778       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1779     diagnostic = diag::err_undeclared_use;
1780     diagnostic_suggest = diag::err_undeclared_use_suggest;
1781   }
1782 
1783   // If the original lookup was an unqualified lookup, fake an
1784   // unqualified lookup.  This is useful when (for example) the
1785   // original lookup would not have found something because it was a
1786   // dependent name.
1787   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1788   while (DC) {
1789     if (isa<CXXRecordDecl>(DC)) {
1790       LookupQualifiedName(R, DC);
1791 
1792       if (!R.empty()) {
1793         // Don't give errors about ambiguities in this lookup.
1794         R.suppressDiagnostics();
1795 
1796         // During a default argument instantiation the CurContext points
1797         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1798         // function parameter list, hence add an explicit check.
1799         bool isDefaultArgument =
1800             !CodeSynthesisContexts.empty() &&
1801             CodeSynthesisContexts.back().Kind ==
1802                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1803         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1804         bool isInstance = CurMethod &&
1805                           CurMethod->isInstance() &&
1806                           DC == CurMethod->getParent() && !isDefaultArgument;
1807 
1808         // Give a code modification hint to insert 'this->'.
1809         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1810         // Actually quite difficult!
1811         if (getLangOpts().MSVCCompat)
1812           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1813         if (isInstance) {
1814           Diag(R.getNameLoc(), diagnostic) << Name
1815             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1816           CheckCXXThisCapture(R.getNameLoc());
1817         } else {
1818           Diag(R.getNameLoc(), diagnostic) << Name;
1819         }
1820 
1821         // Do we really want to note all of these?
1822         for (NamedDecl *D : R)
1823           Diag(D->getLocation(), diag::note_dependent_var_use);
1824 
1825         // Return true if we are inside a default argument instantiation
1826         // and the found name refers to an instance member function, otherwise
1827         // the function calling DiagnoseEmptyLookup will try to create an
1828         // implicit member call and this is wrong for default argument.
1829         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1830           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1831           return true;
1832         }
1833 
1834         // Tell the callee to try to recover.
1835         return false;
1836       }
1837 
1838       R.clear();
1839     }
1840 
1841     // In Microsoft mode, if we are performing lookup from within a friend
1842     // function definition declared at class scope then we must set
1843     // DC to the lexical parent to be able to search into the parent
1844     // class.
1845     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1846         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1847         DC->getLexicalParent()->isRecord())
1848       DC = DC->getLexicalParent();
1849     else
1850       DC = DC->getParent();
1851   }
1852 
1853   // We didn't find anything, so try to correct for a typo.
1854   TypoCorrection Corrected;
1855   if (S && Out) {
1856     SourceLocation TypoLoc = R.getNameLoc();
1857     assert(!ExplicitTemplateArgs &&
1858            "Diagnosing an empty lookup with explicit template args!");
1859     *Out = CorrectTypoDelayed(
1860         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1861         [=](const TypoCorrection &TC) {
1862           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1863                                         diagnostic, diagnostic_suggest);
1864         },
1865         nullptr, CTK_ErrorRecovery);
1866     if (*Out)
1867       return true;
1868   } else if (S && (Corrected =
1869                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1870                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1871     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1872     bool DroppedSpecifier =
1873         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1874     R.setLookupName(Corrected.getCorrection());
1875 
1876     bool AcceptableWithRecovery = false;
1877     bool AcceptableWithoutRecovery = false;
1878     NamedDecl *ND = Corrected.getFoundDecl();
1879     if (ND) {
1880       if (Corrected.isOverloaded()) {
1881         OverloadCandidateSet OCS(R.getNameLoc(),
1882                                  OverloadCandidateSet::CSK_Normal);
1883         OverloadCandidateSet::iterator Best;
1884         for (NamedDecl *CD : Corrected) {
1885           if (FunctionTemplateDecl *FTD =
1886                    dyn_cast<FunctionTemplateDecl>(CD))
1887             AddTemplateOverloadCandidate(
1888                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1889                 Args, OCS);
1890           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1891             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1892               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1893                                    Args, OCS);
1894         }
1895         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1896         case OR_Success:
1897           ND = Best->FoundDecl;
1898           Corrected.setCorrectionDecl(ND);
1899           break;
1900         default:
1901           // FIXME: Arbitrarily pick the first declaration for the note.
1902           Corrected.setCorrectionDecl(ND);
1903           break;
1904         }
1905       }
1906       R.addDecl(ND);
1907       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1908         CXXRecordDecl *Record = nullptr;
1909         if (Corrected.getCorrectionSpecifier()) {
1910           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1911           Record = Ty->getAsCXXRecordDecl();
1912         }
1913         if (!Record)
1914           Record = cast<CXXRecordDecl>(
1915               ND->getDeclContext()->getRedeclContext());
1916         R.setNamingClass(Record);
1917       }
1918 
1919       auto *UnderlyingND = ND->getUnderlyingDecl();
1920       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
1921                                isa<FunctionTemplateDecl>(UnderlyingND);
1922       // FIXME: If we ended up with a typo for a type name or
1923       // Objective-C class name, we're in trouble because the parser
1924       // is in the wrong place to recover. Suggest the typo
1925       // correction, but don't make it a fix-it since we're not going
1926       // to recover well anyway.
1927       AcceptableWithoutRecovery =
1928           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
1929     } else {
1930       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1931       // because we aren't able to recover.
1932       AcceptableWithoutRecovery = true;
1933     }
1934 
1935     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1936       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
1937                             ? diag::note_implicit_param_decl
1938                             : diag::note_previous_decl;
1939       if (SS.isEmpty())
1940         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1941                      PDiag(NoteID), AcceptableWithRecovery);
1942       else
1943         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1944                                   << Name << computeDeclContext(SS, false)
1945                                   << DroppedSpecifier << SS.getRange(),
1946                      PDiag(NoteID), AcceptableWithRecovery);
1947 
1948       // Tell the callee whether to try to recover.
1949       return !AcceptableWithRecovery;
1950     }
1951   }
1952   R.clear();
1953 
1954   // Emit a special diagnostic for failed member lookups.
1955   // FIXME: computing the declaration context might fail here (?)
1956   if (!SS.isEmpty()) {
1957     Diag(R.getNameLoc(), diag::err_no_member)
1958       << Name << computeDeclContext(SS, false)
1959       << SS.getRange();
1960     return true;
1961   }
1962 
1963   // Give up, we can't recover.
1964   Diag(R.getNameLoc(), diagnostic) << Name;
1965   return true;
1966 }
1967 
1968 /// In Microsoft mode, if we are inside a template class whose parent class has
1969 /// dependent base classes, and we can't resolve an unqualified identifier, then
1970 /// assume the identifier is a member of a dependent base class.  We can only
1971 /// recover successfully in static methods, instance methods, and other contexts
1972 /// where 'this' is available.  This doesn't precisely match MSVC's
1973 /// instantiation model, but it's close enough.
1974 static Expr *
1975 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
1976                                DeclarationNameInfo &NameInfo,
1977                                SourceLocation TemplateKWLoc,
1978                                const TemplateArgumentListInfo *TemplateArgs) {
1979   // Only try to recover from lookup into dependent bases in static methods or
1980   // contexts where 'this' is available.
1981   QualType ThisType = S.getCurrentThisType();
1982   const CXXRecordDecl *RD = nullptr;
1983   if (!ThisType.isNull())
1984     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
1985   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
1986     RD = MD->getParent();
1987   if (!RD || !RD->hasAnyDependentBases())
1988     return nullptr;
1989 
1990   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
1991   // is available, suggest inserting 'this->' as a fixit.
1992   SourceLocation Loc = NameInfo.getLoc();
1993   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
1994   DB << NameInfo.getName() << RD;
1995 
1996   if (!ThisType.isNull()) {
1997     DB << FixItHint::CreateInsertion(Loc, "this->");
1998     return CXXDependentScopeMemberExpr::Create(
1999         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2000         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2001         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2002   }
2003 
2004   // Synthesize a fake NNS that points to the derived class.  This will
2005   // perform name lookup during template instantiation.
2006   CXXScopeSpec SS;
2007   auto *NNS =
2008       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2009   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2010   return DependentScopeDeclRefExpr::Create(
2011       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2012       TemplateArgs);
2013 }
2014 
2015 ExprResult
2016 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2017                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2018                         bool HasTrailingLParen, bool IsAddressOfOperand,
2019                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2020                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2021   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2022          "cannot be direct & operand and have a trailing lparen");
2023   if (SS.isInvalid())
2024     return ExprError();
2025 
2026   TemplateArgumentListInfo TemplateArgsBuffer;
2027 
2028   // Decompose the UnqualifiedId into the following data.
2029   DeclarationNameInfo NameInfo;
2030   const TemplateArgumentListInfo *TemplateArgs;
2031   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2032 
2033   DeclarationName Name = NameInfo.getName();
2034   IdentifierInfo *II = Name.getAsIdentifierInfo();
2035   SourceLocation NameLoc = NameInfo.getLoc();
2036 
2037   if (II && II->isEditorPlaceholder()) {
2038     // FIXME: When typed placeholders are supported we can create a typed
2039     // placeholder expression node.
2040     return ExprError();
2041   }
2042 
2043   // C++ [temp.dep.expr]p3:
2044   //   An id-expression is type-dependent if it contains:
2045   //     -- an identifier that was declared with a dependent type,
2046   //        (note: handled after lookup)
2047   //     -- a template-id that is dependent,
2048   //        (note: handled in BuildTemplateIdExpr)
2049   //     -- a conversion-function-id that specifies a dependent type,
2050   //     -- a nested-name-specifier that contains a class-name that
2051   //        names a dependent type.
2052   // Determine whether this is a member of an unknown specialization;
2053   // we need to handle these differently.
2054   bool DependentID = false;
2055   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2056       Name.getCXXNameType()->isDependentType()) {
2057     DependentID = true;
2058   } else if (SS.isSet()) {
2059     if (DeclContext *DC = computeDeclContext(SS, false)) {
2060       if (RequireCompleteDeclContext(SS, DC))
2061         return ExprError();
2062     } else {
2063       DependentID = true;
2064     }
2065   }
2066 
2067   if (DependentID)
2068     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2069                                       IsAddressOfOperand, TemplateArgs);
2070 
2071   // Perform the required lookup.
2072   LookupResult R(*this, NameInfo,
2073                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2074                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2075   if (TemplateArgs) {
2076     // Lookup the template name again to correctly establish the context in
2077     // which it was found. This is really unfortunate as we already did the
2078     // lookup to determine that it was a template name in the first place. If
2079     // this becomes a performance hit, we can work harder to preserve those
2080     // results until we get here but it's likely not worth it.
2081     bool MemberOfUnknownSpecialization;
2082     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2083                        MemberOfUnknownSpecialization);
2084 
2085     if (MemberOfUnknownSpecialization ||
2086         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2087       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2088                                         IsAddressOfOperand, TemplateArgs);
2089   } else {
2090     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2091     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2092 
2093     // If the result might be in a dependent base class, this is a dependent
2094     // id-expression.
2095     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2096       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2097                                         IsAddressOfOperand, TemplateArgs);
2098 
2099     // If this reference is in an Objective-C method, then we need to do
2100     // some special Objective-C lookup, too.
2101     if (IvarLookupFollowUp) {
2102       ExprResult E(LookupInObjCMethod(R, S, II, true));
2103       if (E.isInvalid())
2104         return ExprError();
2105 
2106       if (Expr *Ex = E.getAs<Expr>())
2107         return Ex;
2108     }
2109   }
2110 
2111   if (R.isAmbiguous())
2112     return ExprError();
2113 
2114   // This could be an implicitly declared function reference (legal in C90,
2115   // extension in C99, forbidden in C++).
2116   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2117     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2118     if (D) R.addDecl(D);
2119   }
2120 
2121   // Determine whether this name might be a candidate for
2122   // argument-dependent lookup.
2123   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2124 
2125   if (R.empty() && !ADL) {
2126     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2127       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2128                                                    TemplateKWLoc, TemplateArgs))
2129         return E;
2130     }
2131 
2132     // Don't diagnose an empty lookup for inline assembly.
2133     if (IsInlineAsmIdentifier)
2134       return ExprError();
2135 
2136     // If this name wasn't predeclared and if this is not a function
2137     // call, diagnose the problem.
2138     TypoExpr *TE = nullptr;
2139     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2140         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2141     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2142     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2143            "Typo correction callback misconfigured");
2144     if (CCC) {
2145       // Make sure the callback knows what the typo being diagnosed is.
2146       CCC->setTypoName(II);
2147       if (SS.isValid())
2148         CCC->setTypoNNS(SS.getScopeRep());
2149     }
2150     if (DiagnoseEmptyLookup(S, SS, R,
2151                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2152                             nullptr, None, &TE)) {
2153       if (TE && KeywordReplacement) {
2154         auto &State = getTypoExprState(TE);
2155         auto BestTC = State.Consumer->getNextCorrection();
2156         if (BestTC.isKeyword()) {
2157           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2158           if (State.DiagHandler)
2159             State.DiagHandler(BestTC);
2160           KeywordReplacement->startToken();
2161           KeywordReplacement->setKind(II->getTokenID());
2162           KeywordReplacement->setIdentifierInfo(II);
2163           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2164           // Clean up the state associated with the TypoExpr, since it has
2165           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2166           clearDelayedTypo(TE);
2167           // Signal that a correction to a keyword was performed by returning a
2168           // valid-but-null ExprResult.
2169           return (Expr*)nullptr;
2170         }
2171         State.Consumer->resetCorrectionStream();
2172       }
2173       return TE ? TE : ExprError();
2174     }
2175 
2176     assert(!R.empty() &&
2177            "DiagnoseEmptyLookup returned false but added no results");
2178 
2179     // If we found an Objective-C instance variable, let
2180     // LookupInObjCMethod build the appropriate expression to
2181     // reference the ivar.
2182     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2183       R.clear();
2184       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2185       // In a hopelessly buggy code, Objective-C instance variable
2186       // lookup fails and no expression will be built to reference it.
2187       if (!E.isInvalid() && !E.get())
2188         return ExprError();
2189       return E;
2190     }
2191   }
2192 
2193   // This is guaranteed from this point on.
2194   assert(!R.empty() || ADL);
2195 
2196   // Check whether this might be a C++ implicit instance member access.
2197   // C++ [class.mfct.non-static]p3:
2198   //   When an id-expression that is not part of a class member access
2199   //   syntax and not used to form a pointer to member is used in the
2200   //   body of a non-static member function of class X, if name lookup
2201   //   resolves the name in the id-expression to a non-static non-type
2202   //   member of some class C, the id-expression is transformed into a
2203   //   class member access expression using (*this) as the
2204   //   postfix-expression to the left of the . operator.
2205   //
2206   // But we don't actually need to do this for '&' operands if R
2207   // resolved to a function or overloaded function set, because the
2208   // expression is ill-formed if it actually works out to be a
2209   // non-static member function:
2210   //
2211   // C++ [expr.ref]p4:
2212   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2213   //   [t]he expression can be used only as the left-hand operand of a
2214   //   member function call.
2215   //
2216   // There are other safeguards against such uses, but it's important
2217   // to get this right here so that we don't end up making a
2218   // spuriously dependent expression if we're inside a dependent
2219   // instance method.
2220   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2221     bool MightBeImplicitMember;
2222     if (!IsAddressOfOperand)
2223       MightBeImplicitMember = true;
2224     else if (!SS.isEmpty())
2225       MightBeImplicitMember = false;
2226     else if (R.isOverloadedResult())
2227       MightBeImplicitMember = false;
2228     else if (R.isUnresolvableResult())
2229       MightBeImplicitMember = true;
2230     else
2231       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2232                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2233                               isa<MSPropertyDecl>(R.getFoundDecl());
2234 
2235     if (MightBeImplicitMember)
2236       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2237                                              R, TemplateArgs, S);
2238   }
2239 
2240   if (TemplateArgs || TemplateKWLoc.isValid()) {
2241 
2242     // In C++1y, if this is a variable template id, then check it
2243     // in BuildTemplateIdExpr().
2244     // The single lookup result must be a variable template declaration.
2245     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2246         Id.TemplateId->Kind == TNK_Var_template) {
2247       assert(R.getAsSingle<VarTemplateDecl>() &&
2248              "There should only be one declaration found.");
2249     }
2250 
2251     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2252   }
2253 
2254   return BuildDeclarationNameExpr(SS, R, ADL);
2255 }
2256 
2257 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2258 /// declaration name, generally during template instantiation.
2259 /// There's a large number of things which don't need to be done along
2260 /// this path.
2261 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2262     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2263     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2264   DeclContext *DC = computeDeclContext(SS, false);
2265   if (!DC)
2266     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2267                                      NameInfo, /*TemplateArgs=*/nullptr);
2268 
2269   if (RequireCompleteDeclContext(SS, DC))
2270     return ExprError();
2271 
2272   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2273   LookupQualifiedName(R, DC);
2274 
2275   if (R.isAmbiguous())
2276     return ExprError();
2277 
2278   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2279     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2280                                      NameInfo, /*TemplateArgs=*/nullptr);
2281 
2282   if (R.empty()) {
2283     Diag(NameInfo.getLoc(), diag::err_no_member)
2284       << NameInfo.getName() << DC << SS.getRange();
2285     return ExprError();
2286   }
2287 
2288   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2289     // Diagnose a missing typename if this resolved unambiguously to a type in
2290     // a dependent context.  If we can recover with a type, downgrade this to
2291     // a warning in Microsoft compatibility mode.
2292     unsigned DiagID = diag::err_typename_missing;
2293     if (RecoveryTSI && getLangOpts().MSVCCompat)
2294       DiagID = diag::ext_typename_missing;
2295     SourceLocation Loc = SS.getBeginLoc();
2296     auto D = Diag(Loc, DiagID);
2297     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2298       << SourceRange(Loc, NameInfo.getEndLoc());
2299 
2300     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2301     // context.
2302     if (!RecoveryTSI)
2303       return ExprError();
2304 
2305     // Only issue the fixit if we're prepared to recover.
2306     D << FixItHint::CreateInsertion(Loc, "typename ");
2307 
2308     // Recover by pretending this was an elaborated type.
2309     QualType Ty = Context.getTypeDeclType(TD);
2310     TypeLocBuilder TLB;
2311     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2312 
2313     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2314     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2315     QTL.setElaboratedKeywordLoc(SourceLocation());
2316     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2317 
2318     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2319 
2320     return ExprEmpty();
2321   }
2322 
2323   // Defend against this resolving to an implicit member access. We usually
2324   // won't get here if this might be a legitimate a class member (we end up in
2325   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2326   // a pointer-to-member or in an unevaluated context in C++11.
2327   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2328     return BuildPossibleImplicitMemberExpr(SS,
2329                                            /*TemplateKWLoc=*/SourceLocation(),
2330                                            R, /*TemplateArgs=*/nullptr, S);
2331 
2332   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2333 }
2334 
2335 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2336 /// detected that we're currently inside an ObjC method.  Perform some
2337 /// additional lookup.
2338 ///
2339 /// Ideally, most of this would be done by lookup, but there's
2340 /// actually quite a lot of extra work involved.
2341 ///
2342 /// Returns a null sentinel to indicate trivial success.
2343 ExprResult
2344 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2345                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2346   SourceLocation Loc = Lookup.getNameLoc();
2347   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2348 
2349   // Check for error condition which is already reported.
2350   if (!CurMethod)
2351     return ExprError();
2352 
2353   // There are two cases to handle here.  1) scoped lookup could have failed,
2354   // in which case we should look for an ivar.  2) scoped lookup could have
2355   // found a decl, but that decl is outside the current instance method (i.e.
2356   // a global variable).  In these two cases, we do a lookup for an ivar with
2357   // this name, if the lookup sucedes, we replace it our current decl.
2358 
2359   // If we're in a class method, we don't normally want to look for
2360   // ivars.  But if we don't find anything else, and there's an
2361   // ivar, that's an error.
2362   bool IsClassMethod = CurMethod->isClassMethod();
2363 
2364   bool LookForIvars;
2365   if (Lookup.empty())
2366     LookForIvars = true;
2367   else if (IsClassMethod)
2368     LookForIvars = false;
2369   else
2370     LookForIvars = (Lookup.isSingleResult() &&
2371                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2372   ObjCInterfaceDecl *IFace = nullptr;
2373   if (LookForIvars) {
2374     IFace = CurMethod->getClassInterface();
2375     ObjCInterfaceDecl *ClassDeclared;
2376     ObjCIvarDecl *IV = nullptr;
2377     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2378       // Diagnose using an ivar in a class method.
2379       if (IsClassMethod)
2380         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2381                          << IV->getDeclName());
2382 
2383       // If we're referencing an invalid decl, just return this as a silent
2384       // error node.  The error diagnostic was already emitted on the decl.
2385       if (IV->isInvalidDecl())
2386         return ExprError();
2387 
2388       // Check if referencing a field with __attribute__((deprecated)).
2389       if (DiagnoseUseOfDecl(IV, Loc))
2390         return ExprError();
2391 
2392       // Diagnose the use of an ivar outside of the declaring class.
2393       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2394           !declaresSameEntity(ClassDeclared, IFace) &&
2395           !getLangOpts().DebuggerSupport)
2396         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2397 
2398       // FIXME: This should use a new expr for a direct reference, don't
2399       // turn this into Self->ivar, just return a BareIVarExpr or something.
2400       IdentifierInfo &II = Context.Idents.get("self");
2401       UnqualifiedId SelfName;
2402       SelfName.setIdentifier(&II, SourceLocation());
2403       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2404       CXXScopeSpec SelfScopeSpec;
2405       SourceLocation TemplateKWLoc;
2406       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2407                                               SelfName, false, false);
2408       if (SelfExpr.isInvalid())
2409         return ExprError();
2410 
2411       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2412       if (SelfExpr.isInvalid())
2413         return ExprError();
2414 
2415       MarkAnyDeclReferenced(Loc, IV, true);
2416 
2417       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2418       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2419           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2420         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2421 
2422       ObjCIvarRefExpr *Result = new (Context)
2423           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2424                           IV->getLocation(), SelfExpr.get(), true, true);
2425 
2426       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2427         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2428           recordUseOfEvaluatedWeak(Result);
2429       }
2430       if (getLangOpts().ObjCAutoRefCount) {
2431         if (CurContext->isClosure())
2432           Diag(Loc, diag::warn_implicitly_retains_self)
2433             << FixItHint::CreateInsertion(Loc, "self->");
2434       }
2435 
2436       return Result;
2437     }
2438   } else if (CurMethod->isInstanceMethod()) {
2439     // We should warn if a local variable hides an ivar.
2440     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2441       ObjCInterfaceDecl *ClassDeclared;
2442       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2443         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2444             declaresSameEntity(IFace, ClassDeclared))
2445           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2446       }
2447     }
2448   } else if (Lookup.isSingleResult() &&
2449              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2450     // If accessing a stand-alone ivar in a class method, this is an error.
2451     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2452       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2453                        << IV->getDeclName());
2454   }
2455 
2456   if (Lookup.empty() && II && AllowBuiltinCreation) {
2457     // FIXME. Consolidate this with similar code in LookupName.
2458     if (unsigned BuiltinID = II->getBuiltinID()) {
2459       if (!(getLangOpts().CPlusPlus &&
2460             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2461         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2462                                            S, Lookup.isForRedeclaration(),
2463                                            Lookup.getNameLoc());
2464         if (D) Lookup.addDecl(D);
2465       }
2466     }
2467   }
2468   // Sentinel value saying that we didn't do anything special.
2469   return ExprResult((Expr *)nullptr);
2470 }
2471 
2472 /// \brief Cast a base object to a member's actual type.
2473 ///
2474 /// Logically this happens in three phases:
2475 ///
2476 /// * First we cast from the base type to the naming class.
2477 ///   The naming class is the class into which we were looking
2478 ///   when we found the member;  it's the qualifier type if a
2479 ///   qualifier was provided, and otherwise it's the base type.
2480 ///
2481 /// * Next we cast from the naming class to the declaring class.
2482 ///   If the member we found was brought into a class's scope by
2483 ///   a using declaration, this is that class;  otherwise it's
2484 ///   the class declaring the member.
2485 ///
2486 /// * Finally we cast from the declaring class to the "true"
2487 ///   declaring class of the member.  This conversion does not
2488 ///   obey access control.
2489 ExprResult
2490 Sema::PerformObjectMemberConversion(Expr *From,
2491                                     NestedNameSpecifier *Qualifier,
2492                                     NamedDecl *FoundDecl,
2493                                     NamedDecl *Member) {
2494   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2495   if (!RD)
2496     return From;
2497 
2498   QualType DestRecordType;
2499   QualType DestType;
2500   QualType FromRecordType;
2501   QualType FromType = From->getType();
2502   bool PointerConversions = false;
2503   if (isa<FieldDecl>(Member)) {
2504     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2505 
2506     if (FromType->getAs<PointerType>()) {
2507       DestType = Context.getPointerType(DestRecordType);
2508       FromRecordType = FromType->getPointeeType();
2509       PointerConversions = true;
2510     } else {
2511       DestType = DestRecordType;
2512       FromRecordType = FromType;
2513     }
2514   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2515     if (Method->isStatic())
2516       return From;
2517 
2518     DestType = Method->getThisType(Context);
2519     DestRecordType = DestType->getPointeeType();
2520 
2521     if (FromType->getAs<PointerType>()) {
2522       FromRecordType = FromType->getPointeeType();
2523       PointerConversions = true;
2524     } else {
2525       FromRecordType = FromType;
2526       DestType = DestRecordType;
2527     }
2528   } else {
2529     // No conversion necessary.
2530     return From;
2531   }
2532 
2533   if (DestType->isDependentType() || FromType->isDependentType())
2534     return From;
2535 
2536   // If the unqualified types are the same, no conversion is necessary.
2537   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2538     return From;
2539 
2540   SourceRange FromRange = From->getSourceRange();
2541   SourceLocation FromLoc = FromRange.getBegin();
2542 
2543   ExprValueKind VK = From->getValueKind();
2544 
2545   // C++ [class.member.lookup]p8:
2546   //   [...] Ambiguities can often be resolved by qualifying a name with its
2547   //   class name.
2548   //
2549   // If the member was a qualified name and the qualified referred to a
2550   // specific base subobject type, we'll cast to that intermediate type
2551   // first and then to the object in which the member is declared. That allows
2552   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2553   //
2554   //   class Base { public: int x; };
2555   //   class Derived1 : public Base { };
2556   //   class Derived2 : public Base { };
2557   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2558   //
2559   //   void VeryDerived::f() {
2560   //     x = 17; // error: ambiguous base subobjects
2561   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2562   //   }
2563   if (Qualifier && Qualifier->getAsType()) {
2564     QualType QType = QualType(Qualifier->getAsType(), 0);
2565     assert(QType->isRecordType() && "lookup done with non-record type");
2566 
2567     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2568 
2569     // In C++98, the qualifier type doesn't actually have to be a base
2570     // type of the object type, in which case we just ignore it.
2571     // Otherwise build the appropriate casts.
2572     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2573       CXXCastPath BasePath;
2574       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2575                                        FromLoc, FromRange, &BasePath))
2576         return ExprError();
2577 
2578       if (PointerConversions)
2579         QType = Context.getPointerType(QType);
2580       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2581                                VK, &BasePath).get();
2582 
2583       FromType = QType;
2584       FromRecordType = QRecordType;
2585 
2586       // If the qualifier type was the same as the destination type,
2587       // we're done.
2588       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2589         return From;
2590     }
2591   }
2592 
2593   bool IgnoreAccess = false;
2594 
2595   // If we actually found the member through a using declaration, cast
2596   // down to the using declaration's type.
2597   //
2598   // Pointer equality is fine here because only one declaration of a
2599   // class ever has member declarations.
2600   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2601     assert(isa<UsingShadowDecl>(FoundDecl));
2602     QualType URecordType = Context.getTypeDeclType(
2603                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2604 
2605     // We only need to do this if the naming-class to declaring-class
2606     // conversion is non-trivial.
2607     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2608       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2609       CXXCastPath BasePath;
2610       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2611                                        FromLoc, FromRange, &BasePath))
2612         return ExprError();
2613 
2614       QualType UType = URecordType;
2615       if (PointerConversions)
2616         UType = Context.getPointerType(UType);
2617       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2618                                VK, &BasePath).get();
2619       FromType = UType;
2620       FromRecordType = URecordType;
2621     }
2622 
2623     // We don't do access control for the conversion from the
2624     // declaring class to the true declaring class.
2625     IgnoreAccess = true;
2626   }
2627 
2628   CXXCastPath BasePath;
2629   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2630                                    FromLoc, FromRange, &BasePath,
2631                                    IgnoreAccess))
2632     return ExprError();
2633 
2634   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2635                            VK, &BasePath);
2636 }
2637 
2638 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2639                                       const LookupResult &R,
2640                                       bool HasTrailingLParen) {
2641   // Only when used directly as the postfix-expression of a call.
2642   if (!HasTrailingLParen)
2643     return false;
2644 
2645   // Never if a scope specifier was provided.
2646   if (SS.isSet())
2647     return false;
2648 
2649   // Only in C++ or ObjC++.
2650   if (!getLangOpts().CPlusPlus)
2651     return false;
2652 
2653   // Turn off ADL when we find certain kinds of declarations during
2654   // normal lookup:
2655   for (NamedDecl *D : R) {
2656     // C++0x [basic.lookup.argdep]p3:
2657     //     -- a declaration of a class member
2658     // Since using decls preserve this property, we check this on the
2659     // original decl.
2660     if (D->isCXXClassMember())
2661       return false;
2662 
2663     // C++0x [basic.lookup.argdep]p3:
2664     //     -- a block-scope function declaration that is not a
2665     //        using-declaration
2666     // NOTE: we also trigger this for function templates (in fact, we
2667     // don't check the decl type at all, since all other decl types
2668     // turn off ADL anyway).
2669     if (isa<UsingShadowDecl>(D))
2670       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2671     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2672       return false;
2673 
2674     // C++0x [basic.lookup.argdep]p3:
2675     //     -- a declaration that is neither a function or a function
2676     //        template
2677     // And also for builtin functions.
2678     if (isa<FunctionDecl>(D)) {
2679       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2680 
2681       // But also builtin functions.
2682       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2683         return false;
2684     } else if (!isa<FunctionTemplateDecl>(D))
2685       return false;
2686   }
2687 
2688   return true;
2689 }
2690 
2691 
2692 /// Diagnoses obvious problems with the use of the given declaration
2693 /// as an expression.  This is only actually called for lookups that
2694 /// were not overloaded, and it doesn't promise that the declaration
2695 /// will in fact be used.
2696 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2697   if (D->isInvalidDecl())
2698     return true;
2699 
2700   if (isa<TypedefNameDecl>(D)) {
2701     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2702     return true;
2703   }
2704 
2705   if (isa<ObjCInterfaceDecl>(D)) {
2706     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2707     return true;
2708   }
2709 
2710   if (isa<NamespaceDecl>(D)) {
2711     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2712     return true;
2713   }
2714 
2715   return false;
2716 }
2717 
2718 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2719                                           LookupResult &R, bool NeedsADL,
2720                                           bool AcceptInvalidDecl) {
2721   // If this is a single, fully-resolved result and we don't need ADL,
2722   // just build an ordinary singleton decl ref.
2723   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2724     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2725                                     R.getRepresentativeDecl(), nullptr,
2726                                     AcceptInvalidDecl);
2727 
2728   // We only need to check the declaration if there's exactly one
2729   // result, because in the overloaded case the results can only be
2730   // functions and function templates.
2731   if (R.isSingleResult() &&
2732       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2733     return ExprError();
2734 
2735   // Otherwise, just build an unresolved lookup expression.  Suppress
2736   // any lookup-related diagnostics; we'll hash these out later, when
2737   // we've picked a target.
2738   R.suppressDiagnostics();
2739 
2740   UnresolvedLookupExpr *ULE
2741     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2742                                    SS.getWithLocInContext(Context),
2743                                    R.getLookupNameInfo(),
2744                                    NeedsADL, R.isOverloadedResult(),
2745                                    R.begin(), R.end());
2746 
2747   return ULE;
2748 }
2749 
2750 static void
2751 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2752                                    ValueDecl *var, DeclContext *DC);
2753 
2754 /// \brief Complete semantic analysis for a reference to the given declaration.
2755 ExprResult Sema::BuildDeclarationNameExpr(
2756     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2757     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2758     bool AcceptInvalidDecl) {
2759   assert(D && "Cannot refer to a NULL declaration");
2760   assert(!isa<FunctionTemplateDecl>(D) &&
2761          "Cannot refer unambiguously to a function template");
2762 
2763   SourceLocation Loc = NameInfo.getLoc();
2764   if (CheckDeclInExpr(*this, Loc, D))
2765     return ExprError();
2766 
2767   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2768     // Specifically diagnose references to class templates that are missing
2769     // a template argument list.
2770     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2771                                            << Template << SS.getRange();
2772     Diag(Template->getLocation(), diag::note_template_decl_here);
2773     return ExprError();
2774   }
2775 
2776   // Make sure that we're referring to a value.
2777   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2778   if (!VD) {
2779     Diag(Loc, diag::err_ref_non_value)
2780       << D << SS.getRange();
2781     Diag(D->getLocation(), diag::note_declared_at);
2782     return ExprError();
2783   }
2784 
2785   // Check whether this declaration can be used. Note that we suppress
2786   // this check when we're going to perform argument-dependent lookup
2787   // on this function name, because this might not be the function
2788   // that overload resolution actually selects.
2789   if (DiagnoseUseOfDecl(VD, Loc))
2790     return ExprError();
2791 
2792   // Only create DeclRefExpr's for valid Decl's.
2793   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2794     return ExprError();
2795 
2796   // Handle members of anonymous structs and unions.  If we got here,
2797   // and the reference is to a class member indirect field, then this
2798   // must be the subject of a pointer-to-member expression.
2799   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2800     if (!indirectField->isCXXClassMember())
2801       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2802                                                       indirectField);
2803 
2804   {
2805     QualType type = VD->getType();
2806     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2807       // C++ [except.spec]p17:
2808       //   An exception-specification is considered to be needed when:
2809       //   - in an expression, the function is the unique lookup result or
2810       //     the selected member of a set of overloaded functions.
2811       ResolveExceptionSpec(Loc, FPT);
2812       type = VD->getType();
2813     }
2814     ExprValueKind valueKind = VK_RValue;
2815 
2816     switch (D->getKind()) {
2817     // Ignore all the non-ValueDecl kinds.
2818 #define ABSTRACT_DECL(kind)
2819 #define VALUE(type, base)
2820 #define DECL(type, base) \
2821     case Decl::type:
2822 #include "clang/AST/DeclNodes.inc"
2823       llvm_unreachable("invalid value decl kind");
2824 
2825     // These shouldn't make it here.
2826     case Decl::ObjCAtDefsField:
2827     case Decl::ObjCIvar:
2828       llvm_unreachable("forming non-member reference to ivar?");
2829 
2830     // Enum constants are always r-values and never references.
2831     // Unresolved using declarations are dependent.
2832     case Decl::EnumConstant:
2833     case Decl::UnresolvedUsingValue:
2834     case Decl::OMPDeclareReduction:
2835       valueKind = VK_RValue;
2836       break;
2837 
2838     // Fields and indirect fields that got here must be for
2839     // pointer-to-member expressions; we just call them l-values for
2840     // internal consistency, because this subexpression doesn't really
2841     // exist in the high-level semantics.
2842     case Decl::Field:
2843     case Decl::IndirectField:
2844       assert(getLangOpts().CPlusPlus &&
2845              "building reference to field in C?");
2846 
2847       // These can't have reference type in well-formed programs, but
2848       // for internal consistency we do this anyway.
2849       type = type.getNonReferenceType();
2850       valueKind = VK_LValue;
2851       break;
2852 
2853     // Non-type template parameters are either l-values or r-values
2854     // depending on the type.
2855     case Decl::NonTypeTemplateParm: {
2856       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2857         type = reftype->getPointeeType();
2858         valueKind = VK_LValue; // even if the parameter is an r-value reference
2859         break;
2860       }
2861 
2862       // For non-references, we need to strip qualifiers just in case
2863       // the template parameter was declared as 'const int' or whatever.
2864       valueKind = VK_RValue;
2865       type = type.getUnqualifiedType();
2866       break;
2867     }
2868 
2869     case Decl::Var:
2870     case Decl::VarTemplateSpecialization:
2871     case Decl::VarTemplatePartialSpecialization:
2872     case Decl::Decomposition:
2873     case Decl::OMPCapturedExpr:
2874       // In C, "extern void blah;" is valid and is an r-value.
2875       if (!getLangOpts().CPlusPlus &&
2876           !type.hasQualifiers() &&
2877           type->isVoidType()) {
2878         valueKind = VK_RValue;
2879         break;
2880       }
2881       // fallthrough
2882 
2883     case Decl::ImplicitParam:
2884     case Decl::ParmVar: {
2885       // These are always l-values.
2886       valueKind = VK_LValue;
2887       type = type.getNonReferenceType();
2888 
2889       // FIXME: Does the addition of const really only apply in
2890       // potentially-evaluated contexts? Since the variable isn't actually
2891       // captured in an unevaluated context, it seems that the answer is no.
2892       if (!isUnevaluatedContext()) {
2893         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2894         if (!CapturedType.isNull())
2895           type = CapturedType;
2896       }
2897 
2898       break;
2899     }
2900 
2901     case Decl::Binding: {
2902       // These are always lvalues.
2903       valueKind = VK_LValue;
2904       type = type.getNonReferenceType();
2905       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2906       // decides how that's supposed to work.
2907       auto *BD = cast<BindingDecl>(VD);
2908       if (BD->getDeclContext()->isFunctionOrMethod() &&
2909           BD->getDeclContext() != CurContext)
2910         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2911       break;
2912     }
2913 
2914     case Decl::Function: {
2915       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2916         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2917           type = Context.BuiltinFnTy;
2918           valueKind = VK_RValue;
2919           break;
2920         }
2921       }
2922 
2923       const FunctionType *fty = type->castAs<FunctionType>();
2924 
2925       // If we're referring to a function with an __unknown_anytype
2926       // result type, make the entire expression __unknown_anytype.
2927       if (fty->getReturnType() == Context.UnknownAnyTy) {
2928         type = Context.UnknownAnyTy;
2929         valueKind = VK_RValue;
2930         break;
2931       }
2932 
2933       // Functions are l-values in C++.
2934       if (getLangOpts().CPlusPlus) {
2935         valueKind = VK_LValue;
2936         break;
2937       }
2938 
2939       // C99 DR 316 says that, if a function type comes from a
2940       // function definition (without a prototype), that type is only
2941       // used for checking compatibility. Therefore, when referencing
2942       // the function, we pretend that we don't have the full function
2943       // type.
2944       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2945           isa<FunctionProtoType>(fty))
2946         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2947                                               fty->getExtInfo());
2948 
2949       // Functions are r-values in C.
2950       valueKind = VK_RValue;
2951       break;
2952     }
2953 
2954     case Decl::CXXDeductionGuide:
2955       llvm_unreachable("building reference to deduction guide");
2956 
2957     case Decl::MSProperty:
2958       valueKind = VK_LValue;
2959       break;
2960 
2961     case Decl::CXXMethod:
2962       // If we're referring to a method with an __unknown_anytype
2963       // result type, make the entire expression __unknown_anytype.
2964       // This should only be possible with a type written directly.
2965       if (const FunctionProtoType *proto
2966             = dyn_cast<FunctionProtoType>(VD->getType()))
2967         if (proto->getReturnType() == Context.UnknownAnyTy) {
2968           type = Context.UnknownAnyTy;
2969           valueKind = VK_RValue;
2970           break;
2971         }
2972 
2973       // C++ methods are l-values if static, r-values if non-static.
2974       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2975         valueKind = VK_LValue;
2976         break;
2977       }
2978       // fallthrough
2979 
2980     case Decl::CXXConversion:
2981     case Decl::CXXDestructor:
2982     case Decl::CXXConstructor:
2983       valueKind = VK_RValue;
2984       break;
2985     }
2986 
2987     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2988                             TemplateArgs);
2989   }
2990 }
2991 
2992 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
2993                                     SmallString<32> &Target) {
2994   Target.resize(CharByteWidth * (Source.size() + 1));
2995   char *ResultPtr = &Target[0];
2996   const llvm::UTF8 *ErrorPtr;
2997   bool success =
2998       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
2999   (void)success;
3000   assert(success);
3001   Target.resize(ResultPtr - &Target[0]);
3002 }
3003 
3004 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3005                                      PredefinedExpr::IdentType IT) {
3006   // Pick the current block, lambda, captured statement or function.
3007   Decl *currentDecl = nullptr;
3008   if (const BlockScopeInfo *BSI = getCurBlock())
3009     currentDecl = BSI->TheDecl;
3010   else if (const LambdaScopeInfo *LSI = getCurLambda())
3011     currentDecl = LSI->CallOperator;
3012   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3013     currentDecl = CSI->TheCapturedDecl;
3014   else
3015     currentDecl = getCurFunctionOrMethodDecl();
3016 
3017   if (!currentDecl) {
3018     Diag(Loc, diag::ext_predef_outside_function);
3019     currentDecl = Context.getTranslationUnitDecl();
3020   }
3021 
3022   QualType ResTy;
3023   StringLiteral *SL = nullptr;
3024   if (cast<DeclContext>(currentDecl)->isDependentContext())
3025     ResTy = Context.DependentTy;
3026   else {
3027     // Pre-defined identifiers are of type char[x], where x is the length of
3028     // the string.
3029     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3030     unsigned Length = Str.length();
3031 
3032     llvm::APInt LengthI(32, Length + 1);
3033     if (IT == PredefinedExpr::LFunction) {
3034       ResTy = Context.WideCharTy.withConst();
3035       SmallString<32> RawChars;
3036       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3037                               Str, RawChars);
3038       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3039                                            /*IndexTypeQuals*/ 0);
3040       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3041                                  /*Pascal*/ false, ResTy, Loc);
3042     } else {
3043       ResTy = Context.CharTy.withConst();
3044       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3045                                            /*IndexTypeQuals*/ 0);
3046       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3047                                  /*Pascal*/ false, ResTy, Loc);
3048     }
3049   }
3050 
3051   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3052 }
3053 
3054 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3055   PredefinedExpr::IdentType IT;
3056 
3057   switch (Kind) {
3058   default: llvm_unreachable("Unknown simple primary expr!");
3059   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3060   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3061   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3062   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3063   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3064   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3065   }
3066 
3067   return BuildPredefinedExpr(Loc, IT);
3068 }
3069 
3070 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3071   SmallString<16> CharBuffer;
3072   bool Invalid = false;
3073   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3074   if (Invalid)
3075     return ExprError();
3076 
3077   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3078                             PP, Tok.getKind());
3079   if (Literal.hadError())
3080     return ExprError();
3081 
3082   QualType Ty;
3083   if (Literal.isWide())
3084     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3085   else if (Literal.isUTF16())
3086     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3087   else if (Literal.isUTF32())
3088     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3089   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3090     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3091   else
3092     Ty = Context.CharTy;  // 'x' -> char in C++
3093 
3094   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3095   if (Literal.isWide())
3096     Kind = CharacterLiteral::Wide;
3097   else if (Literal.isUTF16())
3098     Kind = CharacterLiteral::UTF16;
3099   else if (Literal.isUTF32())
3100     Kind = CharacterLiteral::UTF32;
3101   else if (Literal.isUTF8())
3102     Kind = CharacterLiteral::UTF8;
3103 
3104   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3105                                              Tok.getLocation());
3106 
3107   if (Literal.getUDSuffix().empty())
3108     return Lit;
3109 
3110   // We're building a user-defined literal.
3111   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3112   SourceLocation UDSuffixLoc =
3113     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3114 
3115   // Make sure we're allowed user-defined literals here.
3116   if (!UDLScope)
3117     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3118 
3119   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3120   //   operator "" X (ch)
3121   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3122                                         Lit, Tok.getLocation());
3123 }
3124 
3125 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3126   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3127   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3128                                 Context.IntTy, Loc);
3129 }
3130 
3131 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3132                                   QualType Ty, SourceLocation Loc) {
3133   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3134 
3135   using llvm::APFloat;
3136   APFloat Val(Format);
3137 
3138   APFloat::opStatus result = Literal.GetFloatValue(Val);
3139 
3140   // Overflow is always an error, but underflow is only an error if
3141   // we underflowed to zero (APFloat reports denormals as underflow).
3142   if ((result & APFloat::opOverflow) ||
3143       ((result & APFloat::opUnderflow) && Val.isZero())) {
3144     unsigned diagnostic;
3145     SmallString<20> buffer;
3146     if (result & APFloat::opOverflow) {
3147       diagnostic = diag::warn_float_overflow;
3148       APFloat::getLargest(Format).toString(buffer);
3149     } else {
3150       diagnostic = diag::warn_float_underflow;
3151       APFloat::getSmallest(Format).toString(buffer);
3152     }
3153 
3154     S.Diag(Loc, diagnostic)
3155       << Ty
3156       << StringRef(buffer.data(), buffer.size());
3157   }
3158 
3159   bool isExact = (result == APFloat::opOK);
3160   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3161 }
3162 
3163 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3164   assert(E && "Invalid expression");
3165 
3166   if (E->isValueDependent())
3167     return false;
3168 
3169   QualType QT = E->getType();
3170   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3171     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3172     return true;
3173   }
3174 
3175   llvm::APSInt ValueAPS;
3176   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3177 
3178   if (R.isInvalid())
3179     return true;
3180 
3181   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3182   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3183     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3184         << ValueAPS.toString(10) << ValueIsPositive;
3185     return true;
3186   }
3187 
3188   return false;
3189 }
3190 
3191 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3192   // Fast path for a single digit (which is quite common).  A single digit
3193   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3194   if (Tok.getLength() == 1) {
3195     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3196     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3197   }
3198 
3199   SmallString<128> SpellingBuffer;
3200   // NumericLiteralParser wants to overread by one character.  Add padding to
3201   // the buffer in case the token is copied to the buffer.  If getSpelling()
3202   // returns a StringRef to the memory buffer, it should have a null char at
3203   // the EOF, so it is also safe.
3204   SpellingBuffer.resize(Tok.getLength() + 1);
3205 
3206   // Get the spelling of the token, which eliminates trigraphs, etc.
3207   bool Invalid = false;
3208   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3209   if (Invalid)
3210     return ExprError();
3211 
3212   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3213   if (Literal.hadError)
3214     return ExprError();
3215 
3216   if (Literal.hasUDSuffix()) {
3217     // We're building a user-defined literal.
3218     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3219     SourceLocation UDSuffixLoc =
3220       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3221 
3222     // Make sure we're allowed user-defined literals here.
3223     if (!UDLScope)
3224       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3225 
3226     QualType CookedTy;
3227     if (Literal.isFloatingLiteral()) {
3228       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3229       // long double, the literal is treated as a call of the form
3230       //   operator "" X (f L)
3231       CookedTy = Context.LongDoubleTy;
3232     } else {
3233       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3234       // unsigned long long, the literal is treated as a call of the form
3235       //   operator "" X (n ULL)
3236       CookedTy = Context.UnsignedLongLongTy;
3237     }
3238 
3239     DeclarationName OpName =
3240       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3241     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3242     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3243 
3244     SourceLocation TokLoc = Tok.getLocation();
3245 
3246     // Perform literal operator lookup to determine if we're building a raw
3247     // literal or a cooked one.
3248     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3249     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3250                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3251                                   /*AllowStringTemplate*/ false,
3252                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3253     case LOLR_ErrorNoDiagnostic:
3254       // Lookup failure for imaginary constants isn't fatal, there's still the
3255       // GNU extension producing _Complex types.
3256       break;
3257     case LOLR_Error:
3258       return ExprError();
3259     case LOLR_Cooked: {
3260       Expr *Lit;
3261       if (Literal.isFloatingLiteral()) {
3262         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3263       } else {
3264         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3265         if (Literal.GetIntegerValue(ResultVal))
3266           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3267               << /* Unsigned */ 1;
3268         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3269                                      Tok.getLocation());
3270       }
3271       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3272     }
3273 
3274     case LOLR_Raw: {
3275       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3276       // literal is treated as a call of the form
3277       //   operator "" X ("n")
3278       unsigned Length = Literal.getUDSuffixOffset();
3279       QualType StrTy = Context.getConstantArrayType(
3280           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3281           ArrayType::Normal, 0);
3282       Expr *Lit = StringLiteral::Create(
3283           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3284           /*Pascal*/false, StrTy, &TokLoc, 1);
3285       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3286     }
3287 
3288     case LOLR_Template: {
3289       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3290       // template), L is treated as a call fo the form
3291       //   operator "" X <'c1', 'c2', ... 'ck'>()
3292       // where n is the source character sequence c1 c2 ... ck.
3293       TemplateArgumentListInfo ExplicitArgs;
3294       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3295       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3296       llvm::APSInt Value(CharBits, CharIsUnsigned);
3297       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3298         Value = TokSpelling[I];
3299         TemplateArgument Arg(Context, Value, Context.CharTy);
3300         TemplateArgumentLocInfo ArgInfo;
3301         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3302       }
3303       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3304                                       &ExplicitArgs);
3305     }
3306     case LOLR_StringTemplate:
3307       llvm_unreachable("unexpected literal operator lookup result");
3308     }
3309   }
3310 
3311   Expr *Res;
3312 
3313   if (Literal.isFloatingLiteral()) {
3314     QualType Ty;
3315     if (Literal.isHalf){
3316       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3317         Ty = Context.HalfTy;
3318       else {
3319         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3320         return ExprError();
3321       }
3322     } else if (Literal.isFloat)
3323       Ty = Context.FloatTy;
3324     else if (Literal.isLong)
3325       Ty = Context.LongDoubleTy;
3326     else if (Literal.isFloat16)
3327       Ty = Context.Float16Ty;
3328     else if (Literal.isFloat128)
3329       Ty = Context.Float128Ty;
3330     else
3331       Ty = Context.DoubleTy;
3332 
3333     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3334 
3335     if (Ty == Context.DoubleTy) {
3336       if (getLangOpts().SinglePrecisionConstants) {
3337         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3338         if (BTy->getKind() != BuiltinType::Float) {
3339           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3340         }
3341       } else if (getLangOpts().OpenCL &&
3342                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3343         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3344         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3345         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3346       }
3347     }
3348   } else if (!Literal.isIntegerLiteral()) {
3349     return ExprError();
3350   } else {
3351     QualType Ty;
3352 
3353     // 'long long' is a C99 or C++11 feature.
3354     if (!getLangOpts().C99 && Literal.isLongLong) {
3355       if (getLangOpts().CPlusPlus)
3356         Diag(Tok.getLocation(),
3357              getLangOpts().CPlusPlus11 ?
3358              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3359       else
3360         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3361     }
3362 
3363     // Get the value in the widest-possible width.
3364     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3365     llvm::APInt ResultVal(MaxWidth, 0);
3366 
3367     if (Literal.GetIntegerValue(ResultVal)) {
3368       // If this value didn't fit into uintmax_t, error and force to ull.
3369       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3370           << /* Unsigned */ 1;
3371       Ty = Context.UnsignedLongLongTy;
3372       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3373              "long long is not intmax_t?");
3374     } else {
3375       // If this value fits into a ULL, try to figure out what else it fits into
3376       // according to the rules of C99 6.4.4.1p5.
3377 
3378       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3379       // be an unsigned int.
3380       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3381 
3382       // Check from smallest to largest, picking the smallest type we can.
3383       unsigned Width = 0;
3384 
3385       // Microsoft specific integer suffixes are explicitly sized.
3386       if (Literal.MicrosoftInteger) {
3387         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3388           Width = 8;
3389           Ty = Context.CharTy;
3390         } else {
3391           Width = Literal.MicrosoftInteger;
3392           Ty = Context.getIntTypeForBitwidth(Width,
3393                                              /*Signed=*/!Literal.isUnsigned);
3394         }
3395       }
3396 
3397       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3398         // Are int/unsigned possibilities?
3399         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3400 
3401         // Does it fit in a unsigned int?
3402         if (ResultVal.isIntN(IntSize)) {
3403           // Does it fit in a signed int?
3404           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3405             Ty = Context.IntTy;
3406           else if (AllowUnsigned)
3407             Ty = Context.UnsignedIntTy;
3408           Width = IntSize;
3409         }
3410       }
3411 
3412       // Are long/unsigned long possibilities?
3413       if (Ty.isNull() && !Literal.isLongLong) {
3414         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3415 
3416         // Does it fit in a unsigned long?
3417         if (ResultVal.isIntN(LongSize)) {
3418           // Does it fit in a signed long?
3419           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3420             Ty = Context.LongTy;
3421           else if (AllowUnsigned)
3422             Ty = Context.UnsignedLongTy;
3423           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3424           // is compatible.
3425           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3426             const unsigned LongLongSize =
3427                 Context.getTargetInfo().getLongLongWidth();
3428             Diag(Tok.getLocation(),
3429                  getLangOpts().CPlusPlus
3430                      ? Literal.isLong
3431                            ? diag::warn_old_implicitly_unsigned_long_cxx
3432                            : /*C++98 UB*/ diag::
3433                                  ext_old_implicitly_unsigned_long_cxx
3434                      : diag::warn_old_implicitly_unsigned_long)
3435                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3436                                             : /*will be ill-formed*/ 1);
3437             Ty = Context.UnsignedLongTy;
3438           }
3439           Width = LongSize;
3440         }
3441       }
3442 
3443       // Check long long if needed.
3444       if (Ty.isNull()) {
3445         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3446 
3447         // Does it fit in a unsigned long long?
3448         if (ResultVal.isIntN(LongLongSize)) {
3449           // Does it fit in a signed long long?
3450           // To be compatible with MSVC, hex integer literals ending with the
3451           // LL or i64 suffix are always signed in Microsoft mode.
3452           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3453               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3454             Ty = Context.LongLongTy;
3455           else if (AllowUnsigned)
3456             Ty = Context.UnsignedLongLongTy;
3457           Width = LongLongSize;
3458         }
3459       }
3460 
3461       // If we still couldn't decide a type, we probably have something that
3462       // does not fit in a signed long long, but has no U suffix.
3463       if (Ty.isNull()) {
3464         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3465         Ty = Context.UnsignedLongLongTy;
3466         Width = Context.getTargetInfo().getLongLongWidth();
3467       }
3468 
3469       if (ResultVal.getBitWidth() != Width)
3470         ResultVal = ResultVal.trunc(Width);
3471     }
3472     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3473   }
3474 
3475   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3476   if (Literal.isImaginary) {
3477     Res = new (Context) ImaginaryLiteral(Res,
3478                                         Context.getComplexType(Res->getType()));
3479 
3480     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3481   }
3482   return Res;
3483 }
3484 
3485 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3486   assert(E && "ActOnParenExpr() missing expr");
3487   return new (Context) ParenExpr(L, R, E);
3488 }
3489 
3490 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3491                                          SourceLocation Loc,
3492                                          SourceRange ArgRange) {
3493   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3494   // scalar or vector data type argument..."
3495   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3496   // type (C99 6.2.5p18) or void.
3497   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3498     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3499       << T << ArgRange;
3500     return true;
3501   }
3502 
3503   assert((T->isVoidType() || !T->isIncompleteType()) &&
3504          "Scalar types should always be complete");
3505   return false;
3506 }
3507 
3508 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3509                                            SourceLocation Loc,
3510                                            SourceRange ArgRange,
3511                                            UnaryExprOrTypeTrait TraitKind) {
3512   // Invalid types must be hard errors for SFINAE in C++.
3513   if (S.LangOpts.CPlusPlus)
3514     return true;
3515 
3516   // C99 6.5.3.4p1:
3517   if (T->isFunctionType() &&
3518       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3519     // sizeof(function)/alignof(function) is allowed as an extension.
3520     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3521       << TraitKind << ArgRange;
3522     return false;
3523   }
3524 
3525   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3526   // this is an error (OpenCL v1.1 s6.3.k)
3527   if (T->isVoidType()) {
3528     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3529                                         : diag::ext_sizeof_alignof_void_type;
3530     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3531     return false;
3532   }
3533 
3534   return true;
3535 }
3536 
3537 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3538                                              SourceLocation Loc,
3539                                              SourceRange ArgRange,
3540                                              UnaryExprOrTypeTrait TraitKind) {
3541   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3542   // runtime doesn't allow it.
3543   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3544     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3545       << T << (TraitKind == UETT_SizeOf)
3546       << ArgRange;
3547     return true;
3548   }
3549 
3550   return false;
3551 }
3552 
3553 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3554 /// pointer type is equal to T) and emit a warning if it is.
3555 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3556                                      Expr *E) {
3557   // Don't warn if the operation changed the type.
3558   if (T != E->getType())
3559     return;
3560 
3561   // Now look for array decays.
3562   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3563   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3564     return;
3565 
3566   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3567                                              << ICE->getType()
3568                                              << ICE->getSubExpr()->getType();
3569 }
3570 
3571 /// \brief Check the constraints on expression operands to unary type expression
3572 /// and type traits.
3573 ///
3574 /// Completes any types necessary and validates the constraints on the operand
3575 /// expression. The logic mostly mirrors the type-based overload, but may modify
3576 /// the expression as it completes the type for that expression through template
3577 /// instantiation, etc.
3578 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3579                                             UnaryExprOrTypeTrait ExprKind) {
3580   QualType ExprTy = E->getType();
3581   assert(!ExprTy->isReferenceType());
3582 
3583   if (ExprKind == UETT_VecStep)
3584     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3585                                         E->getSourceRange());
3586 
3587   // Whitelist some types as extensions
3588   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3589                                       E->getSourceRange(), ExprKind))
3590     return false;
3591 
3592   // 'alignof' applied to an expression only requires the base element type of
3593   // the expression to be complete. 'sizeof' requires the expression's type to
3594   // be complete (and will attempt to complete it if it's an array of unknown
3595   // bound).
3596   if (ExprKind == UETT_AlignOf) {
3597     if (RequireCompleteType(E->getExprLoc(),
3598                             Context.getBaseElementType(E->getType()),
3599                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3600                             E->getSourceRange()))
3601       return true;
3602   } else {
3603     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3604                                 ExprKind, E->getSourceRange()))
3605       return true;
3606   }
3607 
3608   // Completing the expression's type may have changed it.
3609   ExprTy = E->getType();
3610   assert(!ExprTy->isReferenceType());
3611 
3612   if (ExprTy->isFunctionType()) {
3613     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3614       << ExprKind << E->getSourceRange();
3615     return true;
3616   }
3617 
3618   // The operand for sizeof and alignof is in an unevaluated expression context,
3619   // so side effects could result in unintended consequences.
3620   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3621       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3622     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3623 
3624   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3625                                        E->getSourceRange(), ExprKind))
3626     return true;
3627 
3628   if (ExprKind == UETT_SizeOf) {
3629     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3630       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3631         QualType OType = PVD->getOriginalType();
3632         QualType Type = PVD->getType();
3633         if (Type->isPointerType() && OType->isArrayType()) {
3634           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3635             << Type << OType;
3636           Diag(PVD->getLocation(), diag::note_declared_at);
3637         }
3638       }
3639     }
3640 
3641     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3642     // decays into a pointer and returns an unintended result. This is most
3643     // likely a typo for "sizeof(array) op x".
3644     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3645       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3646                                BO->getLHS());
3647       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3648                                BO->getRHS());
3649     }
3650   }
3651 
3652   return false;
3653 }
3654 
3655 /// \brief Check the constraints on operands to unary expression and type
3656 /// traits.
3657 ///
3658 /// This will complete any types necessary, and validate the various constraints
3659 /// on those operands.
3660 ///
3661 /// The UsualUnaryConversions() function is *not* called by this routine.
3662 /// C99 6.3.2.1p[2-4] all state:
3663 ///   Except when it is the operand of the sizeof operator ...
3664 ///
3665 /// C++ [expr.sizeof]p4
3666 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3667 ///   standard conversions are not applied to the operand of sizeof.
3668 ///
3669 /// This policy is followed for all of the unary trait expressions.
3670 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3671                                             SourceLocation OpLoc,
3672                                             SourceRange ExprRange,
3673                                             UnaryExprOrTypeTrait ExprKind) {
3674   if (ExprType->isDependentType())
3675     return false;
3676 
3677   // C++ [expr.sizeof]p2:
3678   //     When applied to a reference or a reference type, the result
3679   //     is the size of the referenced type.
3680   // C++11 [expr.alignof]p3:
3681   //     When alignof is applied to a reference type, the result
3682   //     shall be the alignment of the referenced type.
3683   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3684     ExprType = Ref->getPointeeType();
3685 
3686   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3687   //   When alignof or _Alignof is applied to an array type, the result
3688   //   is the alignment of the element type.
3689   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3690     ExprType = Context.getBaseElementType(ExprType);
3691 
3692   if (ExprKind == UETT_VecStep)
3693     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3694 
3695   // Whitelist some types as extensions
3696   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3697                                       ExprKind))
3698     return false;
3699 
3700   if (RequireCompleteType(OpLoc, ExprType,
3701                           diag::err_sizeof_alignof_incomplete_type,
3702                           ExprKind, ExprRange))
3703     return true;
3704 
3705   if (ExprType->isFunctionType()) {
3706     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3707       << ExprKind << ExprRange;
3708     return true;
3709   }
3710 
3711   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3712                                        ExprKind))
3713     return true;
3714 
3715   return false;
3716 }
3717 
3718 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3719   E = E->IgnoreParens();
3720 
3721   // Cannot know anything else if the expression is dependent.
3722   if (E->isTypeDependent())
3723     return false;
3724 
3725   if (E->getObjectKind() == OK_BitField) {
3726     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3727        << 1 << E->getSourceRange();
3728     return true;
3729   }
3730 
3731   ValueDecl *D = nullptr;
3732   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3733     D = DRE->getDecl();
3734   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3735     D = ME->getMemberDecl();
3736   }
3737 
3738   // If it's a field, require the containing struct to have a
3739   // complete definition so that we can compute the layout.
3740   //
3741   // This can happen in C++11 onwards, either by naming the member
3742   // in a way that is not transformed into a member access expression
3743   // (in an unevaluated operand, for instance), or by naming the member
3744   // in a trailing-return-type.
3745   //
3746   // For the record, since __alignof__ on expressions is a GCC
3747   // extension, GCC seems to permit this but always gives the
3748   // nonsensical answer 0.
3749   //
3750   // We don't really need the layout here --- we could instead just
3751   // directly check for all the appropriate alignment-lowing
3752   // attributes --- but that would require duplicating a lot of
3753   // logic that just isn't worth duplicating for such a marginal
3754   // use-case.
3755   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3756     // Fast path this check, since we at least know the record has a
3757     // definition if we can find a member of it.
3758     if (!FD->getParent()->isCompleteDefinition()) {
3759       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3760         << E->getSourceRange();
3761       return true;
3762     }
3763 
3764     // Otherwise, if it's a field, and the field doesn't have
3765     // reference type, then it must have a complete type (or be a
3766     // flexible array member, which we explicitly want to
3767     // white-list anyway), which makes the following checks trivial.
3768     if (!FD->getType()->isReferenceType())
3769       return false;
3770   }
3771 
3772   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3773 }
3774 
3775 bool Sema::CheckVecStepExpr(Expr *E) {
3776   E = E->IgnoreParens();
3777 
3778   // Cannot know anything else if the expression is dependent.
3779   if (E->isTypeDependent())
3780     return false;
3781 
3782   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3783 }
3784 
3785 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3786                                         CapturingScopeInfo *CSI) {
3787   assert(T->isVariablyModifiedType());
3788   assert(CSI != nullptr);
3789 
3790   // We're going to walk down into the type and look for VLA expressions.
3791   do {
3792     const Type *Ty = T.getTypePtr();
3793     switch (Ty->getTypeClass()) {
3794 #define TYPE(Class, Base)
3795 #define ABSTRACT_TYPE(Class, Base)
3796 #define NON_CANONICAL_TYPE(Class, Base)
3797 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3798 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3799 #include "clang/AST/TypeNodes.def"
3800       T = QualType();
3801       break;
3802     // These types are never variably-modified.
3803     case Type::Builtin:
3804     case Type::Complex:
3805     case Type::Vector:
3806     case Type::ExtVector:
3807     case Type::Record:
3808     case Type::Enum:
3809     case Type::Elaborated:
3810     case Type::TemplateSpecialization:
3811     case Type::ObjCObject:
3812     case Type::ObjCInterface:
3813     case Type::ObjCObjectPointer:
3814     case Type::ObjCTypeParam:
3815     case Type::Pipe:
3816       llvm_unreachable("type class is never variably-modified!");
3817     case Type::Adjusted:
3818       T = cast<AdjustedType>(Ty)->getOriginalType();
3819       break;
3820     case Type::Decayed:
3821       T = cast<DecayedType>(Ty)->getPointeeType();
3822       break;
3823     case Type::Pointer:
3824       T = cast<PointerType>(Ty)->getPointeeType();
3825       break;
3826     case Type::BlockPointer:
3827       T = cast<BlockPointerType>(Ty)->getPointeeType();
3828       break;
3829     case Type::LValueReference:
3830     case Type::RValueReference:
3831       T = cast<ReferenceType>(Ty)->getPointeeType();
3832       break;
3833     case Type::MemberPointer:
3834       T = cast<MemberPointerType>(Ty)->getPointeeType();
3835       break;
3836     case Type::ConstantArray:
3837     case Type::IncompleteArray:
3838       // Losing element qualification here is fine.
3839       T = cast<ArrayType>(Ty)->getElementType();
3840       break;
3841     case Type::VariableArray: {
3842       // Losing element qualification here is fine.
3843       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3844 
3845       // Unknown size indication requires no size computation.
3846       // Otherwise, evaluate and record it.
3847       if (auto Size = VAT->getSizeExpr()) {
3848         if (!CSI->isVLATypeCaptured(VAT)) {
3849           RecordDecl *CapRecord = nullptr;
3850           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3851             CapRecord = LSI->Lambda;
3852           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3853             CapRecord = CRSI->TheRecordDecl;
3854           }
3855           if (CapRecord) {
3856             auto ExprLoc = Size->getExprLoc();
3857             auto SizeType = Context.getSizeType();
3858             // Build the non-static data member.
3859             auto Field =
3860                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3861                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3862                                   /*BW*/ nullptr, /*Mutable*/ false,
3863                                   /*InitStyle*/ ICIS_NoInit);
3864             Field->setImplicit(true);
3865             Field->setAccess(AS_private);
3866             Field->setCapturedVLAType(VAT);
3867             CapRecord->addDecl(Field);
3868 
3869             CSI->addVLATypeCapture(ExprLoc, SizeType);
3870           }
3871         }
3872       }
3873       T = VAT->getElementType();
3874       break;
3875     }
3876     case Type::FunctionProto:
3877     case Type::FunctionNoProto:
3878       T = cast<FunctionType>(Ty)->getReturnType();
3879       break;
3880     case Type::Paren:
3881     case Type::TypeOf:
3882     case Type::UnaryTransform:
3883     case Type::Attributed:
3884     case Type::SubstTemplateTypeParm:
3885     case Type::PackExpansion:
3886       // Keep walking after single level desugaring.
3887       T = T.getSingleStepDesugaredType(Context);
3888       break;
3889     case Type::Typedef:
3890       T = cast<TypedefType>(Ty)->desugar();
3891       break;
3892     case Type::Decltype:
3893       T = cast<DecltypeType>(Ty)->desugar();
3894       break;
3895     case Type::Auto:
3896     case Type::DeducedTemplateSpecialization:
3897       T = cast<DeducedType>(Ty)->getDeducedType();
3898       break;
3899     case Type::TypeOfExpr:
3900       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3901       break;
3902     case Type::Atomic:
3903       T = cast<AtomicType>(Ty)->getValueType();
3904       break;
3905     }
3906   } while (!T.isNull() && T->isVariablyModifiedType());
3907 }
3908 
3909 /// \brief Build a sizeof or alignof expression given a type operand.
3910 ExprResult
3911 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3912                                      SourceLocation OpLoc,
3913                                      UnaryExprOrTypeTrait ExprKind,
3914                                      SourceRange R) {
3915   if (!TInfo)
3916     return ExprError();
3917 
3918   QualType T = TInfo->getType();
3919 
3920   if (!T->isDependentType() &&
3921       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3922     return ExprError();
3923 
3924   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3925     if (auto *TT = T->getAs<TypedefType>()) {
3926       for (auto I = FunctionScopes.rbegin(),
3927                 E = std::prev(FunctionScopes.rend());
3928            I != E; ++I) {
3929         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3930         if (CSI == nullptr)
3931           break;
3932         DeclContext *DC = nullptr;
3933         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
3934           DC = LSI->CallOperator;
3935         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
3936           DC = CRSI->TheCapturedDecl;
3937         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
3938           DC = BSI->TheDecl;
3939         if (DC) {
3940           if (DC->containsDecl(TT->getDecl()))
3941             break;
3942           captureVariablyModifiedType(Context, T, CSI);
3943         }
3944       }
3945     }
3946   }
3947 
3948   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3949   return new (Context) UnaryExprOrTypeTraitExpr(
3950       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3951 }
3952 
3953 /// \brief Build a sizeof or alignof expression given an expression
3954 /// operand.
3955 ExprResult
3956 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3957                                      UnaryExprOrTypeTrait ExprKind) {
3958   ExprResult PE = CheckPlaceholderExpr(E);
3959   if (PE.isInvalid())
3960     return ExprError();
3961 
3962   E = PE.get();
3963 
3964   // Verify that the operand is valid.
3965   bool isInvalid = false;
3966   if (E->isTypeDependent()) {
3967     // Delay type-checking for type-dependent expressions.
3968   } else if (ExprKind == UETT_AlignOf) {
3969     isInvalid = CheckAlignOfExpr(*this, E);
3970   } else if (ExprKind == UETT_VecStep) {
3971     isInvalid = CheckVecStepExpr(E);
3972   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
3973       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
3974       isInvalid = true;
3975   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3976     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
3977     isInvalid = true;
3978   } else {
3979     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3980   }
3981 
3982   if (isInvalid)
3983     return ExprError();
3984 
3985   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3986     PE = TransformToPotentiallyEvaluated(E);
3987     if (PE.isInvalid()) return ExprError();
3988     E = PE.get();
3989   }
3990 
3991   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3992   return new (Context) UnaryExprOrTypeTraitExpr(
3993       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
3994 }
3995 
3996 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3997 /// expr and the same for @c alignof and @c __alignof
3998 /// Note that the ArgRange is invalid if isType is false.
3999 ExprResult
4000 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4001                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4002                                     void *TyOrEx, SourceRange ArgRange) {
4003   // If error parsing type, ignore.
4004   if (!TyOrEx) return ExprError();
4005 
4006   if (IsType) {
4007     TypeSourceInfo *TInfo;
4008     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4009     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4010   }
4011 
4012   Expr *ArgEx = (Expr *)TyOrEx;
4013   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4014   return Result;
4015 }
4016 
4017 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4018                                      bool IsReal) {
4019   if (V.get()->isTypeDependent())
4020     return S.Context.DependentTy;
4021 
4022   // _Real and _Imag are only l-values for normal l-values.
4023   if (V.get()->getObjectKind() != OK_Ordinary) {
4024     V = S.DefaultLvalueConversion(V.get());
4025     if (V.isInvalid())
4026       return QualType();
4027   }
4028 
4029   // These operators return the element type of a complex type.
4030   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4031     return CT->getElementType();
4032 
4033   // Otherwise they pass through real integer and floating point types here.
4034   if (V.get()->getType()->isArithmeticType())
4035     return V.get()->getType();
4036 
4037   // Test for placeholders.
4038   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4039   if (PR.isInvalid()) return QualType();
4040   if (PR.get() != V.get()) {
4041     V = PR;
4042     return CheckRealImagOperand(S, V, Loc, IsReal);
4043   }
4044 
4045   // Reject anything else.
4046   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4047     << (IsReal ? "__real" : "__imag");
4048   return QualType();
4049 }
4050 
4051 
4052 
4053 ExprResult
4054 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4055                           tok::TokenKind Kind, Expr *Input) {
4056   UnaryOperatorKind Opc;
4057   switch (Kind) {
4058   default: llvm_unreachable("Unknown unary op!");
4059   case tok::plusplus:   Opc = UO_PostInc; break;
4060   case tok::minusminus: Opc = UO_PostDec; break;
4061   }
4062 
4063   // Since this might is a postfix expression, get rid of ParenListExprs.
4064   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4065   if (Result.isInvalid()) return ExprError();
4066   Input = Result.get();
4067 
4068   return BuildUnaryOp(S, OpLoc, Opc, Input);
4069 }
4070 
4071 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4072 ///
4073 /// \return true on error
4074 static bool checkArithmeticOnObjCPointer(Sema &S,
4075                                          SourceLocation opLoc,
4076                                          Expr *op) {
4077   assert(op->getType()->isObjCObjectPointerType());
4078   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4079       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4080     return false;
4081 
4082   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4083     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4084     << op->getSourceRange();
4085   return true;
4086 }
4087 
4088 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4089   auto *BaseNoParens = Base->IgnoreParens();
4090   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4091     return MSProp->getPropertyDecl()->getType()->isArrayType();
4092   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4093 }
4094 
4095 ExprResult
4096 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4097                               Expr *idx, SourceLocation rbLoc) {
4098   if (base && !base->getType().isNull() &&
4099       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4100     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4101                                     /*Length=*/nullptr, rbLoc);
4102 
4103   // Since this might be a postfix expression, get rid of ParenListExprs.
4104   if (isa<ParenListExpr>(base)) {
4105     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4106     if (result.isInvalid()) return ExprError();
4107     base = result.get();
4108   }
4109 
4110   // Handle any non-overload placeholder types in the base and index
4111   // expressions.  We can't handle overloads here because the other
4112   // operand might be an overloadable type, in which case the overload
4113   // resolution for the operator overload should get the first crack
4114   // at the overload.
4115   bool IsMSPropertySubscript = false;
4116   if (base->getType()->isNonOverloadPlaceholderType()) {
4117     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4118     if (!IsMSPropertySubscript) {
4119       ExprResult result = CheckPlaceholderExpr(base);
4120       if (result.isInvalid())
4121         return ExprError();
4122       base = result.get();
4123     }
4124   }
4125   if (idx->getType()->isNonOverloadPlaceholderType()) {
4126     ExprResult result = CheckPlaceholderExpr(idx);
4127     if (result.isInvalid()) return ExprError();
4128     idx = result.get();
4129   }
4130 
4131   // Build an unanalyzed expression if either operand is type-dependent.
4132   if (getLangOpts().CPlusPlus &&
4133       (base->isTypeDependent() || idx->isTypeDependent())) {
4134     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4135                                             VK_LValue, OK_Ordinary, rbLoc);
4136   }
4137 
4138   // MSDN, property (C++)
4139   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4140   // This attribute can also be used in the declaration of an empty array in a
4141   // class or structure definition. For example:
4142   // __declspec(property(get=GetX, put=PutX)) int x[];
4143   // The above statement indicates that x[] can be used with one or more array
4144   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4145   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4146   if (IsMSPropertySubscript) {
4147     // Build MS property subscript expression if base is MS property reference
4148     // or MS property subscript.
4149     return new (Context) MSPropertySubscriptExpr(
4150         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4151   }
4152 
4153   // Use C++ overloaded-operator rules if either operand has record
4154   // type.  The spec says to do this if either type is *overloadable*,
4155   // but enum types can't declare subscript operators or conversion
4156   // operators, so there's nothing interesting for overload resolution
4157   // to do if there aren't any record types involved.
4158   //
4159   // ObjC pointers have their own subscripting logic that is not tied
4160   // to overload resolution and so should not take this path.
4161   if (getLangOpts().CPlusPlus &&
4162       (base->getType()->isRecordType() ||
4163        (!base->getType()->isObjCObjectPointerType() &&
4164         idx->getType()->isRecordType()))) {
4165     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4166   }
4167 
4168   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4169 }
4170 
4171 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4172                                           Expr *LowerBound,
4173                                           SourceLocation ColonLoc, Expr *Length,
4174                                           SourceLocation RBLoc) {
4175   if (Base->getType()->isPlaceholderType() &&
4176       !Base->getType()->isSpecificPlaceholderType(
4177           BuiltinType::OMPArraySection)) {
4178     ExprResult Result = CheckPlaceholderExpr(Base);
4179     if (Result.isInvalid())
4180       return ExprError();
4181     Base = Result.get();
4182   }
4183   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4184     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4185     if (Result.isInvalid())
4186       return ExprError();
4187     Result = DefaultLvalueConversion(Result.get());
4188     if (Result.isInvalid())
4189       return ExprError();
4190     LowerBound = Result.get();
4191   }
4192   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4193     ExprResult Result = CheckPlaceholderExpr(Length);
4194     if (Result.isInvalid())
4195       return ExprError();
4196     Result = DefaultLvalueConversion(Result.get());
4197     if (Result.isInvalid())
4198       return ExprError();
4199     Length = Result.get();
4200   }
4201 
4202   // Build an unanalyzed expression if either operand is type-dependent.
4203   if (Base->isTypeDependent() ||
4204       (LowerBound &&
4205        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4206       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4207     return new (Context)
4208         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4209                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4210   }
4211 
4212   // Perform default conversions.
4213   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4214   QualType ResultTy;
4215   if (OriginalTy->isAnyPointerType()) {
4216     ResultTy = OriginalTy->getPointeeType();
4217   } else if (OriginalTy->isArrayType()) {
4218     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4219   } else {
4220     return ExprError(
4221         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4222         << Base->getSourceRange());
4223   }
4224   // C99 6.5.2.1p1
4225   if (LowerBound) {
4226     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4227                                                       LowerBound);
4228     if (Res.isInvalid())
4229       return ExprError(Diag(LowerBound->getExprLoc(),
4230                             diag::err_omp_typecheck_section_not_integer)
4231                        << 0 << LowerBound->getSourceRange());
4232     LowerBound = Res.get();
4233 
4234     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4235         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4236       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4237           << 0 << LowerBound->getSourceRange();
4238   }
4239   if (Length) {
4240     auto Res =
4241         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4242     if (Res.isInvalid())
4243       return ExprError(Diag(Length->getExprLoc(),
4244                             diag::err_omp_typecheck_section_not_integer)
4245                        << 1 << Length->getSourceRange());
4246     Length = Res.get();
4247 
4248     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4249         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4250       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4251           << 1 << Length->getSourceRange();
4252   }
4253 
4254   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4255   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4256   // type. Note that functions are not objects, and that (in C99 parlance)
4257   // incomplete types are not object types.
4258   if (ResultTy->isFunctionType()) {
4259     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4260         << ResultTy << Base->getSourceRange();
4261     return ExprError();
4262   }
4263 
4264   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4265                           diag::err_omp_section_incomplete_type, Base))
4266     return ExprError();
4267 
4268   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4269     llvm::APSInt LowerBoundValue;
4270     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4271       // OpenMP 4.5, [2.4 Array Sections]
4272       // The array section must be a subset of the original array.
4273       if (LowerBoundValue.isNegative()) {
4274         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4275             << LowerBound->getSourceRange();
4276         return ExprError();
4277       }
4278     }
4279   }
4280 
4281   if (Length) {
4282     llvm::APSInt LengthValue;
4283     if (Length->EvaluateAsInt(LengthValue, Context)) {
4284       // OpenMP 4.5, [2.4 Array Sections]
4285       // The length must evaluate to non-negative integers.
4286       if (LengthValue.isNegative()) {
4287         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4288             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4289             << Length->getSourceRange();
4290         return ExprError();
4291       }
4292     }
4293   } else if (ColonLoc.isValid() &&
4294              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4295                                       !OriginalTy->isVariableArrayType()))) {
4296     // OpenMP 4.5, [2.4 Array Sections]
4297     // When the size of the array dimension is not known, the length must be
4298     // specified explicitly.
4299     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4300         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4301     return ExprError();
4302   }
4303 
4304   if (!Base->getType()->isSpecificPlaceholderType(
4305           BuiltinType::OMPArraySection)) {
4306     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4307     if (Result.isInvalid())
4308       return ExprError();
4309     Base = Result.get();
4310   }
4311   return new (Context)
4312       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4313                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4314 }
4315 
4316 ExprResult
4317 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4318                                       Expr *Idx, SourceLocation RLoc) {
4319   Expr *LHSExp = Base;
4320   Expr *RHSExp = Idx;
4321 
4322   ExprValueKind VK = VK_LValue;
4323   ExprObjectKind OK = OK_Ordinary;
4324 
4325   // Per C++ core issue 1213, the result is an xvalue if either operand is
4326   // a non-lvalue array, and an lvalue otherwise.
4327   if (getLangOpts().CPlusPlus11 &&
4328       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4329        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4330     VK = VK_XValue;
4331 
4332   // Perform default conversions.
4333   if (!LHSExp->getType()->getAs<VectorType>()) {
4334     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4335     if (Result.isInvalid())
4336       return ExprError();
4337     LHSExp = Result.get();
4338   }
4339   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4340   if (Result.isInvalid())
4341     return ExprError();
4342   RHSExp = Result.get();
4343 
4344   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4345 
4346   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4347   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4348   // in the subscript position. As a result, we need to derive the array base
4349   // and index from the expression types.
4350   Expr *BaseExpr, *IndexExpr;
4351   QualType ResultType;
4352   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4353     BaseExpr = LHSExp;
4354     IndexExpr = RHSExp;
4355     ResultType = Context.DependentTy;
4356   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4357     BaseExpr = LHSExp;
4358     IndexExpr = RHSExp;
4359     ResultType = PTy->getPointeeType();
4360   } else if (const ObjCObjectPointerType *PTy =
4361                LHSTy->getAs<ObjCObjectPointerType>()) {
4362     BaseExpr = LHSExp;
4363     IndexExpr = RHSExp;
4364 
4365     // Use custom logic if this should be the pseudo-object subscript
4366     // expression.
4367     if (!LangOpts.isSubscriptPointerArithmetic())
4368       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4369                                           nullptr);
4370 
4371     ResultType = PTy->getPointeeType();
4372   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4373      // Handle the uncommon case of "123[Ptr]".
4374     BaseExpr = RHSExp;
4375     IndexExpr = LHSExp;
4376     ResultType = PTy->getPointeeType();
4377   } else if (const ObjCObjectPointerType *PTy =
4378                RHSTy->getAs<ObjCObjectPointerType>()) {
4379      // Handle the uncommon case of "123[Ptr]".
4380     BaseExpr = RHSExp;
4381     IndexExpr = LHSExp;
4382     ResultType = PTy->getPointeeType();
4383     if (!LangOpts.isSubscriptPointerArithmetic()) {
4384       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4385         << ResultType << BaseExpr->getSourceRange();
4386       return ExprError();
4387     }
4388   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4389     BaseExpr = LHSExp;    // vectors: V[123]
4390     IndexExpr = RHSExp;
4391     VK = LHSExp->getValueKind();
4392     if (VK != VK_RValue)
4393       OK = OK_VectorComponent;
4394 
4395     // FIXME: need to deal with const...
4396     ResultType = VTy->getElementType();
4397   } else if (LHSTy->isArrayType()) {
4398     // If we see an array that wasn't promoted by
4399     // DefaultFunctionArrayLvalueConversion, it must be an array that
4400     // wasn't promoted because of the C90 rule that doesn't
4401     // allow promoting non-lvalue arrays.  Warn, then
4402     // force the promotion here.
4403     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4404         LHSExp->getSourceRange();
4405     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4406                                CK_ArrayToPointerDecay).get();
4407     LHSTy = LHSExp->getType();
4408 
4409     BaseExpr = LHSExp;
4410     IndexExpr = RHSExp;
4411     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4412   } else if (RHSTy->isArrayType()) {
4413     // Same as previous, except for 123[f().a] case
4414     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4415         RHSExp->getSourceRange();
4416     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4417                                CK_ArrayToPointerDecay).get();
4418     RHSTy = RHSExp->getType();
4419 
4420     BaseExpr = RHSExp;
4421     IndexExpr = LHSExp;
4422     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4423   } else {
4424     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4425        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4426   }
4427   // C99 6.5.2.1p1
4428   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4429     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4430                      << IndexExpr->getSourceRange());
4431 
4432   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4433        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4434          && !IndexExpr->isTypeDependent())
4435     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4436 
4437   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4438   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4439   // type. Note that Functions are not objects, and that (in C99 parlance)
4440   // incomplete types are not object types.
4441   if (ResultType->isFunctionType()) {
4442     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4443       << ResultType << BaseExpr->getSourceRange();
4444     return ExprError();
4445   }
4446 
4447   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4448     // GNU extension: subscripting on pointer to void
4449     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4450       << BaseExpr->getSourceRange();
4451 
4452     // C forbids expressions of unqualified void type from being l-values.
4453     // See IsCForbiddenLValueType.
4454     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4455   } else if (!ResultType->isDependentType() &&
4456       RequireCompleteType(LLoc, ResultType,
4457                           diag::err_subscript_incomplete_type, BaseExpr))
4458     return ExprError();
4459 
4460   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4461          !ResultType.isCForbiddenLValueType());
4462 
4463   return new (Context)
4464       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4465 }
4466 
4467 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4468                                   ParmVarDecl *Param) {
4469   if (Param->hasUnparsedDefaultArg()) {
4470     Diag(CallLoc,
4471          diag::err_use_of_default_argument_to_function_declared_later) <<
4472       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4473     Diag(UnparsedDefaultArgLocs[Param],
4474          diag::note_default_argument_declared_here);
4475     return true;
4476   }
4477 
4478   if (Param->hasUninstantiatedDefaultArg()) {
4479     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4480 
4481     EnterExpressionEvaluationContext EvalContext(
4482         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4483 
4484     // Instantiate the expression.
4485     //
4486     // FIXME: Pass in a correct Pattern argument, otherwise
4487     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4488     //
4489     // template<typename T>
4490     // struct A {
4491     //   static int FooImpl();
4492     //
4493     //   template<typename Tp>
4494     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4495     //   // template argument list [[T], [Tp]], should be [[Tp]].
4496     //   friend A<Tp> Foo(int a);
4497     // };
4498     //
4499     // template<typename T>
4500     // A<T> Foo(int a = A<T>::FooImpl());
4501     MultiLevelTemplateArgumentList MutiLevelArgList
4502       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4503 
4504     InstantiatingTemplate Inst(*this, CallLoc, Param,
4505                                MutiLevelArgList.getInnermost());
4506     if (Inst.isInvalid())
4507       return true;
4508     if (Inst.isAlreadyInstantiating()) {
4509       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4510       Param->setInvalidDecl();
4511       return true;
4512     }
4513 
4514     ExprResult Result;
4515     {
4516       // C++ [dcl.fct.default]p5:
4517       //   The names in the [default argument] expression are bound, and
4518       //   the semantic constraints are checked, at the point where the
4519       //   default argument expression appears.
4520       ContextRAII SavedContext(*this, FD);
4521       LocalInstantiationScope Local(*this);
4522       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4523                                 /*DirectInit*/false);
4524     }
4525     if (Result.isInvalid())
4526       return true;
4527 
4528     // Check the expression as an initializer for the parameter.
4529     InitializedEntity Entity
4530       = InitializedEntity::InitializeParameter(Context, Param);
4531     InitializationKind Kind
4532       = InitializationKind::CreateCopy(Param->getLocation(),
4533              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4534     Expr *ResultE = Result.getAs<Expr>();
4535 
4536     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4537     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4538     if (Result.isInvalid())
4539       return true;
4540 
4541     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4542                                  Param->getOuterLocStart());
4543     if (Result.isInvalid())
4544       return true;
4545 
4546     // Remember the instantiated default argument.
4547     Param->setDefaultArg(Result.getAs<Expr>());
4548     if (ASTMutationListener *L = getASTMutationListener()) {
4549       L->DefaultArgumentInstantiated(Param);
4550     }
4551   }
4552 
4553   // If the default argument expression is not set yet, we are building it now.
4554   if (!Param->hasInit()) {
4555     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4556     Param->setInvalidDecl();
4557     return true;
4558   }
4559 
4560   // If the default expression creates temporaries, we need to
4561   // push them to the current stack of expression temporaries so they'll
4562   // be properly destroyed.
4563   // FIXME: We should really be rebuilding the default argument with new
4564   // bound temporaries; see the comment in PR5810.
4565   // We don't need to do that with block decls, though, because
4566   // blocks in default argument expression can never capture anything.
4567   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4568     // Set the "needs cleanups" bit regardless of whether there are
4569     // any explicit objects.
4570     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4571 
4572     // Append all the objects to the cleanup list.  Right now, this
4573     // should always be a no-op, because blocks in default argument
4574     // expressions should never be able to capture anything.
4575     assert(!Init->getNumObjects() &&
4576            "default argument expression has capturing blocks?");
4577   }
4578 
4579   // We already type-checked the argument, so we know it works.
4580   // Just mark all of the declarations in this potentially-evaluated expression
4581   // as being "referenced".
4582   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4583                                    /*SkipLocalVariables=*/true);
4584   return false;
4585 }
4586 
4587 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4588                                         FunctionDecl *FD, ParmVarDecl *Param) {
4589   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4590     return ExprError();
4591   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4592 }
4593 
4594 Sema::VariadicCallType
4595 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4596                           Expr *Fn) {
4597   if (Proto && Proto->isVariadic()) {
4598     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4599       return VariadicConstructor;
4600     else if (Fn && Fn->getType()->isBlockPointerType())
4601       return VariadicBlock;
4602     else if (FDecl) {
4603       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4604         if (Method->isInstance())
4605           return VariadicMethod;
4606     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4607       return VariadicMethod;
4608     return VariadicFunction;
4609   }
4610   return VariadicDoesNotApply;
4611 }
4612 
4613 namespace {
4614 class FunctionCallCCC : public FunctionCallFilterCCC {
4615 public:
4616   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4617                   unsigned NumArgs, MemberExpr *ME)
4618       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4619         FunctionName(FuncName) {}
4620 
4621   bool ValidateCandidate(const TypoCorrection &candidate) override {
4622     if (!candidate.getCorrectionSpecifier() ||
4623         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4624       return false;
4625     }
4626 
4627     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4628   }
4629 
4630 private:
4631   const IdentifierInfo *const FunctionName;
4632 };
4633 }
4634 
4635 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4636                                                FunctionDecl *FDecl,
4637                                                ArrayRef<Expr *> Args) {
4638   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4639   DeclarationName FuncName = FDecl->getDeclName();
4640   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4641 
4642   if (TypoCorrection Corrected = S.CorrectTypo(
4643           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4644           S.getScopeForContext(S.CurContext), nullptr,
4645           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4646                                              Args.size(), ME),
4647           Sema::CTK_ErrorRecovery)) {
4648     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4649       if (Corrected.isOverloaded()) {
4650         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4651         OverloadCandidateSet::iterator Best;
4652         for (NamedDecl *CD : Corrected) {
4653           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4654             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4655                                    OCS);
4656         }
4657         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4658         case OR_Success:
4659           ND = Best->FoundDecl;
4660           Corrected.setCorrectionDecl(ND);
4661           break;
4662         default:
4663           break;
4664         }
4665       }
4666       ND = ND->getUnderlyingDecl();
4667       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4668         return Corrected;
4669     }
4670   }
4671   return TypoCorrection();
4672 }
4673 
4674 /// ConvertArgumentsForCall - Converts the arguments specified in
4675 /// Args/NumArgs to the parameter types of the function FDecl with
4676 /// function prototype Proto. Call is the call expression itself, and
4677 /// Fn is the function expression. For a C++ member function, this
4678 /// routine does not attempt to convert the object argument. Returns
4679 /// true if the call is ill-formed.
4680 bool
4681 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4682                               FunctionDecl *FDecl,
4683                               const FunctionProtoType *Proto,
4684                               ArrayRef<Expr *> Args,
4685                               SourceLocation RParenLoc,
4686                               bool IsExecConfig) {
4687   // Bail out early if calling a builtin with custom typechecking.
4688   if (FDecl)
4689     if (unsigned ID = FDecl->getBuiltinID())
4690       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4691         return false;
4692 
4693   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4694   // assignment, to the types of the corresponding parameter, ...
4695   unsigned NumParams = Proto->getNumParams();
4696   bool Invalid = false;
4697   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4698   unsigned FnKind = Fn->getType()->isBlockPointerType()
4699                        ? 1 /* block */
4700                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4701                                        : 0 /* function */);
4702 
4703   // If too few arguments are available (and we don't have default
4704   // arguments for the remaining parameters), don't make the call.
4705   if (Args.size() < NumParams) {
4706     if (Args.size() < MinArgs) {
4707       TypoCorrection TC;
4708       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4709         unsigned diag_id =
4710             MinArgs == NumParams && !Proto->isVariadic()
4711                 ? diag::err_typecheck_call_too_few_args_suggest
4712                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4713         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4714                                         << static_cast<unsigned>(Args.size())
4715                                         << TC.getCorrectionRange());
4716       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4717         Diag(RParenLoc,
4718              MinArgs == NumParams && !Proto->isVariadic()
4719                  ? diag::err_typecheck_call_too_few_args_one
4720                  : diag::err_typecheck_call_too_few_args_at_least_one)
4721             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4722       else
4723         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4724                             ? diag::err_typecheck_call_too_few_args
4725                             : diag::err_typecheck_call_too_few_args_at_least)
4726             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4727             << Fn->getSourceRange();
4728 
4729       // Emit the location of the prototype.
4730       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4731         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4732           << FDecl;
4733 
4734       return true;
4735     }
4736     Call->setNumArgs(Context, NumParams);
4737   }
4738 
4739   // If too many are passed and not variadic, error on the extras and drop
4740   // them.
4741   if (Args.size() > NumParams) {
4742     if (!Proto->isVariadic()) {
4743       TypoCorrection TC;
4744       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4745         unsigned diag_id =
4746             MinArgs == NumParams && !Proto->isVariadic()
4747                 ? diag::err_typecheck_call_too_many_args_suggest
4748                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4749         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4750                                         << static_cast<unsigned>(Args.size())
4751                                         << TC.getCorrectionRange());
4752       } else if (NumParams == 1 && FDecl &&
4753                  FDecl->getParamDecl(0)->getDeclName())
4754         Diag(Args[NumParams]->getLocStart(),
4755              MinArgs == NumParams
4756                  ? diag::err_typecheck_call_too_many_args_one
4757                  : diag::err_typecheck_call_too_many_args_at_most_one)
4758             << FnKind << FDecl->getParamDecl(0)
4759             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4760             << SourceRange(Args[NumParams]->getLocStart(),
4761                            Args.back()->getLocEnd());
4762       else
4763         Diag(Args[NumParams]->getLocStart(),
4764              MinArgs == NumParams
4765                  ? diag::err_typecheck_call_too_many_args
4766                  : diag::err_typecheck_call_too_many_args_at_most)
4767             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4768             << Fn->getSourceRange()
4769             << SourceRange(Args[NumParams]->getLocStart(),
4770                            Args.back()->getLocEnd());
4771 
4772       // Emit the location of the prototype.
4773       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4774         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4775           << FDecl;
4776 
4777       // This deletes the extra arguments.
4778       Call->setNumArgs(Context, NumParams);
4779       return true;
4780     }
4781   }
4782   SmallVector<Expr *, 8> AllArgs;
4783   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4784 
4785   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4786                                    Proto, 0, Args, AllArgs, CallType);
4787   if (Invalid)
4788     return true;
4789   unsigned TotalNumArgs = AllArgs.size();
4790   for (unsigned i = 0; i < TotalNumArgs; ++i)
4791     Call->setArg(i, AllArgs[i]);
4792 
4793   return false;
4794 }
4795 
4796 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4797                                   const FunctionProtoType *Proto,
4798                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4799                                   SmallVectorImpl<Expr *> &AllArgs,
4800                                   VariadicCallType CallType, bool AllowExplicit,
4801                                   bool IsListInitialization) {
4802   unsigned NumParams = Proto->getNumParams();
4803   bool Invalid = false;
4804   size_t ArgIx = 0;
4805   // Continue to check argument types (even if we have too few/many args).
4806   for (unsigned i = FirstParam; i < NumParams; i++) {
4807     QualType ProtoArgType = Proto->getParamType(i);
4808 
4809     Expr *Arg;
4810     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4811     if (ArgIx < Args.size()) {
4812       Arg = Args[ArgIx++];
4813 
4814       if (RequireCompleteType(Arg->getLocStart(),
4815                               ProtoArgType,
4816                               diag::err_call_incomplete_argument, Arg))
4817         return true;
4818 
4819       // Strip the unbridged-cast placeholder expression off, if applicable.
4820       bool CFAudited = false;
4821       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4822           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4823           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4824         Arg = stripARCUnbridgedCast(Arg);
4825       else if (getLangOpts().ObjCAutoRefCount &&
4826                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4827                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4828         CFAudited = true;
4829 
4830       InitializedEntity Entity =
4831           Param ? InitializedEntity::InitializeParameter(Context, Param,
4832                                                          ProtoArgType)
4833                 : InitializedEntity::InitializeParameter(
4834                       Context, ProtoArgType, Proto->isParamConsumed(i));
4835 
4836       // Remember that parameter belongs to a CF audited API.
4837       if (CFAudited)
4838         Entity.setParameterCFAudited();
4839 
4840       ExprResult ArgE = PerformCopyInitialization(
4841           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4842       if (ArgE.isInvalid())
4843         return true;
4844 
4845       Arg = ArgE.getAs<Expr>();
4846     } else {
4847       assert(Param && "can't use default arguments without a known callee");
4848 
4849       ExprResult ArgExpr =
4850         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4851       if (ArgExpr.isInvalid())
4852         return true;
4853 
4854       Arg = ArgExpr.getAs<Expr>();
4855     }
4856 
4857     // Check for array bounds violations for each argument to the call. This
4858     // check only triggers warnings when the argument isn't a more complex Expr
4859     // with its own checking, such as a BinaryOperator.
4860     CheckArrayAccess(Arg);
4861 
4862     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4863     CheckStaticArrayArgument(CallLoc, Param, Arg);
4864 
4865     AllArgs.push_back(Arg);
4866   }
4867 
4868   // If this is a variadic call, handle args passed through "...".
4869   if (CallType != VariadicDoesNotApply) {
4870     // Assume that extern "C" functions with variadic arguments that
4871     // return __unknown_anytype aren't *really* variadic.
4872     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4873         FDecl->isExternC()) {
4874       for (Expr *A : Args.slice(ArgIx)) {
4875         QualType paramType; // ignored
4876         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4877         Invalid |= arg.isInvalid();
4878         AllArgs.push_back(arg.get());
4879       }
4880 
4881     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4882     } else {
4883       for (Expr *A : Args.slice(ArgIx)) {
4884         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4885         Invalid |= Arg.isInvalid();
4886         AllArgs.push_back(Arg.get());
4887       }
4888     }
4889 
4890     // Check for array bounds violations.
4891     for (Expr *A : Args.slice(ArgIx))
4892       CheckArrayAccess(A);
4893   }
4894   return Invalid;
4895 }
4896 
4897 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4898   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4899   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4900     TL = DTL.getOriginalLoc();
4901   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4902     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4903       << ATL.getLocalSourceRange();
4904 }
4905 
4906 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4907 /// array parameter, check that it is non-null, and that if it is formed by
4908 /// array-to-pointer decay, the underlying array is sufficiently large.
4909 ///
4910 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4911 /// array type derivation, then for each call to the function, the value of the
4912 /// corresponding actual argument shall provide access to the first element of
4913 /// an array with at least as many elements as specified by the size expression.
4914 void
4915 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4916                                ParmVarDecl *Param,
4917                                const Expr *ArgExpr) {
4918   // Static array parameters are not supported in C++.
4919   if (!Param || getLangOpts().CPlusPlus)
4920     return;
4921 
4922   QualType OrigTy = Param->getOriginalType();
4923 
4924   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4925   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4926     return;
4927 
4928   if (ArgExpr->isNullPointerConstant(Context,
4929                                      Expr::NPC_NeverValueDependent)) {
4930     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4931     DiagnoseCalleeStaticArrayParam(*this, Param);
4932     return;
4933   }
4934 
4935   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4936   if (!CAT)
4937     return;
4938 
4939   const ConstantArrayType *ArgCAT =
4940     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4941   if (!ArgCAT)
4942     return;
4943 
4944   if (ArgCAT->getSize().ult(CAT->getSize())) {
4945     Diag(CallLoc, diag::warn_static_array_too_small)
4946       << ArgExpr->getSourceRange()
4947       << (unsigned) ArgCAT->getSize().getZExtValue()
4948       << (unsigned) CAT->getSize().getZExtValue();
4949     DiagnoseCalleeStaticArrayParam(*this, Param);
4950   }
4951 }
4952 
4953 /// Given a function expression of unknown-any type, try to rebuild it
4954 /// to have a function type.
4955 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4956 
4957 /// Is the given type a placeholder that we need to lower out
4958 /// immediately during argument processing?
4959 static bool isPlaceholderToRemoveAsArg(QualType type) {
4960   // Placeholders are never sugared.
4961   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4962   if (!placeholder) return false;
4963 
4964   switch (placeholder->getKind()) {
4965   // Ignore all the non-placeholder types.
4966 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4967   case BuiltinType::Id:
4968 #include "clang/Basic/OpenCLImageTypes.def"
4969 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4970 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4971 #include "clang/AST/BuiltinTypes.def"
4972     return false;
4973 
4974   // We cannot lower out overload sets; they might validly be resolved
4975   // by the call machinery.
4976   case BuiltinType::Overload:
4977     return false;
4978 
4979   // Unbridged casts in ARC can be handled in some call positions and
4980   // should be left in place.
4981   case BuiltinType::ARCUnbridgedCast:
4982     return false;
4983 
4984   // Pseudo-objects should be converted as soon as possible.
4985   case BuiltinType::PseudoObject:
4986     return true;
4987 
4988   // The debugger mode could theoretically but currently does not try
4989   // to resolve unknown-typed arguments based on known parameter types.
4990   case BuiltinType::UnknownAny:
4991     return true;
4992 
4993   // These are always invalid as call arguments and should be reported.
4994   case BuiltinType::BoundMember:
4995   case BuiltinType::BuiltinFn:
4996   case BuiltinType::OMPArraySection:
4997     return true;
4998 
4999   }
5000   llvm_unreachable("bad builtin type kind");
5001 }
5002 
5003 /// Check an argument list for placeholders that we won't try to
5004 /// handle later.
5005 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5006   // Apply this processing to all the arguments at once instead of
5007   // dying at the first failure.
5008   bool hasInvalid = false;
5009   for (size_t i = 0, e = args.size(); i != e; i++) {
5010     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5011       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5012       if (result.isInvalid()) hasInvalid = true;
5013       else args[i] = result.get();
5014     } else if (hasInvalid) {
5015       (void)S.CorrectDelayedTyposInExpr(args[i]);
5016     }
5017   }
5018   return hasInvalid;
5019 }
5020 
5021 /// If a builtin function has a pointer argument with no explicit address
5022 /// space, then it should be able to accept a pointer to any address
5023 /// space as input.  In order to do this, we need to replace the
5024 /// standard builtin declaration with one that uses the same address space
5025 /// as the call.
5026 ///
5027 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5028 ///                  it does not contain any pointer arguments without
5029 ///                  an address space qualifer.  Otherwise the rewritten
5030 ///                  FunctionDecl is returned.
5031 /// TODO: Handle pointer return types.
5032 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5033                                                 const FunctionDecl *FDecl,
5034                                                 MultiExprArg ArgExprs) {
5035 
5036   QualType DeclType = FDecl->getType();
5037   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5038 
5039   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5040       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5041     return nullptr;
5042 
5043   bool NeedsNewDecl = false;
5044   unsigned i = 0;
5045   SmallVector<QualType, 8> OverloadParams;
5046 
5047   for (QualType ParamType : FT->param_types()) {
5048 
5049     // Convert array arguments to pointer to simplify type lookup.
5050     ExprResult ArgRes =
5051         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5052     if (ArgRes.isInvalid())
5053       return nullptr;
5054     Expr *Arg = ArgRes.get();
5055     QualType ArgType = Arg->getType();
5056     if (!ParamType->isPointerType() ||
5057         ParamType.getQualifiers().hasAddressSpace() ||
5058         !ArgType->isPointerType() ||
5059         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5060       OverloadParams.push_back(ParamType);
5061       continue;
5062     }
5063 
5064     NeedsNewDecl = true;
5065     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5066 
5067     QualType PointeeType = ParamType->getPointeeType();
5068     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5069     OverloadParams.push_back(Context.getPointerType(PointeeType));
5070   }
5071 
5072   if (!NeedsNewDecl)
5073     return nullptr;
5074 
5075   FunctionProtoType::ExtProtoInfo EPI;
5076   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5077                                                 OverloadParams, EPI);
5078   DeclContext *Parent = Context.getTranslationUnitDecl();
5079   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5080                                                     FDecl->getLocation(),
5081                                                     FDecl->getLocation(),
5082                                                     FDecl->getIdentifier(),
5083                                                     OverloadTy,
5084                                                     /*TInfo=*/nullptr,
5085                                                     SC_Extern, false,
5086                                                     /*hasPrototype=*/true);
5087   SmallVector<ParmVarDecl*, 16> Params;
5088   FT = cast<FunctionProtoType>(OverloadTy);
5089   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5090     QualType ParamType = FT->getParamType(i);
5091     ParmVarDecl *Parm =
5092         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5093                                 SourceLocation(), nullptr, ParamType,
5094                                 /*TInfo=*/nullptr, SC_None, nullptr);
5095     Parm->setScopeInfo(0, i);
5096     Params.push_back(Parm);
5097   }
5098   OverloadDecl->setParams(Params);
5099   return OverloadDecl;
5100 }
5101 
5102 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5103                                     FunctionDecl *Callee,
5104                                     MultiExprArg ArgExprs) {
5105   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5106   // similar attributes) really don't like it when functions are called with an
5107   // invalid number of args.
5108   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5109                          /*PartialOverloading=*/false) &&
5110       !Callee->isVariadic())
5111     return;
5112   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5113     return;
5114 
5115   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5116     S.Diag(Fn->getLocStart(),
5117            isa<CXXMethodDecl>(Callee)
5118                ? diag::err_ovl_no_viable_member_function_in_call
5119                : diag::err_ovl_no_viable_function_in_call)
5120         << Callee << Callee->getSourceRange();
5121     S.Diag(Callee->getLocation(),
5122            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5123         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5124     return;
5125   }
5126 }
5127 
5128 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5129 /// This provides the location of the left/right parens and a list of comma
5130 /// locations.
5131 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5132                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5133                                Expr *ExecConfig, bool IsExecConfig) {
5134   // Since this might be a postfix expression, get rid of ParenListExprs.
5135   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5136   if (Result.isInvalid()) return ExprError();
5137   Fn = Result.get();
5138 
5139   if (checkArgsForPlaceholders(*this, ArgExprs))
5140     return ExprError();
5141 
5142   if (getLangOpts().CPlusPlus) {
5143     // If this is a pseudo-destructor expression, build the call immediately.
5144     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5145       if (!ArgExprs.empty()) {
5146         // Pseudo-destructor calls should not have any arguments.
5147         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5148             << FixItHint::CreateRemoval(
5149                    SourceRange(ArgExprs.front()->getLocStart(),
5150                                ArgExprs.back()->getLocEnd()));
5151       }
5152 
5153       return new (Context)
5154           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5155     }
5156     if (Fn->getType() == Context.PseudoObjectTy) {
5157       ExprResult result = CheckPlaceholderExpr(Fn);
5158       if (result.isInvalid()) return ExprError();
5159       Fn = result.get();
5160     }
5161 
5162     // Determine whether this is a dependent call inside a C++ template,
5163     // in which case we won't do any semantic analysis now.
5164     bool Dependent = false;
5165     if (Fn->isTypeDependent())
5166       Dependent = true;
5167     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5168       Dependent = true;
5169 
5170     if (Dependent) {
5171       if (ExecConfig) {
5172         return new (Context) CUDAKernelCallExpr(
5173             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5174             Context.DependentTy, VK_RValue, RParenLoc);
5175       } else {
5176         return new (Context) CallExpr(
5177             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5178       }
5179     }
5180 
5181     // Determine whether this is a call to an object (C++ [over.call.object]).
5182     if (Fn->getType()->isRecordType())
5183       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5184                                           RParenLoc);
5185 
5186     if (Fn->getType() == Context.UnknownAnyTy) {
5187       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5188       if (result.isInvalid()) return ExprError();
5189       Fn = result.get();
5190     }
5191 
5192     if (Fn->getType() == Context.BoundMemberTy) {
5193       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5194                                        RParenLoc);
5195     }
5196   }
5197 
5198   // Check for overloaded calls.  This can happen even in C due to extensions.
5199   if (Fn->getType() == Context.OverloadTy) {
5200     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5201 
5202     // We aren't supposed to apply this logic if there's an '&' involved.
5203     if (!find.HasFormOfMemberPointer) {
5204       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5205         return new (Context) CallExpr(
5206             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5207       OverloadExpr *ovl = find.Expression;
5208       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5209         return BuildOverloadedCallExpr(
5210             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5211             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5212       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5213                                        RParenLoc);
5214     }
5215   }
5216 
5217   // If we're directly calling a function, get the appropriate declaration.
5218   if (Fn->getType() == Context.UnknownAnyTy) {
5219     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5220     if (result.isInvalid()) return ExprError();
5221     Fn = result.get();
5222   }
5223 
5224   Expr *NakedFn = Fn->IgnoreParens();
5225 
5226   bool CallingNDeclIndirectly = false;
5227   NamedDecl *NDecl = nullptr;
5228   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5229     if (UnOp->getOpcode() == UO_AddrOf) {
5230       CallingNDeclIndirectly = true;
5231       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5232     }
5233   }
5234 
5235   if (isa<DeclRefExpr>(NakedFn)) {
5236     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5237 
5238     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5239     if (FDecl && FDecl->getBuiltinID()) {
5240       // Rewrite the function decl for this builtin by replacing parameters
5241       // with no explicit address space with the address space of the arguments
5242       // in ArgExprs.
5243       if ((FDecl =
5244                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5245         NDecl = FDecl;
5246         Fn = DeclRefExpr::Create(
5247             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5248             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5249       }
5250     }
5251   } else if (isa<MemberExpr>(NakedFn))
5252     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5253 
5254   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5255     if (CallingNDeclIndirectly &&
5256         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5257                                            Fn->getLocStart()))
5258       return ExprError();
5259 
5260     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5261       return ExprError();
5262 
5263     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5264   }
5265 
5266   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5267                                ExecConfig, IsExecConfig);
5268 }
5269 
5270 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5271 ///
5272 /// __builtin_astype( value, dst type )
5273 ///
5274 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5275                                  SourceLocation BuiltinLoc,
5276                                  SourceLocation RParenLoc) {
5277   ExprValueKind VK = VK_RValue;
5278   ExprObjectKind OK = OK_Ordinary;
5279   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5280   QualType SrcTy = E->getType();
5281   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5282     return ExprError(Diag(BuiltinLoc,
5283                           diag::err_invalid_astype_of_different_size)
5284                      << DstTy
5285                      << SrcTy
5286                      << E->getSourceRange());
5287   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5288 }
5289 
5290 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5291 /// provided arguments.
5292 ///
5293 /// __builtin_convertvector( value, dst type )
5294 ///
5295 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5296                                         SourceLocation BuiltinLoc,
5297                                         SourceLocation RParenLoc) {
5298   TypeSourceInfo *TInfo;
5299   GetTypeFromParser(ParsedDestTy, &TInfo);
5300   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5301 }
5302 
5303 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5304 /// i.e. an expression not of \p OverloadTy.  The expression should
5305 /// unary-convert to an expression of function-pointer or
5306 /// block-pointer type.
5307 ///
5308 /// \param NDecl the declaration being called, if available
5309 ExprResult
5310 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5311                             SourceLocation LParenLoc,
5312                             ArrayRef<Expr *> Args,
5313                             SourceLocation RParenLoc,
5314                             Expr *Config, bool IsExecConfig) {
5315   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5316   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5317 
5318   // Functions with 'interrupt' attribute cannot be called directly.
5319   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5320     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5321     return ExprError();
5322   }
5323 
5324   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5325   // so there's some risk when calling out to non-interrupt handler functions
5326   // that the callee might not preserve them. This is easy to diagnose here,
5327   // but can be very challenging to debug.
5328   if (auto *Caller = getCurFunctionDecl())
5329     if (Caller->hasAttr<ARMInterruptAttr>()) {
5330       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5331       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5332         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5333     }
5334 
5335   // Promote the function operand.
5336   // We special-case function promotion here because we only allow promoting
5337   // builtin functions to function pointers in the callee of a call.
5338   ExprResult Result;
5339   if (BuiltinID &&
5340       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5341     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5342                                CK_BuiltinFnToFnPtr).get();
5343   } else {
5344     Result = CallExprUnaryConversions(Fn);
5345   }
5346   if (Result.isInvalid())
5347     return ExprError();
5348   Fn = Result.get();
5349 
5350   // Make the call expr early, before semantic checks.  This guarantees cleanup
5351   // of arguments and function on error.
5352   CallExpr *TheCall;
5353   if (Config)
5354     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5355                                                cast<CallExpr>(Config), Args,
5356                                                Context.BoolTy, VK_RValue,
5357                                                RParenLoc);
5358   else
5359     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5360                                      VK_RValue, RParenLoc);
5361 
5362   if (!getLangOpts().CPlusPlus) {
5363     // C cannot always handle TypoExpr nodes in builtin calls and direct
5364     // function calls as their argument checking don't necessarily handle
5365     // dependent types properly, so make sure any TypoExprs have been
5366     // dealt with.
5367     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5368     if (!Result.isUsable()) return ExprError();
5369     TheCall = dyn_cast<CallExpr>(Result.get());
5370     if (!TheCall) return Result;
5371     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5372   }
5373 
5374   // Bail out early if calling a builtin with custom typechecking.
5375   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5376     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5377 
5378  retry:
5379   const FunctionType *FuncT;
5380   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5381     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5382     // have type pointer to function".
5383     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5384     if (!FuncT)
5385       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5386                          << Fn->getType() << Fn->getSourceRange());
5387   } else if (const BlockPointerType *BPT =
5388                Fn->getType()->getAs<BlockPointerType>()) {
5389     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5390   } else {
5391     // Handle calls to expressions of unknown-any type.
5392     if (Fn->getType() == Context.UnknownAnyTy) {
5393       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5394       if (rewrite.isInvalid()) return ExprError();
5395       Fn = rewrite.get();
5396       TheCall->setCallee(Fn);
5397       goto retry;
5398     }
5399 
5400     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5401       << Fn->getType() << Fn->getSourceRange());
5402   }
5403 
5404   if (getLangOpts().CUDA) {
5405     if (Config) {
5406       // CUDA: Kernel calls must be to global functions
5407       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5408         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5409             << FDecl->getName() << Fn->getSourceRange());
5410 
5411       // CUDA: Kernel function must have 'void' return type
5412       if (!FuncT->getReturnType()->isVoidType())
5413         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5414             << Fn->getType() << Fn->getSourceRange());
5415     } else {
5416       // CUDA: Calls to global functions must be configured
5417       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5418         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5419             << FDecl->getName() << Fn->getSourceRange());
5420     }
5421   }
5422 
5423   // Check for a valid return type
5424   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5425                           FDecl))
5426     return ExprError();
5427 
5428   // We know the result type of the call, set it.
5429   TheCall->setType(FuncT->getCallResultType(Context));
5430   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5431 
5432   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5433   if (Proto) {
5434     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5435                                 IsExecConfig))
5436       return ExprError();
5437   } else {
5438     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5439 
5440     if (FDecl) {
5441       // Check if we have too few/too many template arguments, based
5442       // on our knowledge of the function definition.
5443       const FunctionDecl *Def = nullptr;
5444       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5445         Proto = Def->getType()->getAs<FunctionProtoType>();
5446        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5447           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5448           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5449       }
5450 
5451       // If the function we're calling isn't a function prototype, but we have
5452       // a function prototype from a prior declaratiom, use that prototype.
5453       if (!FDecl->hasPrototype())
5454         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5455     }
5456 
5457     // Promote the arguments (C99 6.5.2.2p6).
5458     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5459       Expr *Arg = Args[i];
5460 
5461       if (Proto && i < Proto->getNumParams()) {
5462         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5463             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5464         ExprResult ArgE =
5465             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5466         if (ArgE.isInvalid())
5467           return true;
5468 
5469         Arg = ArgE.getAs<Expr>();
5470 
5471       } else {
5472         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5473 
5474         if (ArgE.isInvalid())
5475           return true;
5476 
5477         Arg = ArgE.getAs<Expr>();
5478       }
5479 
5480       if (RequireCompleteType(Arg->getLocStart(),
5481                               Arg->getType(),
5482                               diag::err_call_incomplete_argument, Arg))
5483         return ExprError();
5484 
5485       TheCall->setArg(i, Arg);
5486     }
5487   }
5488 
5489   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5490     if (!Method->isStatic())
5491       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5492         << Fn->getSourceRange());
5493 
5494   // Check for sentinels
5495   if (NDecl)
5496     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5497 
5498   // Do special checking on direct calls to functions.
5499   if (FDecl) {
5500     if (CheckFunctionCall(FDecl, TheCall, Proto))
5501       return ExprError();
5502 
5503     if (BuiltinID)
5504       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5505   } else if (NDecl) {
5506     if (CheckPointerCall(NDecl, TheCall, Proto))
5507       return ExprError();
5508   } else {
5509     if (CheckOtherCall(TheCall, Proto))
5510       return ExprError();
5511   }
5512 
5513   return MaybeBindToTemporary(TheCall);
5514 }
5515 
5516 ExprResult
5517 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5518                            SourceLocation RParenLoc, Expr *InitExpr) {
5519   assert(Ty && "ActOnCompoundLiteral(): missing type");
5520   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5521 
5522   TypeSourceInfo *TInfo;
5523   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5524   if (!TInfo)
5525     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5526 
5527   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5528 }
5529 
5530 ExprResult
5531 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5532                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5533   QualType literalType = TInfo->getType();
5534 
5535   if (literalType->isArrayType()) {
5536     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5537           diag::err_illegal_decl_array_incomplete_type,
5538           SourceRange(LParenLoc,
5539                       LiteralExpr->getSourceRange().getEnd())))
5540       return ExprError();
5541     if (literalType->isVariableArrayType())
5542       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5543         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5544   } else if (!literalType->isDependentType() &&
5545              RequireCompleteType(LParenLoc, literalType,
5546                diag::err_typecheck_decl_incomplete_type,
5547                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5548     return ExprError();
5549 
5550   InitializedEntity Entity
5551     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5552   InitializationKind Kind
5553     = InitializationKind::CreateCStyleCast(LParenLoc,
5554                                            SourceRange(LParenLoc, RParenLoc),
5555                                            /*InitList=*/true);
5556   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5557   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5558                                       &literalType);
5559   if (Result.isInvalid())
5560     return ExprError();
5561   LiteralExpr = Result.get();
5562 
5563   bool isFileScope = !CurContext->isFunctionOrMethod();
5564   if (isFileScope &&
5565       !LiteralExpr->isTypeDependent() &&
5566       !LiteralExpr->isValueDependent() &&
5567       !literalType->isDependentType()) { // 6.5.2.5p3
5568     if (CheckForConstantInitializer(LiteralExpr, literalType))
5569       return ExprError();
5570   }
5571 
5572   // In C, compound literals are l-values for some reason.
5573   // For GCC compatibility, in C++, file-scope array compound literals with
5574   // constant initializers are also l-values, and compound literals are
5575   // otherwise prvalues.
5576   //
5577   // (GCC also treats C++ list-initialized file-scope array prvalues with
5578   // constant initializers as l-values, but that's non-conforming, so we don't
5579   // follow it there.)
5580   //
5581   // FIXME: It would be better to handle the lvalue cases as materializing and
5582   // lifetime-extending a temporary object, but our materialized temporaries
5583   // representation only supports lifetime extension from a variable, not "out
5584   // of thin air".
5585   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5586   // is bound to the result of applying array-to-pointer decay to the compound
5587   // literal.
5588   // FIXME: GCC supports compound literals of reference type, which should
5589   // obviously have a value kind derived from the kind of reference involved.
5590   ExprValueKind VK =
5591       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5592           ? VK_RValue
5593           : VK_LValue;
5594 
5595   return MaybeBindToTemporary(
5596       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5597                                         VK, LiteralExpr, isFileScope));
5598 }
5599 
5600 ExprResult
5601 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5602                     SourceLocation RBraceLoc) {
5603   // Immediately handle non-overload placeholders.  Overloads can be
5604   // resolved contextually, but everything else here can't.
5605   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5606     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5607       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5608 
5609       // Ignore failures; dropping the entire initializer list because
5610       // of one failure would be terrible for indexing/etc.
5611       if (result.isInvalid()) continue;
5612 
5613       InitArgList[I] = result.get();
5614     }
5615   }
5616 
5617   // Semantic analysis for initializers is done by ActOnDeclarator() and
5618   // CheckInitializer() - it requires knowledge of the object being intialized.
5619 
5620   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5621                                                RBraceLoc);
5622   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5623   return E;
5624 }
5625 
5626 /// Do an explicit extend of the given block pointer if we're in ARC.
5627 void Sema::maybeExtendBlockObject(ExprResult &E) {
5628   assert(E.get()->getType()->isBlockPointerType());
5629   assert(E.get()->isRValue());
5630 
5631   // Only do this in an r-value context.
5632   if (!getLangOpts().ObjCAutoRefCount) return;
5633 
5634   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5635                                CK_ARCExtendBlockObject, E.get(),
5636                                /*base path*/ nullptr, VK_RValue);
5637   Cleanup.setExprNeedsCleanups(true);
5638 }
5639 
5640 /// Prepare a conversion of the given expression to an ObjC object
5641 /// pointer type.
5642 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5643   QualType type = E.get()->getType();
5644   if (type->isObjCObjectPointerType()) {
5645     return CK_BitCast;
5646   } else if (type->isBlockPointerType()) {
5647     maybeExtendBlockObject(E);
5648     return CK_BlockPointerToObjCPointerCast;
5649   } else {
5650     assert(type->isPointerType());
5651     return CK_CPointerToObjCPointerCast;
5652   }
5653 }
5654 
5655 /// Prepares for a scalar cast, performing all the necessary stages
5656 /// except the final cast and returning the kind required.
5657 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5658   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5659   // Also, callers should have filtered out the invalid cases with
5660   // pointers.  Everything else should be possible.
5661 
5662   QualType SrcTy = Src.get()->getType();
5663   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5664     return CK_NoOp;
5665 
5666   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5667   case Type::STK_MemberPointer:
5668     llvm_unreachable("member pointer type in C");
5669 
5670   case Type::STK_CPointer:
5671   case Type::STK_BlockPointer:
5672   case Type::STK_ObjCObjectPointer:
5673     switch (DestTy->getScalarTypeKind()) {
5674     case Type::STK_CPointer: {
5675       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5676       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5677       if (SrcAS != DestAS)
5678         return CK_AddressSpaceConversion;
5679       return CK_BitCast;
5680     }
5681     case Type::STK_BlockPointer:
5682       return (SrcKind == Type::STK_BlockPointer
5683                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5684     case Type::STK_ObjCObjectPointer:
5685       if (SrcKind == Type::STK_ObjCObjectPointer)
5686         return CK_BitCast;
5687       if (SrcKind == Type::STK_CPointer)
5688         return CK_CPointerToObjCPointerCast;
5689       maybeExtendBlockObject(Src);
5690       return CK_BlockPointerToObjCPointerCast;
5691     case Type::STK_Bool:
5692       return CK_PointerToBoolean;
5693     case Type::STK_Integral:
5694       return CK_PointerToIntegral;
5695     case Type::STK_Floating:
5696     case Type::STK_FloatingComplex:
5697     case Type::STK_IntegralComplex:
5698     case Type::STK_MemberPointer:
5699       llvm_unreachable("illegal cast from pointer");
5700     }
5701     llvm_unreachable("Should have returned before this");
5702 
5703   case Type::STK_Bool: // casting from bool is like casting from an integer
5704   case Type::STK_Integral:
5705     switch (DestTy->getScalarTypeKind()) {
5706     case Type::STK_CPointer:
5707     case Type::STK_ObjCObjectPointer:
5708     case Type::STK_BlockPointer:
5709       if (Src.get()->isNullPointerConstant(Context,
5710                                            Expr::NPC_ValueDependentIsNull))
5711         return CK_NullToPointer;
5712       return CK_IntegralToPointer;
5713     case Type::STK_Bool:
5714       return CK_IntegralToBoolean;
5715     case Type::STK_Integral:
5716       return CK_IntegralCast;
5717     case Type::STK_Floating:
5718       return CK_IntegralToFloating;
5719     case Type::STK_IntegralComplex:
5720       Src = ImpCastExprToType(Src.get(),
5721                       DestTy->castAs<ComplexType>()->getElementType(),
5722                       CK_IntegralCast);
5723       return CK_IntegralRealToComplex;
5724     case Type::STK_FloatingComplex:
5725       Src = ImpCastExprToType(Src.get(),
5726                       DestTy->castAs<ComplexType>()->getElementType(),
5727                       CK_IntegralToFloating);
5728       return CK_FloatingRealToComplex;
5729     case Type::STK_MemberPointer:
5730       llvm_unreachable("member pointer type in C");
5731     }
5732     llvm_unreachable("Should have returned before this");
5733 
5734   case Type::STK_Floating:
5735     switch (DestTy->getScalarTypeKind()) {
5736     case Type::STK_Floating:
5737       return CK_FloatingCast;
5738     case Type::STK_Bool:
5739       return CK_FloatingToBoolean;
5740     case Type::STK_Integral:
5741       return CK_FloatingToIntegral;
5742     case Type::STK_FloatingComplex:
5743       Src = ImpCastExprToType(Src.get(),
5744                               DestTy->castAs<ComplexType>()->getElementType(),
5745                               CK_FloatingCast);
5746       return CK_FloatingRealToComplex;
5747     case Type::STK_IntegralComplex:
5748       Src = ImpCastExprToType(Src.get(),
5749                               DestTy->castAs<ComplexType>()->getElementType(),
5750                               CK_FloatingToIntegral);
5751       return CK_IntegralRealToComplex;
5752     case Type::STK_CPointer:
5753     case Type::STK_ObjCObjectPointer:
5754     case Type::STK_BlockPointer:
5755       llvm_unreachable("valid float->pointer cast?");
5756     case Type::STK_MemberPointer:
5757       llvm_unreachable("member pointer type in C");
5758     }
5759     llvm_unreachable("Should have returned before this");
5760 
5761   case Type::STK_FloatingComplex:
5762     switch (DestTy->getScalarTypeKind()) {
5763     case Type::STK_FloatingComplex:
5764       return CK_FloatingComplexCast;
5765     case Type::STK_IntegralComplex:
5766       return CK_FloatingComplexToIntegralComplex;
5767     case Type::STK_Floating: {
5768       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5769       if (Context.hasSameType(ET, DestTy))
5770         return CK_FloatingComplexToReal;
5771       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5772       return CK_FloatingCast;
5773     }
5774     case Type::STK_Bool:
5775       return CK_FloatingComplexToBoolean;
5776     case Type::STK_Integral:
5777       Src = ImpCastExprToType(Src.get(),
5778                               SrcTy->castAs<ComplexType>()->getElementType(),
5779                               CK_FloatingComplexToReal);
5780       return CK_FloatingToIntegral;
5781     case Type::STK_CPointer:
5782     case Type::STK_ObjCObjectPointer:
5783     case Type::STK_BlockPointer:
5784       llvm_unreachable("valid complex float->pointer cast?");
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_IntegralComplex:
5791     switch (DestTy->getScalarTypeKind()) {
5792     case Type::STK_FloatingComplex:
5793       return CK_IntegralComplexToFloatingComplex;
5794     case Type::STK_IntegralComplex:
5795       return CK_IntegralComplexCast;
5796     case Type::STK_Integral: {
5797       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5798       if (Context.hasSameType(ET, DestTy))
5799         return CK_IntegralComplexToReal;
5800       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5801       return CK_IntegralCast;
5802     }
5803     case Type::STK_Bool:
5804       return CK_IntegralComplexToBoolean;
5805     case Type::STK_Floating:
5806       Src = ImpCastExprToType(Src.get(),
5807                               SrcTy->castAs<ComplexType>()->getElementType(),
5808                               CK_IntegralComplexToReal);
5809       return CK_IntegralToFloating;
5810     case Type::STK_CPointer:
5811     case Type::STK_ObjCObjectPointer:
5812     case Type::STK_BlockPointer:
5813       llvm_unreachable("valid complex int->pointer cast?");
5814     case Type::STK_MemberPointer:
5815       llvm_unreachable("member pointer type in C");
5816     }
5817     llvm_unreachable("Should have returned before this");
5818   }
5819 
5820   llvm_unreachable("Unhandled scalar cast");
5821 }
5822 
5823 static bool breakDownVectorType(QualType type, uint64_t &len,
5824                                 QualType &eltType) {
5825   // Vectors are simple.
5826   if (const VectorType *vecType = type->getAs<VectorType>()) {
5827     len = vecType->getNumElements();
5828     eltType = vecType->getElementType();
5829     assert(eltType->isScalarType());
5830     return true;
5831   }
5832 
5833   // We allow lax conversion to and from non-vector types, but only if
5834   // they're real types (i.e. non-complex, non-pointer scalar types).
5835   if (!type->isRealType()) return false;
5836 
5837   len = 1;
5838   eltType = type;
5839   return true;
5840 }
5841 
5842 /// Are the two types lax-compatible vector types?  That is, given
5843 /// that one of them is a vector, do they have equal storage sizes,
5844 /// where the storage size is the number of elements times the element
5845 /// size?
5846 ///
5847 /// This will also return false if either of the types is neither a
5848 /// vector nor a real type.
5849 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5850   assert(destTy->isVectorType() || srcTy->isVectorType());
5851 
5852   // Disallow lax conversions between scalars and ExtVectors (these
5853   // conversions are allowed for other vector types because common headers
5854   // depend on them).  Most scalar OP ExtVector cases are handled by the
5855   // splat path anyway, which does what we want (convert, not bitcast).
5856   // What this rules out for ExtVectors is crazy things like char4*float.
5857   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5858   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5859 
5860   uint64_t srcLen, destLen;
5861   QualType srcEltTy, destEltTy;
5862   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5863   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5864 
5865   // ASTContext::getTypeSize will return the size rounded up to a
5866   // power of 2, so instead of using that, we need to use the raw
5867   // element size multiplied by the element count.
5868   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5869   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5870 
5871   return (srcLen * srcEltSize == destLen * destEltSize);
5872 }
5873 
5874 /// Is this a legal conversion between two types, one of which is
5875 /// known to be a vector type?
5876 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5877   assert(destTy->isVectorType() || srcTy->isVectorType());
5878 
5879   if (!Context.getLangOpts().LaxVectorConversions)
5880     return false;
5881   return areLaxCompatibleVectorTypes(srcTy, destTy);
5882 }
5883 
5884 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5885                            CastKind &Kind) {
5886   assert(VectorTy->isVectorType() && "Not a vector type!");
5887 
5888   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5889     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5890       return Diag(R.getBegin(),
5891                   Ty->isVectorType() ?
5892                   diag::err_invalid_conversion_between_vectors :
5893                   diag::err_invalid_conversion_between_vector_and_integer)
5894         << VectorTy << Ty << R;
5895   } else
5896     return Diag(R.getBegin(),
5897                 diag::err_invalid_conversion_between_vector_and_scalar)
5898       << VectorTy << Ty << R;
5899 
5900   Kind = CK_BitCast;
5901   return false;
5902 }
5903 
5904 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5905   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5906 
5907   if (DestElemTy == SplattedExpr->getType())
5908     return SplattedExpr;
5909 
5910   assert(DestElemTy->isFloatingType() ||
5911          DestElemTy->isIntegralOrEnumerationType());
5912 
5913   CastKind CK;
5914   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5915     // OpenCL requires that we convert `true` boolean expressions to -1, but
5916     // only when splatting vectors.
5917     if (DestElemTy->isFloatingType()) {
5918       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5919       // in two steps: boolean to signed integral, then to floating.
5920       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5921                                                  CK_BooleanToSignedIntegral);
5922       SplattedExpr = CastExprRes.get();
5923       CK = CK_IntegralToFloating;
5924     } else {
5925       CK = CK_BooleanToSignedIntegral;
5926     }
5927   } else {
5928     ExprResult CastExprRes = SplattedExpr;
5929     CK = PrepareScalarCast(CastExprRes, DestElemTy);
5930     if (CastExprRes.isInvalid())
5931       return ExprError();
5932     SplattedExpr = CastExprRes.get();
5933   }
5934   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5935 }
5936 
5937 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5938                                     Expr *CastExpr, CastKind &Kind) {
5939   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5940 
5941   QualType SrcTy = CastExpr->getType();
5942 
5943   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5944   // an ExtVectorType.
5945   // In OpenCL, casts between vectors of different types are not allowed.
5946   // (See OpenCL 6.2).
5947   if (SrcTy->isVectorType()) {
5948     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
5949         || (getLangOpts().OpenCL &&
5950             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5951       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5952         << DestTy << SrcTy << R;
5953       return ExprError();
5954     }
5955     Kind = CK_BitCast;
5956     return CastExpr;
5957   }
5958 
5959   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5960   // conversion will take place first from scalar to elt type, and then
5961   // splat from elt type to vector.
5962   if (SrcTy->isPointerType())
5963     return Diag(R.getBegin(),
5964                 diag::err_invalid_conversion_between_vector_and_scalar)
5965       << DestTy << SrcTy << R;
5966 
5967   Kind = CK_VectorSplat;
5968   return prepareVectorSplat(DestTy, CastExpr);
5969 }
5970 
5971 ExprResult
5972 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5973                     Declarator &D, ParsedType &Ty,
5974                     SourceLocation RParenLoc, Expr *CastExpr) {
5975   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5976          "ActOnCastExpr(): missing type or expr");
5977 
5978   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5979   if (D.isInvalidType())
5980     return ExprError();
5981 
5982   if (getLangOpts().CPlusPlus) {
5983     // Check that there are no default arguments (C++ only).
5984     CheckExtraCXXDefaultArguments(D);
5985   } else {
5986     // Make sure any TypoExprs have been dealt with.
5987     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
5988     if (!Res.isUsable())
5989       return ExprError();
5990     CastExpr = Res.get();
5991   }
5992 
5993   checkUnusedDeclAttributes(D);
5994 
5995   QualType castType = castTInfo->getType();
5996   Ty = CreateParsedType(castType, castTInfo);
5997 
5998   bool isVectorLiteral = false;
5999 
6000   // Check for an altivec or OpenCL literal,
6001   // i.e. all the elements are integer constants.
6002   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6003   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6004   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6005        && castType->isVectorType() && (PE || PLE)) {
6006     if (PLE && PLE->getNumExprs() == 0) {
6007       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6008       return ExprError();
6009     }
6010     if (PE || PLE->getNumExprs() == 1) {
6011       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6012       if (!E->getType()->isVectorType())
6013         isVectorLiteral = true;
6014     }
6015     else
6016       isVectorLiteral = true;
6017   }
6018 
6019   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6020   // then handle it as such.
6021   if (isVectorLiteral)
6022     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6023 
6024   // If the Expr being casted is a ParenListExpr, handle it specially.
6025   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6026   // sequence of BinOp comma operators.
6027   if (isa<ParenListExpr>(CastExpr)) {
6028     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6029     if (Result.isInvalid()) return ExprError();
6030     CastExpr = Result.get();
6031   }
6032 
6033   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6034       !getSourceManager().isInSystemMacro(LParenLoc))
6035     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6036 
6037   CheckTollFreeBridgeCast(castType, CastExpr);
6038 
6039   CheckObjCBridgeRelatedCast(castType, CastExpr);
6040 
6041   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6042 
6043   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6044 }
6045 
6046 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6047                                     SourceLocation RParenLoc, Expr *E,
6048                                     TypeSourceInfo *TInfo) {
6049   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6050          "Expected paren or paren list expression");
6051 
6052   Expr **exprs;
6053   unsigned numExprs;
6054   Expr *subExpr;
6055   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6056   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6057     LiteralLParenLoc = PE->getLParenLoc();
6058     LiteralRParenLoc = PE->getRParenLoc();
6059     exprs = PE->getExprs();
6060     numExprs = PE->getNumExprs();
6061   } else { // isa<ParenExpr> by assertion at function entrance
6062     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6063     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6064     subExpr = cast<ParenExpr>(E)->getSubExpr();
6065     exprs = &subExpr;
6066     numExprs = 1;
6067   }
6068 
6069   QualType Ty = TInfo->getType();
6070   assert(Ty->isVectorType() && "Expected vector type");
6071 
6072   SmallVector<Expr *, 8> initExprs;
6073   const VectorType *VTy = Ty->getAs<VectorType>();
6074   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6075 
6076   // '(...)' form of vector initialization in AltiVec: the number of
6077   // initializers must be one or must match the size of the vector.
6078   // If a single value is specified in the initializer then it will be
6079   // replicated to all the components of the vector
6080   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6081     // The number of initializers must be one or must match the size of the
6082     // vector. If a single value is specified in the initializer then it will
6083     // be replicated to all the components of the vector
6084     if (numExprs == 1) {
6085       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6086       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6087       if (Literal.isInvalid())
6088         return ExprError();
6089       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6090                                   PrepareScalarCast(Literal, ElemTy));
6091       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6092     }
6093     else if (numExprs < numElems) {
6094       Diag(E->getExprLoc(),
6095            diag::err_incorrect_number_of_vector_initializers);
6096       return ExprError();
6097     }
6098     else
6099       initExprs.append(exprs, exprs + numExprs);
6100   }
6101   else {
6102     // For OpenCL, when the number of initializers is a single value,
6103     // it will be replicated to all components of the vector.
6104     if (getLangOpts().OpenCL &&
6105         VTy->getVectorKind() == VectorType::GenericVector &&
6106         numExprs == 1) {
6107         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6108         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6109         if (Literal.isInvalid())
6110           return ExprError();
6111         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6112                                     PrepareScalarCast(Literal, ElemTy));
6113         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6114     }
6115 
6116     initExprs.append(exprs, exprs + numExprs);
6117   }
6118   // FIXME: This means that pretty-printing the final AST will produce curly
6119   // braces instead of the original commas.
6120   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6121                                                    initExprs, LiteralRParenLoc);
6122   initE->setType(Ty);
6123   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6124 }
6125 
6126 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6127 /// the ParenListExpr into a sequence of comma binary operators.
6128 ExprResult
6129 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6130   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6131   if (!E)
6132     return OrigExpr;
6133 
6134   ExprResult Result(E->getExpr(0));
6135 
6136   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6137     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6138                         E->getExpr(i));
6139 
6140   if (Result.isInvalid()) return ExprError();
6141 
6142   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6143 }
6144 
6145 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6146                                     SourceLocation R,
6147                                     MultiExprArg Val) {
6148   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6149   return expr;
6150 }
6151 
6152 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6153 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6154 /// emitted.
6155 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6156                                       SourceLocation QuestionLoc) {
6157   Expr *NullExpr = LHSExpr;
6158   Expr *NonPointerExpr = RHSExpr;
6159   Expr::NullPointerConstantKind NullKind =
6160       NullExpr->isNullPointerConstant(Context,
6161                                       Expr::NPC_ValueDependentIsNotNull);
6162 
6163   if (NullKind == Expr::NPCK_NotNull) {
6164     NullExpr = RHSExpr;
6165     NonPointerExpr = LHSExpr;
6166     NullKind =
6167         NullExpr->isNullPointerConstant(Context,
6168                                         Expr::NPC_ValueDependentIsNotNull);
6169   }
6170 
6171   if (NullKind == Expr::NPCK_NotNull)
6172     return false;
6173 
6174   if (NullKind == Expr::NPCK_ZeroExpression)
6175     return false;
6176 
6177   if (NullKind == Expr::NPCK_ZeroLiteral) {
6178     // In this case, check to make sure that we got here from a "NULL"
6179     // string in the source code.
6180     NullExpr = NullExpr->IgnoreParenImpCasts();
6181     SourceLocation loc = NullExpr->getExprLoc();
6182     if (!findMacroSpelling(loc, "NULL"))
6183       return false;
6184   }
6185 
6186   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6187   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6188       << NonPointerExpr->getType() << DiagType
6189       << NonPointerExpr->getSourceRange();
6190   return true;
6191 }
6192 
6193 /// \brief Return false if the condition expression is valid, true otherwise.
6194 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6195   QualType CondTy = Cond->getType();
6196 
6197   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6198   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6199     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6200       << CondTy << Cond->getSourceRange();
6201     return true;
6202   }
6203 
6204   // C99 6.5.15p2
6205   if (CondTy->isScalarType()) return false;
6206 
6207   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6208     << CondTy << Cond->getSourceRange();
6209   return true;
6210 }
6211 
6212 /// \brief Handle when one or both operands are void type.
6213 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6214                                          ExprResult &RHS) {
6215     Expr *LHSExpr = LHS.get();
6216     Expr *RHSExpr = RHS.get();
6217 
6218     if (!LHSExpr->getType()->isVoidType())
6219       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6220         << RHSExpr->getSourceRange();
6221     if (!RHSExpr->getType()->isVoidType())
6222       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6223         << LHSExpr->getSourceRange();
6224     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6225     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6226     return S.Context.VoidTy;
6227 }
6228 
6229 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6230 /// true otherwise.
6231 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6232                                         QualType PointerTy) {
6233   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6234       !NullExpr.get()->isNullPointerConstant(S.Context,
6235                                             Expr::NPC_ValueDependentIsNull))
6236     return true;
6237 
6238   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6239   return false;
6240 }
6241 
6242 /// \brief Checks compatibility between two pointers and return the resulting
6243 /// type.
6244 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6245                                                      ExprResult &RHS,
6246                                                      SourceLocation Loc) {
6247   QualType LHSTy = LHS.get()->getType();
6248   QualType RHSTy = RHS.get()->getType();
6249 
6250   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6251     // Two identical pointers types are always compatible.
6252     return LHSTy;
6253   }
6254 
6255   QualType lhptee, rhptee;
6256 
6257   // Get the pointee types.
6258   bool IsBlockPointer = false;
6259   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6260     lhptee = LHSBTy->getPointeeType();
6261     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6262     IsBlockPointer = true;
6263   } else {
6264     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6265     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6266   }
6267 
6268   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6269   // differently qualified versions of compatible types, the result type is
6270   // a pointer to an appropriately qualified version of the composite
6271   // type.
6272 
6273   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6274   // clause doesn't make sense for our extensions. E.g. address space 2 should
6275   // be incompatible with address space 3: they may live on different devices or
6276   // anything.
6277   Qualifiers lhQual = lhptee.getQualifiers();
6278   Qualifiers rhQual = rhptee.getQualifiers();
6279 
6280   unsigned ResultAddrSpace = 0;
6281   unsigned LAddrSpace = lhQual.getAddressSpace();
6282   unsigned RAddrSpace = rhQual.getAddressSpace();
6283   if (S.getLangOpts().OpenCL) {
6284     // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6285     // spaces is disallowed.
6286     if (lhQual.isAddressSpaceSupersetOf(rhQual))
6287       ResultAddrSpace = LAddrSpace;
6288     else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6289       ResultAddrSpace = RAddrSpace;
6290     else {
6291       S.Diag(Loc,
6292              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6293           << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6294           << RHS.get()->getSourceRange();
6295       return QualType();
6296     }
6297   }
6298 
6299   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6300   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6301   lhQual.removeCVRQualifiers();
6302   rhQual.removeCVRQualifiers();
6303 
6304   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6305   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6306   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6307   // qual types are compatible iff
6308   //  * corresponded types are compatible
6309   //  * CVR qualifiers are equal
6310   //  * address spaces are equal
6311   // Thus for conditional operator we merge CVR and address space unqualified
6312   // pointees and if there is a composite type we return a pointer to it with
6313   // merged qualifiers.
6314   if (S.getLangOpts().OpenCL) {
6315     LHSCastKind = LAddrSpace == ResultAddrSpace
6316                       ? CK_BitCast
6317                       : CK_AddressSpaceConversion;
6318     RHSCastKind = RAddrSpace == ResultAddrSpace
6319                       ? CK_BitCast
6320                       : CK_AddressSpaceConversion;
6321     lhQual.removeAddressSpace();
6322     rhQual.removeAddressSpace();
6323   }
6324 
6325   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6326   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6327 
6328   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6329 
6330   if (CompositeTy.isNull()) {
6331     // In this situation, we assume void* type. No especially good
6332     // reason, but this is what gcc does, and we do have to pick
6333     // to get a consistent AST.
6334     QualType incompatTy;
6335     incompatTy = S.Context.getPointerType(
6336         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6337     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6338     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6339     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6340     // for casts between types with incompatible address space qualifiers.
6341     // For the following code the compiler produces casts between global and
6342     // local address spaces of the corresponded innermost pointees:
6343     // local int *global *a;
6344     // global int *global *b;
6345     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6346     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6347         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6348         << RHS.get()->getSourceRange();
6349     return incompatTy;
6350   }
6351 
6352   // The pointer types are compatible.
6353   // In case of OpenCL ResultTy should have the address space qualifier
6354   // which is a superset of address spaces of both the 2nd and the 3rd
6355   // operands of the conditional operator.
6356   QualType ResultTy = [&, ResultAddrSpace]() {
6357     if (S.getLangOpts().OpenCL) {
6358       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6359       CompositeQuals.setAddressSpace(ResultAddrSpace);
6360       return S.Context
6361           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6362           .withCVRQualifiers(MergedCVRQual);
6363     }
6364     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6365   }();
6366   if (IsBlockPointer)
6367     ResultTy = S.Context.getBlockPointerType(ResultTy);
6368   else
6369     ResultTy = S.Context.getPointerType(ResultTy);
6370 
6371   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6372   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6373   return ResultTy;
6374 }
6375 
6376 /// \brief Return the resulting type when the operands are both block pointers.
6377 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6378                                                           ExprResult &LHS,
6379                                                           ExprResult &RHS,
6380                                                           SourceLocation Loc) {
6381   QualType LHSTy = LHS.get()->getType();
6382   QualType RHSTy = RHS.get()->getType();
6383 
6384   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6385     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6386       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6387       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6388       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6389       return destType;
6390     }
6391     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6392       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6393       << RHS.get()->getSourceRange();
6394     return QualType();
6395   }
6396 
6397   // We have 2 block pointer types.
6398   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6399 }
6400 
6401 /// \brief Return the resulting type when the operands are both pointers.
6402 static QualType
6403 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6404                                             ExprResult &RHS,
6405                                             SourceLocation Loc) {
6406   // get the pointer types
6407   QualType LHSTy = LHS.get()->getType();
6408   QualType RHSTy = RHS.get()->getType();
6409 
6410   // get the "pointed to" types
6411   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6412   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6413 
6414   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6415   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6416     // Figure out necessary qualifiers (C99 6.5.15p6)
6417     QualType destPointee
6418       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6419     QualType destType = S.Context.getPointerType(destPointee);
6420     // Add qualifiers if necessary.
6421     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6422     // Promote to void*.
6423     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6424     return destType;
6425   }
6426   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6427     QualType destPointee
6428       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6429     QualType destType = S.Context.getPointerType(destPointee);
6430     // Add qualifiers if necessary.
6431     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6432     // Promote to void*.
6433     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6434     return destType;
6435   }
6436 
6437   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6438 }
6439 
6440 /// \brief Return false if the first expression is not an integer and the second
6441 /// expression is not a pointer, true otherwise.
6442 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6443                                         Expr* PointerExpr, SourceLocation Loc,
6444                                         bool IsIntFirstExpr) {
6445   if (!PointerExpr->getType()->isPointerType() ||
6446       !Int.get()->getType()->isIntegerType())
6447     return false;
6448 
6449   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6450   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6451 
6452   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6453     << Expr1->getType() << Expr2->getType()
6454     << Expr1->getSourceRange() << Expr2->getSourceRange();
6455   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6456                             CK_IntegralToPointer);
6457   return true;
6458 }
6459 
6460 /// \brief Simple conversion between integer and floating point types.
6461 ///
6462 /// Used when handling the OpenCL conditional operator where the
6463 /// condition is a vector while the other operands are scalar.
6464 ///
6465 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6466 /// types are either integer or floating type. Between the two
6467 /// operands, the type with the higher rank is defined as the "result
6468 /// type". The other operand needs to be promoted to the same type. No
6469 /// other type promotion is allowed. We cannot use
6470 /// UsualArithmeticConversions() for this purpose, since it always
6471 /// promotes promotable types.
6472 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6473                                             ExprResult &RHS,
6474                                             SourceLocation QuestionLoc) {
6475   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6476   if (LHS.isInvalid())
6477     return QualType();
6478   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6479   if (RHS.isInvalid())
6480     return QualType();
6481 
6482   // For conversion purposes, we ignore any qualifiers.
6483   // For example, "const float" and "float" are equivalent.
6484   QualType LHSType =
6485     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6486   QualType RHSType =
6487     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6488 
6489   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6490     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6491       << LHSType << LHS.get()->getSourceRange();
6492     return QualType();
6493   }
6494 
6495   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6496     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6497       << RHSType << RHS.get()->getSourceRange();
6498     return QualType();
6499   }
6500 
6501   // If both types are identical, no conversion is needed.
6502   if (LHSType == RHSType)
6503     return LHSType;
6504 
6505   // Now handle "real" floating types (i.e. float, double, long double).
6506   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6507     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6508                                  /*IsCompAssign = */ false);
6509 
6510   // Finally, we have two differing integer types.
6511   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6512   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6513 }
6514 
6515 /// \brief Convert scalar operands to a vector that matches the
6516 ///        condition in length.
6517 ///
6518 /// Used when handling the OpenCL conditional operator where the
6519 /// condition is a vector while the other operands are scalar.
6520 ///
6521 /// We first compute the "result type" for the scalar operands
6522 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6523 /// into a vector of that type where the length matches the condition
6524 /// vector type. s6.11.6 requires that the element types of the result
6525 /// and the condition must have the same number of bits.
6526 static QualType
6527 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6528                               QualType CondTy, SourceLocation QuestionLoc) {
6529   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6530   if (ResTy.isNull()) return QualType();
6531 
6532   const VectorType *CV = CondTy->getAs<VectorType>();
6533   assert(CV);
6534 
6535   // Determine the vector result type
6536   unsigned NumElements = CV->getNumElements();
6537   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6538 
6539   // Ensure that all types have the same number of bits
6540   if (S.Context.getTypeSize(CV->getElementType())
6541       != S.Context.getTypeSize(ResTy)) {
6542     // Since VectorTy is created internally, it does not pretty print
6543     // with an OpenCL name. Instead, we just print a description.
6544     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6545     SmallString<64> Str;
6546     llvm::raw_svector_ostream OS(Str);
6547     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6548     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6549       << CondTy << OS.str();
6550     return QualType();
6551   }
6552 
6553   // Convert operands to the vector result type
6554   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6555   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6556 
6557   return VectorTy;
6558 }
6559 
6560 /// \brief Return false if this is a valid OpenCL condition vector
6561 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6562                                        SourceLocation QuestionLoc) {
6563   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6564   // integral type.
6565   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6566   assert(CondTy);
6567   QualType EleTy = CondTy->getElementType();
6568   if (EleTy->isIntegerType()) return false;
6569 
6570   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6571     << Cond->getType() << Cond->getSourceRange();
6572   return true;
6573 }
6574 
6575 /// \brief Return false if the vector condition type and the vector
6576 ///        result type are compatible.
6577 ///
6578 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6579 /// number of elements, and their element types have the same number
6580 /// of bits.
6581 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6582                               SourceLocation QuestionLoc) {
6583   const VectorType *CV = CondTy->getAs<VectorType>();
6584   const VectorType *RV = VecResTy->getAs<VectorType>();
6585   assert(CV && RV);
6586 
6587   if (CV->getNumElements() != RV->getNumElements()) {
6588     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6589       << CondTy << VecResTy;
6590     return true;
6591   }
6592 
6593   QualType CVE = CV->getElementType();
6594   QualType RVE = RV->getElementType();
6595 
6596   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6597     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6598       << CondTy << VecResTy;
6599     return true;
6600   }
6601 
6602   return false;
6603 }
6604 
6605 /// \brief Return the resulting type for the conditional operator in
6606 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6607 ///        s6.3.i) when the condition is a vector type.
6608 static QualType
6609 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6610                              ExprResult &LHS, ExprResult &RHS,
6611                              SourceLocation QuestionLoc) {
6612   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6613   if (Cond.isInvalid())
6614     return QualType();
6615   QualType CondTy = Cond.get()->getType();
6616 
6617   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6618     return QualType();
6619 
6620   // If either operand is a vector then find the vector type of the
6621   // result as specified in OpenCL v1.1 s6.3.i.
6622   if (LHS.get()->getType()->isVectorType() ||
6623       RHS.get()->getType()->isVectorType()) {
6624     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6625                                               /*isCompAssign*/false,
6626                                               /*AllowBothBool*/true,
6627                                               /*AllowBoolConversions*/false);
6628     if (VecResTy.isNull()) return QualType();
6629     // The result type must match the condition type as specified in
6630     // OpenCL v1.1 s6.11.6.
6631     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6632       return QualType();
6633     return VecResTy;
6634   }
6635 
6636   // Both operands are scalar.
6637   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6638 }
6639 
6640 /// \brief Return true if the Expr is block type
6641 static bool checkBlockType(Sema &S, const Expr *E) {
6642   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6643     QualType Ty = CE->getCallee()->getType();
6644     if (Ty->isBlockPointerType()) {
6645       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6646       return true;
6647     }
6648   }
6649   return false;
6650 }
6651 
6652 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6653 /// In that case, LHS = cond.
6654 /// C99 6.5.15
6655 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6656                                         ExprResult &RHS, ExprValueKind &VK,
6657                                         ExprObjectKind &OK,
6658                                         SourceLocation QuestionLoc) {
6659 
6660   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6661   if (!LHSResult.isUsable()) return QualType();
6662   LHS = LHSResult;
6663 
6664   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6665   if (!RHSResult.isUsable()) return QualType();
6666   RHS = RHSResult;
6667 
6668   // C++ is sufficiently different to merit its own checker.
6669   if (getLangOpts().CPlusPlus)
6670     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6671 
6672   VK = VK_RValue;
6673   OK = OK_Ordinary;
6674 
6675   // The OpenCL operator with a vector condition is sufficiently
6676   // different to merit its own checker.
6677   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6678     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6679 
6680   // First, check the condition.
6681   Cond = UsualUnaryConversions(Cond.get());
6682   if (Cond.isInvalid())
6683     return QualType();
6684   if (checkCondition(*this, Cond.get(), QuestionLoc))
6685     return QualType();
6686 
6687   // Now check the two expressions.
6688   if (LHS.get()->getType()->isVectorType() ||
6689       RHS.get()->getType()->isVectorType())
6690     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6691                                /*AllowBothBool*/true,
6692                                /*AllowBoolConversions*/false);
6693 
6694   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6695   if (LHS.isInvalid() || RHS.isInvalid())
6696     return QualType();
6697 
6698   QualType LHSTy = LHS.get()->getType();
6699   QualType RHSTy = RHS.get()->getType();
6700 
6701   // Diagnose attempts to convert between __float128 and long double where
6702   // such conversions currently can't be handled.
6703   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6704     Diag(QuestionLoc,
6705          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6706       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6707     return QualType();
6708   }
6709 
6710   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6711   // selection operator (?:).
6712   if (getLangOpts().OpenCL &&
6713       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6714     return QualType();
6715   }
6716 
6717   // If both operands have arithmetic type, do the usual arithmetic conversions
6718   // to find a common type: C99 6.5.15p3,5.
6719   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6720     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6721     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6722 
6723     return ResTy;
6724   }
6725 
6726   // If both operands are the same structure or union type, the result is that
6727   // type.
6728   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6729     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6730       if (LHSRT->getDecl() == RHSRT->getDecl())
6731         // "If both the operands have structure or union type, the result has
6732         // that type."  This implies that CV qualifiers are dropped.
6733         return LHSTy.getUnqualifiedType();
6734     // FIXME: Type of conditional expression must be complete in C mode.
6735   }
6736 
6737   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6738   // The following || allows only one side to be void (a GCC-ism).
6739   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6740     return checkConditionalVoidType(*this, LHS, RHS);
6741   }
6742 
6743   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6744   // the type of the other operand."
6745   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6746   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6747 
6748   // All objective-c pointer type analysis is done here.
6749   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6750                                                         QuestionLoc);
6751   if (LHS.isInvalid() || RHS.isInvalid())
6752     return QualType();
6753   if (!compositeType.isNull())
6754     return compositeType;
6755 
6756 
6757   // Handle block pointer types.
6758   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6759     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6760                                                      QuestionLoc);
6761 
6762   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6763   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6764     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6765                                                        QuestionLoc);
6766 
6767   // GCC compatibility: soften pointer/integer mismatch.  Note that
6768   // null pointers have been filtered out by this point.
6769   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6770       /*isIntFirstExpr=*/true))
6771     return RHSTy;
6772   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6773       /*isIntFirstExpr=*/false))
6774     return LHSTy;
6775 
6776   // Emit a better diagnostic if one of the expressions is a null pointer
6777   // constant and the other is not a pointer type. In this case, the user most
6778   // likely forgot to take the address of the other expression.
6779   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6780     return QualType();
6781 
6782   // Otherwise, the operands are not compatible.
6783   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6784     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6785     << RHS.get()->getSourceRange();
6786   return QualType();
6787 }
6788 
6789 /// FindCompositeObjCPointerType - Helper method to find composite type of
6790 /// two objective-c pointer types of the two input expressions.
6791 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6792                                             SourceLocation QuestionLoc) {
6793   QualType LHSTy = LHS.get()->getType();
6794   QualType RHSTy = RHS.get()->getType();
6795 
6796   // Handle things like Class and struct objc_class*.  Here we case the result
6797   // to the pseudo-builtin, because that will be implicitly cast back to the
6798   // redefinition type if an attempt is made to access its fields.
6799   if (LHSTy->isObjCClassType() &&
6800       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6801     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6802     return LHSTy;
6803   }
6804   if (RHSTy->isObjCClassType() &&
6805       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6806     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6807     return RHSTy;
6808   }
6809   // And the same for struct objc_object* / id
6810   if (LHSTy->isObjCIdType() &&
6811       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6812     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6813     return LHSTy;
6814   }
6815   if (RHSTy->isObjCIdType() &&
6816       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6817     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6818     return RHSTy;
6819   }
6820   // And the same for struct objc_selector* / SEL
6821   if (Context.isObjCSelType(LHSTy) &&
6822       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6823     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6824     return LHSTy;
6825   }
6826   if (Context.isObjCSelType(RHSTy) &&
6827       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6828     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6829     return RHSTy;
6830   }
6831   // Check constraints for Objective-C object pointers types.
6832   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6833 
6834     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6835       // Two identical object pointer types are always compatible.
6836       return LHSTy;
6837     }
6838     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6839     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6840     QualType compositeType = LHSTy;
6841 
6842     // If both operands are interfaces and either operand can be
6843     // assigned to the other, use that type as the composite
6844     // type. This allows
6845     //   xxx ? (A*) a : (B*) b
6846     // where B is a subclass of A.
6847     //
6848     // Additionally, as for assignment, if either type is 'id'
6849     // allow silent coercion. Finally, if the types are
6850     // incompatible then make sure to use 'id' as the composite
6851     // type so the result is acceptable for sending messages to.
6852 
6853     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6854     // It could return the composite type.
6855     if (!(compositeType =
6856           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6857       // Nothing more to do.
6858     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6859       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6860     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6861       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6862     } else if ((LHSTy->isObjCQualifiedIdType() ||
6863                 RHSTy->isObjCQualifiedIdType()) &&
6864                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6865       // Need to handle "id<xx>" explicitly.
6866       // GCC allows qualified id and any Objective-C type to devolve to
6867       // id. Currently localizing to here until clear this should be
6868       // part of ObjCQualifiedIdTypesAreCompatible.
6869       compositeType = Context.getObjCIdType();
6870     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6871       compositeType = Context.getObjCIdType();
6872     } else {
6873       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6874       << LHSTy << RHSTy
6875       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6876       QualType incompatTy = Context.getObjCIdType();
6877       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6878       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6879       return incompatTy;
6880     }
6881     // The object pointer types are compatible.
6882     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6883     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6884     return compositeType;
6885   }
6886   // Check Objective-C object pointer types and 'void *'
6887   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6888     if (getLangOpts().ObjCAutoRefCount) {
6889       // ARC forbids the implicit conversion of object pointers to 'void *',
6890       // so these types are not compatible.
6891       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6892           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6893       LHS = RHS = true;
6894       return QualType();
6895     }
6896     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6897     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6898     QualType destPointee
6899     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6900     QualType destType = Context.getPointerType(destPointee);
6901     // Add qualifiers if necessary.
6902     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6903     // Promote to void*.
6904     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6905     return destType;
6906   }
6907   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6908     if (getLangOpts().ObjCAutoRefCount) {
6909       // ARC forbids the implicit conversion of object pointers to 'void *',
6910       // so these types are not compatible.
6911       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6912           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6913       LHS = RHS = true;
6914       return QualType();
6915     }
6916     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6917     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6918     QualType destPointee
6919     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6920     QualType destType = Context.getPointerType(destPointee);
6921     // Add qualifiers if necessary.
6922     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6923     // Promote to void*.
6924     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6925     return destType;
6926   }
6927   return QualType();
6928 }
6929 
6930 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6931 /// ParenRange in parentheses.
6932 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6933                                const PartialDiagnostic &Note,
6934                                SourceRange ParenRange) {
6935   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6936   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6937       EndLoc.isValid()) {
6938     Self.Diag(Loc, Note)
6939       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6940       << FixItHint::CreateInsertion(EndLoc, ")");
6941   } else {
6942     // We can't display the parentheses, so just show the bare note.
6943     Self.Diag(Loc, Note) << ParenRange;
6944   }
6945 }
6946 
6947 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6948   return BinaryOperator::isAdditiveOp(Opc) ||
6949          BinaryOperator::isMultiplicativeOp(Opc) ||
6950          BinaryOperator::isShiftOp(Opc);
6951 }
6952 
6953 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6954 /// expression, either using a built-in or overloaded operator,
6955 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6956 /// expression.
6957 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6958                                    Expr **RHSExprs) {
6959   // Don't strip parenthesis: we should not warn if E is in parenthesis.
6960   E = E->IgnoreImpCasts();
6961   E = E->IgnoreConversionOperator();
6962   E = E->IgnoreImpCasts();
6963 
6964   // Built-in binary operator.
6965   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6966     if (IsArithmeticOp(OP->getOpcode())) {
6967       *Opcode = OP->getOpcode();
6968       *RHSExprs = OP->getRHS();
6969       return true;
6970     }
6971   }
6972 
6973   // Overloaded operator.
6974   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6975     if (Call->getNumArgs() != 2)
6976       return false;
6977 
6978     // Make sure this is really a binary operator that is safe to pass into
6979     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6980     OverloadedOperatorKind OO = Call->getOperator();
6981     if (OO < OO_Plus || OO > OO_Arrow ||
6982         OO == OO_PlusPlus || OO == OO_MinusMinus)
6983       return false;
6984 
6985     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6986     if (IsArithmeticOp(OpKind)) {
6987       *Opcode = OpKind;
6988       *RHSExprs = Call->getArg(1);
6989       return true;
6990     }
6991   }
6992 
6993   return false;
6994 }
6995 
6996 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6997 /// or is a logical expression such as (x==y) which has int type, but is
6998 /// commonly interpreted as boolean.
6999 static bool ExprLooksBoolean(Expr *E) {
7000   E = E->IgnoreParenImpCasts();
7001 
7002   if (E->getType()->isBooleanType())
7003     return true;
7004   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7005     return OP->isComparisonOp() || OP->isLogicalOp();
7006   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7007     return OP->getOpcode() == UO_LNot;
7008   if (E->getType()->isPointerType())
7009     return true;
7010 
7011   return false;
7012 }
7013 
7014 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7015 /// and binary operator are mixed in a way that suggests the programmer assumed
7016 /// the conditional operator has higher precedence, for example:
7017 /// "int x = a + someBinaryCondition ? 1 : 2".
7018 static void DiagnoseConditionalPrecedence(Sema &Self,
7019                                           SourceLocation OpLoc,
7020                                           Expr *Condition,
7021                                           Expr *LHSExpr,
7022                                           Expr *RHSExpr) {
7023   BinaryOperatorKind CondOpcode;
7024   Expr *CondRHS;
7025 
7026   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7027     return;
7028   if (!ExprLooksBoolean(CondRHS))
7029     return;
7030 
7031   // The condition is an arithmetic binary expression, with a right-
7032   // hand side that looks boolean, so warn.
7033 
7034   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7035       << Condition->getSourceRange()
7036       << BinaryOperator::getOpcodeStr(CondOpcode);
7037 
7038   SuggestParentheses(Self, OpLoc,
7039     Self.PDiag(diag::note_precedence_silence)
7040       << BinaryOperator::getOpcodeStr(CondOpcode),
7041     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7042 
7043   SuggestParentheses(Self, OpLoc,
7044     Self.PDiag(diag::note_precedence_conditional_first),
7045     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7046 }
7047 
7048 /// Compute the nullability of a conditional expression.
7049 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7050                                               QualType LHSTy, QualType RHSTy,
7051                                               ASTContext &Ctx) {
7052   if (!ResTy->isAnyPointerType())
7053     return ResTy;
7054 
7055   auto GetNullability = [&Ctx](QualType Ty) {
7056     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7057     if (Kind)
7058       return *Kind;
7059     return NullabilityKind::Unspecified;
7060   };
7061 
7062   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7063   NullabilityKind MergedKind;
7064 
7065   // Compute nullability of a binary conditional expression.
7066   if (IsBin) {
7067     if (LHSKind == NullabilityKind::NonNull)
7068       MergedKind = NullabilityKind::NonNull;
7069     else
7070       MergedKind = RHSKind;
7071   // Compute nullability of a normal conditional expression.
7072   } else {
7073     if (LHSKind == NullabilityKind::Nullable ||
7074         RHSKind == NullabilityKind::Nullable)
7075       MergedKind = NullabilityKind::Nullable;
7076     else if (LHSKind == NullabilityKind::NonNull)
7077       MergedKind = RHSKind;
7078     else if (RHSKind == NullabilityKind::NonNull)
7079       MergedKind = LHSKind;
7080     else
7081       MergedKind = NullabilityKind::Unspecified;
7082   }
7083 
7084   // Return if ResTy already has the correct nullability.
7085   if (GetNullability(ResTy) == MergedKind)
7086     return ResTy;
7087 
7088   // Strip all nullability from ResTy.
7089   while (ResTy->getNullability(Ctx))
7090     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7091 
7092   // Create a new AttributedType with the new nullability kind.
7093   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7094   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7095 }
7096 
7097 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7098 /// in the case of a the GNU conditional expr extension.
7099 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7100                                     SourceLocation ColonLoc,
7101                                     Expr *CondExpr, Expr *LHSExpr,
7102                                     Expr *RHSExpr) {
7103   if (!getLangOpts().CPlusPlus) {
7104     // C cannot handle TypoExpr nodes in the condition because it
7105     // doesn't handle dependent types properly, so make sure any TypoExprs have
7106     // been dealt with before checking the operands.
7107     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7108     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7109     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7110 
7111     if (!CondResult.isUsable())
7112       return ExprError();
7113 
7114     if (LHSExpr) {
7115       if (!LHSResult.isUsable())
7116         return ExprError();
7117     }
7118 
7119     if (!RHSResult.isUsable())
7120       return ExprError();
7121 
7122     CondExpr = CondResult.get();
7123     LHSExpr = LHSResult.get();
7124     RHSExpr = RHSResult.get();
7125   }
7126 
7127   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7128   // was the condition.
7129   OpaqueValueExpr *opaqueValue = nullptr;
7130   Expr *commonExpr = nullptr;
7131   if (!LHSExpr) {
7132     commonExpr = CondExpr;
7133     // Lower out placeholder types first.  This is important so that we don't
7134     // try to capture a placeholder. This happens in few cases in C++; such
7135     // as Objective-C++'s dictionary subscripting syntax.
7136     if (commonExpr->hasPlaceholderType()) {
7137       ExprResult result = CheckPlaceholderExpr(commonExpr);
7138       if (!result.isUsable()) return ExprError();
7139       commonExpr = result.get();
7140     }
7141     // We usually want to apply unary conversions *before* saving, except
7142     // in the special case of a C++ l-value conditional.
7143     if (!(getLangOpts().CPlusPlus
7144           && !commonExpr->isTypeDependent()
7145           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7146           && commonExpr->isGLValue()
7147           && commonExpr->isOrdinaryOrBitFieldObject()
7148           && RHSExpr->isOrdinaryOrBitFieldObject()
7149           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7150       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7151       if (commonRes.isInvalid())
7152         return ExprError();
7153       commonExpr = commonRes.get();
7154     }
7155 
7156     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7157                                                 commonExpr->getType(),
7158                                                 commonExpr->getValueKind(),
7159                                                 commonExpr->getObjectKind(),
7160                                                 commonExpr);
7161     LHSExpr = CondExpr = opaqueValue;
7162   }
7163 
7164   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7165   ExprValueKind VK = VK_RValue;
7166   ExprObjectKind OK = OK_Ordinary;
7167   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7168   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7169                                              VK, OK, QuestionLoc);
7170   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7171       RHS.isInvalid())
7172     return ExprError();
7173 
7174   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7175                                 RHS.get());
7176 
7177   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7178 
7179   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7180                                          Context);
7181 
7182   if (!commonExpr)
7183     return new (Context)
7184         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7185                             RHS.get(), result, VK, OK);
7186 
7187   return new (Context) BinaryConditionalOperator(
7188       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7189       ColonLoc, result, VK, OK);
7190 }
7191 
7192 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7193 // being closely modeled after the C99 spec:-). The odd characteristic of this
7194 // routine is it effectively iqnores the qualifiers on the top level pointee.
7195 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7196 // FIXME: add a couple examples in this comment.
7197 static Sema::AssignConvertType
7198 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7199   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7200   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7201 
7202   // get the "pointed to" type (ignoring qualifiers at the top level)
7203   const Type *lhptee, *rhptee;
7204   Qualifiers lhq, rhq;
7205   std::tie(lhptee, lhq) =
7206       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7207   std::tie(rhptee, rhq) =
7208       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7209 
7210   Sema::AssignConvertType ConvTy = Sema::Compatible;
7211 
7212   // C99 6.5.16.1p1: This following citation is common to constraints
7213   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7214   // qualifiers of the type *pointed to* by the right;
7215 
7216   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7217   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7218       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7219     // Ignore lifetime for further calculation.
7220     lhq.removeObjCLifetime();
7221     rhq.removeObjCLifetime();
7222   }
7223 
7224   if (!lhq.compatiblyIncludes(rhq)) {
7225     // Treat address-space mismatches as fatal.  TODO: address subspaces
7226     if (!lhq.isAddressSpaceSupersetOf(rhq))
7227       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7228 
7229     // It's okay to add or remove GC or lifetime qualifiers when converting to
7230     // and from void*.
7231     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7232                         .compatiblyIncludes(
7233                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7234              && (lhptee->isVoidType() || rhptee->isVoidType()))
7235       ; // keep old
7236 
7237     // Treat lifetime mismatches as fatal.
7238     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7239       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7240 
7241     // For GCC/MS compatibility, other qualifier mismatches are treated
7242     // as still compatible in C.
7243     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7244   }
7245 
7246   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7247   // incomplete type and the other is a pointer to a qualified or unqualified
7248   // version of void...
7249   if (lhptee->isVoidType()) {
7250     if (rhptee->isIncompleteOrObjectType())
7251       return ConvTy;
7252 
7253     // As an extension, we allow cast to/from void* to function pointer.
7254     assert(rhptee->isFunctionType());
7255     return Sema::FunctionVoidPointer;
7256   }
7257 
7258   if (rhptee->isVoidType()) {
7259     if (lhptee->isIncompleteOrObjectType())
7260       return ConvTy;
7261 
7262     // As an extension, we allow cast to/from void* to function pointer.
7263     assert(lhptee->isFunctionType());
7264     return Sema::FunctionVoidPointer;
7265   }
7266 
7267   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7268   // unqualified versions of compatible types, ...
7269   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7270   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7271     // Check if the pointee types are compatible ignoring the sign.
7272     // We explicitly check for char so that we catch "char" vs
7273     // "unsigned char" on systems where "char" is unsigned.
7274     if (lhptee->isCharType())
7275       ltrans = S.Context.UnsignedCharTy;
7276     else if (lhptee->hasSignedIntegerRepresentation())
7277       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7278 
7279     if (rhptee->isCharType())
7280       rtrans = S.Context.UnsignedCharTy;
7281     else if (rhptee->hasSignedIntegerRepresentation())
7282       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7283 
7284     if (ltrans == rtrans) {
7285       // Types are compatible ignoring the sign. Qualifier incompatibility
7286       // takes priority over sign incompatibility because the sign
7287       // warning can be disabled.
7288       if (ConvTy != Sema::Compatible)
7289         return ConvTy;
7290 
7291       return Sema::IncompatiblePointerSign;
7292     }
7293 
7294     // If we are a multi-level pointer, it's possible that our issue is simply
7295     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7296     // the eventual target type is the same and the pointers have the same
7297     // level of indirection, this must be the issue.
7298     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7299       do {
7300         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7301         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7302       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7303 
7304       if (lhptee == rhptee)
7305         return Sema::IncompatibleNestedPointerQualifiers;
7306     }
7307 
7308     // General pointer incompatibility takes priority over qualifiers.
7309     return Sema::IncompatiblePointer;
7310   }
7311   if (!S.getLangOpts().CPlusPlus &&
7312       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7313     return Sema::IncompatiblePointer;
7314   return ConvTy;
7315 }
7316 
7317 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7318 /// block pointer types are compatible or whether a block and normal pointer
7319 /// are compatible. It is more restrict than comparing two function pointer
7320 // types.
7321 static Sema::AssignConvertType
7322 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7323                                     QualType RHSType) {
7324   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7325   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7326 
7327   QualType lhptee, rhptee;
7328 
7329   // get the "pointed to" type (ignoring qualifiers at the top level)
7330   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7331   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7332 
7333   // In C++, the types have to match exactly.
7334   if (S.getLangOpts().CPlusPlus)
7335     return Sema::IncompatibleBlockPointer;
7336 
7337   Sema::AssignConvertType ConvTy = Sema::Compatible;
7338 
7339   // For blocks we enforce that qualifiers are identical.
7340   Qualifiers LQuals = lhptee.getLocalQualifiers();
7341   Qualifiers RQuals = rhptee.getLocalQualifiers();
7342   if (S.getLangOpts().OpenCL) {
7343     LQuals.removeAddressSpace();
7344     RQuals.removeAddressSpace();
7345   }
7346   if (LQuals != RQuals)
7347     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7348 
7349   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7350   // assignment.
7351   // The current behavior is similar to C++ lambdas. A block might be
7352   // assigned to a variable iff its return type and parameters are compatible
7353   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7354   // an assignment. Presumably it should behave in way that a function pointer
7355   // assignment does in C, so for each parameter and return type:
7356   //  * CVR and address space of LHS should be a superset of CVR and address
7357   //  space of RHS.
7358   //  * unqualified types should be compatible.
7359   if (S.getLangOpts().OpenCL) {
7360     if (!S.Context.typesAreBlockPointerCompatible(
7361             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7362             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7363       return Sema::IncompatibleBlockPointer;
7364   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7365     return Sema::IncompatibleBlockPointer;
7366 
7367   return ConvTy;
7368 }
7369 
7370 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7371 /// for assignment compatibility.
7372 static Sema::AssignConvertType
7373 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7374                                    QualType RHSType) {
7375   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7376   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7377 
7378   if (LHSType->isObjCBuiltinType()) {
7379     // Class is not compatible with ObjC object pointers.
7380     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7381         !RHSType->isObjCQualifiedClassType())
7382       return Sema::IncompatiblePointer;
7383     return Sema::Compatible;
7384   }
7385   if (RHSType->isObjCBuiltinType()) {
7386     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7387         !LHSType->isObjCQualifiedClassType())
7388       return Sema::IncompatiblePointer;
7389     return Sema::Compatible;
7390   }
7391   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7392   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7393 
7394   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7395       // make an exception for id<P>
7396       !LHSType->isObjCQualifiedIdType())
7397     return Sema::CompatiblePointerDiscardsQualifiers;
7398 
7399   if (S.Context.typesAreCompatible(LHSType, RHSType))
7400     return Sema::Compatible;
7401   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7402     return Sema::IncompatibleObjCQualifiedId;
7403   return Sema::IncompatiblePointer;
7404 }
7405 
7406 Sema::AssignConvertType
7407 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7408                                  QualType LHSType, QualType RHSType) {
7409   // Fake up an opaque expression.  We don't actually care about what
7410   // cast operations are required, so if CheckAssignmentConstraints
7411   // adds casts to this they'll be wasted, but fortunately that doesn't
7412   // usually happen on valid code.
7413   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7414   ExprResult RHSPtr = &RHSExpr;
7415   CastKind K = CK_Invalid;
7416 
7417   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7418 }
7419 
7420 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7421 /// has code to accommodate several GCC extensions when type checking
7422 /// pointers. Here are some objectionable examples that GCC considers warnings:
7423 ///
7424 ///  int a, *pint;
7425 ///  short *pshort;
7426 ///  struct foo *pfoo;
7427 ///
7428 ///  pint = pshort; // warning: assignment from incompatible pointer type
7429 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7430 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7431 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7432 ///
7433 /// As a result, the code for dealing with pointers is more complex than the
7434 /// C99 spec dictates.
7435 ///
7436 /// Sets 'Kind' for any result kind except Incompatible.
7437 Sema::AssignConvertType
7438 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7439                                  CastKind &Kind, bool ConvertRHS) {
7440   QualType RHSType = RHS.get()->getType();
7441   QualType OrigLHSType = LHSType;
7442 
7443   // Get canonical types.  We're not formatting these types, just comparing
7444   // them.
7445   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7446   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7447 
7448   // Common case: no conversion required.
7449   if (LHSType == RHSType) {
7450     Kind = CK_NoOp;
7451     return Compatible;
7452   }
7453 
7454   // If we have an atomic type, try a non-atomic assignment, then just add an
7455   // atomic qualification step.
7456   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7457     Sema::AssignConvertType result =
7458       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7459     if (result != Compatible)
7460       return result;
7461     if (Kind != CK_NoOp && ConvertRHS)
7462       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7463     Kind = CK_NonAtomicToAtomic;
7464     return Compatible;
7465   }
7466 
7467   // If the left-hand side is a reference type, then we are in a
7468   // (rare!) case where we've allowed the use of references in C,
7469   // e.g., as a parameter type in a built-in function. In this case,
7470   // just make sure that the type referenced is compatible with the
7471   // right-hand side type. The caller is responsible for adjusting
7472   // LHSType so that the resulting expression does not have reference
7473   // type.
7474   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7475     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7476       Kind = CK_LValueBitCast;
7477       return Compatible;
7478     }
7479     return Incompatible;
7480   }
7481 
7482   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7483   // to the same ExtVector type.
7484   if (LHSType->isExtVectorType()) {
7485     if (RHSType->isExtVectorType())
7486       return Incompatible;
7487     if (RHSType->isArithmeticType()) {
7488       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7489       if (ConvertRHS)
7490         RHS = prepareVectorSplat(LHSType, RHS.get());
7491       Kind = CK_VectorSplat;
7492       return Compatible;
7493     }
7494   }
7495 
7496   // Conversions to or from vector type.
7497   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7498     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7499       // Allow assignments of an AltiVec vector type to an equivalent GCC
7500       // vector type and vice versa
7501       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7502         Kind = CK_BitCast;
7503         return Compatible;
7504       }
7505 
7506       // If we are allowing lax vector conversions, and LHS and RHS are both
7507       // vectors, the total size only needs to be the same. This is a bitcast;
7508       // no bits are changed but the result type is different.
7509       if (isLaxVectorConversion(RHSType, LHSType)) {
7510         Kind = CK_BitCast;
7511         return IncompatibleVectors;
7512       }
7513     }
7514 
7515     // When the RHS comes from another lax conversion (e.g. binops between
7516     // scalars and vectors) the result is canonicalized as a vector. When the
7517     // LHS is also a vector, the lax is allowed by the condition above. Handle
7518     // the case where LHS is a scalar.
7519     if (LHSType->isScalarType()) {
7520       const VectorType *VecType = RHSType->getAs<VectorType>();
7521       if (VecType && VecType->getNumElements() == 1 &&
7522           isLaxVectorConversion(RHSType, LHSType)) {
7523         ExprResult *VecExpr = &RHS;
7524         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7525         Kind = CK_BitCast;
7526         return Compatible;
7527       }
7528     }
7529 
7530     return Incompatible;
7531   }
7532 
7533   // Diagnose attempts to convert between __float128 and long double where
7534   // such conversions currently can't be handled.
7535   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7536     return Incompatible;
7537 
7538   // Disallow assigning a _Complex to a real type in C++ mode since it simply
7539   // discards the imaginary part.
7540   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
7541       !LHSType->getAs<ComplexType>())
7542     return Incompatible;
7543 
7544   // Arithmetic conversions.
7545   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7546       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7547     if (ConvertRHS)
7548       Kind = PrepareScalarCast(RHS, LHSType);
7549     return Compatible;
7550   }
7551 
7552   // Conversions to normal pointers.
7553   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7554     // U* -> T*
7555     if (isa<PointerType>(RHSType)) {
7556       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7557       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7558       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7559       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7560     }
7561 
7562     // int -> T*
7563     if (RHSType->isIntegerType()) {
7564       Kind = CK_IntegralToPointer; // FIXME: null?
7565       return IntToPointer;
7566     }
7567 
7568     // C pointers are not compatible with ObjC object pointers,
7569     // with two exceptions:
7570     if (isa<ObjCObjectPointerType>(RHSType)) {
7571       //  - conversions to void*
7572       if (LHSPointer->getPointeeType()->isVoidType()) {
7573         Kind = CK_BitCast;
7574         return Compatible;
7575       }
7576 
7577       //  - conversions from 'Class' to the redefinition type
7578       if (RHSType->isObjCClassType() &&
7579           Context.hasSameType(LHSType,
7580                               Context.getObjCClassRedefinitionType())) {
7581         Kind = CK_BitCast;
7582         return Compatible;
7583       }
7584 
7585       Kind = CK_BitCast;
7586       return IncompatiblePointer;
7587     }
7588 
7589     // U^ -> void*
7590     if (RHSType->getAs<BlockPointerType>()) {
7591       if (LHSPointer->getPointeeType()->isVoidType()) {
7592         unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7593         unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7594                                   ->getPointeeType()
7595                                   .getAddressSpace();
7596         Kind =
7597             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7598         return Compatible;
7599       }
7600     }
7601 
7602     return Incompatible;
7603   }
7604 
7605   // Conversions to block pointers.
7606   if (isa<BlockPointerType>(LHSType)) {
7607     // U^ -> T^
7608     if (RHSType->isBlockPointerType()) {
7609       unsigned AddrSpaceL = LHSType->getAs<BlockPointerType>()
7610                                 ->getPointeeType()
7611                                 .getAddressSpace();
7612       unsigned AddrSpaceR = RHSType->getAs<BlockPointerType>()
7613                                 ->getPointeeType()
7614                                 .getAddressSpace();
7615       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7616       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7617     }
7618 
7619     // int or null -> T^
7620     if (RHSType->isIntegerType()) {
7621       Kind = CK_IntegralToPointer; // FIXME: null
7622       return IntToBlockPointer;
7623     }
7624 
7625     // id -> T^
7626     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7627       Kind = CK_AnyPointerToBlockPointerCast;
7628       return Compatible;
7629     }
7630 
7631     // void* -> T^
7632     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7633       if (RHSPT->getPointeeType()->isVoidType()) {
7634         Kind = CK_AnyPointerToBlockPointerCast;
7635         return Compatible;
7636       }
7637 
7638     return Incompatible;
7639   }
7640 
7641   // Conversions to Objective-C pointers.
7642   if (isa<ObjCObjectPointerType>(LHSType)) {
7643     // A* -> B*
7644     if (RHSType->isObjCObjectPointerType()) {
7645       Kind = CK_BitCast;
7646       Sema::AssignConvertType result =
7647         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7648       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7649           result == Compatible &&
7650           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7651         result = IncompatibleObjCWeakRef;
7652       return result;
7653     }
7654 
7655     // int or null -> A*
7656     if (RHSType->isIntegerType()) {
7657       Kind = CK_IntegralToPointer; // FIXME: null
7658       return IntToPointer;
7659     }
7660 
7661     // In general, C pointers are not compatible with ObjC object pointers,
7662     // with two exceptions:
7663     if (isa<PointerType>(RHSType)) {
7664       Kind = CK_CPointerToObjCPointerCast;
7665 
7666       //  - conversions from 'void*'
7667       if (RHSType->isVoidPointerType()) {
7668         return Compatible;
7669       }
7670 
7671       //  - conversions to 'Class' from its redefinition type
7672       if (LHSType->isObjCClassType() &&
7673           Context.hasSameType(RHSType,
7674                               Context.getObjCClassRedefinitionType())) {
7675         return Compatible;
7676       }
7677 
7678       return IncompatiblePointer;
7679     }
7680 
7681     // Only under strict condition T^ is compatible with an Objective-C pointer.
7682     if (RHSType->isBlockPointerType() &&
7683         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7684       if (ConvertRHS)
7685         maybeExtendBlockObject(RHS);
7686       Kind = CK_BlockPointerToObjCPointerCast;
7687       return Compatible;
7688     }
7689 
7690     return Incompatible;
7691   }
7692 
7693   // Conversions from pointers that are not covered by the above.
7694   if (isa<PointerType>(RHSType)) {
7695     // T* -> _Bool
7696     if (LHSType == Context.BoolTy) {
7697       Kind = CK_PointerToBoolean;
7698       return Compatible;
7699     }
7700 
7701     // T* -> int
7702     if (LHSType->isIntegerType()) {
7703       Kind = CK_PointerToIntegral;
7704       return PointerToInt;
7705     }
7706 
7707     return Incompatible;
7708   }
7709 
7710   // Conversions from Objective-C pointers that are not covered by the above.
7711   if (isa<ObjCObjectPointerType>(RHSType)) {
7712     // T* -> _Bool
7713     if (LHSType == Context.BoolTy) {
7714       Kind = CK_PointerToBoolean;
7715       return Compatible;
7716     }
7717 
7718     // T* -> int
7719     if (LHSType->isIntegerType()) {
7720       Kind = CK_PointerToIntegral;
7721       return PointerToInt;
7722     }
7723 
7724     return Incompatible;
7725   }
7726 
7727   // struct A -> struct B
7728   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7729     if (Context.typesAreCompatible(LHSType, RHSType)) {
7730       Kind = CK_NoOp;
7731       return Compatible;
7732     }
7733   }
7734 
7735   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7736     Kind = CK_IntToOCLSampler;
7737     return Compatible;
7738   }
7739 
7740   return Incompatible;
7741 }
7742 
7743 /// \brief Constructs a transparent union from an expression that is
7744 /// used to initialize the transparent union.
7745 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7746                                       ExprResult &EResult, QualType UnionType,
7747                                       FieldDecl *Field) {
7748   // Build an initializer list that designates the appropriate member
7749   // of the transparent union.
7750   Expr *E = EResult.get();
7751   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7752                                                    E, SourceLocation());
7753   Initializer->setType(UnionType);
7754   Initializer->setInitializedFieldInUnion(Field);
7755 
7756   // Build a compound literal constructing a value of the transparent
7757   // union type from this initializer list.
7758   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7759   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7760                                         VK_RValue, Initializer, false);
7761 }
7762 
7763 Sema::AssignConvertType
7764 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7765                                                ExprResult &RHS) {
7766   QualType RHSType = RHS.get()->getType();
7767 
7768   // If the ArgType is a Union type, we want to handle a potential
7769   // transparent_union GCC extension.
7770   const RecordType *UT = ArgType->getAsUnionType();
7771   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7772     return Incompatible;
7773 
7774   // The field to initialize within the transparent union.
7775   RecordDecl *UD = UT->getDecl();
7776   FieldDecl *InitField = nullptr;
7777   // It's compatible if the expression matches any of the fields.
7778   for (auto *it : UD->fields()) {
7779     if (it->getType()->isPointerType()) {
7780       // If the transparent union contains a pointer type, we allow:
7781       // 1) void pointer
7782       // 2) null pointer constant
7783       if (RHSType->isPointerType())
7784         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7785           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7786           InitField = it;
7787           break;
7788         }
7789 
7790       if (RHS.get()->isNullPointerConstant(Context,
7791                                            Expr::NPC_ValueDependentIsNull)) {
7792         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7793                                 CK_NullToPointer);
7794         InitField = it;
7795         break;
7796       }
7797     }
7798 
7799     CastKind Kind = CK_Invalid;
7800     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7801           == Compatible) {
7802       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7803       InitField = it;
7804       break;
7805     }
7806   }
7807 
7808   if (!InitField)
7809     return Incompatible;
7810 
7811   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7812   return Compatible;
7813 }
7814 
7815 Sema::AssignConvertType
7816 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7817                                        bool Diagnose,
7818                                        bool DiagnoseCFAudited,
7819                                        bool ConvertRHS) {
7820   // We need to be able to tell the caller whether we diagnosed a problem, if
7821   // they ask us to issue diagnostics.
7822   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7823 
7824   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7825   // we can't avoid *all* modifications at the moment, so we need some somewhere
7826   // to put the updated value.
7827   ExprResult LocalRHS = CallerRHS;
7828   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7829 
7830   if (getLangOpts().CPlusPlus) {
7831     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7832       // C++ 5.17p3: If the left operand is not of class type, the
7833       // expression is implicitly converted (C++ 4) to the
7834       // cv-unqualified type of the left operand.
7835       QualType RHSType = RHS.get()->getType();
7836       if (Diagnose) {
7837         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7838                                         AA_Assigning);
7839       } else {
7840         ImplicitConversionSequence ICS =
7841             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7842                                   /*SuppressUserConversions=*/false,
7843                                   /*AllowExplicit=*/false,
7844                                   /*InOverloadResolution=*/false,
7845                                   /*CStyle=*/false,
7846                                   /*AllowObjCWritebackConversion=*/false);
7847         if (ICS.isFailure())
7848           return Incompatible;
7849         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7850                                         ICS, AA_Assigning);
7851       }
7852       if (RHS.isInvalid())
7853         return Incompatible;
7854       Sema::AssignConvertType result = Compatible;
7855       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7856           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7857         result = IncompatibleObjCWeakRef;
7858       return result;
7859     }
7860 
7861     // FIXME: Currently, we fall through and treat C++ classes like C
7862     // structures.
7863     // FIXME: We also fall through for atomics; not sure what should
7864     // happen there, though.
7865   } else if (RHS.get()->getType() == Context.OverloadTy) {
7866     // As a set of extensions to C, we support overloading on functions. These
7867     // functions need to be resolved here.
7868     DeclAccessPair DAP;
7869     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7870             RHS.get(), LHSType, /*Complain=*/false, DAP))
7871       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7872     else
7873       return Incompatible;
7874   }
7875 
7876   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7877   // a null pointer constant.
7878   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7879        LHSType->isBlockPointerType()) &&
7880       RHS.get()->isNullPointerConstant(Context,
7881                                        Expr::NPC_ValueDependentIsNull)) {
7882     if (Diagnose || ConvertRHS) {
7883       CastKind Kind;
7884       CXXCastPath Path;
7885       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7886                              /*IgnoreBaseAccess=*/false, Diagnose);
7887       if (ConvertRHS)
7888         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7889     }
7890     return Compatible;
7891   }
7892 
7893   // This check seems unnatural, however it is necessary to ensure the proper
7894   // conversion of functions/arrays. If the conversion were done for all
7895   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7896   // expressions that suppress this implicit conversion (&, sizeof).
7897   //
7898   // Suppress this for references: C++ 8.5.3p5.
7899   if (!LHSType->isReferenceType()) {
7900     // FIXME: We potentially allocate here even if ConvertRHS is false.
7901     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7902     if (RHS.isInvalid())
7903       return Incompatible;
7904   }
7905 
7906   Expr *PRE = RHS.get()->IgnoreParenCasts();
7907   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7908     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7909     if (PDecl && !PDecl->hasDefinition()) {
7910       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7911       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7912     }
7913   }
7914 
7915   CastKind Kind = CK_Invalid;
7916   Sema::AssignConvertType result =
7917     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7918 
7919   // C99 6.5.16.1p2: The value of the right operand is converted to the
7920   // type of the assignment expression.
7921   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7922   // so that we can use references in built-in functions even in C.
7923   // The getNonReferenceType() call makes sure that the resulting expression
7924   // does not have reference type.
7925   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7926     QualType Ty = LHSType.getNonLValueExprType(Context);
7927     Expr *E = RHS.get();
7928 
7929     // Check for various Objective-C errors. If we are not reporting
7930     // diagnostics and just checking for errors, e.g., during overload
7931     // resolution, return Incompatible to indicate the failure.
7932     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7933         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7934                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
7935       if (!Diagnose)
7936         return Incompatible;
7937     }
7938     if (getLangOpts().ObjC1 &&
7939         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7940                                            E->getType(), E, Diagnose) ||
7941          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7942       if (!Diagnose)
7943         return Incompatible;
7944       // Replace the expression with a corrected version and continue so we
7945       // can find further errors.
7946       RHS = E;
7947       return Compatible;
7948     }
7949 
7950     if (ConvertRHS)
7951       RHS = ImpCastExprToType(E, Ty, Kind);
7952   }
7953   return result;
7954 }
7955 
7956 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7957                                ExprResult &RHS) {
7958   Diag(Loc, diag::err_typecheck_invalid_operands)
7959     << LHS.get()->getType() << RHS.get()->getType()
7960     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7961   return QualType();
7962 }
7963 
7964 // Diagnose cases where a scalar was implicitly converted to a vector and
7965 // diagnose the underlying types. Otherwise, diagnose the error
7966 // as invalid vector logical operands for non-C++ cases.
7967 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
7968                                             ExprResult &RHS) {
7969   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
7970   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
7971 
7972   bool LHSNatVec = LHSType->isVectorType();
7973   bool RHSNatVec = RHSType->isVectorType();
7974 
7975   if (!(LHSNatVec && RHSNatVec)) {
7976     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
7977     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
7978     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
7979         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
7980         << Vector->getSourceRange();
7981     return QualType();
7982   }
7983 
7984   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
7985       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
7986       << RHS.get()->getSourceRange();
7987 
7988   return QualType();
7989 }
7990 
7991 /// Try to convert a value of non-vector type to a vector type by converting
7992 /// the type to the element type of the vector and then performing a splat.
7993 /// If the language is OpenCL, we only use conversions that promote scalar
7994 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7995 /// for float->int.
7996 ///
7997 /// OpenCL V2.0 6.2.6.p2:
7998 /// An error shall occur if any scalar operand type has greater rank
7999 /// than the type of the vector element.
8000 ///
8001 /// \param scalar - if non-null, actually perform the conversions
8002 /// \return true if the operation fails (but without diagnosing the failure)
8003 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8004                                      QualType scalarTy,
8005                                      QualType vectorEltTy,
8006                                      QualType vectorTy,
8007                                      unsigned &DiagID) {
8008   // The conversion to apply to the scalar before splatting it,
8009   // if necessary.
8010   CastKind scalarCast = CK_Invalid;
8011 
8012   if (vectorEltTy->isIntegralType(S.Context)) {
8013     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8014         (scalarTy->isIntegerType() &&
8015          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8016       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8017       return true;
8018     }
8019     if (!scalarTy->isIntegralType(S.Context))
8020       return true;
8021     scalarCast = CK_IntegralCast;
8022   } else if (vectorEltTy->isRealFloatingType()) {
8023     if (scalarTy->isRealFloatingType()) {
8024       if (S.getLangOpts().OpenCL &&
8025           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8026         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8027         return true;
8028       }
8029       scalarCast = CK_FloatingCast;
8030     }
8031     else if (scalarTy->isIntegralType(S.Context))
8032       scalarCast = CK_IntegralToFloating;
8033     else
8034       return true;
8035   } else {
8036     return true;
8037   }
8038 
8039   // Adjust scalar if desired.
8040   if (scalar) {
8041     if (scalarCast != CK_Invalid)
8042       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8043     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8044   }
8045   return false;
8046 }
8047 
8048 /// Test if a (constant) integer Int can be casted to another integer type
8049 /// IntTy without losing precision.
8050 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8051                                       QualType OtherIntTy) {
8052   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8053 
8054   // Reject cases where the value of the Int is unknown as that would
8055   // possibly cause truncation, but accept cases where the scalar can be
8056   // demoted without loss of precision.
8057   llvm::APSInt Result;
8058   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8059   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8060   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8061   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8062 
8063   if (CstInt) {
8064     // If the scalar is constant and is of a higher order and has more active
8065     // bits that the vector element type, reject it.
8066     unsigned NumBits = IntSigned
8067                            ? (Result.isNegative() ? Result.getMinSignedBits()
8068                                                   : Result.getActiveBits())
8069                            : Result.getActiveBits();
8070     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8071       return true;
8072 
8073     // If the signedness of the scalar type and the vector element type
8074     // differs and the number of bits is greater than that of the vector
8075     // element reject it.
8076     return (IntSigned != OtherIntSigned &&
8077             NumBits > S.Context.getIntWidth(OtherIntTy));
8078   }
8079 
8080   // Reject cases where the value of the scalar is not constant and it's
8081   // order is greater than that of the vector element type.
8082   return (Order < 0);
8083 }
8084 
8085 /// Test if a (constant) integer Int can be casted to floating point type
8086 /// FloatTy without losing precision.
8087 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8088                                      QualType FloatTy) {
8089   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8090 
8091   // Determine if the integer constant can be expressed as a floating point
8092   // number of the appropiate type.
8093   llvm::APSInt Result;
8094   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8095   uint64_t Bits = 0;
8096   if (CstInt) {
8097     // Reject constants that would be truncated if they were converted to
8098     // the floating point type. Test by simple to/from conversion.
8099     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8100     //        could be avoided if there was a convertFromAPInt method
8101     //        which could signal back if implicit truncation occurred.
8102     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8103     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8104                            llvm::APFloat::rmTowardZero);
8105     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8106                              !IntTy->hasSignedIntegerRepresentation());
8107     bool Ignored = false;
8108     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8109                            &Ignored);
8110     if (Result != ConvertBack)
8111       return true;
8112   } else {
8113     // Reject types that cannot be fully encoded into the mantissa of
8114     // the float.
8115     Bits = S.Context.getTypeSize(IntTy);
8116     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8117         S.Context.getFloatTypeSemantics(FloatTy));
8118     if (Bits > FloatPrec)
8119       return true;
8120   }
8121 
8122   return false;
8123 }
8124 
8125 /// Attempt to convert and splat Scalar into a vector whose types matches
8126 /// Vector following GCC conversion rules. The rule is that implicit
8127 /// conversion can occur when Scalar can be casted to match Vector's element
8128 /// type without causing truncation of Scalar.
8129 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8130                                         ExprResult *Vector) {
8131   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8132   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8133   const VectorType *VT = VectorTy->getAs<VectorType>();
8134 
8135   assert(!isa<ExtVectorType>(VT) &&
8136          "ExtVectorTypes should not be handled here!");
8137 
8138   QualType VectorEltTy = VT->getElementType();
8139 
8140   // Reject cases where the vector element type or the scalar element type are
8141   // not integral or floating point types.
8142   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8143     return true;
8144 
8145   // The conversion to apply to the scalar before splatting it,
8146   // if necessary.
8147   CastKind ScalarCast = CK_NoOp;
8148 
8149   // Accept cases where the vector elements are integers and the scalar is
8150   // an integer.
8151   // FIXME: Notionally if the scalar was a floating point value with a precise
8152   //        integral representation, we could cast it to an appropriate integer
8153   //        type and then perform the rest of the checks here. GCC will perform
8154   //        this conversion in some cases as determined by the input language.
8155   //        We should accept it on a language independent basis.
8156   if (VectorEltTy->isIntegralType(S.Context) &&
8157       ScalarTy->isIntegralType(S.Context) &&
8158       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8159 
8160     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8161       return true;
8162 
8163     ScalarCast = CK_IntegralCast;
8164   } else if (VectorEltTy->isRealFloatingType()) {
8165     if (ScalarTy->isRealFloatingType()) {
8166 
8167       // Reject cases where the scalar type is not a constant and has a higher
8168       // Order than the vector element type.
8169       llvm::APFloat Result(0.0);
8170       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8171       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8172       if (!CstScalar && Order < 0)
8173         return true;
8174 
8175       // If the scalar cannot be safely casted to the vector element type,
8176       // reject it.
8177       if (CstScalar) {
8178         bool Truncated = false;
8179         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8180                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8181         if (Truncated)
8182           return true;
8183       }
8184 
8185       ScalarCast = CK_FloatingCast;
8186     } else if (ScalarTy->isIntegralType(S.Context)) {
8187       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8188         return true;
8189 
8190       ScalarCast = CK_IntegralToFloating;
8191     } else
8192       return true;
8193   }
8194 
8195   // Adjust scalar if desired.
8196   if (Scalar) {
8197     if (ScalarCast != CK_NoOp)
8198       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8199     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8200   }
8201   return false;
8202 }
8203 
8204 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8205                                    SourceLocation Loc, bool IsCompAssign,
8206                                    bool AllowBothBool,
8207                                    bool AllowBoolConversions) {
8208   if (!IsCompAssign) {
8209     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8210     if (LHS.isInvalid())
8211       return QualType();
8212   }
8213   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8214   if (RHS.isInvalid())
8215     return QualType();
8216 
8217   // For conversion purposes, we ignore any qualifiers.
8218   // For example, "const float" and "float" are equivalent.
8219   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8220   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8221 
8222   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8223   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8224   assert(LHSVecType || RHSVecType);
8225 
8226   // AltiVec-style "vector bool op vector bool" combinations are allowed
8227   // for some operators but not others.
8228   if (!AllowBothBool &&
8229       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8230       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8231     return InvalidOperands(Loc, LHS, RHS);
8232 
8233   // If the vector types are identical, return.
8234   if (Context.hasSameType(LHSType, RHSType))
8235     return LHSType;
8236 
8237   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8238   if (LHSVecType && RHSVecType &&
8239       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8240     if (isa<ExtVectorType>(LHSVecType)) {
8241       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8242       return LHSType;
8243     }
8244 
8245     if (!IsCompAssign)
8246       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8247     return RHSType;
8248   }
8249 
8250   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8251   // can be mixed, with the result being the non-bool type.  The non-bool
8252   // operand must have integer element type.
8253   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8254       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8255       (Context.getTypeSize(LHSVecType->getElementType()) ==
8256        Context.getTypeSize(RHSVecType->getElementType()))) {
8257     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8258         LHSVecType->getElementType()->isIntegerType() &&
8259         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8260       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8261       return LHSType;
8262     }
8263     if (!IsCompAssign &&
8264         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8265         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8266         RHSVecType->getElementType()->isIntegerType()) {
8267       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8268       return RHSType;
8269     }
8270   }
8271 
8272   // If there's a vector type and a scalar, try to convert the scalar to
8273   // the vector element type and splat.
8274   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8275   if (!RHSVecType) {
8276     if (isa<ExtVectorType>(LHSVecType)) {
8277       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8278                                     LHSVecType->getElementType(), LHSType,
8279                                     DiagID))
8280         return LHSType;
8281     } else {
8282       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8283         return LHSType;
8284     }
8285   }
8286   if (!LHSVecType) {
8287     if (isa<ExtVectorType>(RHSVecType)) {
8288       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8289                                     LHSType, RHSVecType->getElementType(),
8290                                     RHSType, DiagID))
8291         return RHSType;
8292     } else {
8293       if (LHS.get()->getValueKind() == VK_LValue ||
8294           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8295         return RHSType;
8296     }
8297   }
8298 
8299   // FIXME: The code below also handles conversion between vectors and
8300   // non-scalars, we should break this down into fine grained specific checks
8301   // and emit proper diagnostics.
8302   QualType VecType = LHSVecType ? LHSType : RHSType;
8303   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8304   QualType OtherType = LHSVecType ? RHSType : LHSType;
8305   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8306   if (isLaxVectorConversion(OtherType, VecType)) {
8307     // If we're allowing lax vector conversions, only the total (data) size
8308     // needs to be the same. For non compound assignment, if one of the types is
8309     // scalar, the result is always the vector type.
8310     if (!IsCompAssign) {
8311       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8312       return VecType;
8313     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8314     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8315     // type. Note that this is already done by non-compound assignments in
8316     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8317     // <1 x T> -> T. The result is also a vector type.
8318     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8319                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8320       ExprResult *RHSExpr = &RHS;
8321       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8322       return VecType;
8323     }
8324   }
8325 
8326   // Okay, the expression is invalid.
8327 
8328   // If there's a non-vector, non-real operand, diagnose that.
8329   if ((!RHSVecType && !RHSType->isRealType()) ||
8330       (!LHSVecType && !LHSType->isRealType())) {
8331     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8332       << LHSType << RHSType
8333       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8334     return QualType();
8335   }
8336 
8337   // OpenCL V1.1 6.2.6.p1:
8338   // If the operands are of more than one vector type, then an error shall
8339   // occur. Implicit conversions between vector types are not permitted, per
8340   // section 6.2.1.
8341   if (getLangOpts().OpenCL &&
8342       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8343       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8344     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8345                                                            << RHSType;
8346     return QualType();
8347   }
8348 
8349 
8350   // If there is a vector type that is not a ExtVector and a scalar, we reach
8351   // this point if scalar could not be converted to the vector's element type
8352   // without truncation.
8353   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8354       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8355     QualType Scalar = LHSVecType ? RHSType : LHSType;
8356     QualType Vector = LHSVecType ? LHSType : RHSType;
8357     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8358     Diag(Loc,
8359          diag::err_typecheck_vector_not_convertable_implict_truncation)
8360         << ScalarOrVector << Scalar << Vector;
8361 
8362     return QualType();
8363   }
8364 
8365   // Otherwise, use the generic diagnostic.
8366   Diag(Loc, DiagID)
8367     << LHSType << RHSType
8368     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8369   return QualType();
8370 }
8371 
8372 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8373 // expression.  These are mainly cases where the null pointer is used as an
8374 // integer instead of a pointer.
8375 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8376                                 SourceLocation Loc, bool IsCompare) {
8377   // The canonical way to check for a GNU null is with isNullPointerConstant,
8378   // but we use a bit of a hack here for speed; this is a relatively
8379   // hot path, and isNullPointerConstant is slow.
8380   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8381   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8382 
8383   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8384 
8385   // Avoid analyzing cases where the result will either be invalid (and
8386   // diagnosed as such) or entirely valid and not something to warn about.
8387   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8388       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8389     return;
8390 
8391   // Comparison operations would not make sense with a null pointer no matter
8392   // what the other expression is.
8393   if (!IsCompare) {
8394     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8395         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8396         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8397     return;
8398   }
8399 
8400   // The rest of the operations only make sense with a null pointer
8401   // if the other expression is a pointer.
8402   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8403       NonNullType->canDecayToPointerType())
8404     return;
8405 
8406   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8407       << LHSNull /* LHS is NULL */ << NonNullType
8408       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8409 }
8410 
8411 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8412                                                ExprResult &RHS,
8413                                                SourceLocation Loc, bool IsDiv) {
8414   // Check for division/remainder by zero.
8415   llvm::APSInt RHSValue;
8416   if (!RHS.get()->isValueDependent() &&
8417       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8418     S.DiagRuntimeBehavior(Loc, RHS.get(),
8419                           S.PDiag(diag::warn_remainder_division_by_zero)
8420                             << IsDiv << RHS.get()->getSourceRange());
8421 }
8422 
8423 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8424                                            SourceLocation Loc,
8425                                            bool IsCompAssign, bool IsDiv) {
8426   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8427 
8428   if (LHS.get()->getType()->isVectorType() ||
8429       RHS.get()->getType()->isVectorType())
8430     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8431                                /*AllowBothBool*/getLangOpts().AltiVec,
8432                                /*AllowBoolConversions*/false);
8433 
8434   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8435   if (LHS.isInvalid() || RHS.isInvalid())
8436     return QualType();
8437 
8438 
8439   if (compType.isNull() || !compType->isArithmeticType())
8440     return InvalidOperands(Loc, LHS, RHS);
8441   if (IsDiv)
8442     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8443   return compType;
8444 }
8445 
8446 QualType Sema::CheckRemainderOperands(
8447   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8448   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8449 
8450   if (LHS.get()->getType()->isVectorType() ||
8451       RHS.get()->getType()->isVectorType()) {
8452     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8453         RHS.get()->getType()->hasIntegerRepresentation())
8454       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8455                                  /*AllowBothBool*/getLangOpts().AltiVec,
8456                                  /*AllowBoolConversions*/false);
8457     return InvalidOperands(Loc, LHS, RHS);
8458   }
8459 
8460   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8461   if (LHS.isInvalid() || RHS.isInvalid())
8462     return QualType();
8463 
8464   if (compType.isNull() || !compType->isIntegerType())
8465     return InvalidOperands(Loc, LHS, RHS);
8466   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8467   return compType;
8468 }
8469 
8470 /// \brief Diagnose invalid arithmetic on two void pointers.
8471 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8472                                                 Expr *LHSExpr, Expr *RHSExpr) {
8473   S.Diag(Loc, S.getLangOpts().CPlusPlus
8474                 ? diag::err_typecheck_pointer_arith_void_type
8475                 : diag::ext_gnu_void_ptr)
8476     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8477                             << RHSExpr->getSourceRange();
8478 }
8479 
8480 /// \brief Diagnose invalid arithmetic on a void pointer.
8481 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8482                                             Expr *Pointer) {
8483   S.Diag(Loc, S.getLangOpts().CPlusPlus
8484                 ? diag::err_typecheck_pointer_arith_void_type
8485                 : diag::ext_gnu_void_ptr)
8486     << 0 /* one pointer */ << Pointer->getSourceRange();
8487 }
8488 
8489 /// \brief Diagnose invalid arithmetic on two function pointers.
8490 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8491                                                     Expr *LHS, Expr *RHS) {
8492   assert(LHS->getType()->isAnyPointerType());
8493   assert(RHS->getType()->isAnyPointerType());
8494   S.Diag(Loc, S.getLangOpts().CPlusPlus
8495                 ? diag::err_typecheck_pointer_arith_function_type
8496                 : diag::ext_gnu_ptr_func_arith)
8497     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8498     // We only show the second type if it differs from the first.
8499     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8500                                                    RHS->getType())
8501     << RHS->getType()->getPointeeType()
8502     << LHS->getSourceRange() << RHS->getSourceRange();
8503 }
8504 
8505 /// \brief Diagnose invalid arithmetic on a function pointer.
8506 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8507                                                 Expr *Pointer) {
8508   assert(Pointer->getType()->isAnyPointerType());
8509   S.Diag(Loc, S.getLangOpts().CPlusPlus
8510                 ? diag::err_typecheck_pointer_arith_function_type
8511                 : diag::ext_gnu_ptr_func_arith)
8512     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8513     << 0 /* one pointer, so only one type */
8514     << Pointer->getSourceRange();
8515 }
8516 
8517 /// \brief Emit error if Operand is incomplete pointer type
8518 ///
8519 /// \returns True if pointer has incomplete type
8520 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8521                                                  Expr *Operand) {
8522   QualType ResType = Operand->getType();
8523   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8524     ResType = ResAtomicType->getValueType();
8525 
8526   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8527   QualType PointeeTy = ResType->getPointeeType();
8528   return S.RequireCompleteType(Loc, PointeeTy,
8529                                diag::err_typecheck_arithmetic_incomplete_type,
8530                                PointeeTy, Operand->getSourceRange());
8531 }
8532 
8533 /// \brief Check the validity of an arithmetic pointer operand.
8534 ///
8535 /// If the operand has pointer type, this code will check for pointer types
8536 /// which are invalid in arithmetic operations. These will be diagnosed
8537 /// appropriately, including whether or not the use is supported as an
8538 /// extension.
8539 ///
8540 /// \returns True when the operand is valid to use (even if as an extension).
8541 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8542                                             Expr *Operand) {
8543   QualType ResType = Operand->getType();
8544   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8545     ResType = ResAtomicType->getValueType();
8546 
8547   if (!ResType->isAnyPointerType()) return true;
8548 
8549   QualType PointeeTy = ResType->getPointeeType();
8550   if (PointeeTy->isVoidType()) {
8551     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8552     return !S.getLangOpts().CPlusPlus;
8553   }
8554   if (PointeeTy->isFunctionType()) {
8555     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8556     return !S.getLangOpts().CPlusPlus;
8557   }
8558 
8559   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8560 
8561   return true;
8562 }
8563 
8564 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8565 /// operands.
8566 ///
8567 /// This routine will diagnose any invalid arithmetic on pointer operands much
8568 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8569 /// for emitting a single diagnostic even for operations where both LHS and RHS
8570 /// are (potentially problematic) pointers.
8571 ///
8572 /// \returns True when the operand is valid to use (even if as an extension).
8573 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8574                                                 Expr *LHSExpr, Expr *RHSExpr) {
8575   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8576   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8577   if (!isLHSPointer && !isRHSPointer) return true;
8578 
8579   QualType LHSPointeeTy, RHSPointeeTy;
8580   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8581   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8582 
8583   // if both are pointers check if operation is valid wrt address spaces
8584   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8585     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8586     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8587     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8588       S.Diag(Loc,
8589              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8590           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8591           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8592       return false;
8593     }
8594   }
8595 
8596   // Check for arithmetic on pointers to incomplete types.
8597   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8598   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8599   if (isLHSVoidPtr || isRHSVoidPtr) {
8600     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8601     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8602     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8603 
8604     return !S.getLangOpts().CPlusPlus;
8605   }
8606 
8607   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8608   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8609   if (isLHSFuncPtr || isRHSFuncPtr) {
8610     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8611     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8612                                                                 RHSExpr);
8613     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8614 
8615     return !S.getLangOpts().CPlusPlus;
8616   }
8617 
8618   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8619     return false;
8620   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8621     return false;
8622 
8623   return true;
8624 }
8625 
8626 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8627 /// literal.
8628 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8629                                   Expr *LHSExpr, Expr *RHSExpr) {
8630   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8631   Expr* IndexExpr = RHSExpr;
8632   if (!StrExpr) {
8633     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8634     IndexExpr = LHSExpr;
8635   }
8636 
8637   bool IsStringPlusInt = StrExpr &&
8638       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8639   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8640     return;
8641 
8642   llvm::APSInt index;
8643   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8644     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8645     if (index.isNonNegative() &&
8646         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8647                               index.isUnsigned()))
8648       return;
8649   }
8650 
8651   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8652   Self.Diag(OpLoc, diag::warn_string_plus_int)
8653       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8654 
8655   // Only print a fixit for "str" + int, not for int + "str".
8656   if (IndexExpr == RHSExpr) {
8657     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8658     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8659         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8660         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8661         << FixItHint::CreateInsertion(EndLoc, "]");
8662   } else
8663     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8664 }
8665 
8666 /// \brief Emit a warning when adding a char literal to a string.
8667 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8668                                    Expr *LHSExpr, Expr *RHSExpr) {
8669   const Expr *StringRefExpr = LHSExpr;
8670   const CharacterLiteral *CharExpr =
8671       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8672 
8673   if (!CharExpr) {
8674     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8675     StringRefExpr = RHSExpr;
8676   }
8677 
8678   if (!CharExpr || !StringRefExpr)
8679     return;
8680 
8681   const QualType StringType = StringRefExpr->getType();
8682 
8683   // Return if not a PointerType.
8684   if (!StringType->isAnyPointerType())
8685     return;
8686 
8687   // Return if not a CharacterType.
8688   if (!StringType->getPointeeType()->isAnyCharacterType())
8689     return;
8690 
8691   ASTContext &Ctx = Self.getASTContext();
8692   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8693 
8694   const QualType CharType = CharExpr->getType();
8695   if (!CharType->isAnyCharacterType() &&
8696       CharType->isIntegerType() &&
8697       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8698     Self.Diag(OpLoc, diag::warn_string_plus_char)
8699         << DiagRange << Ctx.CharTy;
8700   } else {
8701     Self.Diag(OpLoc, diag::warn_string_plus_char)
8702         << DiagRange << CharExpr->getType();
8703   }
8704 
8705   // Only print a fixit for str + char, not for char + str.
8706   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
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 
8717 /// \brief Emit error when two pointers are incompatible.
8718 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8719                                            Expr *LHSExpr, Expr *RHSExpr) {
8720   assert(LHSExpr->getType()->isAnyPointerType());
8721   assert(RHSExpr->getType()->isAnyPointerType());
8722   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8723     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8724     << RHSExpr->getSourceRange();
8725 }
8726 
8727 // C99 6.5.6
8728 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8729                                      SourceLocation Loc, BinaryOperatorKind Opc,
8730                                      QualType* CompLHSTy) {
8731   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8732 
8733   if (LHS.get()->getType()->isVectorType() ||
8734       RHS.get()->getType()->isVectorType()) {
8735     QualType compType = CheckVectorOperands(
8736         LHS, RHS, Loc, CompLHSTy,
8737         /*AllowBothBool*/getLangOpts().AltiVec,
8738         /*AllowBoolConversions*/getLangOpts().ZVector);
8739     if (CompLHSTy) *CompLHSTy = compType;
8740     return compType;
8741   }
8742 
8743   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8744   if (LHS.isInvalid() || RHS.isInvalid())
8745     return QualType();
8746 
8747   // Diagnose "string literal" '+' int and string '+' "char literal".
8748   if (Opc == BO_Add) {
8749     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8750     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8751   }
8752 
8753   // handle the common case first (both operands are arithmetic).
8754   if (!compType.isNull() && compType->isArithmeticType()) {
8755     if (CompLHSTy) *CompLHSTy = compType;
8756     return compType;
8757   }
8758 
8759   // Type-checking.  Ultimately the pointer's going to be in PExp;
8760   // note that we bias towards the LHS being the pointer.
8761   Expr *PExp = LHS.get(), *IExp = RHS.get();
8762 
8763   bool isObjCPointer;
8764   if (PExp->getType()->isPointerType()) {
8765     isObjCPointer = false;
8766   } else if (PExp->getType()->isObjCObjectPointerType()) {
8767     isObjCPointer = true;
8768   } else {
8769     std::swap(PExp, IExp);
8770     if (PExp->getType()->isPointerType()) {
8771       isObjCPointer = false;
8772     } else if (PExp->getType()->isObjCObjectPointerType()) {
8773       isObjCPointer = true;
8774     } else {
8775       return InvalidOperands(Loc, LHS, RHS);
8776     }
8777   }
8778   assert(PExp->getType()->isAnyPointerType());
8779 
8780   if (!IExp->getType()->isIntegerType())
8781     return InvalidOperands(Loc, LHS, RHS);
8782 
8783   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8784     return QualType();
8785 
8786   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8787     return QualType();
8788 
8789   // Check array bounds for pointer arithemtic
8790   CheckArrayAccess(PExp, IExp);
8791 
8792   if (CompLHSTy) {
8793     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8794     if (LHSTy.isNull()) {
8795       LHSTy = LHS.get()->getType();
8796       if (LHSTy->isPromotableIntegerType())
8797         LHSTy = Context.getPromotedIntegerType(LHSTy);
8798     }
8799     *CompLHSTy = LHSTy;
8800   }
8801 
8802   return PExp->getType();
8803 }
8804 
8805 // C99 6.5.6
8806 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8807                                         SourceLocation Loc,
8808                                         QualType* CompLHSTy) {
8809   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8810 
8811   if (LHS.get()->getType()->isVectorType() ||
8812       RHS.get()->getType()->isVectorType()) {
8813     QualType compType = CheckVectorOperands(
8814         LHS, RHS, Loc, CompLHSTy,
8815         /*AllowBothBool*/getLangOpts().AltiVec,
8816         /*AllowBoolConversions*/getLangOpts().ZVector);
8817     if (CompLHSTy) *CompLHSTy = compType;
8818     return compType;
8819   }
8820 
8821   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8822   if (LHS.isInvalid() || RHS.isInvalid())
8823     return QualType();
8824 
8825   // Enforce type constraints: C99 6.5.6p3.
8826 
8827   // Handle the common case first (both operands are arithmetic).
8828   if (!compType.isNull() && compType->isArithmeticType()) {
8829     if (CompLHSTy) *CompLHSTy = compType;
8830     return compType;
8831   }
8832 
8833   // Either ptr - int   or   ptr - ptr.
8834   if (LHS.get()->getType()->isAnyPointerType()) {
8835     QualType lpointee = LHS.get()->getType()->getPointeeType();
8836 
8837     // Diagnose bad cases where we step over interface counts.
8838     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8839         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8840       return QualType();
8841 
8842     // The result type of a pointer-int computation is the pointer type.
8843     if (RHS.get()->getType()->isIntegerType()) {
8844       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8845         return QualType();
8846 
8847       // Check array bounds for pointer arithemtic
8848       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8849                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8850 
8851       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8852       return LHS.get()->getType();
8853     }
8854 
8855     // Handle pointer-pointer subtractions.
8856     if (const PointerType *RHSPTy
8857           = RHS.get()->getType()->getAs<PointerType>()) {
8858       QualType rpointee = RHSPTy->getPointeeType();
8859 
8860       if (getLangOpts().CPlusPlus) {
8861         // Pointee types must be the same: C++ [expr.add]
8862         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8863           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8864         }
8865       } else {
8866         // Pointee types must be compatible C99 6.5.6p3
8867         if (!Context.typesAreCompatible(
8868                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8869                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8870           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8871           return QualType();
8872         }
8873       }
8874 
8875       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8876                                                LHS.get(), RHS.get()))
8877         return QualType();
8878 
8879       // The pointee type may have zero size.  As an extension, a structure or
8880       // union may have zero size or an array may have zero length.  In this
8881       // case subtraction does not make sense.
8882       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8883         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8884         if (ElementSize.isZero()) {
8885           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8886             << rpointee.getUnqualifiedType()
8887             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8888         }
8889       }
8890 
8891       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8892       return Context.getPointerDiffType();
8893     }
8894   }
8895 
8896   return InvalidOperands(Loc, LHS, RHS);
8897 }
8898 
8899 static bool isScopedEnumerationType(QualType T) {
8900   if (const EnumType *ET = T->getAs<EnumType>())
8901     return ET->getDecl()->isScoped();
8902   return false;
8903 }
8904 
8905 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8906                                    SourceLocation Loc, BinaryOperatorKind Opc,
8907                                    QualType LHSType) {
8908   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8909   // so skip remaining warnings as we don't want to modify values within Sema.
8910   if (S.getLangOpts().OpenCL)
8911     return;
8912 
8913   llvm::APSInt Right;
8914   // Check right/shifter operand
8915   if (RHS.get()->isValueDependent() ||
8916       !RHS.get()->EvaluateAsInt(Right, S.Context))
8917     return;
8918 
8919   if (Right.isNegative()) {
8920     S.DiagRuntimeBehavior(Loc, RHS.get(),
8921                           S.PDiag(diag::warn_shift_negative)
8922                             << RHS.get()->getSourceRange());
8923     return;
8924   }
8925   llvm::APInt LeftBits(Right.getBitWidth(),
8926                        S.Context.getTypeSize(LHS.get()->getType()));
8927   if (Right.uge(LeftBits)) {
8928     S.DiagRuntimeBehavior(Loc, RHS.get(),
8929                           S.PDiag(diag::warn_shift_gt_typewidth)
8930                             << RHS.get()->getSourceRange());
8931     return;
8932   }
8933   if (Opc != BO_Shl)
8934     return;
8935 
8936   // When left shifting an ICE which is signed, we can check for overflow which
8937   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8938   // integers have defined behavior modulo one more than the maximum value
8939   // representable in the result type, so never warn for those.
8940   llvm::APSInt Left;
8941   if (LHS.get()->isValueDependent() ||
8942       LHSType->hasUnsignedIntegerRepresentation() ||
8943       !LHS.get()->EvaluateAsInt(Left, S.Context))
8944     return;
8945 
8946   // If LHS does not have a signed type and non-negative value
8947   // then, the behavior is undefined. Warn about it.
8948   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8949     S.DiagRuntimeBehavior(Loc, LHS.get(),
8950                           S.PDiag(diag::warn_shift_lhs_negative)
8951                             << LHS.get()->getSourceRange());
8952     return;
8953   }
8954 
8955   llvm::APInt ResultBits =
8956       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8957   if (LeftBits.uge(ResultBits))
8958     return;
8959   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8960   Result = Result.shl(Right);
8961 
8962   // Print the bit representation of the signed integer as an unsigned
8963   // hexadecimal number.
8964   SmallString<40> HexResult;
8965   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8966 
8967   // If we are only missing a sign bit, this is less likely to result in actual
8968   // bugs -- if the result is cast back to an unsigned type, it will have the
8969   // expected value. Thus we place this behind a different warning that can be
8970   // turned off separately if needed.
8971   if (LeftBits == ResultBits - 1) {
8972     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8973         << HexResult << LHSType
8974         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8975     return;
8976   }
8977 
8978   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8979     << HexResult.str() << Result.getMinSignedBits() << LHSType
8980     << Left.getBitWidth() << LHS.get()->getSourceRange()
8981     << RHS.get()->getSourceRange();
8982 }
8983 
8984 /// \brief Return the resulting type when a vector is shifted
8985 ///        by a scalar or vector shift amount.
8986 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8987                                  SourceLocation Loc, bool IsCompAssign) {
8988   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8989   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
8990       !LHS.get()->getType()->isVectorType()) {
8991     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8992       << RHS.get()->getType() << LHS.get()->getType()
8993       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8994     return QualType();
8995   }
8996 
8997   if (!IsCompAssign) {
8998     LHS = S.UsualUnaryConversions(LHS.get());
8999     if (LHS.isInvalid()) return QualType();
9000   }
9001 
9002   RHS = S.UsualUnaryConversions(RHS.get());
9003   if (RHS.isInvalid()) return QualType();
9004 
9005   QualType LHSType = LHS.get()->getType();
9006   // Note that LHS might be a scalar because the routine calls not only in
9007   // OpenCL case.
9008   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9009   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9010 
9011   // Note that RHS might not be a vector.
9012   QualType RHSType = RHS.get()->getType();
9013   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9014   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9015 
9016   // The operands need to be integers.
9017   if (!LHSEleType->isIntegerType()) {
9018     S.Diag(Loc, diag::err_typecheck_expect_int)
9019       << LHS.get()->getType() << LHS.get()->getSourceRange();
9020     return QualType();
9021   }
9022 
9023   if (!RHSEleType->isIntegerType()) {
9024     S.Diag(Loc, diag::err_typecheck_expect_int)
9025       << RHS.get()->getType() << RHS.get()->getSourceRange();
9026     return QualType();
9027   }
9028 
9029   if (!LHSVecTy) {
9030     assert(RHSVecTy);
9031     if (IsCompAssign)
9032       return RHSType;
9033     if (LHSEleType != RHSEleType) {
9034       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9035       LHSEleType = RHSEleType;
9036     }
9037     QualType VecTy =
9038         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9039     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9040     LHSType = VecTy;
9041   } else if (RHSVecTy) {
9042     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9043     // are applied component-wise. So if RHS is a vector, then ensure
9044     // that the number of elements is the same as LHS...
9045     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9046       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9047         << LHS.get()->getType() << RHS.get()->getType()
9048         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9049       return QualType();
9050     }
9051     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9052       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9053       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9054       if (LHSBT != RHSBT &&
9055           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9056         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9057             << LHS.get()->getType() << RHS.get()->getType()
9058             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9059       }
9060     }
9061   } else {
9062     // ...else expand RHS to match the number of elements in LHS.
9063     QualType VecTy =
9064       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9065     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9066   }
9067 
9068   return LHSType;
9069 }
9070 
9071 // C99 6.5.7
9072 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9073                                   SourceLocation Loc, BinaryOperatorKind Opc,
9074                                   bool IsCompAssign) {
9075   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9076 
9077   // Vector shifts promote their scalar inputs to vector type.
9078   if (LHS.get()->getType()->isVectorType() ||
9079       RHS.get()->getType()->isVectorType()) {
9080     if (LangOpts.ZVector) {
9081       // The shift operators for the z vector extensions work basically
9082       // like general shifts, except that neither the LHS nor the RHS is
9083       // allowed to be a "vector bool".
9084       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9085         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9086           return InvalidOperands(Loc, LHS, RHS);
9087       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9088         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9089           return InvalidOperands(Loc, LHS, RHS);
9090     }
9091     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9092   }
9093 
9094   // Shifts don't perform usual arithmetic conversions, they just do integer
9095   // promotions on each operand. C99 6.5.7p3
9096 
9097   // For the LHS, do usual unary conversions, but then reset them away
9098   // if this is a compound assignment.
9099   ExprResult OldLHS = LHS;
9100   LHS = UsualUnaryConversions(LHS.get());
9101   if (LHS.isInvalid())
9102     return QualType();
9103   QualType LHSType = LHS.get()->getType();
9104   if (IsCompAssign) LHS = OldLHS;
9105 
9106   // The RHS is simpler.
9107   RHS = UsualUnaryConversions(RHS.get());
9108   if (RHS.isInvalid())
9109     return QualType();
9110   QualType RHSType = RHS.get()->getType();
9111 
9112   // C99 6.5.7p2: Each of the operands shall have integer type.
9113   if (!LHSType->hasIntegerRepresentation() ||
9114       !RHSType->hasIntegerRepresentation())
9115     return InvalidOperands(Loc, LHS, RHS);
9116 
9117   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9118   // hasIntegerRepresentation() above instead of this.
9119   if (isScopedEnumerationType(LHSType) ||
9120       isScopedEnumerationType(RHSType)) {
9121     return InvalidOperands(Loc, LHS, RHS);
9122   }
9123   // Sanity-check shift operands
9124   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9125 
9126   // "The type of the result is that of the promoted left operand."
9127   return LHSType;
9128 }
9129 
9130 static bool IsWithinTemplateSpecialization(Decl *D) {
9131   if (DeclContext *DC = D->getDeclContext()) {
9132     if (isa<ClassTemplateSpecializationDecl>(DC))
9133       return true;
9134     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
9135       return FD->isFunctionTemplateSpecialization();
9136   }
9137   return false;
9138 }
9139 
9140 /// If two different enums are compared, raise a warning.
9141 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9142                                 Expr *RHS) {
9143   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9144   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9145 
9146   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9147   if (!LHSEnumType)
9148     return;
9149   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9150   if (!RHSEnumType)
9151     return;
9152 
9153   // Ignore anonymous enums.
9154   if (!LHSEnumType->getDecl()->getIdentifier() &&
9155       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9156     return;
9157   if (!RHSEnumType->getDecl()->getIdentifier() &&
9158       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9159     return;
9160 
9161   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9162     return;
9163 
9164   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9165       << LHSStrippedType << RHSStrippedType
9166       << LHS->getSourceRange() << RHS->getSourceRange();
9167 }
9168 
9169 /// \brief Diagnose bad pointer comparisons.
9170 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9171                                               ExprResult &LHS, ExprResult &RHS,
9172                                               bool IsError) {
9173   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9174                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9175     << LHS.get()->getType() << RHS.get()->getType()
9176     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9177 }
9178 
9179 /// \brief Returns false if the pointers are converted to a composite type,
9180 /// true otherwise.
9181 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9182                                            ExprResult &LHS, ExprResult &RHS) {
9183   // C++ [expr.rel]p2:
9184   //   [...] Pointer conversions (4.10) and qualification
9185   //   conversions (4.4) are performed on pointer operands (or on
9186   //   a pointer operand and a null pointer constant) to bring
9187   //   them to their composite pointer type. [...]
9188   //
9189   // C++ [expr.eq]p1 uses the same notion for (in)equality
9190   // comparisons of pointers.
9191 
9192   QualType LHSType = LHS.get()->getType();
9193   QualType RHSType = RHS.get()->getType();
9194   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9195          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9196 
9197   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9198   if (T.isNull()) {
9199     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9200         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9201       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9202     else
9203       S.InvalidOperands(Loc, LHS, RHS);
9204     return true;
9205   }
9206 
9207   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9208   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9209   return false;
9210 }
9211 
9212 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9213                                                     ExprResult &LHS,
9214                                                     ExprResult &RHS,
9215                                                     bool IsError) {
9216   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9217                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9218     << LHS.get()->getType() << RHS.get()->getType()
9219     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9220 }
9221 
9222 static bool isObjCObjectLiteral(ExprResult &E) {
9223   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9224   case Stmt::ObjCArrayLiteralClass:
9225   case Stmt::ObjCDictionaryLiteralClass:
9226   case Stmt::ObjCStringLiteralClass:
9227   case Stmt::ObjCBoxedExprClass:
9228     return true;
9229   default:
9230     // Note that ObjCBoolLiteral is NOT an object literal!
9231     return false;
9232   }
9233 }
9234 
9235 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9236   const ObjCObjectPointerType *Type =
9237     LHS->getType()->getAs<ObjCObjectPointerType>();
9238 
9239   // If this is not actually an Objective-C object, bail out.
9240   if (!Type)
9241     return false;
9242 
9243   // Get the LHS object's interface type.
9244   QualType InterfaceType = Type->getPointeeType();
9245 
9246   // If the RHS isn't an Objective-C object, bail out.
9247   if (!RHS->getType()->isObjCObjectPointerType())
9248     return false;
9249 
9250   // Try to find the -isEqual: method.
9251   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9252   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9253                                                       InterfaceType,
9254                                                       /*instance=*/true);
9255   if (!Method) {
9256     if (Type->isObjCIdType()) {
9257       // For 'id', just check the global pool.
9258       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9259                                                   /*receiverId=*/true);
9260     } else {
9261       // Check protocols.
9262       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9263                                              /*instance=*/true);
9264     }
9265   }
9266 
9267   if (!Method)
9268     return false;
9269 
9270   QualType T = Method->parameters()[0]->getType();
9271   if (!T->isObjCObjectPointerType())
9272     return false;
9273 
9274   QualType R = Method->getReturnType();
9275   if (!R->isScalarType())
9276     return false;
9277 
9278   return true;
9279 }
9280 
9281 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9282   FromE = FromE->IgnoreParenImpCasts();
9283   switch (FromE->getStmtClass()) {
9284     default:
9285       break;
9286     case Stmt::ObjCStringLiteralClass:
9287       // "string literal"
9288       return LK_String;
9289     case Stmt::ObjCArrayLiteralClass:
9290       // "array literal"
9291       return LK_Array;
9292     case Stmt::ObjCDictionaryLiteralClass:
9293       // "dictionary literal"
9294       return LK_Dictionary;
9295     case Stmt::BlockExprClass:
9296       return LK_Block;
9297     case Stmt::ObjCBoxedExprClass: {
9298       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9299       switch (Inner->getStmtClass()) {
9300         case Stmt::IntegerLiteralClass:
9301         case Stmt::FloatingLiteralClass:
9302         case Stmt::CharacterLiteralClass:
9303         case Stmt::ObjCBoolLiteralExprClass:
9304         case Stmt::CXXBoolLiteralExprClass:
9305           // "numeric literal"
9306           return LK_Numeric;
9307         case Stmt::ImplicitCastExprClass: {
9308           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9309           // Boolean literals can be represented by implicit casts.
9310           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9311             return LK_Numeric;
9312           break;
9313         }
9314         default:
9315           break;
9316       }
9317       return LK_Boxed;
9318     }
9319   }
9320   return LK_None;
9321 }
9322 
9323 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9324                                           ExprResult &LHS, ExprResult &RHS,
9325                                           BinaryOperator::Opcode Opc){
9326   Expr *Literal;
9327   Expr *Other;
9328   if (isObjCObjectLiteral(LHS)) {
9329     Literal = LHS.get();
9330     Other = RHS.get();
9331   } else {
9332     Literal = RHS.get();
9333     Other = LHS.get();
9334   }
9335 
9336   // Don't warn on comparisons against nil.
9337   Other = Other->IgnoreParenCasts();
9338   if (Other->isNullPointerConstant(S.getASTContext(),
9339                                    Expr::NPC_ValueDependentIsNotNull))
9340     return;
9341 
9342   // This should be kept in sync with warn_objc_literal_comparison.
9343   // LK_String should always be after the other literals, since it has its own
9344   // warning flag.
9345   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9346   assert(LiteralKind != Sema::LK_Block);
9347   if (LiteralKind == Sema::LK_None) {
9348     llvm_unreachable("Unknown Objective-C object literal kind");
9349   }
9350 
9351   if (LiteralKind == Sema::LK_String)
9352     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9353       << Literal->getSourceRange();
9354   else
9355     S.Diag(Loc, diag::warn_objc_literal_comparison)
9356       << LiteralKind << Literal->getSourceRange();
9357 
9358   if (BinaryOperator::isEqualityOp(Opc) &&
9359       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9360     SourceLocation Start = LHS.get()->getLocStart();
9361     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9362     CharSourceRange OpRange =
9363       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9364 
9365     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9366       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9367       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9368       << FixItHint::CreateInsertion(End, "]");
9369   }
9370 }
9371 
9372 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9373 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9374                                            ExprResult &RHS, SourceLocation Loc,
9375                                            BinaryOperatorKind Opc) {
9376   // Check that left hand side is !something.
9377   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9378   if (!UO || UO->getOpcode() != UO_LNot) return;
9379 
9380   // Only check if the right hand side is non-bool arithmetic type.
9381   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9382 
9383   // Make sure that the something in !something is not bool.
9384   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9385   if (SubExpr->isKnownToHaveBooleanValue()) return;
9386 
9387   // Emit warning.
9388   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9389   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9390       << Loc << IsBitwiseOp;
9391 
9392   // First note suggest !(x < y)
9393   SourceLocation FirstOpen = SubExpr->getLocStart();
9394   SourceLocation FirstClose = RHS.get()->getLocEnd();
9395   FirstClose = S.getLocForEndOfToken(FirstClose);
9396   if (FirstClose.isInvalid())
9397     FirstOpen = SourceLocation();
9398   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9399       << IsBitwiseOp
9400       << FixItHint::CreateInsertion(FirstOpen, "(")
9401       << FixItHint::CreateInsertion(FirstClose, ")");
9402 
9403   // Second note suggests (!x) < y
9404   SourceLocation SecondOpen = LHS.get()->getLocStart();
9405   SourceLocation SecondClose = LHS.get()->getLocEnd();
9406   SecondClose = S.getLocForEndOfToken(SecondClose);
9407   if (SecondClose.isInvalid())
9408     SecondOpen = SourceLocation();
9409   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9410       << FixItHint::CreateInsertion(SecondOpen, "(")
9411       << FixItHint::CreateInsertion(SecondClose, ")");
9412 }
9413 
9414 // Get the decl for a simple expression: a reference to a variable,
9415 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9416 static ValueDecl *getCompareDecl(Expr *E) {
9417   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9418     return DR->getDecl();
9419   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9420     if (Ivar->isFreeIvar())
9421       return Ivar->getDecl();
9422   }
9423   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9424     if (Mem->isImplicitAccess())
9425       return Mem->getMemberDecl();
9426   }
9427   return nullptr;
9428 }
9429 
9430 // C99 6.5.8, C++ [expr.rel]
9431 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9432                                     SourceLocation Loc, BinaryOperatorKind Opc,
9433                                     bool IsRelational) {
9434   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9435 
9436   // Handle vector comparisons separately.
9437   if (LHS.get()->getType()->isVectorType() ||
9438       RHS.get()->getType()->isVectorType())
9439     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9440 
9441   QualType LHSType = LHS.get()->getType();
9442   QualType RHSType = RHS.get()->getType();
9443 
9444   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9445   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9446 
9447   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9448   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9449 
9450   if (!LHSType->hasFloatingRepresentation() &&
9451       !(LHSType->isBlockPointerType() && IsRelational) &&
9452       !LHS.get()->getLocStart().isMacroID() &&
9453       !RHS.get()->getLocStart().isMacroID() &&
9454       !inTemplateInstantiation()) {
9455     // For non-floating point types, check for self-comparisons of the form
9456     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9457     // often indicate logic errors in the program.
9458     //
9459     // NOTE: Don't warn about comparison expressions resulting from macro
9460     // expansion. Also don't warn about comparisons which are only self
9461     // comparisons within a template specialization. The warnings should catch
9462     // obvious cases in the definition of the template anyways. The idea is to
9463     // warn when the typed comparison operator will always evaluate to the same
9464     // result.
9465     ValueDecl *DL = getCompareDecl(LHSStripped);
9466     ValueDecl *DR = getCompareDecl(RHSStripped);
9467     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9468       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9469                           << 0 // self-
9470                           << (Opc == BO_EQ
9471                               || Opc == BO_LE
9472                               || Opc == BO_GE));
9473     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9474                !DL->getType()->isReferenceType() &&
9475                !DR->getType()->isReferenceType()) {
9476         // what is it always going to eval to?
9477         char always_evals_to;
9478         switch(Opc) {
9479         case BO_EQ: // e.g. array1 == array2
9480           always_evals_to = 0; // false
9481           break;
9482         case BO_NE: // e.g. array1 != array2
9483           always_evals_to = 1; // true
9484           break;
9485         default:
9486           // best we can say is 'a constant'
9487           always_evals_to = 2; // e.g. array1 <= array2
9488           break;
9489         }
9490         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9491                             << 1 // array
9492                             << always_evals_to);
9493     }
9494 
9495     if (isa<CastExpr>(LHSStripped))
9496       LHSStripped = LHSStripped->IgnoreParenCasts();
9497     if (isa<CastExpr>(RHSStripped))
9498       RHSStripped = RHSStripped->IgnoreParenCasts();
9499 
9500     // Warn about comparisons against a string constant (unless the other
9501     // operand is null), the user probably wants strcmp.
9502     Expr *literalString = nullptr;
9503     Expr *literalStringStripped = nullptr;
9504     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9505         !RHSStripped->isNullPointerConstant(Context,
9506                                             Expr::NPC_ValueDependentIsNull)) {
9507       literalString = LHS.get();
9508       literalStringStripped = LHSStripped;
9509     } else if ((isa<StringLiteral>(RHSStripped) ||
9510                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9511                !LHSStripped->isNullPointerConstant(Context,
9512                                             Expr::NPC_ValueDependentIsNull)) {
9513       literalString = RHS.get();
9514       literalStringStripped = RHSStripped;
9515     }
9516 
9517     if (literalString) {
9518       DiagRuntimeBehavior(Loc, nullptr,
9519         PDiag(diag::warn_stringcompare)
9520           << isa<ObjCEncodeExpr>(literalStringStripped)
9521           << literalString->getSourceRange());
9522     }
9523   }
9524 
9525   // C99 6.5.8p3 / C99 6.5.9p4
9526   UsualArithmeticConversions(LHS, RHS);
9527   if (LHS.isInvalid() || RHS.isInvalid())
9528     return QualType();
9529 
9530   LHSType = LHS.get()->getType();
9531   RHSType = RHS.get()->getType();
9532 
9533   // The result of comparisons is 'bool' in C++, 'int' in C.
9534   QualType ResultTy = Context.getLogicalOperationType();
9535 
9536   if (IsRelational) {
9537     if (LHSType->isRealType() && RHSType->isRealType())
9538       return ResultTy;
9539   } else {
9540     // Check for comparisons of floating point operands using != and ==.
9541     if (LHSType->hasFloatingRepresentation())
9542       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9543 
9544     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9545       return ResultTy;
9546   }
9547 
9548   const Expr::NullPointerConstantKind LHSNullKind =
9549       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9550   const Expr::NullPointerConstantKind RHSNullKind =
9551       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9552   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9553   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9554 
9555   if (!IsRelational && LHSIsNull != RHSIsNull) {
9556     bool IsEquality = Opc == BO_EQ;
9557     if (RHSIsNull)
9558       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9559                                    RHS.get()->getSourceRange());
9560     else
9561       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9562                                    LHS.get()->getSourceRange());
9563   }
9564 
9565   if ((LHSType->isIntegerType() && !LHSIsNull) ||
9566       (RHSType->isIntegerType() && !RHSIsNull)) {
9567     // Skip normal pointer conversion checks in this case; we have better
9568     // diagnostics for this below.
9569   } else if (getLangOpts().CPlusPlus) {
9570     // Equality comparison of a function pointer to a void pointer is invalid,
9571     // but we allow it as an extension.
9572     // FIXME: If we really want to allow this, should it be part of composite
9573     // pointer type computation so it works in conditionals too?
9574     if (!IsRelational &&
9575         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9576          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9577       // This is a gcc extension compatibility comparison.
9578       // In a SFINAE context, we treat this as a hard error to maintain
9579       // conformance with the C++ standard.
9580       diagnoseFunctionPointerToVoidComparison(
9581           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9582 
9583       if (isSFINAEContext())
9584         return QualType();
9585 
9586       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9587       return ResultTy;
9588     }
9589 
9590     // C++ [expr.eq]p2:
9591     //   If at least one operand is a pointer [...] bring them to their
9592     //   composite pointer type.
9593     // C++ [expr.rel]p2:
9594     //   If both operands are pointers, [...] bring them to their composite
9595     //   pointer type.
9596     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9597             (IsRelational ? 2 : 1) &&
9598         (!LangOpts.ObjCAutoRefCount ||
9599          !(LHSType->isObjCObjectPointerType() ||
9600            RHSType->isObjCObjectPointerType()))) {
9601       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9602         return QualType();
9603       else
9604         return ResultTy;
9605     }
9606   } else if (LHSType->isPointerType() &&
9607              RHSType->isPointerType()) { // C99 6.5.8p2
9608     // All of the following pointer-related warnings are GCC extensions, except
9609     // when handling null pointer constants.
9610     QualType LCanPointeeTy =
9611       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9612     QualType RCanPointeeTy =
9613       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9614 
9615     // C99 6.5.9p2 and C99 6.5.8p2
9616     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9617                                    RCanPointeeTy.getUnqualifiedType())) {
9618       // Valid unless a relational comparison of function pointers
9619       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9620         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9621           << LHSType << RHSType << LHS.get()->getSourceRange()
9622           << RHS.get()->getSourceRange();
9623       }
9624     } else if (!IsRelational &&
9625                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9626       // Valid unless comparison between non-null pointer and function pointer
9627       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9628           && !LHSIsNull && !RHSIsNull)
9629         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9630                                                 /*isError*/false);
9631     } else {
9632       // Invalid
9633       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9634     }
9635     if (LCanPointeeTy != RCanPointeeTy) {
9636       // Treat NULL constant as a special case in OpenCL.
9637       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9638         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9639         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9640           Diag(Loc,
9641                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9642               << LHSType << RHSType << 0 /* comparison */
9643               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9644         }
9645       }
9646       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9647       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9648       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9649                                                : CK_BitCast;
9650       if (LHSIsNull && !RHSIsNull)
9651         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9652       else
9653         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9654     }
9655     return ResultTy;
9656   }
9657 
9658   if (getLangOpts().CPlusPlus) {
9659     // C++ [expr.eq]p4:
9660     //   Two operands of type std::nullptr_t or one operand of type
9661     //   std::nullptr_t and the other a null pointer constant compare equal.
9662     if (!IsRelational && LHSIsNull && RHSIsNull) {
9663       if (LHSType->isNullPtrType()) {
9664         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9665         return ResultTy;
9666       }
9667       if (RHSType->isNullPtrType()) {
9668         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9669         return ResultTy;
9670       }
9671     }
9672 
9673     // Comparison of Objective-C pointers and block pointers against nullptr_t.
9674     // These aren't covered by the composite pointer type rules.
9675     if (!IsRelational && RHSType->isNullPtrType() &&
9676         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9677       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9678       return ResultTy;
9679     }
9680     if (!IsRelational && LHSType->isNullPtrType() &&
9681         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9682       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9683       return ResultTy;
9684     }
9685 
9686     if (IsRelational &&
9687         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9688          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9689       // HACK: Relational comparison of nullptr_t against a pointer type is
9690       // invalid per DR583, but we allow it within std::less<> and friends,
9691       // since otherwise common uses of it break.
9692       // FIXME: Consider removing this hack once LWG fixes std::less<> and
9693       // friends to have std::nullptr_t overload candidates.
9694       DeclContext *DC = CurContext;
9695       if (isa<FunctionDecl>(DC))
9696         DC = DC->getParent();
9697       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9698         if (CTSD->isInStdNamespace() &&
9699             llvm::StringSwitch<bool>(CTSD->getName())
9700                 .Cases("less", "less_equal", "greater", "greater_equal", true)
9701                 .Default(false)) {
9702           if (RHSType->isNullPtrType())
9703             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9704           else
9705             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9706           return ResultTy;
9707         }
9708       }
9709     }
9710 
9711     // C++ [expr.eq]p2:
9712     //   If at least one operand is a pointer to member, [...] bring them to
9713     //   their composite pointer type.
9714     if (!IsRelational &&
9715         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9716       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9717         return QualType();
9718       else
9719         return ResultTy;
9720     }
9721 
9722     // Handle scoped enumeration types specifically, since they don't promote
9723     // to integers.
9724     if (LHS.get()->getType()->isEnumeralType() &&
9725         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9726                                        RHS.get()->getType()))
9727       return ResultTy;
9728   }
9729 
9730   // Handle block pointer types.
9731   if (!IsRelational && LHSType->isBlockPointerType() &&
9732       RHSType->isBlockPointerType()) {
9733     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9734     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9735 
9736     if (!LHSIsNull && !RHSIsNull &&
9737         !Context.typesAreCompatible(lpointee, rpointee)) {
9738       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9739         << LHSType << RHSType << LHS.get()->getSourceRange()
9740         << RHS.get()->getSourceRange();
9741     }
9742     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9743     return ResultTy;
9744   }
9745 
9746   // Allow block pointers to be compared with null pointer constants.
9747   if (!IsRelational
9748       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9749           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9750     if (!LHSIsNull && !RHSIsNull) {
9751       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9752              ->getPointeeType()->isVoidType())
9753             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9754                 ->getPointeeType()->isVoidType())))
9755         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9756           << LHSType << RHSType << LHS.get()->getSourceRange()
9757           << RHS.get()->getSourceRange();
9758     }
9759     if (LHSIsNull && !RHSIsNull)
9760       LHS = ImpCastExprToType(LHS.get(), RHSType,
9761                               RHSType->isPointerType() ? CK_BitCast
9762                                 : CK_AnyPointerToBlockPointerCast);
9763     else
9764       RHS = ImpCastExprToType(RHS.get(), LHSType,
9765                               LHSType->isPointerType() ? CK_BitCast
9766                                 : CK_AnyPointerToBlockPointerCast);
9767     return ResultTy;
9768   }
9769 
9770   if (LHSType->isObjCObjectPointerType() ||
9771       RHSType->isObjCObjectPointerType()) {
9772     const PointerType *LPT = LHSType->getAs<PointerType>();
9773     const PointerType *RPT = RHSType->getAs<PointerType>();
9774     if (LPT || RPT) {
9775       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9776       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9777 
9778       if (!LPtrToVoid && !RPtrToVoid &&
9779           !Context.typesAreCompatible(LHSType, RHSType)) {
9780         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9781                                           /*isError*/false);
9782       }
9783       if (LHSIsNull && !RHSIsNull) {
9784         Expr *E = LHS.get();
9785         if (getLangOpts().ObjCAutoRefCount)
9786           CheckObjCConversion(SourceRange(), RHSType, E,
9787                               CCK_ImplicitConversion);
9788         LHS = ImpCastExprToType(E, RHSType,
9789                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9790       }
9791       else {
9792         Expr *E = RHS.get();
9793         if (getLangOpts().ObjCAutoRefCount)
9794           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
9795                               /*Diagnose=*/true,
9796                               /*DiagnoseCFAudited=*/false, Opc);
9797         RHS = ImpCastExprToType(E, LHSType,
9798                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9799       }
9800       return ResultTy;
9801     }
9802     if (LHSType->isObjCObjectPointerType() &&
9803         RHSType->isObjCObjectPointerType()) {
9804       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9805         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9806                                           /*isError*/false);
9807       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9808         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9809 
9810       if (LHSIsNull && !RHSIsNull)
9811         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9812       else
9813         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9814       return ResultTy;
9815     }
9816   }
9817   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9818       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9819     unsigned DiagID = 0;
9820     bool isError = false;
9821     if (LangOpts.DebuggerSupport) {
9822       // Under a debugger, allow the comparison of pointers to integers,
9823       // since users tend to want to compare addresses.
9824     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9825                (RHSIsNull && RHSType->isIntegerType())) {
9826       if (IsRelational) {
9827         isError = getLangOpts().CPlusPlus;
9828         DiagID =
9829           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9830                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9831       }
9832     } else if (getLangOpts().CPlusPlus) {
9833       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9834       isError = true;
9835     } else if (IsRelational)
9836       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9837     else
9838       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9839 
9840     if (DiagID) {
9841       Diag(Loc, DiagID)
9842         << LHSType << RHSType << LHS.get()->getSourceRange()
9843         << RHS.get()->getSourceRange();
9844       if (isError)
9845         return QualType();
9846     }
9847 
9848     if (LHSType->isIntegerType())
9849       LHS = ImpCastExprToType(LHS.get(), RHSType,
9850                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9851     else
9852       RHS = ImpCastExprToType(RHS.get(), LHSType,
9853                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9854     return ResultTy;
9855   }
9856 
9857   // Handle block pointers.
9858   if (!IsRelational && RHSIsNull
9859       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9860     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9861     return ResultTy;
9862   }
9863   if (!IsRelational && LHSIsNull
9864       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9865     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9866     return ResultTy;
9867   }
9868 
9869   if (getLangOpts().OpenCLVersion >= 200) {
9870     if (LHSIsNull && RHSType->isQueueT()) {
9871       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9872       return ResultTy;
9873     }
9874 
9875     if (LHSType->isQueueT() && RHSIsNull) {
9876       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9877       return ResultTy;
9878     }
9879   }
9880 
9881   return InvalidOperands(Loc, LHS, RHS);
9882 }
9883 
9884 // Return a signed ext_vector_type that is of identical size and number of
9885 // elements. For floating point vectors, return an integer type of identical
9886 // size and number of elements. In the non ext_vector_type case, search from
9887 // the largest type to the smallest type to avoid cases where long long == long,
9888 // where long gets picked over long long.
9889 QualType Sema::GetSignedVectorType(QualType V) {
9890   const VectorType *VTy = V->getAs<VectorType>();
9891   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9892 
9893   if (isa<ExtVectorType>(VTy)) {
9894     if (TypeSize == Context.getTypeSize(Context.CharTy))
9895       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9896     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9897       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9898     else if (TypeSize == Context.getTypeSize(Context.IntTy))
9899       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9900     else if (TypeSize == Context.getTypeSize(Context.LongTy))
9901       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9902     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9903            "Unhandled vector element size in vector compare");
9904     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9905   }
9906 
9907   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
9908     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
9909                                  VectorType::GenericVector);
9910   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9911     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
9912                                  VectorType::GenericVector);
9913   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9914     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
9915                                  VectorType::GenericVector);
9916   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9917     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
9918                                  VectorType::GenericVector);
9919   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
9920          "Unhandled vector element size in vector compare");
9921   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
9922                                VectorType::GenericVector);
9923 }
9924 
9925 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9926 /// operates on extended vector types.  Instead of producing an IntTy result,
9927 /// like a scalar comparison, a vector comparison produces a vector of integer
9928 /// types.
9929 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9930                                           SourceLocation Loc,
9931                                           bool IsRelational) {
9932   // Check to make sure we're operating on vectors of the same type and width,
9933   // Allowing one side to be a scalar of element type.
9934   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9935                               /*AllowBothBool*/true,
9936                               /*AllowBoolConversions*/getLangOpts().ZVector);
9937   if (vType.isNull())
9938     return vType;
9939 
9940   QualType LHSType = LHS.get()->getType();
9941 
9942   // If AltiVec, the comparison results in a numeric type, i.e.
9943   // bool for C++, int for C
9944   if (getLangOpts().AltiVec &&
9945       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9946     return Context.getLogicalOperationType();
9947 
9948   // For non-floating point types, check for self-comparisons of the form
9949   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9950   // often indicate logic errors in the program.
9951   if (!LHSType->hasFloatingRepresentation() && !inTemplateInstantiation()) {
9952     if (DeclRefExpr* DRL
9953           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9954       if (DeclRefExpr* DRR
9955             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9956         if (DRL->getDecl() == DRR->getDecl())
9957           DiagRuntimeBehavior(Loc, nullptr,
9958                               PDiag(diag::warn_comparison_always)
9959                                 << 0 // self-
9960                                 << 2 // "a constant"
9961                               );
9962   }
9963 
9964   // Check for comparisons of floating point operands using != and ==.
9965   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9966     assert (RHS.get()->getType()->hasFloatingRepresentation());
9967     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9968   }
9969 
9970   // Return a signed type for the vector.
9971   return GetSignedVectorType(vType);
9972 }
9973 
9974 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9975                                           SourceLocation Loc) {
9976   // Ensure that either both operands are of the same vector type, or
9977   // one operand is of a vector type and the other is of its element type.
9978   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9979                                        /*AllowBothBool*/true,
9980                                        /*AllowBoolConversions*/false);
9981   if (vType.isNull())
9982     return InvalidOperands(Loc, LHS, RHS);
9983   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9984       vType->hasFloatingRepresentation())
9985     return InvalidOperands(Loc, LHS, RHS);
9986   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
9987   //        usage of the logical operators && and || with vectors in C. This
9988   //        check could be notionally dropped.
9989   if (!getLangOpts().CPlusPlus &&
9990       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
9991     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
9992 
9993   return GetSignedVectorType(LHS.get()->getType());
9994 }
9995 
9996 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
9997                                            SourceLocation Loc,
9998                                            BinaryOperatorKind Opc) {
9999   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10000 
10001   bool IsCompAssign =
10002       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10003 
10004   if (LHS.get()->getType()->isVectorType() ||
10005       RHS.get()->getType()->isVectorType()) {
10006     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10007         RHS.get()->getType()->hasIntegerRepresentation())
10008       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10009                         /*AllowBothBool*/true,
10010                         /*AllowBoolConversions*/getLangOpts().ZVector);
10011     return InvalidOperands(Loc, LHS, RHS);
10012   }
10013 
10014   if (Opc == BO_And)
10015     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10016 
10017   ExprResult LHSResult = LHS, RHSResult = RHS;
10018   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10019                                                  IsCompAssign);
10020   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10021     return QualType();
10022   LHS = LHSResult.get();
10023   RHS = RHSResult.get();
10024 
10025   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10026     return compType;
10027   return InvalidOperands(Loc, LHS, RHS);
10028 }
10029 
10030 // C99 6.5.[13,14]
10031 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10032                                            SourceLocation Loc,
10033                                            BinaryOperatorKind Opc) {
10034   // Check vector operands differently.
10035   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10036     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10037 
10038   // Diagnose cases where the user write a logical and/or but probably meant a
10039   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10040   // is a constant.
10041   if (LHS.get()->getType()->isIntegerType() &&
10042       !LHS.get()->getType()->isBooleanType() &&
10043       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10044       // Don't warn in macros or template instantiations.
10045       !Loc.isMacroID() && !inTemplateInstantiation()) {
10046     // If the RHS can be constant folded, and if it constant folds to something
10047     // that isn't 0 or 1 (which indicate a potential logical operation that
10048     // happened to fold to true/false) then warn.
10049     // Parens on the RHS are ignored.
10050     llvm::APSInt Result;
10051     if (RHS.get()->EvaluateAsInt(Result, Context))
10052       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10053            !RHS.get()->getExprLoc().isMacroID()) ||
10054           (Result != 0 && Result != 1)) {
10055         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10056           << RHS.get()->getSourceRange()
10057           << (Opc == BO_LAnd ? "&&" : "||");
10058         // Suggest replacing the logical operator with the bitwise version
10059         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10060             << (Opc == BO_LAnd ? "&" : "|")
10061             << FixItHint::CreateReplacement(SourceRange(
10062                                                  Loc, getLocForEndOfToken(Loc)),
10063                                             Opc == BO_LAnd ? "&" : "|");
10064         if (Opc == BO_LAnd)
10065           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10066           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10067               << FixItHint::CreateRemoval(
10068                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
10069                               RHS.get()->getLocEnd()));
10070       }
10071   }
10072 
10073   if (!Context.getLangOpts().CPlusPlus) {
10074     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10075     // not operate on the built-in scalar and vector float types.
10076     if (Context.getLangOpts().OpenCL &&
10077         Context.getLangOpts().OpenCLVersion < 120) {
10078       if (LHS.get()->getType()->isFloatingType() ||
10079           RHS.get()->getType()->isFloatingType())
10080         return InvalidOperands(Loc, LHS, RHS);
10081     }
10082 
10083     LHS = UsualUnaryConversions(LHS.get());
10084     if (LHS.isInvalid())
10085       return QualType();
10086 
10087     RHS = UsualUnaryConversions(RHS.get());
10088     if (RHS.isInvalid())
10089       return QualType();
10090 
10091     if (!LHS.get()->getType()->isScalarType() ||
10092         !RHS.get()->getType()->isScalarType())
10093       return InvalidOperands(Loc, LHS, RHS);
10094 
10095     return Context.IntTy;
10096   }
10097 
10098   // The following is safe because we only use this method for
10099   // non-overloadable operands.
10100 
10101   // C++ [expr.log.and]p1
10102   // C++ [expr.log.or]p1
10103   // The operands are both contextually converted to type bool.
10104   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10105   if (LHSRes.isInvalid())
10106     return InvalidOperands(Loc, LHS, RHS);
10107   LHS = LHSRes;
10108 
10109   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10110   if (RHSRes.isInvalid())
10111     return InvalidOperands(Loc, LHS, RHS);
10112   RHS = RHSRes;
10113 
10114   // C++ [expr.log.and]p2
10115   // C++ [expr.log.or]p2
10116   // The result is a bool.
10117   return Context.BoolTy;
10118 }
10119 
10120 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10121   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10122   if (!ME) return false;
10123   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10124   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10125       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
10126   if (!Base) return false;
10127   return Base->getMethodDecl() != nullptr;
10128 }
10129 
10130 /// Is the given expression (which must be 'const') a reference to a
10131 /// variable which was originally non-const, but which has become
10132 /// 'const' due to being captured within a block?
10133 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
10134 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
10135   assert(E->isLValue() && E->getType().isConstQualified());
10136   E = E->IgnoreParens();
10137 
10138   // Must be a reference to a declaration from an enclosing scope.
10139   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10140   if (!DRE) return NCCK_None;
10141   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10142 
10143   // The declaration must be a variable which is not declared 'const'.
10144   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10145   if (!var) return NCCK_None;
10146   if (var->getType().isConstQualified()) return NCCK_None;
10147   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10148 
10149   // Decide whether the first capture was for a block or a lambda.
10150   DeclContext *DC = S.CurContext, *Prev = nullptr;
10151   // Decide whether the first capture was for a block or a lambda.
10152   while (DC) {
10153     // For init-capture, it is possible that the variable belongs to the
10154     // template pattern of the current context.
10155     if (auto *FD = dyn_cast<FunctionDecl>(DC))
10156       if (var->isInitCapture() &&
10157           FD->getTemplateInstantiationPattern() == var->getDeclContext())
10158         break;
10159     if (DC == var->getDeclContext())
10160       break;
10161     Prev = DC;
10162     DC = DC->getParent();
10163   }
10164   // Unless we have an init-capture, we've gone one step too far.
10165   if (!var->isInitCapture())
10166     DC = Prev;
10167   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10168 }
10169 
10170 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10171   Ty = Ty.getNonReferenceType();
10172   if (IsDereference && Ty->isPointerType())
10173     Ty = Ty->getPointeeType();
10174   return !Ty.isConstQualified();
10175 }
10176 
10177 /// Emit the "read-only variable not assignable" error and print notes to give
10178 /// more information about why the variable is not assignable, such as pointing
10179 /// to the declaration of a const variable, showing that a method is const, or
10180 /// that the function is returning a const reference.
10181 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10182                                     SourceLocation Loc) {
10183   // Update err_typecheck_assign_const and note_typecheck_assign_const
10184   // when this enum is changed.
10185   enum {
10186     ConstFunction,
10187     ConstVariable,
10188     ConstMember,
10189     ConstMethod,
10190     ConstUnknown,  // Keep as last element
10191   };
10192 
10193   SourceRange ExprRange = E->getSourceRange();
10194 
10195   // Only emit one error on the first const found.  All other consts will emit
10196   // a note to the error.
10197   bool DiagnosticEmitted = false;
10198 
10199   // Track if the current expression is the result of a dereference, and if the
10200   // next checked expression is the result of a dereference.
10201   bool IsDereference = false;
10202   bool NextIsDereference = false;
10203 
10204   // Loop to process MemberExpr chains.
10205   while (true) {
10206     IsDereference = NextIsDereference;
10207 
10208     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10209     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10210       NextIsDereference = ME->isArrow();
10211       const ValueDecl *VD = ME->getMemberDecl();
10212       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10213         // Mutable fields can be modified even if the class is const.
10214         if (Field->isMutable()) {
10215           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10216           break;
10217         }
10218 
10219         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10220           if (!DiagnosticEmitted) {
10221             S.Diag(Loc, diag::err_typecheck_assign_const)
10222                 << ExprRange << ConstMember << false /*static*/ << Field
10223                 << Field->getType();
10224             DiagnosticEmitted = true;
10225           }
10226           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10227               << ConstMember << false /*static*/ << Field << Field->getType()
10228               << Field->getSourceRange();
10229         }
10230         E = ME->getBase();
10231         continue;
10232       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10233         if (VDecl->getType().isConstQualified()) {
10234           if (!DiagnosticEmitted) {
10235             S.Diag(Loc, diag::err_typecheck_assign_const)
10236                 << ExprRange << ConstMember << true /*static*/ << VDecl
10237                 << VDecl->getType();
10238             DiagnosticEmitted = true;
10239           }
10240           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10241               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10242               << VDecl->getSourceRange();
10243         }
10244         // Static fields do not inherit constness from parents.
10245         break;
10246       }
10247       break;
10248     } // End MemberExpr
10249     break;
10250   }
10251 
10252   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10253     // Function calls
10254     const FunctionDecl *FD = CE->getDirectCallee();
10255     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10256       if (!DiagnosticEmitted) {
10257         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10258                                                       << ConstFunction << FD;
10259         DiagnosticEmitted = true;
10260       }
10261       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10262              diag::note_typecheck_assign_const)
10263           << ConstFunction << FD << FD->getReturnType()
10264           << FD->getReturnTypeSourceRange();
10265     }
10266   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10267     // Point to variable declaration.
10268     if (const ValueDecl *VD = DRE->getDecl()) {
10269       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10270         if (!DiagnosticEmitted) {
10271           S.Diag(Loc, diag::err_typecheck_assign_const)
10272               << ExprRange << ConstVariable << VD << VD->getType();
10273           DiagnosticEmitted = true;
10274         }
10275         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10276             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10277       }
10278     }
10279   } else if (isa<CXXThisExpr>(E)) {
10280     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10281       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10282         if (MD->isConst()) {
10283           if (!DiagnosticEmitted) {
10284             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10285                                                           << ConstMethod << MD;
10286             DiagnosticEmitted = true;
10287           }
10288           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10289               << ConstMethod << MD << MD->getSourceRange();
10290         }
10291       }
10292     }
10293   }
10294 
10295   if (DiagnosticEmitted)
10296     return;
10297 
10298   // Can't determine a more specific message, so display the generic error.
10299   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10300 }
10301 
10302 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10303 /// emit an error and return true.  If so, return false.
10304 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10305   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10306 
10307   S.CheckShadowingDeclModification(E, Loc);
10308 
10309   SourceLocation OrigLoc = Loc;
10310   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10311                                                               &Loc);
10312   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10313     IsLV = Expr::MLV_InvalidMessageExpression;
10314   if (IsLV == Expr::MLV_Valid)
10315     return false;
10316 
10317   unsigned DiagID = 0;
10318   bool NeedType = false;
10319   switch (IsLV) { // C99 6.5.16p2
10320   case Expr::MLV_ConstQualified:
10321     // Use a specialized diagnostic when we're assigning to an object
10322     // from an enclosing function or block.
10323     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10324       if (NCCK == NCCK_Block)
10325         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10326       else
10327         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10328       break;
10329     }
10330 
10331     // In ARC, use some specialized diagnostics for occasions where we
10332     // infer 'const'.  These are always pseudo-strong variables.
10333     if (S.getLangOpts().ObjCAutoRefCount) {
10334       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10335       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10336         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10337 
10338         // Use the normal diagnostic if it's pseudo-__strong but the
10339         // user actually wrote 'const'.
10340         if (var->isARCPseudoStrong() &&
10341             (!var->getTypeSourceInfo() ||
10342              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10343           // There are two pseudo-strong cases:
10344           //  - self
10345           ObjCMethodDecl *method = S.getCurMethodDecl();
10346           if (method && var == method->getSelfDecl())
10347             DiagID = method->isClassMethod()
10348               ? diag::err_typecheck_arc_assign_self_class_method
10349               : diag::err_typecheck_arc_assign_self;
10350 
10351           //  - fast enumeration variables
10352           else
10353             DiagID = diag::err_typecheck_arr_assign_enumeration;
10354 
10355           SourceRange Assign;
10356           if (Loc != OrigLoc)
10357             Assign = SourceRange(OrigLoc, OrigLoc);
10358           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10359           // We need to preserve the AST regardless, so migration tool
10360           // can do its job.
10361           return false;
10362         }
10363       }
10364     }
10365 
10366     // If none of the special cases above are triggered, then this is a
10367     // simple const assignment.
10368     if (DiagID == 0) {
10369       DiagnoseConstAssignment(S, E, Loc);
10370       return true;
10371     }
10372 
10373     break;
10374   case Expr::MLV_ConstAddrSpace:
10375     DiagnoseConstAssignment(S, E, Loc);
10376     return true;
10377   case Expr::MLV_ArrayType:
10378   case Expr::MLV_ArrayTemporary:
10379     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10380     NeedType = true;
10381     break;
10382   case Expr::MLV_NotObjectType:
10383     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10384     NeedType = true;
10385     break;
10386   case Expr::MLV_LValueCast:
10387     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10388     break;
10389   case Expr::MLV_Valid:
10390     llvm_unreachable("did not take early return for MLV_Valid");
10391   case Expr::MLV_InvalidExpression:
10392   case Expr::MLV_MemberFunction:
10393   case Expr::MLV_ClassTemporary:
10394     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10395     break;
10396   case Expr::MLV_IncompleteType:
10397   case Expr::MLV_IncompleteVoidType:
10398     return S.RequireCompleteType(Loc, E->getType(),
10399              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10400   case Expr::MLV_DuplicateVectorComponents:
10401     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10402     break;
10403   case Expr::MLV_NoSetterProperty:
10404     llvm_unreachable("readonly properties should be processed differently");
10405   case Expr::MLV_InvalidMessageExpression:
10406     DiagID = diag::err_readonly_message_assignment;
10407     break;
10408   case Expr::MLV_SubObjCPropertySetting:
10409     DiagID = diag::err_no_subobject_property_setting;
10410     break;
10411   }
10412 
10413   SourceRange Assign;
10414   if (Loc != OrigLoc)
10415     Assign = SourceRange(OrigLoc, OrigLoc);
10416   if (NeedType)
10417     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10418   else
10419     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10420   return true;
10421 }
10422 
10423 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10424                                          SourceLocation Loc,
10425                                          Sema &Sema) {
10426   // C / C++ fields
10427   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10428   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10429   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10430     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10431       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10432   }
10433 
10434   // Objective-C instance variables
10435   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10436   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10437   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10438     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10439     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10440     if (RL && RR && RL->getDecl() == RR->getDecl())
10441       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10442   }
10443 }
10444 
10445 // C99 6.5.16.1
10446 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10447                                        SourceLocation Loc,
10448                                        QualType CompoundType) {
10449   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10450 
10451   // Verify that LHS is a modifiable lvalue, and emit error if not.
10452   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10453     return QualType();
10454 
10455   QualType LHSType = LHSExpr->getType();
10456   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10457                                              CompoundType;
10458   // OpenCL v1.2 s6.1.1.1 p2:
10459   // The half data type can only be used to declare a pointer to a buffer that
10460   // contains half values
10461   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10462     LHSType->isHalfType()) {
10463     Diag(Loc, diag::err_opencl_half_load_store) << 1
10464         << LHSType.getUnqualifiedType();
10465     return QualType();
10466   }
10467 
10468   AssignConvertType ConvTy;
10469   if (CompoundType.isNull()) {
10470     Expr *RHSCheck = RHS.get();
10471 
10472     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10473 
10474     QualType LHSTy(LHSType);
10475     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10476     if (RHS.isInvalid())
10477       return QualType();
10478     // Special case of NSObject attributes on c-style pointer types.
10479     if (ConvTy == IncompatiblePointer &&
10480         ((Context.isObjCNSObjectType(LHSType) &&
10481           RHSType->isObjCObjectPointerType()) ||
10482          (Context.isObjCNSObjectType(RHSType) &&
10483           LHSType->isObjCObjectPointerType())))
10484       ConvTy = Compatible;
10485 
10486     if (ConvTy == Compatible &&
10487         LHSType->isObjCObjectType())
10488         Diag(Loc, diag::err_objc_object_assignment)
10489           << LHSType;
10490 
10491     // If the RHS is a unary plus or minus, check to see if they = and + are
10492     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10493     // instead of "x += 4".
10494     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10495       RHSCheck = ICE->getSubExpr();
10496     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10497       if ((UO->getOpcode() == UO_Plus ||
10498            UO->getOpcode() == UO_Minus) &&
10499           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10500           // Only if the two operators are exactly adjacent.
10501           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10502           // And there is a space or other character before the subexpr of the
10503           // unary +/-.  We don't want to warn on "x=-1".
10504           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10505           UO->getSubExpr()->getLocStart().isFileID()) {
10506         Diag(Loc, diag::warn_not_compound_assign)
10507           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10508           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10509       }
10510     }
10511 
10512     if (ConvTy == Compatible) {
10513       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10514         // Warn about retain cycles where a block captures the LHS, but
10515         // not if the LHS is a simple variable into which the block is
10516         // being stored...unless that variable can be captured by reference!
10517         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10518         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10519         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10520           checkRetainCycles(LHSExpr, RHS.get());
10521       }
10522 
10523       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
10524           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
10525         // It is safe to assign a weak reference into a strong variable.
10526         // Although this code can still have problems:
10527         //   id x = self.weakProp;
10528         //   id y = self.weakProp;
10529         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10530         // paths through the function. This should be revisited if
10531         // -Wrepeated-use-of-weak is made flow-sensitive.
10532         // For ObjCWeak only, we do not warn if the assign is to a non-weak
10533         // variable, which will be valid for the current autorelease scope.
10534         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10535                              RHS.get()->getLocStart()))
10536           getCurFunction()->markSafeWeakUse(RHS.get());
10537 
10538       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
10539         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10540       }
10541     }
10542   } else {
10543     // Compound assignment "x += y"
10544     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10545   }
10546 
10547   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10548                                RHS.get(), AA_Assigning))
10549     return QualType();
10550 
10551   CheckForNullPointerDereference(*this, LHSExpr);
10552 
10553   // C99 6.5.16p3: The type of an assignment expression is the type of the
10554   // left operand unless the left operand has qualified type, in which case
10555   // it is the unqualified version of the type of the left operand.
10556   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10557   // is converted to the type of the assignment expression (above).
10558   // C++ 5.17p1: the type of the assignment expression is that of its left
10559   // operand.
10560   return (getLangOpts().CPlusPlus
10561           ? LHSType : LHSType.getUnqualifiedType());
10562 }
10563 
10564 // Only ignore explicit casts to void.
10565 static bool IgnoreCommaOperand(const Expr *E) {
10566   E = E->IgnoreParens();
10567 
10568   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10569     if (CE->getCastKind() == CK_ToVoid) {
10570       return true;
10571     }
10572   }
10573 
10574   return false;
10575 }
10576 
10577 // Look for instances where it is likely the comma operator is confused with
10578 // another operator.  There is a whitelist of acceptable expressions for the
10579 // left hand side of the comma operator, otherwise emit a warning.
10580 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10581   // No warnings in macros
10582   if (Loc.isMacroID())
10583     return;
10584 
10585   // Don't warn in template instantiations.
10586   if (inTemplateInstantiation())
10587     return;
10588 
10589   // Scope isn't fine-grained enough to whitelist the specific cases, so
10590   // instead, skip more than needed, then call back into here with the
10591   // CommaVisitor in SemaStmt.cpp.
10592   // The whitelisted locations are the initialization and increment portions
10593   // of a for loop.  The additional checks are on the condition of
10594   // if statements, do/while loops, and for loops.
10595   const unsigned ForIncrementFlags =
10596       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10597   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10598   const unsigned ScopeFlags = getCurScope()->getFlags();
10599   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10600       (ScopeFlags & ForInitFlags) == ForInitFlags)
10601     return;
10602 
10603   // If there are multiple comma operators used together, get the RHS of the
10604   // of the comma operator as the LHS.
10605   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10606     if (BO->getOpcode() != BO_Comma)
10607       break;
10608     LHS = BO->getRHS();
10609   }
10610 
10611   // Only allow some expressions on LHS to not warn.
10612   if (IgnoreCommaOperand(LHS))
10613     return;
10614 
10615   Diag(Loc, diag::warn_comma_operator);
10616   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10617       << LHS->getSourceRange()
10618       << FixItHint::CreateInsertion(LHS->getLocStart(),
10619                                     LangOpts.CPlusPlus ? "static_cast<void>("
10620                                                        : "(void)(")
10621       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10622                                     ")");
10623 }
10624 
10625 // C99 6.5.17
10626 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10627                                    SourceLocation Loc) {
10628   LHS = S.CheckPlaceholderExpr(LHS.get());
10629   RHS = S.CheckPlaceholderExpr(RHS.get());
10630   if (LHS.isInvalid() || RHS.isInvalid())
10631     return QualType();
10632 
10633   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10634   // operands, but not unary promotions.
10635   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10636 
10637   // So we treat the LHS as a ignored value, and in C++ we allow the
10638   // containing site to determine what should be done with the RHS.
10639   LHS = S.IgnoredValueConversions(LHS.get());
10640   if (LHS.isInvalid())
10641     return QualType();
10642 
10643   S.DiagnoseUnusedExprResult(LHS.get());
10644 
10645   if (!S.getLangOpts().CPlusPlus) {
10646     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10647     if (RHS.isInvalid())
10648       return QualType();
10649     if (!RHS.get()->getType()->isVoidType())
10650       S.RequireCompleteType(Loc, RHS.get()->getType(),
10651                             diag::err_incomplete_type);
10652   }
10653 
10654   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10655     S.DiagnoseCommaOperator(LHS.get(), Loc);
10656 
10657   return RHS.get()->getType();
10658 }
10659 
10660 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10661 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10662 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10663                                                ExprValueKind &VK,
10664                                                ExprObjectKind &OK,
10665                                                SourceLocation OpLoc,
10666                                                bool IsInc, bool IsPrefix) {
10667   if (Op->isTypeDependent())
10668     return S.Context.DependentTy;
10669 
10670   QualType ResType = Op->getType();
10671   // Atomic types can be used for increment / decrement where the non-atomic
10672   // versions can, so ignore the _Atomic() specifier for the purpose of
10673   // checking.
10674   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10675     ResType = ResAtomicType->getValueType();
10676 
10677   assert(!ResType.isNull() && "no type for increment/decrement expression");
10678 
10679   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10680     // Decrement of bool is not allowed.
10681     if (!IsInc) {
10682       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10683       return QualType();
10684     }
10685     // Increment of bool sets it to true, but is deprecated.
10686     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10687                                               : diag::warn_increment_bool)
10688       << Op->getSourceRange();
10689   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10690     // Error on enum increments and decrements in C++ mode
10691     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10692     return QualType();
10693   } else if (ResType->isRealType()) {
10694     // OK!
10695   } else if (ResType->isPointerType()) {
10696     // C99 6.5.2.4p2, 6.5.6p2
10697     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10698       return QualType();
10699   } else if (ResType->isObjCObjectPointerType()) {
10700     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10701     // Otherwise, we just need a complete type.
10702     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10703         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10704       return QualType();
10705   } else if (ResType->isAnyComplexType()) {
10706     // C99 does not support ++/-- on complex types, we allow as an extension.
10707     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10708       << ResType << Op->getSourceRange();
10709   } else if (ResType->isPlaceholderType()) {
10710     ExprResult PR = S.CheckPlaceholderExpr(Op);
10711     if (PR.isInvalid()) return QualType();
10712     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10713                                           IsInc, IsPrefix);
10714   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10715     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10716   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10717              (ResType->getAs<VectorType>()->getVectorKind() !=
10718               VectorType::AltiVecBool)) {
10719     // The z vector extensions allow ++ and -- for non-bool vectors.
10720   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10721             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10722     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10723   } else {
10724     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10725       << ResType << int(IsInc) << Op->getSourceRange();
10726     return QualType();
10727   }
10728   // At this point, we know we have a real, complex or pointer type.
10729   // Now make sure the operand is a modifiable lvalue.
10730   if (CheckForModifiableLvalue(Op, OpLoc, S))
10731     return QualType();
10732   // In C++, a prefix increment is the same type as the operand. Otherwise
10733   // (in C or with postfix), the increment is the unqualified type of the
10734   // operand.
10735   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10736     VK = VK_LValue;
10737     OK = Op->getObjectKind();
10738     return ResType;
10739   } else {
10740     VK = VK_RValue;
10741     return ResType.getUnqualifiedType();
10742   }
10743 }
10744 
10745 
10746 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10747 /// This routine allows us to typecheck complex/recursive expressions
10748 /// where the declaration is needed for type checking. We only need to
10749 /// handle cases when the expression references a function designator
10750 /// or is an lvalue. Here are some examples:
10751 ///  - &(x) => x
10752 ///  - &*****f => f for f a function designator.
10753 ///  - &s.xx => s
10754 ///  - &s.zz[1].yy -> s, if zz is an array
10755 ///  - *(x + 1) -> x, if x is an array
10756 ///  - &"123"[2] -> 0
10757 ///  - & __real__ x -> x
10758 static ValueDecl *getPrimaryDecl(Expr *E) {
10759   switch (E->getStmtClass()) {
10760   case Stmt::DeclRefExprClass:
10761     return cast<DeclRefExpr>(E)->getDecl();
10762   case Stmt::MemberExprClass:
10763     // If this is an arrow operator, the address is an offset from
10764     // the base's value, so the object the base refers to is
10765     // irrelevant.
10766     if (cast<MemberExpr>(E)->isArrow())
10767       return nullptr;
10768     // Otherwise, the expression refers to a part of the base
10769     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10770   case Stmt::ArraySubscriptExprClass: {
10771     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10772     // promotion of register arrays earlier.
10773     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10774     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10775       if (ICE->getSubExpr()->getType()->isArrayType())
10776         return getPrimaryDecl(ICE->getSubExpr());
10777     }
10778     return nullptr;
10779   }
10780   case Stmt::UnaryOperatorClass: {
10781     UnaryOperator *UO = cast<UnaryOperator>(E);
10782 
10783     switch(UO->getOpcode()) {
10784     case UO_Real:
10785     case UO_Imag:
10786     case UO_Extension:
10787       return getPrimaryDecl(UO->getSubExpr());
10788     default:
10789       return nullptr;
10790     }
10791   }
10792   case Stmt::ParenExprClass:
10793     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10794   case Stmt::ImplicitCastExprClass:
10795     // If the result of an implicit cast is an l-value, we care about
10796     // the sub-expression; otherwise, the result here doesn't matter.
10797     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10798   default:
10799     return nullptr;
10800   }
10801 }
10802 
10803 namespace {
10804   enum {
10805     AO_Bit_Field = 0,
10806     AO_Vector_Element = 1,
10807     AO_Property_Expansion = 2,
10808     AO_Register_Variable = 3,
10809     AO_No_Error = 4
10810   };
10811 }
10812 /// \brief Diagnose invalid operand for address of operations.
10813 ///
10814 /// \param Type The type of operand which cannot have its address taken.
10815 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10816                                          Expr *E, unsigned Type) {
10817   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10818 }
10819 
10820 /// CheckAddressOfOperand - The operand of & must be either a function
10821 /// designator or an lvalue designating an object. If it is an lvalue, the
10822 /// object cannot be declared with storage class register or be a bit field.
10823 /// Note: The usual conversions are *not* applied to the operand of the &
10824 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10825 /// In C++, the operand might be an overloaded function name, in which case
10826 /// we allow the '&' but retain the overloaded-function type.
10827 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10828   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10829     if (PTy->getKind() == BuiltinType::Overload) {
10830       Expr *E = OrigOp.get()->IgnoreParens();
10831       if (!isa<OverloadExpr>(E)) {
10832         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10833         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10834           << OrigOp.get()->getSourceRange();
10835         return QualType();
10836       }
10837 
10838       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10839       if (isa<UnresolvedMemberExpr>(Ovl))
10840         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10841           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10842             << OrigOp.get()->getSourceRange();
10843           return QualType();
10844         }
10845 
10846       return Context.OverloadTy;
10847     }
10848 
10849     if (PTy->getKind() == BuiltinType::UnknownAny)
10850       return Context.UnknownAnyTy;
10851 
10852     if (PTy->getKind() == BuiltinType::BoundMember) {
10853       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10854         << OrigOp.get()->getSourceRange();
10855       return QualType();
10856     }
10857 
10858     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10859     if (OrigOp.isInvalid()) return QualType();
10860   }
10861 
10862   if (OrigOp.get()->isTypeDependent())
10863     return Context.DependentTy;
10864 
10865   assert(!OrigOp.get()->getType()->isPlaceholderType());
10866 
10867   // Make sure to ignore parentheses in subsequent checks
10868   Expr *op = OrigOp.get()->IgnoreParens();
10869 
10870   // In OpenCL captures for blocks called as lambda functions
10871   // are located in the private address space. Blocks used in
10872   // enqueue_kernel can be located in a different address space
10873   // depending on a vendor implementation. Thus preventing
10874   // taking an address of the capture to avoid invalid AS casts.
10875   if (LangOpts.OpenCL) {
10876     auto* VarRef = dyn_cast<DeclRefExpr>(op);
10877     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
10878       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
10879       return QualType();
10880     }
10881   }
10882 
10883   if (getLangOpts().C99) {
10884     // Implement C99-only parts of addressof rules.
10885     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10886       if (uOp->getOpcode() == UO_Deref)
10887         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10888         // (assuming the deref expression is valid).
10889         return uOp->getSubExpr()->getType();
10890     }
10891     // Technically, there should be a check for array subscript
10892     // expressions here, but the result of one is always an lvalue anyway.
10893   }
10894   ValueDecl *dcl = getPrimaryDecl(op);
10895 
10896   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10897     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10898                                            op->getLocStart()))
10899       return QualType();
10900 
10901   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10902   unsigned AddressOfError = AO_No_Error;
10903 
10904   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10905     bool sfinae = (bool)isSFINAEContext();
10906     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10907                                   : diag::ext_typecheck_addrof_temporary)
10908       << op->getType() << op->getSourceRange();
10909     if (sfinae)
10910       return QualType();
10911     // Materialize the temporary as an lvalue so that we can take its address.
10912     OrigOp = op =
10913         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10914   } else if (isa<ObjCSelectorExpr>(op)) {
10915     return Context.getPointerType(op->getType());
10916   } else if (lval == Expr::LV_MemberFunction) {
10917     // If it's an instance method, make a member pointer.
10918     // The expression must have exactly the form &A::foo.
10919 
10920     // If the underlying expression isn't a decl ref, give up.
10921     if (!isa<DeclRefExpr>(op)) {
10922       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10923         << OrigOp.get()->getSourceRange();
10924       return QualType();
10925     }
10926     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10927     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10928 
10929     // The id-expression was parenthesized.
10930     if (OrigOp.get() != DRE) {
10931       Diag(OpLoc, diag::err_parens_pointer_member_function)
10932         << OrigOp.get()->getSourceRange();
10933 
10934     // The method was named without a qualifier.
10935     } else if (!DRE->getQualifier()) {
10936       if (MD->getParent()->getName().empty())
10937         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10938           << op->getSourceRange();
10939       else {
10940         SmallString<32> Str;
10941         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10942         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10943           << op->getSourceRange()
10944           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10945       }
10946     }
10947 
10948     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10949     if (isa<CXXDestructorDecl>(MD))
10950       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10951 
10952     QualType MPTy = Context.getMemberPointerType(
10953         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10954     // Under the MS ABI, lock down the inheritance model now.
10955     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10956       (void)isCompleteType(OpLoc, MPTy);
10957     return MPTy;
10958   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10959     // C99 6.5.3.2p1
10960     // The operand must be either an l-value or a function designator
10961     if (!op->getType()->isFunctionType()) {
10962       // Use a special diagnostic for loads from property references.
10963       if (isa<PseudoObjectExpr>(op)) {
10964         AddressOfError = AO_Property_Expansion;
10965       } else {
10966         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10967           << op->getType() << op->getSourceRange();
10968         return QualType();
10969       }
10970     }
10971   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10972     // The operand cannot be a bit-field
10973     AddressOfError = AO_Bit_Field;
10974   } else if (op->getObjectKind() == OK_VectorComponent) {
10975     // The operand cannot be an element of a vector
10976     AddressOfError = AO_Vector_Element;
10977   } else if (dcl) { // C99 6.5.3.2p1
10978     // We have an lvalue with a decl. Make sure the decl is not declared
10979     // with the register storage-class specifier.
10980     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10981       // in C++ it is not error to take address of a register
10982       // variable (c++03 7.1.1P3)
10983       if (vd->getStorageClass() == SC_Register &&
10984           !getLangOpts().CPlusPlus) {
10985         AddressOfError = AO_Register_Variable;
10986       }
10987     } else if (isa<MSPropertyDecl>(dcl)) {
10988       AddressOfError = AO_Property_Expansion;
10989     } else if (isa<FunctionTemplateDecl>(dcl)) {
10990       return Context.OverloadTy;
10991     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10992       // Okay: we can take the address of a field.
10993       // Could be a pointer to member, though, if there is an explicit
10994       // scope qualifier for the class.
10995       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10996         DeclContext *Ctx = dcl->getDeclContext();
10997         if (Ctx && Ctx->isRecord()) {
10998           if (dcl->getType()->isReferenceType()) {
10999             Diag(OpLoc,
11000                  diag::err_cannot_form_pointer_to_member_of_reference_type)
11001               << dcl->getDeclName() << dcl->getType();
11002             return QualType();
11003           }
11004 
11005           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
11006             Ctx = Ctx->getParent();
11007 
11008           QualType MPTy = Context.getMemberPointerType(
11009               op->getType(),
11010               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
11011           // Under the MS ABI, lock down the inheritance model now.
11012           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11013             (void)isCompleteType(OpLoc, MPTy);
11014           return MPTy;
11015         }
11016       }
11017     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
11018                !isa<BindingDecl>(dcl))
11019       llvm_unreachable("Unknown/unexpected decl type");
11020   }
11021 
11022   if (AddressOfError != AO_No_Error) {
11023     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
11024     return QualType();
11025   }
11026 
11027   if (lval == Expr::LV_IncompleteVoidType) {
11028     // Taking the address of a void variable is technically illegal, but we
11029     // allow it in cases which are otherwise valid.
11030     // Example: "extern void x; void* y = &x;".
11031     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
11032   }
11033 
11034   // If the operand has type "type", the result has type "pointer to type".
11035   if (op->getType()->isObjCObjectType())
11036     return Context.getObjCObjectPointerType(op->getType());
11037 
11038   CheckAddressOfPackedMember(op);
11039 
11040   return Context.getPointerType(op->getType());
11041 }
11042 
11043 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11044   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11045   if (!DRE)
11046     return;
11047   const Decl *D = DRE->getDecl();
11048   if (!D)
11049     return;
11050   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11051   if (!Param)
11052     return;
11053   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11054     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11055       return;
11056   if (FunctionScopeInfo *FD = S.getCurFunction())
11057     if (!FD->ModifiedNonNullParams.count(Param))
11058       FD->ModifiedNonNullParams.insert(Param);
11059 }
11060 
11061 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11062 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
11063                                         SourceLocation OpLoc) {
11064   if (Op->isTypeDependent())
11065     return S.Context.DependentTy;
11066 
11067   ExprResult ConvResult = S.UsualUnaryConversions(Op);
11068   if (ConvResult.isInvalid())
11069     return QualType();
11070   Op = ConvResult.get();
11071   QualType OpTy = Op->getType();
11072   QualType Result;
11073 
11074   if (isa<CXXReinterpretCastExpr>(Op)) {
11075     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11076     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11077                                      Op->getSourceRange());
11078   }
11079 
11080   if (const PointerType *PT = OpTy->getAs<PointerType>())
11081   {
11082     Result = PT->getPointeeType();
11083   }
11084   else if (const ObjCObjectPointerType *OPT =
11085              OpTy->getAs<ObjCObjectPointerType>())
11086     Result = OPT->getPointeeType();
11087   else {
11088     ExprResult PR = S.CheckPlaceholderExpr(Op);
11089     if (PR.isInvalid()) return QualType();
11090     if (PR.get() != Op)
11091       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
11092   }
11093 
11094   if (Result.isNull()) {
11095     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
11096       << OpTy << Op->getSourceRange();
11097     return QualType();
11098   }
11099 
11100   // Note that per both C89 and C99, indirection is always legal, even if Result
11101   // is an incomplete type or void.  It would be possible to warn about
11102   // dereferencing a void pointer, but it's completely well-defined, and such a
11103   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
11104   // for pointers to 'void' but is fine for any other pointer type:
11105   //
11106   // C++ [expr.unary.op]p1:
11107   //   [...] the expression to which [the unary * operator] is applied shall
11108   //   be a pointer to an object type, or a pointer to a function type
11109   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
11110     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
11111       << OpTy << Op->getSourceRange();
11112 
11113   // Dereferences are usually l-values...
11114   VK = VK_LValue;
11115 
11116   // ...except that certain expressions are never l-values in C.
11117   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
11118     VK = VK_RValue;
11119 
11120   return Result;
11121 }
11122 
11123 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
11124   BinaryOperatorKind Opc;
11125   switch (Kind) {
11126   default: llvm_unreachable("Unknown binop!");
11127   case tok::periodstar:           Opc = BO_PtrMemD; break;
11128   case tok::arrowstar:            Opc = BO_PtrMemI; break;
11129   case tok::star:                 Opc = BO_Mul; break;
11130   case tok::slash:                Opc = BO_Div; break;
11131   case tok::percent:              Opc = BO_Rem; break;
11132   case tok::plus:                 Opc = BO_Add; break;
11133   case tok::minus:                Opc = BO_Sub; break;
11134   case tok::lessless:             Opc = BO_Shl; break;
11135   case tok::greatergreater:       Opc = BO_Shr; break;
11136   case tok::lessequal:            Opc = BO_LE; break;
11137   case tok::less:                 Opc = BO_LT; break;
11138   case tok::greaterequal:         Opc = BO_GE; break;
11139   case tok::greater:              Opc = BO_GT; break;
11140   case tok::exclaimequal:         Opc = BO_NE; break;
11141   case tok::equalequal:           Opc = BO_EQ; break;
11142   case tok::amp:                  Opc = BO_And; break;
11143   case tok::caret:                Opc = BO_Xor; break;
11144   case tok::pipe:                 Opc = BO_Or; break;
11145   case tok::ampamp:               Opc = BO_LAnd; break;
11146   case tok::pipepipe:             Opc = BO_LOr; break;
11147   case tok::equal:                Opc = BO_Assign; break;
11148   case tok::starequal:            Opc = BO_MulAssign; break;
11149   case tok::slashequal:           Opc = BO_DivAssign; break;
11150   case tok::percentequal:         Opc = BO_RemAssign; break;
11151   case tok::plusequal:            Opc = BO_AddAssign; break;
11152   case tok::minusequal:           Opc = BO_SubAssign; break;
11153   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
11154   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
11155   case tok::ampequal:             Opc = BO_AndAssign; break;
11156   case tok::caretequal:           Opc = BO_XorAssign; break;
11157   case tok::pipeequal:            Opc = BO_OrAssign; break;
11158   case tok::comma:                Opc = BO_Comma; break;
11159   }
11160   return Opc;
11161 }
11162 
11163 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
11164   tok::TokenKind Kind) {
11165   UnaryOperatorKind Opc;
11166   switch (Kind) {
11167   default: llvm_unreachable("Unknown unary op!");
11168   case tok::plusplus:     Opc = UO_PreInc; break;
11169   case tok::minusminus:   Opc = UO_PreDec; break;
11170   case tok::amp:          Opc = UO_AddrOf; break;
11171   case tok::star:         Opc = UO_Deref; break;
11172   case tok::plus:         Opc = UO_Plus; break;
11173   case tok::minus:        Opc = UO_Minus; break;
11174   case tok::tilde:        Opc = UO_Not; break;
11175   case tok::exclaim:      Opc = UO_LNot; break;
11176   case tok::kw___real:    Opc = UO_Real; break;
11177   case tok::kw___imag:    Opc = UO_Imag; break;
11178   case tok::kw___extension__: Opc = UO_Extension; break;
11179   }
11180   return Opc;
11181 }
11182 
11183 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11184 /// This warning is only emitted for builtin assignment operations. It is also
11185 /// suppressed in the event of macro expansions.
11186 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11187                                    SourceLocation OpLoc) {
11188   if (S.inTemplateInstantiation())
11189     return;
11190   if (OpLoc.isInvalid() || OpLoc.isMacroID())
11191     return;
11192   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11193   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11194   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11195   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11196   if (!LHSDeclRef || !RHSDeclRef ||
11197       LHSDeclRef->getLocation().isMacroID() ||
11198       RHSDeclRef->getLocation().isMacroID())
11199     return;
11200   const ValueDecl *LHSDecl =
11201     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11202   const ValueDecl *RHSDecl =
11203     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11204   if (LHSDecl != RHSDecl)
11205     return;
11206   if (LHSDecl->getType().isVolatileQualified())
11207     return;
11208   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11209     if (RefTy->getPointeeType().isVolatileQualified())
11210       return;
11211 
11212   S.Diag(OpLoc, diag::warn_self_assignment)
11213       << LHSDeclRef->getType()
11214       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11215 }
11216 
11217 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
11218 /// is usually indicative of introspection within the Objective-C pointer.
11219 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11220                                           SourceLocation OpLoc) {
11221   if (!S.getLangOpts().ObjC1)
11222     return;
11223 
11224   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11225   const Expr *LHS = L.get();
11226   const Expr *RHS = R.get();
11227 
11228   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11229     ObjCPointerExpr = LHS;
11230     OtherExpr = RHS;
11231   }
11232   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11233     ObjCPointerExpr = RHS;
11234     OtherExpr = LHS;
11235   }
11236 
11237   // This warning is deliberately made very specific to reduce false
11238   // positives with logic that uses '&' for hashing.  This logic mainly
11239   // looks for code trying to introspect into tagged pointers, which
11240   // code should generally never do.
11241   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11242     unsigned Diag = diag::warn_objc_pointer_masking;
11243     // Determine if we are introspecting the result of performSelectorXXX.
11244     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11245     // Special case messages to -performSelector and friends, which
11246     // can return non-pointer values boxed in a pointer value.
11247     // Some clients may wish to silence warnings in this subcase.
11248     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11249       Selector S = ME->getSelector();
11250       StringRef SelArg0 = S.getNameForSlot(0);
11251       if (SelArg0.startswith("performSelector"))
11252         Diag = diag::warn_objc_pointer_masking_performSelector;
11253     }
11254 
11255     S.Diag(OpLoc, Diag)
11256       << ObjCPointerExpr->getSourceRange();
11257   }
11258 }
11259 
11260 static NamedDecl *getDeclFromExpr(Expr *E) {
11261   if (!E)
11262     return nullptr;
11263   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11264     return DRE->getDecl();
11265   if (auto *ME = dyn_cast<MemberExpr>(E))
11266     return ME->getMemberDecl();
11267   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11268     return IRE->getDecl();
11269   return nullptr;
11270 }
11271 
11272 static std::pair<ExprResult, ExprResult>
11273 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
11274                            Expr *RHSExpr) {
11275   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11276   if (!S.getLangOpts().CPlusPlus) {
11277     // C cannot handle TypoExpr nodes on either side of a binop because it
11278     // doesn't handle dependent types properly, so make sure any TypoExprs have
11279     // been dealt with before checking the operands.
11280     LHS = S.CorrectDelayedTyposInExpr(LHS);
11281     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
11282       if (Opc != BO_Assign)
11283         return ExprResult(E);
11284       // Avoid correcting the RHS to the same Expr as the LHS.
11285       Decl *D = getDeclFromExpr(E);
11286       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11287     });
11288   }
11289   return std::make_pair(LHS, RHS);
11290 }
11291 
11292 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11293 /// operator @p Opc at location @c TokLoc. This routine only supports
11294 /// built-in operations; ActOnBinOp handles overloaded operators.
11295 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11296                                     BinaryOperatorKind Opc,
11297                                     Expr *LHSExpr, Expr *RHSExpr) {
11298   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11299     // The syntax only allows initializer lists on the RHS of assignment,
11300     // so we don't need to worry about accepting invalid code for
11301     // non-assignment operators.
11302     // C++11 5.17p9:
11303     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11304     //   of x = {} is x = T().
11305     InitializationKind Kind =
11306         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
11307     InitializedEntity Entity =
11308         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11309     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11310     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11311     if (Init.isInvalid())
11312       return Init;
11313     RHSExpr = Init.get();
11314   }
11315 
11316   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11317   QualType ResultTy;     // Result type of the binary operator.
11318   // The following two variables are used for compound assignment operators
11319   QualType CompLHSTy;    // Type of LHS after promotions for computation
11320   QualType CompResultTy; // Type of computation result
11321   ExprValueKind VK = VK_RValue;
11322   ExprObjectKind OK = OK_Ordinary;
11323 
11324   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
11325   if (!LHS.isUsable() || !RHS.isUsable())
11326     return ExprError();
11327 
11328   if (getLangOpts().OpenCL) {
11329     QualType LHSTy = LHSExpr->getType();
11330     QualType RHSTy = RHSExpr->getType();
11331     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11332     // the ATOMIC_VAR_INIT macro.
11333     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11334       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11335       if (BO_Assign == Opc)
11336         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
11337       else
11338         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11339       return ExprError();
11340     }
11341 
11342     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11343     // only with a builtin functions and therefore should be disallowed here.
11344     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11345         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11346         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11347         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11348       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11349       return ExprError();
11350     }
11351   }
11352 
11353   switch (Opc) {
11354   case BO_Assign:
11355     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11356     if (getLangOpts().CPlusPlus &&
11357         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11358       VK = LHS.get()->getValueKind();
11359       OK = LHS.get()->getObjectKind();
11360     }
11361     if (!ResultTy.isNull()) {
11362       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11363       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11364     }
11365     RecordModifiableNonNullParam(*this, LHS.get());
11366     break;
11367   case BO_PtrMemD:
11368   case BO_PtrMemI:
11369     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11370                                             Opc == BO_PtrMemI);
11371     break;
11372   case BO_Mul:
11373   case BO_Div:
11374     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11375                                            Opc == BO_Div);
11376     break;
11377   case BO_Rem:
11378     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11379     break;
11380   case BO_Add:
11381     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11382     break;
11383   case BO_Sub:
11384     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11385     break;
11386   case BO_Shl:
11387   case BO_Shr:
11388     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11389     break;
11390   case BO_LE:
11391   case BO_LT:
11392   case BO_GE:
11393   case BO_GT:
11394     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11395     break;
11396   case BO_EQ:
11397   case BO_NE:
11398     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11399     break;
11400   case BO_And:
11401     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11402     LLVM_FALLTHROUGH;
11403   case BO_Xor:
11404   case BO_Or:
11405     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11406     break;
11407   case BO_LAnd:
11408   case BO_LOr:
11409     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11410     break;
11411   case BO_MulAssign:
11412   case BO_DivAssign:
11413     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11414                                                Opc == BO_DivAssign);
11415     CompLHSTy = CompResultTy;
11416     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11417       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11418     break;
11419   case BO_RemAssign:
11420     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11421     CompLHSTy = CompResultTy;
11422     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11423       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11424     break;
11425   case BO_AddAssign:
11426     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11427     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11428       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11429     break;
11430   case BO_SubAssign:
11431     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11432     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11433       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11434     break;
11435   case BO_ShlAssign:
11436   case BO_ShrAssign:
11437     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11438     CompLHSTy = CompResultTy;
11439     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11440       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11441     break;
11442   case BO_AndAssign:
11443   case BO_OrAssign: // fallthrough
11444     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11445     LLVM_FALLTHROUGH;
11446   case BO_XorAssign:
11447     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11448     CompLHSTy = CompResultTy;
11449     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11450       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11451     break;
11452   case BO_Comma:
11453     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11454     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11455       VK = RHS.get()->getValueKind();
11456       OK = RHS.get()->getObjectKind();
11457     }
11458     break;
11459   }
11460   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11461     return ExprError();
11462 
11463   // Check for array bounds violations for both sides of the BinaryOperator
11464   CheckArrayAccess(LHS.get());
11465   CheckArrayAccess(RHS.get());
11466 
11467   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11468     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11469                                                  &Context.Idents.get("object_setClass"),
11470                                                  SourceLocation(), LookupOrdinaryName);
11471     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11472       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11473       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11474       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11475       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11476       FixItHint::CreateInsertion(RHSLocEnd, ")");
11477     }
11478     else
11479       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11480   }
11481   else if (const ObjCIvarRefExpr *OIRE =
11482            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11483     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11484 
11485   if (CompResultTy.isNull())
11486     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11487                                         OK, OpLoc, FPFeatures);
11488   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11489       OK_ObjCProperty) {
11490     VK = VK_LValue;
11491     OK = LHS.get()->getObjectKind();
11492   }
11493   return new (Context) CompoundAssignOperator(
11494       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11495       OpLoc, FPFeatures);
11496 }
11497 
11498 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11499 /// operators are mixed in a way that suggests that the programmer forgot that
11500 /// comparison operators have higher precedence. The most typical example of
11501 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11502 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11503                                       SourceLocation OpLoc, Expr *LHSExpr,
11504                                       Expr *RHSExpr) {
11505   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11506   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11507 
11508   // Check that one of the sides is a comparison operator and the other isn't.
11509   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11510   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11511   if (isLeftComp == isRightComp)
11512     return;
11513 
11514   // Bitwise operations are sometimes used as eager logical ops.
11515   // Don't diagnose this.
11516   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11517   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11518   if (isLeftBitwise || isRightBitwise)
11519     return;
11520 
11521   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11522                                                    OpLoc)
11523                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11524   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11525   SourceRange ParensRange = isLeftComp ?
11526       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11527     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11528 
11529   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11530     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11531   SuggestParentheses(Self, OpLoc,
11532     Self.PDiag(diag::note_precedence_silence) << OpStr,
11533     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11534   SuggestParentheses(Self, OpLoc,
11535     Self.PDiag(diag::note_precedence_bitwise_first)
11536       << BinaryOperator::getOpcodeStr(Opc),
11537     ParensRange);
11538 }
11539 
11540 /// \brief It accepts a '&&' expr that is inside a '||' one.
11541 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11542 /// in parentheses.
11543 static void
11544 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11545                                        BinaryOperator *Bop) {
11546   assert(Bop->getOpcode() == BO_LAnd);
11547   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11548       << Bop->getSourceRange() << OpLoc;
11549   SuggestParentheses(Self, Bop->getOperatorLoc(),
11550     Self.PDiag(diag::note_precedence_silence)
11551       << Bop->getOpcodeStr(),
11552     Bop->getSourceRange());
11553 }
11554 
11555 /// \brief Returns true if the given expression can be evaluated as a constant
11556 /// 'true'.
11557 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11558   bool Res;
11559   return !E->isValueDependent() &&
11560          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11561 }
11562 
11563 /// \brief Returns true if the given expression can be evaluated as a constant
11564 /// 'false'.
11565 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11566   bool Res;
11567   return !E->isValueDependent() &&
11568          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11569 }
11570 
11571 /// \brief Look for '&&' in the left hand of a '||' expr.
11572 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11573                                              Expr *LHSExpr, Expr *RHSExpr) {
11574   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11575     if (Bop->getOpcode() == BO_LAnd) {
11576       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11577       if (EvaluatesAsFalse(S, RHSExpr))
11578         return;
11579       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11580       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11581         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11582     } else if (Bop->getOpcode() == BO_LOr) {
11583       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11584         // If it's "a || b && 1 || c" we didn't warn earlier for
11585         // "a || b && 1", but warn now.
11586         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11587           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11588       }
11589     }
11590   }
11591 }
11592 
11593 /// \brief Look for '&&' in the right hand of a '||' expr.
11594 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11595                                              Expr *LHSExpr, Expr *RHSExpr) {
11596   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11597     if (Bop->getOpcode() == BO_LAnd) {
11598       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11599       if (EvaluatesAsFalse(S, LHSExpr))
11600         return;
11601       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11602       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11603         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11604     }
11605   }
11606 }
11607 
11608 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11609 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11610 /// the '&' expression in parentheses.
11611 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11612                                          SourceLocation OpLoc, Expr *SubExpr) {
11613   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11614     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11615       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11616         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11617         << Bop->getSourceRange() << OpLoc;
11618       SuggestParentheses(S, Bop->getOperatorLoc(),
11619         S.PDiag(diag::note_precedence_silence)
11620           << Bop->getOpcodeStr(),
11621         Bop->getSourceRange());
11622     }
11623   }
11624 }
11625 
11626 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11627                                     Expr *SubExpr, StringRef Shift) {
11628   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11629     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11630       StringRef Op = Bop->getOpcodeStr();
11631       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11632           << Bop->getSourceRange() << OpLoc << Shift << Op;
11633       SuggestParentheses(S, Bop->getOperatorLoc(),
11634           S.PDiag(diag::note_precedence_silence) << Op,
11635           Bop->getSourceRange());
11636     }
11637   }
11638 }
11639 
11640 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11641                                  Expr *LHSExpr, Expr *RHSExpr) {
11642   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11643   if (!OCE)
11644     return;
11645 
11646   FunctionDecl *FD = OCE->getDirectCallee();
11647   if (!FD || !FD->isOverloadedOperator())
11648     return;
11649 
11650   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11651   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11652     return;
11653 
11654   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11655       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11656       << (Kind == OO_LessLess);
11657   SuggestParentheses(S, OCE->getOperatorLoc(),
11658                      S.PDiag(diag::note_precedence_silence)
11659                          << (Kind == OO_LessLess ? "<<" : ">>"),
11660                      OCE->getSourceRange());
11661   SuggestParentheses(S, OpLoc,
11662                      S.PDiag(diag::note_evaluate_comparison_first),
11663                      SourceRange(OCE->getArg(1)->getLocStart(),
11664                                  RHSExpr->getLocEnd()));
11665 }
11666 
11667 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11668 /// precedence.
11669 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11670                                     SourceLocation OpLoc, Expr *LHSExpr,
11671                                     Expr *RHSExpr){
11672   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11673   if (BinaryOperator::isBitwiseOp(Opc))
11674     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11675 
11676   // Diagnose "arg1 & arg2 | arg3"
11677   if ((Opc == BO_Or || Opc == BO_Xor) &&
11678       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11679     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11680     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11681   }
11682 
11683   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11684   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11685   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11686     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11687     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11688   }
11689 
11690   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11691       || Opc == BO_Shr) {
11692     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11693     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11694     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11695   }
11696 
11697   // Warn on overloaded shift operators and comparisons, such as:
11698   // cout << 5 == 4;
11699   if (BinaryOperator::isComparisonOp(Opc))
11700     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11701 }
11702 
11703 // Binary Operators.  'Tok' is the token for the operator.
11704 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11705                             tok::TokenKind Kind,
11706                             Expr *LHSExpr, Expr *RHSExpr) {
11707   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11708   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11709   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11710 
11711   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11712   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11713 
11714   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11715 }
11716 
11717 /// Build an overloaded binary operator expression in the given scope.
11718 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11719                                        BinaryOperatorKind Opc,
11720                                        Expr *LHS, Expr *RHS) {
11721   // Find all of the overloaded operators visible from this
11722   // point. We perform both an operator-name lookup from the local
11723   // scope and an argument-dependent lookup based on the types of
11724   // the arguments.
11725   UnresolvedSet<16> Functions;
11726   OverloadedOperatorKind OverOp
11727     = BinaryOperator::getOverloadedOperator(Opc);
11728   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11729     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11730                                    RHS->getType(), Functions);
11731 
11732   // Build the (potentially-overloaded, potentially-dependent)
11733   // binary operation.
11734   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11735 }
11736 
11737 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11738                             BinaryOperatorKind Opc,
11739                             Expr *LHSExpr, Expr *RHSExpr) {
11740   ExprResult LHS, RHS;
11741   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
11742   if (!LHS.isUsable() || !RHS.isUsable())
11743     return ExprError();
11744   LHSExpr = LHS.get();
11745   RHSExpr = RHS.get();
11746 
11747   // We want to end up calling one of checkPseudoObjectAssignment
11748   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11749   // both expressions are overloadable or either is type-dependent),
11750   // or CreateBuiltinBinOp (in any other case).  We also want to get
11751   // any placeholder types out of the way.
11752 
11753   // Handle pseudo-objects in the LHS.
11754   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11755     // Assignments with a pseudo-object l-value need special analysis.
11756     if (pty->getKind() == BuiltinType::PseudoObject &&
11757         BinaryOperator::isAssignmentOp(Opc))
11758       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11759 
11760     // Don't resolve overloads if the other type is overloadable.
11761     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
11762       // We can't actually test that if we still have a placeholder,
11763       // though.  Fortunately, none of the exceptions we see in that
11764       // code below are valid when the LHS is an overload set.  Note
11765       // that an overload set can be dependently-typed, but it never
11766       // instantiates to having an overloadable type.
11767       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11768       if (resolvedRHS.isInvalid()) return ExprError();
11769       RHSExpr = resolvedRHS.get();
11770 
11771       if (RHSExpr->isTypeDependent() ||
11772           RHSExpr->getType()->isOverloadableType())
11773         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11774     }
11775 
11776     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
11777     // template, diagnose the missing 'template' keyword instead of diagnosing
11778     // an invalid use of a bound member function.
11779     //
11780     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
11781     // to C++1z [over.over]/1.4, but we already checked for that case above.
11782     if (Opc == BO_LT && inTemplateInstantiation() &&
11783         (pty->getKind() == BuiltinType::BoundMember ||
11784          pty->getKind() == BuiltinType::Overload)) {
11785       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
11786       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
11787           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
11788             return isa<FunctionTemplateDecl>(ND);
11789           })) {
11790         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
11791                                 : OE->getNameLoc(),
11792              diag::err_template_kw_missing)
11793           << OE->getName().getAsString() << "";
11794         return ExprError();
11795       }
11796     }
11797 
11798     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11799     if (LHS.isInvalid()) return ExprError();
11800     LHSExpr = LHS.get();
11801   }
11802 
11803   // Handle pseudo-objects in the RHS.
11804   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11805     // An overload in the RHS can potentially be resolved by the type
11806     // being assigned to.
11807     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11808       if (getLangOpts().CPlusPlus &&
11809           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
11810            LHSExpr->getType()->isOverloadableType()))
11811         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11812 
11813       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11814     }
11815 
11816     // Don't resolve overloads if the other type is overloadable.
11817     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
11818         LHSExpr->getType()->isOverloadableType())
11819       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11820 
11821     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11822     if (!resolvedRHS.isUsable()) return ExprError();
11823     RHSExpr = resolvedRHS.get();
11824   }
11825 
11826   if (getLangOpts().CPlusPlus) {
11827     // If either expression is type-dependent, always build an
11828     // overloaded op.
11829     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11830       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11831 
11832     // Otherwise, build an overloaded op if either expression has an
11833     // overloadable type.
11834     if (LHSExpr->getType()->isOverloadableType() ||
11835         RHSExpr->getType()->isOverloadableType())
11836       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11837   }
11838 
11839   // Build a built-in binary operation.
11840   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11841 }
11842 
11843 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11844                                       UnaryOperatorKind Opc,
11845                                       Expr *InputExpr) {
11846   ExprResult Input = InputExpr;
11847   ExprValueKind VK = VK_RValue;
11848   ExprObjectKind OK = OK_Ordinary;
11849   QualType resultType;
11850   if (getLangOpts().OpenCL) {
11851     QualType Ty = InputExpr->getType();
11852     // The only legal unary operation for atomics is '&'.
11853     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11854     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11855     // only with a builtin functions and therefore should be disallowed here.
11856         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11857         || Ty->isBlockPointerType())) {
11858       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11859                        << InputExpr->getType()
11860                        << Input.get()->getSourceRange());
11861     }
11862   }
11863   switch (Opc) {
11864   case UO_PreInc:
11865   case UO_PreDec:
11866   case UO_PostInc:
11867   case UO_PostDec:
11868     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11869                                                 OpLoc,
11870                                                 Opc == UO_PreInc ||
11871                                                 Opc == UO_PostInc,
11872                                                 Opc == UO_PreInc ||
11873                                                 Opc == UO_PreDec);
11874     break;
11875   case UO_AddrOf:
11876     resultType = CheckAddressOfOperand(Input, OpLoc);
11877     RecordModifiableNonNullParam(*this, InputExpr);
11878     break;
11879   case UO_Deref: {
11880     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11881     if (Input.isInvalid()) return ExprError();
11882     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11883     break;
11884   }
11885   case UO_Plus:
11886   case UO_Minus:
11887     Input = UsualUnaryConversions(Input.get());
11888     if (Input.isInvalid()) return ExprError();
11889     resultType = Input.get()->getType();
11890     if (resultType->isDependentType())
11891       break;
11892     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11893       break;
11894     else if (resultType->isVectorType() &&
11895              // The z vector extensions don't allow + or - with bool vectors.
11896              (!Context.getLangOpts().ZVector ||
11897               resultType->getAs<VectorType>()->getVectorKind() !=
11898               VectorType::AltiVecBool))
11899       break;
11900     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11901              Opc == UO_Plus &&
11902              resultType->isPointerType())
11903       break;
11904 
11905     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11906       << resultType << Input.get()->getSourceRange());
11907 
11908   case UO_Not: // bitwise complement
11909     Input = UsualUnaryConversions(Input.get());
11910     if (Input.isInvalid())
11911       return ExprError();
11912     resultType = Input.get()->getType();
11913     if (resultType->isDependentType())
11914       break;
11915     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11916     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11917       // C99 does not support '~' for complex conjugation.
11918       Diag(OpLoc, diag::ext_integer_complement_complex)
11919           << resultType << Input.get()->getSourceRange();
11920     else if (resultType->hasIntegerRepresentation())
11921       break;
11922     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
11923       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11924       // on vector float types.
11925       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11926       if (!T->isIntegerType())
11927         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11928                           << resultType << Input.get()->getSourceRange());
11929     } else {
11930       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11931                        << resultType << Input.get()->getSourceRange());
11932     }
11933     break;
11934 
11935   case UO_LNot: // logical negation
11936     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11937     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11938     if (Input.isInvalid()) return ExprError();
11939     resultType = Input.get()->getType();
11940 
11941     // Though we still have to promote half FP to float...
11942     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11943       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11944       resultType = Context.FloatTy;
11945     }
11946 
11947     if (resultType->isDependentType())
11948       break;
11949     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11950       // C99 6.5.3.3p1: ok, fallthrough;
11951       if (Context.getLangOpts().CPlusPlus) {
11952         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11953         // operand contextually converted to bool.
11954         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11955                                   ScalarTypeToBooleanCastKind(resultType));
11956       } else if (Context.getLangOpts().OpenCL &&
11957                  Context.getLangOpts().OpenCLVersion < 120) {
11958         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11959         // operate on scalar float types.
11960         if (!resultType->isIntegerType() && !resultType->isPointerType())
11961           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11962                            << resultType << Input.get()->getSourceRange());
11963       }
11964     } else if (resultType->isExtVectorType()) {
11965       if (Context.getLangOpts().OpenCL &&
11966           Context.getLangOpts().OpenCLVersion < 120) {
11967         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11968         // operate on vector float types.
11969         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11970         if (!T->isIntegerType())
11971           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11972                            << resultType << Input.get()->getSourceRange());
11973       }
11974       // Vector logical not returns the signed variant of the operand type.
11975       resultType = GetSignedVectorType(resultType);
11976       break;
11977     } else {
11978       // FIXME: GCC's vector extension permits the usage of '!' with a vector
11979       //        type in C++. We should allow that here too.
11980       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11981         << resultType << Input.get()->getSourceRange());
11982     }
11983 
11984     // LNot always has type int. C99 6.5.3.3p5.
11985     // In C++, it's bool. C++ 5.3.1p8
11986     resultType = Context.getLogicalOperationType();
11987     break;
11988   case UO_Real:
11989   case UO_Imag:
11990     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11991     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11992     // complex l-values to ordinary l-values and all other values to r-values.
11993     if (Input.isInvalid()) return ExprError();
11994     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11995       if (Input.get()->getValueKind() != VK_RValue &&
11996           Input.get()->getObjectKind() == OK_Ordinary)
11997         VK = Input.get()->getValueKind();
11998     } else if (!getLangOpts().CPlusPlus) {
11999       // In C, a volatile scalar is read by __imag. In C++, it is not.
12000       Input = DefaultLvalueConversion(Input.get());
12001     }
12002     break;
12003   case UO_Extension:
12004     resultType = Input.get()->getType();
12005     VK = Input.get()->getValueKind();
12006     OK = Input.get()->getObjectKind();
12007     break;
12008   case UO_Coawait:
12009     // It's unnessesary to represent the pass-through operator co_await in the
12010     // AST; just return the input expression instead.
12011     assert(!Input.get()->getType()->isDependentType() &&
12012                    "the co_await expression must be non-dependant before "
12013                    "building operator co_await");
12014     return Input;
12015   }
12016   if (resultType.isNull() || Input.isInvalid())
12017     return ExprError();
12018 
12019   // Check for array bounds violations in the operand of the UnaryOperator,
12020   // except for the '*' and '&' operators that have to be handled specially
12021   // by CheckArrayAccess (as there are special cases like &array[arraysize]
12022   // that are explicitly defined as valid by the standard).
12023   if (Opc != UO_AddrOf && Opc != UO_Deref)
12024     CheckArrayAccess(Input.get());
12025 
12026   return new (Context)
12027       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
12028 }
12029 
12030 /// \brief Determine whether the given expression is a qualified member
12031 /// access expression, of a form that could be turned into a pointer to member
12032 /// with the address-of operator.
12033 static bool isQualifiedMemberAccess(Expr *E) {
12034   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12035     if (!DRE->getQualifier())
12036       return false;
12037 
12038     ValueDecl *VD = DRE->getDecl();
12039     if (!VD->isCXXClassMember())
12040       return false;
12041 
12042     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
12043       return true;
12044     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
12045       return Method->isInstance();
12046 
12047     return false;
12048   }
12049 
12050   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12051     if (!ULE->getQualifier())
12052       return false;
12053 
12054     for (NamedDecl *D : ULE->decls()) {
12055       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
12056         if (Method->isInstance())
12057           return true;
12058       } else {
12059         // Overload set does not contain methods.
12060         break;
12061       }
12062     }
12063 
12064     return false;
12065   }
12066 
12067   return false;
12068 }
12069 
12070 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
12071                               UnaryOperatorKind Opc, Expr *Input) {
12072   // First things first: handle placeholders so that the
12073   // overloaded-operator check considers the right type.
12074   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
12075     // Increment and decrement of pseudo-object references.
12076     if (pty->getKind() == BuiltinType::PseudoObject &&
12077         UnaryOperator::isIncrementDecrementOp(Opc))
12078       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
12079 
12080     // extension is always a builtin operator.
12081     if (Opc == UO_Extension)
12082       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12083 
12084     // & gets special logic for several kinds of placeholder.
12085     // The builtin code knows what to do.
12086     if (Opc == UO_AddrOf &&
12087         (pty->getKind() == BuiltinType::Overload ||
12088          pty->getKind() == BuiltinType::UnknownAny ||
12089          pty->getKind() == BuiltinType::BoundMember))
12090       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12091 
12092     // Anything else needs to be handled now.
12093     ExprResult Result = CheckPlaceholderExpr(Input);
12094     if (Result.isInvalid()) return ExprError();
12095     Input = Result.get();
12096   }
12097 
12098   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
12099       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
12100       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
12101     // Find all of the overloaded operators visible from this
12102     // point. We perform both an operator-name lookup from the local
12103     // scope and an argument-dependent lookup based on the types of
12104     // the arguments.
12105     UnresolvedSet<16> Functions;
12106     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
12107     if (S && OverOp != OO_None)
12108       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
12109                                    Functions);
12110 
12111     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
12112   }
12113 
12114   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12115 }
12116 
12117 // Unary Operators.  'Tok' is the token for the operator.
12118 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
12119                               tok::TokenKind Op, Expr *Input) {
12120   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
12121 }
12122 
12123 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
12124 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
12125                                 LabelDecl *TheDecl) {
12126   TheDecl->markUsed(Context);
12127   // Create the AST node.  The address of a label always has type 'void*'.
12128   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
12129                                      Context.getPointerType(Context.VoidTy));
12130 }
12131 
12132 /// Given the last statement in a statement-expression, check whether
12133 /// the result is a producing expression (like a call to an
12134 /// ns_returns_retained function) and, if so, rebuild it to hoist the
12135 /// release out of the full-expression.  Otherwise, return null.
12136 /// Cannot fail.
12137 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
12138   // Should always be wrapped with one of these.
12139   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
12140   if (!cleanups) return nullptr;
12141 
12142   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
12143   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
12144     return nullptr;
12145 
12146   // Splice out the cast.  This shouldn't modify any interesting
12147   // features of the statement.
12148   Expr *producer = cast->getSubExpr();
12149   assert(producer->getType() == cast->getType());
12150   assert(producer->getValueKind() == cast->getValueKind());
12151   cleanups->setSubExpr(producer);
12152   return cleanups;
12153 }
12154 
12155 void Sema::ActOnStartStmtExpr() {
12156   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12157 }
12158 
12159 void Sema::ActOnStmtExprError() {
12160   // Note that function is also called by TreeTransform when leaving a
12161   // StmtExpr scope without rebuilding anything.
12162 
12163   DiscardCleanupsInEvaluationContext();
12164   PopExpressionEvaluationContext();
12165 }
12166 
12167 ExprResult
12168 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
12169                     SourceLocation RPLoc) { // "({..})"
12170   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
12171   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
12172 
12173   if (hasAnyUnrecoverableErrorsInThisFunction())
12174     DiscardCleanupsInEvaluationContext();
12175   assert(!Cleanup.exprNeedsCleanups() &&
12176          "cleanups within StmtExpr not correctly bound!");
12177   PopExpressionEvaluationContext();
12178 
12179   // FIXME: there are a variety of strange constraints to enforce here, for
12180   // example, it is not possible to goto into a stmt expression apparently.
12181   // More semantic analysis is needed.
12182 
12183   // If there are sub-stmts in the compound stmt, take the type of the last one
12184   // as the type of the stmtexpr.
12185   QualType Ty = Context.VoidTy;
12186   bool StmtExprMayBindToTemp = false;
12187   if (!Compound->body_empty()) {
12188     Stmt *LastStmt = Compound->body_back();
12189     LabelStmt *LastLabelStmt = nullptr;
12190     // If LastStmt is a label, skip down through into the body.
12191     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
12192       LastLabelStmt = Label;
12193       LastStmt = Label->getSubStmt();
12194     }
12195 
12196     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
12197       // Do function/array conversion on the last expression, but not
12198       // lvalue-to-rvalue.  However, initialize an unqualified type.
12199       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
12200       if (LastExpr.isInvalid())
12201         return ExprError();
12202       Ty = LastExpr.get()->getType().getUnqualifiedType();
12203 
12204       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
12205         // In ARC, if the final expression ends in a consume, splice
12206         // the consume out and bind it later.  In the alternate case
12207         // (when dealing with a retainable type), the result
12208         // initialization will create a produce.  In both cases the
12209         // result will be +1, and we'll need to balance that out with
12210         // a bind.
12211         if (Expr *rebuiltLastStmt
12212               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
12213           LastExpr = rebuiltLastStmt;
12214         } else {
12215           LastExpr = PerformCopyInitialization(
12216                             InitializedEntity::InitializeResult(LPLoc,
12217                                                                 Ty,
12218                                                                 false),
12219                                                    SourceLocation(),
12220                                                LastExpr);
12221         }
12222 
12223         if (LastExpr.isInvalid())
12224           return ExprError();
12225         if (LastExpr.get() != nullptr) {
12226           if (!LastLabelStmt)
12227             Compound->setLastStmt(LastExpr.get());
12228           else
12229             LastLabelStmt->setSubStmt(LastExpr.get());
12230           StmtExprMayBindToTemp = true;
12231         }
12232       }
12233     }
12234   }
12235 
12236   // FIXME: Check that expression type is complete/non-abstract; statement
12237   // expressions are not lvalues.
12238   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
12239   if (StmtExprMayBindToTemp)
12240     return MaybeBindToTemporary(ResStmtExpr);
12241   return ResStmtExpr;
12242 }
12243 
12244 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
12245                                       TypeSourceInfo *TInfo,
12246                                       ArrayRef<OffsetOfComponent> Components,
12247                                       SourceLocation RParenLoc) {
12248   QualType ArgTy = TInfo->getType();
12249   bool Dependent = ArgTy->isDependentType();
12250   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
12251 
12252   // We must have at least one component that refers to the type, and the first
12253   // one is known to be a field designator.  Verify that the ArgTy represents
12254   // a struct/union/class.
12255   if (!Dependent && !ArgTy->isRecordType())
12256     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
12257                        << ArgTy << TypeRange);
12258 
12259   // Type must be complete per C99 7.17p3 because a declaring a variable
12260   // with an incomplete type would be ill-formed.
12261   if (!Dependent
12262       && RequireCompleteType(BuiltinLoc, ArgTy,
12263                              diag::err_offsetof_incomplete_type, TypeRange))
12264     return ExprError();
12265 
12266   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
12267   // GCC extension, diagnose them.
12268   // FIXME: This diagnostic isn't actually visible because the location is in
12269   // a system header!
12270   if (Components.size() != 1)
12271     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
12272       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
12273 
12274   bool DidWarnAboutNonPOD = false;
12275   QualType CurrentType = ArgTy;
12276   SmallVector<OffsetOfNode, 4> Comps;
12277   SmallVector<Expr*, 4> Exprs;
12278   for (const OffsetOfComponent &OC : Components) {
12279     if (OC.isBrackets) {
12280       // Offset of an array sub-field.  TODO: Should we allow vector elements?
12281       if (!CurrentType->isDependentType()) {
12282         const ArrayType *AT = Context.getAsArrayType(CurrentType);
12283         if(!AT)
12284           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
12285                            << CurrentType);
12286         CurrentType = AT->getElementType();
12287       } else
12288         CurrentType = Context.DependentTy;
12289 
12290       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
12291       if (IdxRval.isInvalid())
12292         return ExprError();
12293       Expr *Idx = IdxRval.get();
12294 
12295       // The expression must be an integral expression.
12296       // FIXME: An integral constant expression?
12297       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
12298           !Idx->getType()->isIntegerType())
12299         return ExprError(Diag(Idx->getLocStart(),
12300                               diag::err_typecheck_subscript_not_integer)
12301                          << Idx->getSourceRange());
12302 
12303       // Record this array index.
12304       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
12305       Exprs.push_back(Idx);
12306       continue;
12307     }
12308 
12309     // Offset of a field.
12310     if (CurrentType->isDependentType()) {
12311       // We have the offset of a field, but we can't look into the dependent
12312       // type. Just record the identifier of the field.
12313       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12314       CurrentType = Context.DependentTy;
12315       continue;
12316     }
12317 
12318     // We need to have a complete type to look into.
12319     if (RequireCompleteType(OC.LocStart, CurrentType,
12320                             diag::err_offsetof_incomplete_type))
12321       return ExprError();
12322 
12323     // Look for the designated field.
12324     const RecordType *RC = CurrentType->getAs<RecordType>();
12325     if (!RC)
12326       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12327                        << CurrentType);
12328     RecordDecl *RD = RC->getDecl();
12329 
12330     // C++ [lib.support.types]p5:
12331     //   The macro offsetof accepts a restricted set of type arguments in this
12332     //   International Standard. type shall be a POD structure or a POD union
12333     //   (clause 9).
12334     // C++11 [support.types]p4:
12335     //   If type is not a standard-layout class (Clause 9), the results are
12336     //   undefined.
12337     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12338       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12339       unsigned DiagID =
12340         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12341                             : diag::ext_offsetof_non_pod_type;
12342 
12343       if (!IsSafe && !DidWarnAboutNonPOD &&
12344           DiagRuntimeBehavior(BuiltinLoc, nullptr,
12345                               PDiag(DiagID)
12346                               << SourceRange(Components[0].LocStart, OC.LocEnd)
12347                               << CurrentType))
12348         DidWarnAboutNonPOD = true;
12349     }
12350 
12351     // Look for the field.
12352     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12353     LookupQualifiedName(R, RD);
12354     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12355     IndirectFieldDecl *IndirectMemberDecl = nullptr;
12356     if (!MemberDecl) {
12357       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12358         MemberDecl = IndirectMemberDecl->getAnonField();
12359     }
12360 
12361     if (!MemberDecl)
12362       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12363                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
12364                                                               OC.LocEnd));
12365 
12366     // C99 7.17p3:
12367     //   (If the specified member is a bit-field, the behavior is undefined.)
12368     //
12369     // We diagnose this as an error.
12370     if (MemberDecl->isBitField()) {
12371       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12372         << MemberDecl->getDeclName()
12373         << SourceRange(BuiltinLoc, RParenLoc);
12374       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12375       return ExprError();
12376     }
12377 
12378     RecordDecl *Parent = MemberDecl->getParent();
12379     if (IndirectMemberDecl)
12380       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12381 
12382     // If the member was found in a base class, introduce OffsetOfNodes for
12383     // the base class indirections.
12384     CXXBasePaths Paths;
12385     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12386                       Paths)) {
12387       if (Paths.getDetectedVirtual()) {
12388         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12389           << MemberDecl->getDeclName()
12390           << SourceRange(BuiltinLoc, RParenLoc);
12391         return ExprError();
12392       }
12393 
12394       CXXBasePath &Path = Paths.front();
12395       for (const CXXBasePathElement &B : Path)
12396         Comps.push_back(OffsetOfNode(B.Base));
12397     }
12398 
12399     if (IndirectMemberDecl) {
12400       for (auto *FI : IndirectMemberDecl->chain()) {
12401         assert(isa<FieldDecl>(FI));
12402         Comps.push_back(OffsetOfNode(OC.LocStart,
12403                                      cast<FieldDecl>(FI), OC.LocEnd));
12404       }
12405     } else
12406       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12407 
12408     CurrentType = MemberDecl->getType().getNonReferenceType();
12409   }
12410 
12411   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12412                               Comps, Exprs, RParenLoc);
12413 }
12414 
12415 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12416                                       SourceLocation BuiltinLoc,
12417                                       SourceLocation TypeLoc,
12418                                       ParsedType ParsedArgTy,
12419                                       ArrayRef<OffsetOfComponent> Components,
12420                                       SourceLocation RParenLoc) {
12421 
12422   TypeSourceInfo *ArgTInfo;
12423   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12424   if (ArgTy.isNull())
12425     return ExprError();
12426 
12427   if (!ArgTInfo)
12428     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12429 
12430   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12431 }
12432 
12433 
12434 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12435                                  Expr *CondExpr,
12436                                  Expr *LHSExpr, Expr *RHSExpr,
12437                                  SourceLocation RPLoc) {
12438   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12439 
12440   ExprValueKind VK = VK_RValue;
12441   ExprObjectKind OK = OK_Ordinary;
12442   QualType resType;
12443   bool ValueDependent = false;
12444   bool CondIsTrue = false;
12445   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12446     resType = Context.DependentTy;
12447     ValueDependent = true;
12448   } else {
12449     // The conditional expression is required to be a constant expression.
12450     llvm::APSInt condEval(32);
12451     ExprResult CondICE
12452       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12453           diag::err_typecheck_choose_expr_requires_constant, false);
12454     if (CondICE.isInvalid())
12455       return ExprError();
12456     CondExpr = CondICE.get();
12457     CondIsTrue = condEval.getZExtValue();
12458 
12459     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12460     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12461 
12462     resType = ActiveExpr->getType();
12463     ValueDependent = ActiveExpr->isValueDependent();
12464     VK = ActiveExpr->getValueKind();
12465     OK = ActiveExpr->getObjectKind();
12466   }
12467 
12468   return new (Context)
12469       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12470                  CondIsTrue, resType->isDependentType(), ValueDependent);
12471 }
12472 
12473 //===----------------------------------------------------------------------===//
12474 // Clang Extensions.
12475 //===----------------------------------------------------------------------===//
12476 
12477 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12478 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12479   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12480 
12481   if (LangOpts.CPlusPlus) {
12482     Decl *ManglingContextDecl;
12483     if (MangleNumberingContext *MCtx =
12484             getCurrentMangleNumberContext(Block->getDeclContext(),
12485                                           ManglingContextDecl)) {
12486       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12487       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12488     }
12489   }
12490 
12491   PushBlockScope(CurScope, Block);
12492   CurContext->addDecl(Block);
12493   if (CurScope)
12494     PushDeclContext(CurScope, Block);
12495   else
12496     CurContext = Block;
12497 
12498   getCurBlock()->HasImplicitReturnType = true;
12499 
12500   // Enter a new evaluation context to insulate the block from any
12501   // cleanups from the enclosing full-expression.
12502   PushExpressionEvaluationContext(
12503       ExpressionEvaluationContext::PotentiallyEvaluated);
12504 }
12505 
12506 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12507                                Scope *CurScope) {
12508   assert(ParamInfo.getIdentifier() == nullptr &&
12509          "block-id should have no identifier!");
12510   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12511   BlockScopeInfo *CurBlock = getCurBlock();
12512 
12513   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12514   QualType T = Sig->getType();
12515 
12516   // FIXME: We should allow unexpanded parameter packs here, but that would,
12517   // in turn, make the block expression contain unexpanded parameter packs.
12518   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12519     // Drop the parameters.
12520     FunctionProtoType::ExtProtoInfo EPI;
12521     EPI.HasTrailingReturn = false;
12522     EPI.TypeQuals |= DeclSpec::TQ_const;
12523     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12524     Sig = Context.getTrivialTypeSourceInfo(T);
12525   }
12526 
12527   // GetTypeForDeclarator always produces a function type for a block
12528   // literal signature.  Furthermore, it is always a FunctionProtoType
12529   // unless the function was written with a typedef.
12530   assert(T->isFunctionType() &&
12531          "GetTypeForDeclarator made a non-function block signature");
12532 
12533   // Look for an explicit signature in that function type.
12534   FunctionProtoTypeLoc ExplicitSignature;
12535 
12536   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12537   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12538 
12539     // Check whether that explicit signature was synthesized by
12540     // GetTypeForDeclarator.  If so, don't save that as part of the
12541     // written signature.
12542     if (ExplicitSignature.getLocalRangeBegin() ==
12543         ExplicitSignature.getLocalRangeEnd()) {
12544       // This would be much cheaper if we stored TypeLocs instead of
12545       // TypeSourceInfos.
12546       TypeLoc Result = ExplicitSignature.getReturnLoc();
12547       unsigned Size = Result.getFullDataSize();
12548       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12549       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12550 
12551       ExplicitSignature = FunctionProtoTypeLoc();
12552     }
12553   }
12554 
12555   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12556   CurBlock->FunctionType = T;
12557 
12558   const FunctionType *Fn = T->getAs<FunctionType>();
12559   QualType RetTy = Fn->getReturnType();
12560   bool isVariadic =
12561     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12562 
12563   CurBlock->TheDecl->setIsVariadic(isVariadic);
12564 
12565   // Context.DependentTy is used as a placeholder for a missing block
12566   // return type.  TODO:  what should we do with declarators like:
12567   //   ^ * { ... }
12568   // If the answer is "apply template argument deduction"....
12569   if (RetTy != Context.DependentTy) {
12570     CurBlock->ReturnType = RetTy;
12571     CurBlock->TheDecl->setBlockMissingReturnType(false);
12572     CurBlock->HasImplicitReturnType = false;
12573   }
12574 
12575   // Push block parameters from the declarator if we had them.
12576   SmallVector<ParmVarDecl*, 8> Params;
12577   if (ExplicitSignature) {
12578     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12579       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12580       if (Param->getIdentifier() == nullptr &&
12581           !Param->isImplicit() &&
12582           !Param->isInvalidDecl() &&
12583           !getLangOpts().CPlusPlus)
12584         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12585       Params.push_back(Param);
12586     }
12587 
12588   // Fake up parameter variables if we have a typedef, like
12589   //   ^ fntype { ... }
12590   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12591     for (const auto &I : Fn->param_types()) {
12592       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12593           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12594       Params.push_back(Param);
12595     }
12596   }
12597 
12598   // Set the parameters on the block decl.
12599   if (!Params.empty()) {
12600     CurBlock->TheDecl->setParams(Params);
12601     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12602                              /*CheckParameterNames=*/false);
12603   }
12604 
12605   // Finally we can process decl attributes.
12606   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12607 
12608   // Put the parameter variables in scope.
12609   for (auto AI : CurBlock->TheDecl->parameters()) {
12610     AI->setOwningFunction(CurBlock->TheDecl);
12611 
12612     // If this has an identifier, add it to the scope stack.
12613     if (AI->getIdentifier()) {
12614       CheckShadow(CurBlock->TheScope, AI);
12615 
12616       PushOnScopeChains(AI, CurBlock->TheScope);
12617     }
12618   }
12619 }
12620 
12621 /// ActOnBlockError - If there is an error parsing a block, this callback
12622 /// is invoked to pop the information about the block from the action impl.
12623 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12624   // Leave the expression-evaluation context.
12625   DiscardCleanupsInEvaluationContext();
12626   PopExpressionEvaluationContext();
12627 
12628   // Pop off CurBlock, handle nested blocks.
12629   PopDeclContext();
12630   PopFunctionScopeInfo();
12631 }
12632 
12633 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12634 /// literal was successfully completed.  ^(int x){...}
12635 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12636                                     Stmt *Body, Scope *CurScope) {
12637   // If blocks are disabled, emit an error.
12638   if (!LangOpts.Blocks)
12639     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12640 
12641   // Leave the expression-evaluation context.
12642   if (hasAnyUnrecoverableErrorsInThisFunction())
12643     DiscardCleanupsInEvaluationContext();
12644   assert(!Cleanup.exprNeedsCleanups() &&
12645          "cleanups within block not correctly bound!");
12646   PopExpressionEvaluationContext();
12647 
12648   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12649 
12650   if (BSI->HasImplicitReturnType)
12651     deduceClosureReturnType(*BSI);
12652 
12653   PopDeclContext();
12654 
12655   QualType RetTy = Context.VoidTy;
12656   if (!BSI->ReturnType.isNull())
12657     RetTy = BSI->ReturnType;
12658 
12659   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12660   QualType BlockTy;
12661 
12662   // Set the captured variables on the block.
12663   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12664   SmallVector<BlockDecl::Capture, 4> Captures;
12665   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12666     if (Cap.isThisCapture())
12667       continue;
12668     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12669                               Cap.isNested(), Cap.getInitExpr());
12670     Captures.push_back(NewCap);
12671   }
12672   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12673 
12674   // If the user wrote a function type in some form, try to use that.
12675   if (!BSI->FunctionType.isNull()) {
12676     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12677 
12678     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12679     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12680 
12681     // Turn protoless block types into nullary block types.
12682     if (isa<FunctionNoProtoType>(FTy)) {
12683       FunctionProtoType::ExtProtoInfo EPI;
12684       EPI.ExtInfo = Ext;
12685       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12686 
12687     // Otherwise, if we don't need to change anything about the function type,
12688     // preserve its sugar structure.
12689     } else if (FTy->getReturnType() == RetTy &&
12690                (!NoReturn || FTy->getNoReturnAttr())) {
12691       BlockTy = BSI->FunctionType;
12692 
12693     // Otherwise, make the minimal modifications to the function type.
12694     } else {
12695       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12696       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12697       EPI.TypeQuals = 0; // FIXME: silently?
12698       EPI.ExtInfo = Ext;
12699       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12700     }
12701 
12702   // If we don't have a function type, just build one from nothing.
12703   } else {
12704     FunctionProtoType::ExtProtoInfo EPI;
12705     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12706     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12707   }
12708 
12709   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12710   BlockTy = Context.getBlockPointerType(BlockTy);
12711 
12712   // If needed, diagnose invalid gotos and switches in the block.
12713   if (getCurFunction()->NeedsScopeChecking() &&
12714       !PP.isCodeCompletionEnabled())
12715     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12716 
12717   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12718 
12719   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12720     DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl);
12721 
12722   // Try to apply the named return value optimization. We have to check again
12723   // if we can do this, though, because blocks keep return statements around
12724   // to deduce an implicit return type.
12725   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12726       !BSI->TheDecl->isDependentContext())
12727     computeNRVO(Body, BSI);
12728 
12729   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12730   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12731   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12732 
12733   // If the block isn't obviously global, i.e. it captures anything at
12734   // all, then we need to do a few things in the surrounding context:
12735   if (Result->getBlockDecl()->hasCaptures()) {
12736     // First, this expression has a new cleanup object.
12737     ExprCleanupObjects.push_back(Result->getBlockDecl());
12738     Cleanup.setExprNeedsCleanups(true);
12739 
12740     // It also gets a branch-protected scope if any of the captured
12741     // variables needs destruction.
12742     for (const auto &CI : Result->getBlockDecl()->captures()) {
12743       const VarDecl *var = CI.getVariable();
12744       if (var->getType().isDestructedType() != QualType::DK_none) {
12745         getCurFunction()->setHasBranchProtectedScope();
12746         break;
12747       }
12748     }
12749   }
12750 
12751   return Result;
12752 }
12753 
12754 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12755                             SourceLocation RPLoc) {
12756   TypeSourceInfo *TInfo;
12757   GetTypeFromParser(Ty, &TInfo);
12758   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12759 }
12760 
12761 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12762                                 Expr *E, TypeSourceInfo *TInfo,
12763                                 SourceLocation RPLoc) {
12764   Expr *OrigExpr = E;
12765   bool IsMS = false;
12766 
12767   // CUDA device code does not support varargs.
12768   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12769     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12770       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12771       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12772         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12773     }
12774   }
12775 
12776   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12777   // as Microsoft ABI on an actual Microsoft platform, where
12778   // __builtin_ms_va_list and __builtin_va_list are the same.)
12779   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12780       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12781     QualType MSVaListType = Context.getBuiltinMSVaListType();
12782     if (Context.hasSameType(MSVaListType, E->getType())) {
12783       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12784         return ExprError();
12785       IsMS = true;
12786     }
12787   }
12788 
12789   // Get the va_list type
12790   QualType VaListType = Context.getBuiltinVaListType();
12791   if (!IsMS) {
12792     if (VaListType->isArrayType()) {
12793       // Deal with implicit array decay; for example, on x86-64,
12794       // va_list is an array, but it's supposed to decay to
12795       // a pointer for va_arg.
12796       VaListType = Context.getArrayDecayedType(VaListType);
12797       // Make sure the input expression also decays appropriately.
12798       ExprResult Result = UsualUnaryConversions(E);
12799       if (Result.isInvalid())
12800         return ExprError();
12801       E = Result.get();
12802     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12803       // If va_list is a record type and we are compiling in C++ mode,
12804       // check the argument using reference binding.
12805       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12806           Context, Context.getLValueReferenceType(VaListType), false);
12807       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12808       if (Init.isInvalid())
12809         return ExprError();
12810       E = Init.getAs<Expr>();
12811     } else {
12812       // Otherwise, the va_list argument must be an l-value because
12813       // it is modified by va_arg.
12814       if (!E->isTypeDependent() &&
12815           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12816         return ExprError();
12817     }
12818   }
12819 
12820   if (!IsMS && !E->isTypeDependent() &&
12821       !Context.hasSameType(VaListType, E->getType()))
12822     return ExprError(Diag(E->getLocStart(),
12823                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12824       << OrigExpr->getType() << E->getSourceRange());
12825 
12826   if (!TInfo->getType()->isDependentType()) {
12827     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12828                             diag::err_second_parameter_to_va_arg_incomplete,
12829                             TInfo->getTypeLoc()))
12830       return ExprError();
12831 
12832     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12833                                TInfo->getType(),
12834                                diag::err_second_parameter_to_va_arg_abstract,
12835                                TInfo->getTypeLoc()))
12836       return ExprError();
12837 
12838     if (!TInfo->getType().isPODType(Context)) {
12839       Diag(TInfo->getTypeLoc().getBeginLoc(),
12840            TInfo->getType()->isObjCLifetimeType()
12841              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12842              : diag::warn_second_parameter_to_va_arg_not_pod)
12843         << TInfo->getType()
12844         << TInfo->getTypeLoc().getSourceRange();
12845     }
12846 
12847     // Check for va_arg where arguments of the given type will be promoted
12848     // (i.e. this va_arg is guaranteed to have undefined behavior).
12849     QualType PromoteType;
12850     if (TInfo->getType()->isPromotableIntegerType()) {
12851       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12852       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12853         PromoteType = QualType();
12854     }
12855     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12856       PromoteType = Context.DoubleTy;
12857     if (!PromoteType.isNull())
12858       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12859                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12860                           << TInfo->getType()
12861                           << PromoteType
12862                           << TInfo->getTypeLoc().getSourceRange());
12863   }
12864 
12865   QualType T = TInfo->getType().getNonLValueExprType(Context);
12866   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12867 }
12868 
12869 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12870   // The type of __null will be int or long, depending on the size of
12871   // pointers on the target.
12872   QualType Ty;
12873   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12874   if (pw == Context.getTargetInfo().getIntWidth())
12875     Ty = Context.IntTy;
12876   else if (pw == Context.getTargetInfo().getLongWidth())
12877     Ty = Context.LongTy;
12878   else if (pw == Context.getTargetInfo().getLongLongWidth())
12879     Ty = Context.LongLongTy;
12880   else {
12881     llvm_unreachable("I don't know size of pointer!");
12882   }
12883 
12884   return new (Context) GNUNullExpr(Ty, TokenLoc);
12885 }
12886 
12887 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12888                                               bool Diagnose) {
12889   if (!getLangOpts().ObjC1)
12890     return false;
12891 
12892   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12893   if (!PT)
12894     return false;
12895 
12896   if (!PT->isObjCIdType()) {
12897     // Check if the destination is the 'NSString' interface.
12898     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12899     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12900       return false;
12901   }
12902 
12903   // Ignore any parens, implicit casts (should only be
12904   // array-to-pointer decays), and not-so-opaque values.  The last is
12905   // important for making this trigger for property assignments.
12906   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12907   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12908     if (OV->getSourceExpr())
12909       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12910 
12911   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12912   if (!SL || !SL->isAscii())
12913     return false;
12914   if (Diagnose) {
12915     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12916       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12917     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12918   }
12919   return true;
12920 }
12921 
12922 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12923                                               const Expr *SrcExpr) {
12924   if (!DstType->isFunctionPointerType() ||
12925       !SrcExpr->getType()->isFunctionType())
12926     return false;
12927 
12928   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12929   if (!DRE)
12930     return false;
12931 
12932   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12933   if (!FD)
12934     return false;
12935 
12936   return !S.checkAddressOfFunctionIsAvailable(FD,
12937                                               /*Complain=*/true,
12938                                               SrcExpr->getLocStart());
12939 }
12940 
12941 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12942                                     SourceLocation Loc,
12943                                     QualType DstType, QualType SrcType,
12944                                     Expr *SrcExpr, AssignmentAction Action,
12945                                     bool *Complained) {
12946   if (Complained)
12947     *Complained = false;
12948 
12949   // Decode the result (notice that AST's are still created for extensions).
12950   bool CheckInferredResultType = false;
12951   bool isInvalid = false;
12952   unsigned DiagKind = 0;
12953   FixItHint Hint;
12954   ConversionFixItGenerator ConvHints;
12955   bool MayHaveConvFixit = false;
12956   bool MayHaveFunctionDiff = false;
12957   const ObjCInterfaceDecl *IFace = nullptr;
12958   const ObjCProtocolDecl *PDecl = nullptr;
12959 
12960   switch (ConvTy) {
12961   case Compatible:
12962       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12963       return false;
12964 
12965   case PointerToInt:
12966     DiagKind = diag::ext_typecheck_convert_pointer_int;
12967     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12968     MayHaveConvFixit = true;
12969     break;
12970   case IntToPointer:
12971     DiagKind = diag::ext_typecheck_convert_int_pointer;
12972     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12973     MayHaveConvFixit = true;
12974     break;
12975   case IncompatiblePointer:
12976     if (Action == AA_Passing_CFAudited)
12977       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12978     else if (SrcType->isFunctionPointerType() &&
12979              DstType->isFunctionPointerType())
12980       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12981     else
12982       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12983 
12984     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12985       SrcType->isObjCObjectPointerType();
12986     if (Hint.isNull() && !CheckInferredResultType) {
12987       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12988     }
12989     else if (CheckInferredResultType) {
12990       SrcType = SrcType.getUnqualifiedType();
12991       DstType = DstType.getUnqualifiedType();
12992     }
12993     MayHaveConvFixit = true;
12994     break;
12995   case IncompatiblePointerSign:
12996     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12997     break;
12998   case FunctionVoidPointer:
12999     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
13000     break;
13001   case IncompatiblePointerDiscardsQualifiers: {
13002     // Perform array-to-pointer decay if necessary.
13003     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
13004 
13005     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
13006     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
13007     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
13008       DiagKind = diag::err_typecheck_incompatible_address_space;
13009       break;
13010 
13011 
13012     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
13013       DiagKind = diag::err_typecheck_incompatible_ownership;
13014       break;
13015     }
13016 
13017     llvm_unreachable("unknown error case for discarding qualifiers!");
13018     // fallthrough
13019   }
13020   case CompatiblePointerDiscardsQualifiers:
13021     // If the qualifiers lost were because we were applying the
13022     // (deprecated) C++ conversion from a string literal to a char*
13023     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
13024     // Ideally, this check would be performed in
13025     // checkPointerTypesForAssignment. However, that would require a
13026     // bit of refactoring (so that the second argument is an
13027     // expression, rather than a type), which should be done as part
13028     // of a larger effort to fix checkPointerTypesForAssignment for
13029     // C++ semantics.
13030     if (getLangOpts().CPlusPlus &&
13031         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
13032       return false;
13033     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
13034     break;
13035   case IncompatibleNestedPointerQualifiers:
13036     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
13037     break;
13038   case IntToBlockPointer:
13039     DiagKind = diag::err_int_to_block_pointer;
13040     break;
13041   case IncompatibleBlockPointer:
13042     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
13043     break;
13044   case IncompatibleObjCQualifiedId: {
13045     if (SrcType->isObjCQualifiedIdType()) {
13046       const ObjCObjectPointerType *srcOPT =
13047                 SrcType->getAs<ObjCObjectPointerType>();
13048       for (auto *srcProto : srcOPT->quals()) {
13049         PDecl = srcProto;
13050         break;
13051       }
13052       if (const ObjCInterfaceType *IFaceT =
13053             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13054         IFace = IFaceT->getDecl();
13055     }
13056     else if (DstType->isObjCQualifiedIdType()) {
13057       const ObjCObjectPointerType *dstOPT =
13058         DstType->getAs<ObjCObjectPointerType>();
13059       for (auto *dstProto : dstOPT->quals()) {
13060         PDecl = dstProto;
13061         break;
13062       }
13063       if (const ObjCInterfaceType *IFaceT =
13064             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13065         IFace = IFaceT->getDecl();
13066     }
13067     DiagKind = diag::warn_incompatible_qualified_id;
13068     break;
13069   }
13070   case IncompatibleVectors:
13071     DiagKind = diag::warn_incompatible_vectors;
13072     break;
13073   case IncompatibleObjCWeakRef:
13074     DiagKind = diag::err_arc_weak_unavailable_assign;
13075     break;
13076   case Incompatible:
13077     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
13078       if (Complained)
13079         *Complained = true;
13080       return true;
13081     }
13082 
13083     DiagKind = diag::err_typecheck_convert_incompatible;
13084     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13085     MayHaveConvFixit = true;
13086     isInvalid = true;
13087     MayHaveFunctionDiff = true;
13088     break;
13089   }
13090 
13091   QualType FirstType, SecondType;
13092   switch (Action) {
13093   case AA_Assigning:
13094   case AA_Initializing:
13095     // The destination type comes first.
13096     FirstType = DstType;
13097     SecondType = SrcType;
13098     break;
13099 
13100   case AA_Returning:
13101   case AA_Passing:
13102   case AA_Passing_CFAudited:
13103   case AA_Converting:
13104   case AA_Sending:
13105   case AA_Casting:
13106     // The source type comes first.
13107     FirstType = SrcType;
13108     SecondType = DstType;
13109     break;
13110   }
13111 
13112   PartialDiagnostic FDiag = PDiag(DiagKind);
13113   if (Action == AA_Passing_CFAudited)
13114     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
13115   else
13116     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
13117 
13118   // If we can fix the conversion, suggest the FixIts.
13119   assert(ConvHints.isNull() || Hint.isNull());
13120   if (!ConvHints.isNull()) {
13121     for (FixItHint &H : ConvHints.Hints)
13122       FDiag << H;
13123   } else {
13124     FDiag << Hint;
13125   }
13126   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
13127 
13128   if (MayHaveFunctionDiff)
13129     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
13130 
13131   Diag(Loc, FDiag);
13132   if (DiagKind == diag::warn_incompatible_qualified_id &&
13133       PDecl && IFace && !IFace->hasDefinition())
13134       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
13135         << IFace->getName() << PDecl->getName();
13136 
13137   if (SecondType == Context.OverloadTy)
13138     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
13139                               FirstType, /*TakingAddress=*/true);
13140 
13141   if (CheckInferredResultType)
13142     EmitRelatedResultTypeNote(SrcExpr);
13143 
13144   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
13145     EmitRelatedResultTypeNoteForReturn(DstType);
13146 
13147   if (Complained)
13148     *Complained = true;
13149   return isInvalid;
13150 }
13151 
13152 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13153                                                  llvm::APSInt *Result) {
13154   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
13155   public:
13156     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13157       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
13158     }
13159   } Diagnoser;
13160 
13161   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
13162 }
13163 
13164 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13165                                                  llvm::APSInt *Result,
13166                                                  unsigned DiagID,
13167                                                  bool AllowFold) {
13168   class IDDiagnoser : public VerifyICEDiagnoser {
13169     unsigned DiagID;
13170 
13171   public:
13172     IDDiagnoser(unsigned DiagID)
13173       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
13174 
13175     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13176       S.Diag(Loc, DiagID) << SR;
13177     }
13178   } Diagnoser(DiagID);
13179 
13180   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
13181 }
13182 
13183 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
13184                                             SourceRange SR) {
13185   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
13186 }
13187 
13188 ExprResult
13189 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
13190                                       VerifyICEDiagnoser &Diagnoser,
13191                                       bool AllowFold) {
13192   SourceLocation DiagLoc = E->getLocStart();
13193 
13194   if (getLangOpts().CPlusPlus11) {
13195     // C++11 [expr.const]p5:
13196     //   If an expression of literal class type is used in a context where an
13197     //   integral constant expression is required, then that class type shall
13198     //   have a single non-explicit conversion function to an integral or
13199     //   unscoped enumeration type
13200     ExprResult Converted;
13201     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
13202     public:
13203       CXX11ConvertDiagnoser(bool Silent)
13204           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
13205                                 Silent, true) {}
13206 
13207       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
13208                                            QualType T) override {
13209         return S.Diag(Loc, diag::err_ice_not_integral) << T;
13210       }
13211 
13212       SemaDiagnosticBuilder diagnoseIncomplete(
13213           Sema &S, SourceLocation Loc, QualType T) override {
13214         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
13215       }
13216 
13217       SemaDiagnosticBuilder diagnoseExplicitConv(
13218           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13219         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
13220       }
13221 
13222       SemaDiagnosticBuilder noteExplicitConv(
13223           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13224         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13225                  << ConvTy->isEnumeralType() << ConvTy;
13226       }
13227 
13228       SemaDiagnosticBuilder diagnoseAmbiguous(
13229           Sema &S, SourceLocation Loc, QualType T) override {
13230         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
13231       }
13232 
13233       SemaDiagnosticBuilder noteAmbiguous(
13234           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13235         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13236                  << ConvTy->isEnumeralType() << ConvTy;
13237       }
13238 
13239       SemaDiagnosticBuilder diagnoseConversion(
13240           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13241         llvm_unreachable("conversion functions are permitted");
13242       }
13243     } ConvertDiagnoser(Diagnoser.Suppress);
13244 
13245     Converted = PerformContextualImplicitConversion(DiagLoc, E,
13246                                                     ConvertDiagnoser);
13247     if (Converted.isInvalid())
13248       return Converted;
13249     E = Converted.get();
13250     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
13251       return ExprError();
13252   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13253     // An ICE must be of integral or unscoped enumeration type.
13254     if (!Diagnoser.Suppress)
13255       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13256     return ExprError();
13257   }
13258 
13259   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
13260   // in the non-ICE case.
13261   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
13262     if (Result)
13263       *Result = E->EvaluateKnownConstInt(Context);
13264     return E;
13265   }
13266 
13267   Expr::EvalResult EvalResult;
13268   SmallVector<PartialDiagnosticAt, 8> Notes;
13269   EvalResult.Diag = &Notes;
13270 
13271   // Try to evaluate the expression, and produce diagnostics explaining why it's
13272   // not a constant expression as a side-effect.
13273   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
13274                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
13275 
13276   // In C++11, we can rely on diagnostics being produced for any expression
13277   // which is not a constant expression. If no diagnostics were produced, then
13278   // this is a constant expression.
13279   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
13280     if (Result)
13281       *Result = EvalResult.Val.getInt();
13282     return E;
13283   }
13284 
13285   // If our only note is the usual "invalid subexpression" note, just point
13286   // the caret at its location rather than producing an essentially
13287   // redundant note.
13288   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13289         diag::note_invalid_subexpr_in_const_expr) {
13290     DiagLoc = Notes[0].first;
13291     Notes.clear();
13292   }
13293 
13294   if (!Folded || !AllowFold) {
13295     if (!Diagnoser.Suppress) {
13296       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13297       for (const PartialDiagnosticAt &Note : Notes)
13298         Diag(Note.first, Note.second);
13299     }
13300 
13301     return ExprError();
13302   }
13303 
13304   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
13305   for (const PartialDiagnosticAt &Note : Notes)
13306     Diag(Note.first, Note.second);
13307 
13308   if (Result)
13309     *Result = EvalResult.Val.getInt();
13310   return E;
13311 }
13312 
13313 namespace {
13314   // Handle the case where we conclude a expression which we speculatively
13315   // considered to be unevaluated is actually evaluated.
13316   class TransformToPE : public TreeTransform<TransformToPE> {
13317     typedef TreeTransform<TransformToPE> BaseTransform;
13318 
13319   public:
13320     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13321 
13322     // Make sure we redo semantic analysis
13323     bool AlwaysRebuild() { return true; }
13324 
13325     // Make sure we handle LabelStmts correctly.
13326     // FIXME: This does the right thing, but maybe we need a more general
13327     // fix to TreeTransform?
13328     StmtResult TransformLabelStmt(LabelStmt *S) {
13329       S->getDecl()->setStmt(nullptr);
13330       return BaseTransform::TransformLabelStmt(S);
13331     }
13332 
13333     // We need to special-case DeclRefExprs referring to FieldDecls which
13334     // are not part of a member pointer formation; normal TreeTransforming
13335     // doesn't catch this case because of the way we represent them in the AST.
13336     // FIXME: This is a bit ugly; is it really the best way to handle this
13337     // case?
13338     //
13339     // Error on DeclRefExprs referring to FieldDecls.
13340     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13341       if (isa<FieldDecl>(E->getDecl()) &&
13342           !SemaRef.isUnevaluatedContext())
13343         return SemaRef.Diag(E->getLocation(),
13344                             diag::err_invalid_non_static_member_use)
13345             << E->getDecl() << E->getSourceRange();
13346 
13347       return BaseTransform::TransformDeclRefExpr(E);
13348     }
13349 
13350     // Exception: filter out member pointer formation
13351     ExprResult TransformUnaryOperator(UnaryOperator *E) {
13352       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13353         return E;
13354 
13355       return BaseTransform::TransformUnaryOperator(E);
13356     }
13357 
13358     ExprResult TransformLambdaExpr(LambdaExpr *E) {
13359       // Lambdas never need to be transformed.
13360       return E;
13361     }
13362   };
13363 }
13364 
13365 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13366   assert(isUnevaluatedContext() &&
13367          "Should only transform unevaluated expressions");
13368   ExprEvalContexts.back().Context =
13369       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13370   if (isUnevaluatedContext())
13371     return E;
13372   return TransformToPE(*this).TransformExpr(E);
13373 }
13374 
13375 void
13376 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13377                                       Decl *LambdaContextDecl,
13378                                       bool IsDecltype) {
13379   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13380                                 LambdaContextDecl, IsDecltype);
13381   Cleanup.reset();
13382   if (!MaybeODRUseExprs.empty())
13383     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13384 }
13385 
13386 void
13387 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13388                                       ReuseLambdaContextDecl_t,
13389                                       bool IsDecltype) {
13390   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13391   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13392 }
13393 
13394 void Sema::PopExpressionEvaluationContext() {
13395   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13396   unsigned NumTypos = Rec.NumTypos;
13397 
13398   if (!Rec.Lambdas.empty()) {
13399     if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13400       unsigned D;
13401       if (Rec.isUnevaluated()) {
13402         // C++11 [expr.prim.lambda]p2:
13403         //   A lambda-expression shall not appear in an unevaluated operand
13404         //   (Clause 5).
13405         D = diag::err_lambda_unevaluated_operand;
13406       } else {
13407         // C++1y [expr.const]p2:
13408         //   A conditional-expression e is a core constant expression unless the
13409         //   evaluation of e, following the rules of the abstract machine, would
13410         //   evaluate [...] a lambda-expression.
13411         D = diag::err_lambda_in_constant_expression;
13412       }
13413 
13414       // C++1z allows lambda expressions as core constant expressions.
13415       // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
13416       // 1607) from appearing within template-arguments and array-bounds that
13417       // are part of function-signatures.  Be mindful that P0315 (Lambdas in
13418       // unevaluated contexts) might lift some of these restrictions in a
13419       // future version.
13420       if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus1z)
13421         for (const auto *L : Rec.Lambdas)
13422           Diag(L->getLocStart(), D);
13423     } else {
13424       // Mark the capture expressions odr-used. This was deferred
13425       // during lambda expression creation.
13426       for (auto *Lambda : Rec.Lambdas) {
13427         for (auto *C : Lambda->capture_inits())
13428           MarkDeclarationsReferencedInExpr(C);
13429       }
13430     }
13431   }
13432 
13433   // When are coming out of an unevaluated context, clear out any
13434   // temporaries that we may have created as part of the evaluation of
13435   // the expression in that context: they aren't relevant because they
13436   // will never be constructed.
13437   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13438     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13439                              ExprCleanupObjects.end());
13440     Cleanup = Rec.ParentCleanup;
13441     CleanupVarDeclMarking();
13442     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13443   // Otherwise, merge the contexts together.
13444   } else {
13445     Cleanup.mergeFrom(Rec.ParentCleanup);
13446     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13447                             Rec.SavedMaybeODRUseExprs.end());
13448   }
13449 
13450   // Pop the current expression evaluation context off the stack.
13451   ExprEvalContexts.pop_back();
13452 
13453   if (!ExprEvalContexts.empty())
13454     ExprEvalContexts.back().NumTypos += NumTypos;
13455   else
13456     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13457                             "last ExpressionEvaluationContextRecord");
13458 }
13459 
13460 void Sema::DiscardCleanupsInEvaluationContext() {
13461   ExprCleanupObjects.erase(
13462          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13463          ExprCleanupObjects.end());
13464   Cleanup.reset();
13465   MaybeODRUseExprs.clear();
13466 }
13467 
13468 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13469   if (!E->getType()->isVariablyModifiedType())
13470     return E;
13471   return TransformToPotentiallyEvaluated(E);
13472 }
13473 
13474 /// Are we within a context in which some evaluation could be performed (be it
13475 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
13476 /// captured by C++'s idea of an "unevaluated context".
13477 static bool isEvaluatableContext(Sema &SemaRef) {
13478   switch (SemaRef.ExprEvalContexts.back().Context) {
13479     case Sema::ExpressionEvaluationContext::Unevaluated:
13480     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13481     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13482       // Expressions in this context are never evaluated.
13483       return false;
13484 
13485     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13486     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13487     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13488       // Expressions in this context could be evaluated.
13489       return true;
13490 
13491     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13492       // Referenced declarations will only be used if the construct in the
13493       // containing expression is used, at which point we'll be given another
13494       // turn to mark them.
13495       return false;
13496   }
13497   llvm_unreachable("Invalid context");
13498 }
13499 
13500 /// Are we within a context in which references to resolved functions or to
13501 /// variables result in odr-use?
13502 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
13503   // An expression in a template is not really an expression until it's been
13504   // instantiated, so it doesn't trigger odr-use.
13505   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
13506     return false;
13507 
13508   switch (SemaRef.ExprEvalContexts.back().Context) {
13509     case Sema::ExpressionEvaluationContext::Unevaluated:
13510     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13511     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13512     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13513       return false;
13514 
13515     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13516     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13517       return true;
13518 
13519     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13520       return false;
13521   }
13522   llvm_unreachable("Invalid context");
13523 }
13524 
13525 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
13526   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13527   return Func->isConstexpr() &&
13528          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
13529 }
13530 
13531 /// \brief Mark a function referenced, and check whether it is odr-used
13532 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13533 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13534                                   bool MightBeOdrUse) {
13535   assert(Func && "No function?");
13536 
13537   Func->setReferenced();
13538 
13539   // C++11 [basic.def.odr]p3:
13540   //   A function whose name appears as a potentially-evaluated expression is
13541   //   odr-used if it is the unique lookup result or the selected member of a
13542   //   set of overloaded functions [...].
13543   //
13544   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13545   // can just check that here.
13546   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
13547 
13548   // Determine whether we require a function definition to exist, per
13549   // C++11 [temp.inst]p3:
13550   //   Unless a function template specialization has been explicitly
13551   //   instantiated or explicitly specialized, the function template
13552   //   specialization is implicitly instantiated when the specialization is
13553   //   referenced in a context that requires a function definition to exist.
13554   //
13555   // That is either when this is an odr-use, or when a usage of a constexpr
13556   // function occurs within an evaluatable context.
13557   bool NeedDefinition =
13558       OdrUse || (isEvaluatableContext(*this) &&
13559                  isImplicitlyDefinableConstexprFunction(Func));
13560 
13561   // C++14 [temp.expl.spec]p6:
13562   //   If a template [...] is explicitly specialized then that specialization
13563   //   shall be declared before the first use of that specialization that would
13564   //   cause an implicit instantiation to take place, in every translation unit
13565   //   in which such a use occurs
13566   if (NeedDefinition &&
13567       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13568        Func->getMemberSpecializationInfo()))
13569     checkSpecializationVisibility(Loc, Func);
13570 
13571   // C++14 [except.spec]p17:
13572   //   An exception-specification is considered to be needed when:
13573   //   - the function is odr-used or, if it appears in an unevaluated operand,
13574   //     would be odr-used if the expression were potentially-evaluated;
13575   //
13576   // Note, we do this even if MightBeOdrUse is false. That indicates that the
13577   // function is a pure virtual function we're calling, and in that case the
13578   // function was selected by overload resolution and we need to resolve its
13579   // exception specification for a different reason.
13580   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13581   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13582     ResolveExceptionSpec(Loc, FPT);
13583 
13584   // If we don't need to mark the function as used, and we don't need to
13585   // try to provide a definition, there's nothing more to do.
13586   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13587       (!NeedDefinition || Func->getBody()))
13588     return;
13589 
13590   // Note that this declaration has been used.
13591   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13592     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13593     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13594       if (Constructor->isDefaultConstructor()) {
13595         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13596           return;
13597         DefineImplicitDefaultConstructor(Loc, Constructor);
13598       } else if (Constructor->isCopyConstructor()) {
13599         DefineImplicitCopyConstructor(Loc, Constructor);
13600       } else if (Constructor->isMoveConstructor()) {
13601         DefineImplicitMoveConstructor(Loc, Constructor);
13602       }
13603     } else if (Constructor->getInheritedConstructor()) {
13604       DefineInheritingConstructor(Loc, Constructor);
13605     }
13606   } else if (CXXDestructorDecl *Destructor =
13607                  dyn_cast<CXXDestructorDecl>(Func)) {
13608     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13609     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13610       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13611         return;
13612       DefineImplicitDestructor(Loc, Destructor);
13613     }
13614     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13615       MarkVTableUsed(Loc, Destructor->getParent());
13616   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13617     if (MethodDecl->isOverloadedOperator() &&
13618         MethodDecl->getOverloadedOperator() == OO_Equal) {
13619       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13620       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13621         if (MethodDecl->isCopyAssignmentOperator())
13622           DefineImplicitCopyAssignment(Loc, MethodDecl);
13623         else if (MethodDecl->isMoveAssignmentOperator())
13624           DefineImplicitMoveAssignment(Loc, MethodDecl);
13625       }
13626     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13627                MethodDecl->getParent()->isLambda()) {
13628       CXXConversionDecl *Conversion =
13629           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13630       if (Conversion->isLambdaToBlockPointerConversion())
13631         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13632       else
13633         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13634     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13635       MarkVTableUsed(Loc, MethodDecl->getParent());
13636   }
13637 
13638   // Recursive functions should be marked when used from another function.
13639   // FIXME: Is this really right?
13640   if (CurContext == Func) return;
13641 
13642   // Implicit instantiation of function templates and member functions of
13643   // class templates.
13644   if (Func->isImplicitlyInstantiable()) {
13645     bool AlreadyInstantiated = false;
13646     SourceLocation PointOfInstantiation = Loc;
13647     if (FunctionTemplateSpecializationInfo *SpecInfo
13648                               = Func->getTemplateSpecializationInfo()) {
13649       if (SpecInfo->getPointOfInstantiation().isInvalid())
13650         SpecInfo->setPointOfInstantiation(Loc);
13651       else if (SpecInfo->getTemplateSpecializationKind()
13652                  == TSK_ImplicitInstantiation) {
13653         AlreadyInstantiated = true;
13654         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13655       }
13656     } else if (MemberSpecializationInfo *MSInfo
13657                                 = Func->getMemberSpecializationInfo()) {
13658       if (MSInfo->getPointOfInstantiation().isInvalid())
13659         MSInfo->setPointOfInstantiation(Loc);
13660       else if (MSInfo->getTemplateSpecializationKind()
13661                  == TSK_ImplicitInstantiation) {
13662         AlreadyInstantiated = true;
13663         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13664       }
13665     }
13666 
13667     if (!AlreadyInstantiated || Func->isConstexpr()) {
13668       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13669           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13670           CodeSynthesisContexts.size())
13671         PendingLocalImplicitInstantiations.push_back(
13672             std::make_pair(Func, PointOfInstantiation));
13673       else if (Func->isConstexpr())
13674         // Do not defer instantiations of constexpr functions, to avoid the
13675         // expression evaluator needing to call back into Sema if it sees a
13676         // call to such a function.
13677         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13678       else {
13679         Func->setInstantiationIsPending(true);
13680         PendingInstantiations.push_back(std::make_pair(Func,
13681                                                        PointOfInstantiation));
13682         // Notify the consumer that a function was implicitly instantiated.
13683         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13684       }
13685     }
13686   } else {
13687     // Walk redefinitions, as some of them may be instantiable.
13688     for (auto i : Func->redecls()) {
13689       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13690         MarkFunctionReferenced(Loc, i, OdrUse);
13691     }
13692   }
13693 
13694   if (!OdrUse) return;
13695 
13696   // Keep track of used but undefined functions.
13697   if (!Func->isDefined()) {
13698     if (mightHaveNonExternalLinkage(Func))
13699       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13700     else if (Func->getMostRecentDecl()->isInlined() &&
13701              !LangOpts.GNUInline &&
13702              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13703       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13704   }
13705 
13706   Func->markUsed(Context);
13707 }
13708 
13709 static void
13710 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13711                                    ValueDecl *var, DeclContext *DC) {
13712   DeclContext *VarDC = var->getDeclContext();
13713 
13714   //  If the parameter still belongs to the translation unit, then
13715   //  we're actually just using one parameter in the declaration of
13716   //  the next.
13717   if (isa<ParmVarDecl>(var) &&
13718       isa<TranslationUnitDecl>(VarDC))
13719     return;
13720 
13721   // For C code, don't diagnose about capture if we're not actually in code
13722   // right now; it's impossible to write a non-constant expression outside of
13723   // function context, so we'll get other (more useful) diagnostics later.
13724   //
13725   // For C++, things get a bit more nasty... it would be nice to suppress this
13726   // diagnostic for certain cases like using a local variable in an array bound
13727   // for a member of a local class, but the correct predicate is not obvious.
13728   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13729     return;
13730 
13731   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13732   unsigned ContextKind = 3; // unknown
13733   if (isa<CXXMethodDecl>(VarDC) &&
13734       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13735     ContextKind = 2;
13736   } else if (isa<FunctionDecl>(VarDC)) {
13737     ContextKind = 0;
13738   } else if (isa<BlockDecl>(VarDC)) {
13739     ContextKind = 1;
13740   }
13741 
13742   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13743     << var << ValueKind << ContextKind << VarDC;
13744   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13745       << var;
13746 
13747   // FIXME: Add additional diagnostic info about class etc. which prevents
13748   // capture.
13749 }
13750 
13751 
13752 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13753                                       bool &SubCapturesAreNested,
13754                                       QualType &CaptureType,
13755                                       QualType &DeclRefType) {
13756    // Check whether we've already captured it.
13757   if (CSI->CaptureMap.count(Var)) {
13758     // If we found a capture, any subcaptures are nested.
13759     SubCapturesAreNested = true;
13760 
13761     // Retrieve the capture type for this variable.
13762     CaptureType = CSI->getCapture(Var).getCaptureType();
13763 
13764     // Compute the type of an expression that refers to this variable.
13765     DeclRefType = CaptureType.getNonReferenceType();
13766 
13767     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13768     // are mutable in the sense that user can change their value - they are
13769     // private instances of the captured declarations.
13770     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13771     if (Cap.isCopyCapture() &&
13772         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13773         !(isa<CapturedRegionScopeInfo>(CSI) &&
13774           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13775       DeclRefType.addConst();
13776     return true;
13777   }
13778   return false;
13779 }
13780 
13781 // Only block literals, captured statements, and lambda expressions can
13782 // capture; other scopes don't work.
13783 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13784                                  SourceLocation Loc,
13785                                  const bool Diagnose, Sema &S) {
13786   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13787     return getLambdaAwareParentOfDeclContext(DC);
13788   else if (Var->hasLocalStorage()) {
13789     if (Diagnose)
13790        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13791   }
13792   return nullptr;
13793 }
13794 
13795 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13796 // certain types of variables (unnamed, variably modified types etc.)
13797 // so check for eligibility.
13798 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13799                                  SourceLocation Loc,
13800                                  const bool Diagnose, Sema &S) {
13801 
13802   bool IsBlock = isa<BlockScopeInfo>(CSI);
13803   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13804 
13805   // Lambdas are not allowed to capture unnamed variables
13806   // (e.g. anonymous unions).
13807   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13808   // assuming that's the intent.
13809   if (IsLambda && !Var->getDeclName()) {
13810     if (Diagnose) {
13811       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13812       S.Diag(Var->getLocation(), diag::note_declared_at);
13813     }
13814     return false;
13815   }
13816 
13817   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13818   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13819     if (Diagnose) {
13820       S.Diag(Loc, diag::err_ref_vm_type);
13821       S.Diag(Var->getLocation(), diag::note_previous_decl)
13822         << Var->getDeclName();
13823     }
13824     return false;
13825   }
13826   // Prohibit structs with flexible array members too.
13827   // We cannot capture what is in the tail end of the struct.
13828   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13829     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13830       if (Diagnose) {
13831         if (IsBlock)
13832           S.Diag(Loc, diag::err_ref_flexarray_type);
13833         else
13834           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13835             << Var->getDeclName();
13836         S.Diag(Var->getLocation(), diag::note_previous_decl)
13837           << Var->getDeclName();
13838       }
13839       return false;
13840     }
13841   }
13842   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13843   // Lambdas and captured statements are not allowed to capture __block
13844   // variables; they don't support the expected semantics.
13845   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13846     if (Diagnose) {
13847       S.Diag(Loc, diag::err_capture_block_variable)
13848         << Var->getDeclName() << !IsLambda;
13849       S.Diag(Var->getLocation(), diag::note_previous_decl)
13850         << Var->getDeclName();
13851     }
13852     return false;
13853   }
13854   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
13855   if (S.getLangOpts().OpenCL && IsBlock &&
13856       Var->getType()->isBlockPointerType()) {
13857     if (Diagnose)
13858       S.Diag(Loc, diag::err_opencl_block_ref_block);
13859     return false;
13860   }
13861 
13862   return true;
13863 }
13864 
13865 // Returns true if the capture by block was successful.
13866 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13867                                  SourceLocation Loc,
13868                                  const bool BuildAndDiagnose,
13869                                  QualType &CaptureType,
13870                                  QualType &DeclRefType,
13871                                  const bool Nested,
13872                                  Sema &S) {
13873   Expr *CopyExpr = nullptr;
13874   bool ByRef = false;
13875 
13876   // Blocks are not allowed to capture arrays.
13877   if (CaptureType->isArrayType()) {
13878     if (BuildAndDiagnose) {
13879       S.Diag(Loc, diag::err_ref_array_type);
13880       S.Diag(Var->getLocation(), diag::note_previous_decl)
13881       << Var->getDeclName();
13882     }
13883     return false;
13884   }
13885 
13886   // Forbid the block-capture of autoreleasing variables.
13887   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13888     if (BuildAndDiagnose) {
13889       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13890         << /*block*/ 0;
13891       S.Diag(Var->getLocation(), diag::note_previous_decl)
13892         << Var->getDeclName();
13893     }
13894     return false;
13895   }
13896 
13897   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13898   if (const auto *PT = CaptureType->getAs<PointerType>()) {
13899     // This function finds out whether there is an AttributedType of kind
13900     // attr_objc_ownership in Ty. The existence of AttributedType of kind
13901     // attr_objc_ownership implies __autoreleasing was explicitly specified
13902     // rather than being added implicitly by the compiler.
13903     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
13904       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
13905         if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
13906           return true;
13907 
13908         // Peel off AttributedTypes that are not of kind objc_ownership.
13909         Ty = AttrTy->getModifiedType();
13910       }
13911 
13912       return false;
13913     };
13914 
13915     QualType PointeeTy = PT->getPointeeType();
13916 
13917     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
13918         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13919         !IsObjCOwnershipAttributedType(PointeeTy)) {
13920       if (BuildAndDiagnose) {
13921         SourceLocation VarLoc = Var->getLocation();
13922         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13923         {
13924           auto AddAutoreleaseNote =
13925               S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing);
13926           // Provide a fix-it for the '__autoreleasing' keyword at the
13927           // appropriate location in the variable's type.
13928           if (const auto *TSI = Var->getTypeSourceInfo()) {
13929             PointerTypeLoc PTL =
13930                 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>();
13931             if (PTL) {
13932               SourceLocation Loc = PTL.getPointeeLoc().getEndLoc();
13933               Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(),
13934                                                S.getLangOpts());
13935               if (Loc.isValid()) {
13936                 StringRef CharAtLoc = Lexer::getSourceText(
13937                     CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)),
13938                     S.getSourceManager(), S.getLangOpts());
13939                 AddAutoreleaseNote << FixItHint::CreateInsertion(
13940                     Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0])
13941                              ? " __autoreleasing "
13942                              : " __autoreleasing");
13943               }
13944             }
13945           }
13946         }
13947         S.Diag(VarLoc, diag::note_declare_parameter_strong);
13948       }
13949     }
13950   }
13951 
13952   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13953   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13954       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13955     // Block capture by reference does not change the capture or
13956     // declaration reference types.
13957     ByRef = true;
13958   } else {
13959     // Block capture by copy introduces 'const'.
13960     CaptureType = CaptureType.getNonReferenceType().withConst();
13961     DeclRefType = CaptureType;
13962 
13963     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13964       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13965         // The capture logic needs the destructor, so make sure we mark it.
13966         // Usually this is unnecessary because most local variables have
13967         // their destructors marked at declaration time, but parameters are
13968         // an exception because it's technically only the call site that
13969         // actually requires the destructor.
13970         if (isa<ParmVarDecl>(Var))
13971           S.FinalizeVarWithDestructor(Var, Record);
13972 
13973         // Enter a new evaluation context to insulate the copy
13974         // full-expression.
13975         EnterExpressionEvaluationContext scope(
13976             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
13977 
13978         // According to the blocks spec, the capture of a variable from
13979         // the stack requires a const copy constructor.  This is not true
13980         // of the copy/move done to move a __block variable to the heap.
13981         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13982                                                   DeclRefType.withConst(),
13983                                                   VK_LValue, Loc);
13984 
13985         ExprResult Result
13986           = S.PerformCopyInitialization(
13987               InitializedEntity::InitializeBlock(Var->getLocation(),
13988                                                   CaptureType, false),
13989               Loc, DeclRef);
13990 
13991         // Build a full-expression copy expression if initialization
13992         // succeeded and used a non-trivial constructor.  Recover from
13993         // errors by pretending that the copy isn't necessary.
13994         if (!Result.isInvalid() &&
13995             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13996                 ->isTrivial()) {
13997           Result = S.MaybeCreateExprWithCleanups(Result);
13998           CopyExpr = Result.get();
13999         }
14000       }
14001     }
14002   }
14003 
14004   // Actually capture the variable.
14005   if (BuildAndDiagnose)
14006     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
14007                     SourceLocation(), CaptureType, CopyExpr);
14008 
14009   return true;
14010 
14011 }
14012 
14013 
14014 /// \brief Capture the given variable in the captured region.
14015 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
14016                                     VarDecl *Var,
14017                                     SourceLocation Loc,
14018                                     const bool BuildAndDiagnose,
14019                                     QualType &CaptureType,
14020                                     QualType &DeclRefType,
14021                                     const bool RefersToCapturedVariable,
14022                                     Sema &S) {
14023   // By default, capture variables by reference.
14024   bool ByRef = true;
14025   // Using an LValue reference type is consistent with Lambdas (see below).
14026   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
14027     if (S.IsOpenMPCapturedDecl(Var))
14028       DeclRefType = DeclRefType.getUnqualifiedType();
14029     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
14030   }
14031 
14032   if (ByRef)
14033     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14034   else
14035     CaptureType = DeclRefType;
14036 
14037   Expr *CopyExpr = nullptr;
14038   if (BuildAndDiagnose) {
14039     // The current implementation assumes that all variables are captured
14040     // by references. Since there is no capture by copy, no expression
14041     // evaluation will be needed.
14042     RecordDecl *RD = RSI->TheRecordDecl;
14043 
14044     FieldDecl *Field
14045       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
14046                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
14047                           nullptr, false, ICIS_NoInit);
14048     Field->setImplicit(true);
14049     Field->setAccess(AS_private);
14050     RD->addDecl(Field);
14051     if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
14052       S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
14053 
14054     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
14055                                             DeclRefType, VK_LValue, Loc);
14056     Var->setReferenced(true);
14057     Var->markUsed(S.Context);
14058   }
14059 
14060   // Actually capture the variable.
14061   if (BuildAndDiagnose)
14062     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
14063                     SourceLocation(), CaptureType, CopyExpr);
14064 
14065 
14066   return true;
14067 }
14068 
14069 /// \brief Create a field within the lambda class for the variable
14070 /// being captured.
14071 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
14072                                     QualType FieldType, QualType DeclRefType,
14073                                     SourceLocation Loc,
14074                                     bool RefersToCapturedVariable) {
14075   CXXRecordDecl *Lambda = LSI->Lambda;
14076 
14077   // Build the non-static data member.
14078   FieldDecl *Field
14079     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
14080                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
14081                         nullptr, false, ICIS_NoInit);
14082   Field->setImplicit(true);
14083   Field->setAccess(AS_private);
14084   Lambda->addDecl(Field);
14085 }
14086 
14087 /// \brief Capture the given variable in the lambda.
14088 static bool captureInLambda(LambdaScopeInfo *LSI,
14089                             VarDecl *Var,
14090                             SourceLocation Loc,
14091                             const bool BuildAndDiagnose,
14092                             QualType &CaptureType,
14093                             QualType &DeclRefType,
14094                             const bool RefersToCapturedVariable,
14095                             const Sema::TryCaptureKind Kind,
14096                             SourceLocation EllipsisLoc,
14097                             const bool IsTopScope,
14098                             Sema &S) {
14099 
14100   // Determine whether we are capturing by reference or by value.
14101   bool ByRef = false;
14102   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
14103     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
14104   } else {
14105     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
14106   }
14107 
14108   // Compute the type of the field that will capture this variable.
14109   if (ByRef) {
14110     // C++11 [expr.prim.lambda]p15:
14111     //   An entity is captured by reference if it is implicitly or
14112     //   explicitly captured but not captured by copy. It is
14113     //   unspecified whether additional unnamed non-static data
14114     //   members are declared in the closure type for entities
14115     //   captured by reference.
14116     //
14117     // FIXME: It is not clear whether we want to build an lvalue reference
14118     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
14119     // to do the former, while EDG does the latter. Core issue 1249 will
14120     // clarify, but for now we follow GCC because it's a more permissive and
14121     // easily defensible position.
14122     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14123   } else {
14124     // C++11 [expr.prim.lambda]p14:
14125     //   For each entity captured by copy, an unnamed non-static
14126     //   data member is declared in the closure type. The
14127     //   declaration order of these members is unspecified. The type
14128     //   of such a data member is the type of the corresponding
14129     //   captured entity if the entity is not a reference to an
14130     //   object, or the referenced type otherwise. [Note: If the
14131     //   captured entity is a reference to a function, the
14132     //   corresponding data member is also a reference to a
14133     //   function. - end note ]
14134     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
14135       if (!RefType->getPointeeType()->isFunctionType())
14136         CaptureType = RefType->getPointeeType();
14137     }
14138 
14139     // Forbid the lambda copy-capture of autoreleasing variables.
14140     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14141       if (BuildAndDiagnose) {
14142         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
14143         S.Diag(Var->getLocation(), diag::note_previous_decl)
14144           << Var->getDeclName();
14145       }
14146       return false;
14147     }
14148 
14149     // Make sure that by-copy captures are of a complete and non-abstract type.
14150     if (BuildAndDiagnose) {
14151       if (!CaptureType->isDependentType() &&
14152           S.RequireCompleteType(Loc, CaptureType,
14153                                 diag::err_capture_of_incomplete_type,
14154                                 Var->getDeclName()))
14155         return false;
14156 
14157       if (S.RequireNonAbstractType(Loc, CaptureType,
14158                                    diag::err_capture_of_abstract_type))
14159         return false;
14160     }
14161   }
14162 
14163   // Capture this variable in the lambda.
14164   if (BuildAndDiagnose)
14165     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
14166                             RefersToCapturedVariable);
14167 
14168   // Compute the type of a reference to this captured variable.
14169   if (ByRef)
14170     DeclRefType = CaptureType.getNonReferenceType();
14171   else {
14172     // C++ [expr.prim.lambda]p5:
14173     //   The closure type for a lambda-expression has a public inline
14174     //   function call operator [...]. This function call operator is
14175     //   declared const (9.3.1) if and only if the lambda-expression's
14176     //   parameter-declaration-clause is not followed by mutable.
14177     DeclRefType = CaptureType.getNonReferenceType();
14178     if (!LSI->Mutable && !CaptureType->isReferenceType())
14179       DeclRefType.addConst();
14180   }
14181 
14182   // Add the capture.
14183   if (BuildAndDiagnose)
14184     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
14185                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
14186 
14187   return true;
14188 }
14189 
14190 bool Sema::tryCaptureVariable(
14191     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
14192     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
14193     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
14194   // An init-capture is notionally from the context surrounding its
14195   // declaration, but its parent DC is the lambda class.
14196   DeclContext *VarDC = Var->getDeclContext();
14197   if (Var->isInitCapture())
14198     VarDC = VarDC->getParent();
14199 
14200   DeclContext *DC = CurContext;
14201   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
14202       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
14203   // We need to sync up the Declaration Context with the
14204   // FunctionScopeIndexToStopAt
14205   if (FunctionScopeIndexToStopAt) {
14206     unsigned FSIndex = FunctionScopes.size() - 1;
14207     while (FSIndex != MaxFunctionScopesIndex) {
14208       DC = getLambdaAwareParentOfDeclContext(DC);
14209       --FSIndex;
14210     }
14211   }
14212 
14213 
14214   // If the variable is declared in the current context, there is no need to
14215   // capture it.
14216   if (VarDC == DC) return true;
14217 
14218   // Capture global variables if it is required to use private copy of this
14219   // variable.
14220   bool IsGlobal = !Var->hasLocalStorage();
14221   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
14222     return true;
14223   Var = Var->getCanonicalDecl();
14224 
14225   // Walk up the stack to determine whether we can capture the variable,
14226   // performing the "simple" checks that don't depend on type. We stop when
14227   // we've either hit the declared scope of the variable or find an existing
14228   // capture of that variable.  We start from the innermost capturing-entity
14229   // (the DC) and ensure that all intervening capturing-entities
14230   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
14231   // declcontext can either capture the variable or have already captured
14232   // the variable.
14233   CaptureType = Var->getType();
14234   DeclRefType = CaptureType.getNonReferenceType();
14235   bool Nested = false;
14236   bool Explicit = (Kind != TryCapture_Implicit);
14237   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
14238   do {
14239     // Only block literals, captured statements, and lambda expressions can
14240     // capture; other scopes don't work.
14241     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
14242                                                               ExprLoc,
14243                                                               BuildAndDiagnose,
14244                                                               *this);
14245     // We need to check for the parent *first* because, if we *have*
14246     // private-captured a global variable, we need to recursively capture it in
14247     // intermediate blocks, lambdas, etc.
14248     if (!ParentDC) {
14249       if (IsGlobal) {
14250         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
14251         break;
14252       }
14253       return true;
14254     }
14255 
14256     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
14257     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
14258 
14259 
14260     // Check whether we've already captured it.
14261     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
14262                                              DeclRefType)) {
14263       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
14264       break;
14265     }
14266     // If we are instantiating a generic lambda call operator body,
14267     // we do not want to capture new variables.  What was captured
14268     // during either a lambdas transformation or initial parsing
14269     // should be used.
14270     if (isGenericLambdaCallOperatorSpecialization(DC)) {
14271       if (BuildAndDiagnose) {
14272         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14273         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
14274           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14275           Diag(Var->getLocation(), diag::note_previous_decl)
14276              << Var->getDeclName();
14277           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
14278         } else
14279           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
14280       }
14281       return true;
14282     }
14283     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14284     // certain types of variables (unnamed, variably modified types etc.)
14285     // so check for eligibility.
14286     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
14287        return true;
14288 
14289     // Try to capture variable-length arrays types.
14290     if (Var->getType()->isVariablyModifiedType()) {
14291       // We're going to walk down into the type and look for VLA
14292       // expressions.
14293       QualType QTy = Var->getType();
14294       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
14295         QTy = PVD->getOriginalType();
14296       captureVariablyModifiedType(Context, QTy, CSI);
14297     }
14298 
14299     if (getLangOpts().OpenMP) {
14300       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14301         // OpenMP private variables should not be captured in outer scope, so
14302         // just break here. Similarly, global variables that are captured in a
14303         // target region should not be captured outside the scope of the region.
14304         if (RSI->CapRegionKind == CR_OpenMP) {
14305           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
14306           // When we detect target captures we are looking from inside the
14307           // target region, therefore we need to propagate the capture from the
14308           // enclosing region. Therefore, the capture is not initially nested.
14309           if (IsTargetCap)
14310             FunctionScopesIndex--;
14311 
14312           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
14313             Nested = !IsTargetCap;
14314             DeclRefType = DeclRefType.getUnqualifiedType();
14315             CaptureType = Context.getLValueReferenceType(DeclRefType);
14316             break;
14317           }
14318         }
14319       }
14320     }
14321     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
14322       // No capture-default, and this is not an explicit capture
14323       // so cannot capture this variable.
14324       if (BuildAndDiagnose) {
14325         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14326         Diag(Var->getLocation(), diag::note_previous_decl)
14327           << Var->getDeclName();
14328         if (cast<LambdaScopeInfo>(CSI)->Lambda)
14329           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
14330                diag::note_lambda_decl);
14331         // FIXME: If we error out because an outer lambda can not implicitly
14332         // capture a variable that an inner lambda explicitly captures, we
14333         // should have the inner lambda do the explicit capture - because
14334         // it makes for cleaner diagnostics later.  This would purely be done
14335         // so that the diagnostic does not misleadingly claim that a variable
14336         // can not be captured by a lambda implicitly even though it is captured
14337         // explicitly.  Suggestion:
14338         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
14339         //    at the function head
14340         //  - cache the StartingDeclContext - this must be a lambda
14341         //  - captureInLambda in the innermost lambda the variable.
14342       }
14343       return true;
14344     }
14345 
14346     FunctionScopesIndex--;
14347     DC = ParentDC;
14348     Explicit = false;
14349   } while (!VarDC->Equals(DC));
14350 
14351   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
14352   // computing the type of the capture at each step, checking type-specific
14353   // requirements, and adding captures if requested.
14354   // If the variable had already been captured previously, we start capturing
14355   // at the lambda nested within that one.
14356   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
14357        ++I) {
14358     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
14359 
14360     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
14361       if (!captureInBlock(BSI, Var, ExprLoc,
14362                           BuildAndDiagnose, CaptureType,
14363                           DeclRefType, Nested, *this))
14364         return true;
14365       Nested = true;
14366     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14367       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
14368                                    BuildAndDiagnose, CaptureType,
14369                                    DeclRefType, Nested, *this))
14370         return true;
14371       Nested = true;
14372     } else {
14373       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14374       if (!captureInLambda(LSI, Var, ExprLoc,
14375                            BuildAndDiagnose, CaptureType,
14376                            DeclRefType, Nested, Kind, EllipsisLoc,
14377                             /*IsTopScope*/I == N - 1, *this))
14378         return true;
14379       Nested = true;
14380     }
14381   }
14382   return false;
14383 }
14384 
14385 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14386                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
14387   QualType CaptureType;
14388   QualType DeclRefType;
14389   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14390                             /*BuildAndDiagnose=*/true, CaptureType,
14391                             DeclRefType, nullptr);
14392 }
14393 
14394 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14395   QualType CaptureType;
14396   QualType DeclRefType;
14397   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14398                              /*BuildAndDiagnose=*/false, CaptureType,
14399                              DeclRefType, nullptr);
14400 }
14401 
14402 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14403   QualType CaptureType;
14404   QualType DeclRefType;
14405 
14406   // Determine whether we can capture this variable.
14407   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14408                          /*BuildAndDiagnose=*/false, CaptureType,
14409                          DeclRefType, nullptr))
14410     return QualType();
14411 
14412   return DeclRefType;
14413 }
14414 
14415 
14416 
14417 // If either the type of the variable or the initializer is dependent,
14418 // return false. Otherwise, determine whether the variable is a constant
14419 // expression. Use this if you need to know if a variable that might or
14420 // might not be dependent is truly a constant expression.
14421 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
14422     ASTContext &Context) {
14423 
14424   if (Var->getType()->isDependentType())
14425     return false;
14426   const VarDecl *DefVD = nullptr;
14427   Var->getAnyInitializer(DefVD);
14428   if (!DefVD)
14429     return false;
14430   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14431   Expr *Init = cast<Expr>(Eval->Value);
14432   if (Init->isValueDependent())
14433     return false;
14434   return IsVariableAConstantExpression(Var, Context);
14435 }
14436 
14437 
14438 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14439   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
14440   // an object that satisfies the requirements for appearing in a
14441   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14442   // is immediately applied."  This function handles the lvalue-to-rvalue
14443   // conversion part.
14444   MaybeODRUseExprs.erase(E->IgnoreParens());
14445 
14446   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14447   // to a variable that is a constant expression, and if so, identify it as
14448   // a reference to a variable that does not involve an odr-use of that
14449   // variable.
14450   if (LambdaScopeInfo *LSI = getCurLambda()) {
14451     Expr *SansParensExpr = E->IgnoreParens();
14452     VarDecl *Var = nullptr;
14453     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
14454       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14455     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14456       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14457 
14458     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
14459       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
14460   }
14461 }
14462 
14463 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14464   Res = CorrectDelayedTyposInExpr(Res);
14465 
14466   if (!Res.isUsable())
14467     return Res;
14468 
14469   // If a constant-expression is a reference to a variable where we delay
14470   // deciding whether it is an odr-use, just assume we will apply the
14471   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
14472   // (a non-type template argument), we have special handling anyway.
14473   UpdateMarkingForLValueToRValue(Res.get());
14474   return Res;
14475 }
14476 
14477 void Sema::CleanupVarDeclMarking() {
14478   for (Expr *E : MaybeODRUseExprs) {
14479     VarDecl *Var;
14480     SourceLocation Loc;
14481     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14482       Var = cast<VarDecl>(DRE->getDecl());
14483       Loc = DRE->getLocation();
14484     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14485       Var = cast<VarDecl>(ME->getMemberDecl());
14486       Loc = ME->getMemberLoc();
14487     } else {
14488       llvm_unreachable("Unexpected expression");
14489     }
14490 
14491     MarkVarDeclODRUsed(Var, Loc, *this,
14492                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
14493   }
14494 
14495   MaybeODRUseExprs.clear();
14496 }
14497 
14498 
14499 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14500                                     VarDecl *Var, Expr *E) {
14501   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14502          "Invalid Expr argument to DoMarkVarDeclReferenced");
14503   Var->setReferenced();
14504 
14505   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14506 
14507   bool OdrUseContext = isOdrUseContext(SemaRef);
14508   bool NeedDefinition =
14509       OdrUseContext || (isEvaluatableContext(SemaRef) &&
14510                         Var->isUsableInConstantExpressions(SemaRef.Context));
14511 
14512   VarTemplateSpecializationDecl *VarSpec =
14513       dyn_cast<VarTemplateSpecializationDecl>(Var);
14514   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14515          "Can't instantiate a partial template specialization.");
14516 
14517   // If this might be a member specialization of a static data member, check
14518   // the specialization is visible. We already did the checks for variable
14519   // template specializations when we created them.
14520   if (NeedDefinition && TSK != TSK_Undeclared &&
14521       !isa<VarTemplateSpecializationDecl>(Var))
14522     SemaRef.checkSpecializationVisibility(Loc, Var);
14523 
14524   // Perform implicit instantiation of static data members, static data member
14525   // templates of class templates, and variable template specializations. Delay
14526   // instantiations of variable templates, except for those that could be used
14527   // in a constant expression.
14528   if (NeedDefinition && isTemplateInstantiation(TSK)) {
14529     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14530 
14531     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14532       if (Var->getPointOfInstantiation().isInvalid()) {
14533         // This is a modification of an existing AST node. Notify listeners.
14534         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14535           L->StaticDataMemberInstantiated(Var);
14536       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14537         // Don't bother trying to instantiate it again, unless we might need
14538         // its initializer before we get to the end of the TU.
14539         TryInstantiating = false;
14540     }
14541 
14542     if (Var->getPointOfInstantiation().isInvalid())
14543       Var->setTemplateSpecializationKind(TSK, Loc);
14544 
14545     if (TryInstantiating) {
14546       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14547       bool InstantiationDependent = false;
14548       bool IsNonDependent =
14549           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14550                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14551                   : true;
14552 
14553       // Do not instantiate specializations that are still type-dependent.
14554       if (IsNonDependent) {
14555         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14556           // Do not defer instantiations of variables which could be used in a
14557           // constant expression.
14558           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14559         } else {
14560           SemaRef.PendingInstantiations
14561               .push_back(std::make_pair(Var, PointOfInstantiation));
14562         }
14563       }
14564     }
14565   }
14566 
14567   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14568   // the requirements for appearing in a constant expression (5.19) and, if
14569   // it is an object, the lvalue-to-rvalue conversion (4.1)
14570   // is immediately applied."  We check the first part here, and
14571   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14572   // Note that we use the C++11 definition everywhere because nothing in
14573   // C++03 depends on whether we get the C++03 version correct. The second
14574   // part does not apply to references, since they are not objects.
14575   if (OdrUseContext && E &&
14576       IsVariableAConstantExpression(Var, SemaRef.Context)) {
14577     // A reference initialized by a constant expression can never be
14578     // odr-used, so simply ignore it.
14579     if (!Var->getType()->isReferenceType())
14580       SemaRef.MaybeODRUseExprs.insert(E);
14581   } else if (OdrUseContext) {
14582     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14583                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14584   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
14585     // If this is a dependent context, we don't need to mark variables as
14586     // odr-used, but we may still need to track them for lambda capture.
14587     // FIXME: Do we also need to do this inside dependent typeid expressions
14588     // (which are modeled as unevaluated at this point)?
14589     const bool RefersToEnclosingScope =
14590         (SemaRef.CurContext != Var->getDeclContext() &&
14591          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14592     if (RefersToEnclosingScope) {
14593       LambdaScopeInfo *const LSI =
14594           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
14595       if (LSI && !LSI->CallOperator->Encloses(Var->getDeclContext())) {
14596         // If a variable could potentially be odr-used, defer marking it so
14597         // until we finish analyzing the full expression for any
14598         // lvalue-to-rvalue
14599         // or discarded value conversions that would obviate odr-use.
14600         // Add it to the list of potential captures that will be analyzed
14601         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14602         // unless the variable is a reference that was initialized by a constant
14603         // expression (this will never need to be captured or odr-used).
14604         assert(E && "Capture variable should be used in an expression.");
14605         if (!Var->getType()->isReferenceType() ||
14606             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14607           LSI->addPotentialCapture(E->IgnoreParens());
14608       }
14609     }
14610   }
14611 }
14612 
14613 /// \brief Mark a variable referenced, and check whether it is odr-used
14614 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
14615 /// used directly for normal expressions referring to VarDecl.
14616 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14617   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14618 }
14619 
14620 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14621                                Decl *D, Expr *E, bool MightBeOdrUse) {
14622   if (SemaRef.isInOpenMPDeclareTargetContext())
14623     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14624 
14625   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14626     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14627     return;
14628   }
14629 
14630   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14631 
14632   // If this is a call to a method via a cast, also mark the method in the
14633   // derived class used in case codegen can devirtualize the call.
14634   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14635   if (!ME)
14636     return;
14637   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14638   if (!MD)
14639     return;
14640   // Only attempt to devirtualize if this is truly a virtual call.
14641   bool IsVirtualCall = MD->isVirtual() &&
14642                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14643   if (!IsVirtualCall)
14644     return;
14645 
14646   // If it's possible to devirtualize the call, mark the called function
14647   // referenced.
14648   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
14649       ME->getBase(), SemaRef.getLangOpts().AppleKext);
14650   if (DM)
14651     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14652 }
14653 
14654 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14655 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
14656   // TODO: update this with DR# once a defect report is filed.
14657   // C++11 defect. The address of a pure member should not be an ODR use, even
14658   // if it's a qualified reference.
14659   bool OdrUse = true;
14660   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14661     if (Method->isVirtual() &&
14662         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
14663       OdrUse = false;
14664   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14665 }
14666 
14667 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14668 void Sema::MarkMemberReferenced(MemberExpr *E) {
14669   // C++11 [basic.def.odr]p2:
14670   //   A non-overloaded function whose name appears as a potentially-evaluated
14671   //   expression or a member of a set of candidate functions, if selected by
14672   //   overload resolution when referred to from a potentially-evaluated
14673   //   expression, is odr-used, unless it is a pure virtual function and its
14674   //   name is not explicitly qualified.
14675   bool MightBeOdrUse = true;
14676   if (E->performsVirtualDispatch(getLangOpts())) {
14677     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14678       if (Method->isPure())
14679         MightBeOdrUse = false;
14680   }
14681   SourceLocation Loc = E->getMemberLoc().isValid() ?
14682                             E->getMemberLoc() : E->getLocStart();
14683   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14684 }
14685 
14686 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14687 /// marks the declaration referenced, and performs odr-use checking for
14688 /// functions and variables. This method should not be used when building a
14689 /// normal expression which refers to a variable.
14690 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14691                                  bool MightBeOdrUse) {
14692   if (MightBeOdrUse) {
14693     if (auto *VD = dyn_cast<VarDecl>(D)) {
14694       MarkVariableReferenced(Loc, VD);
14695       return;
14696     }
14697   }
14698   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14699     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14700     return;
14701   }
14702   D->setReferenced();
14703 }
14704 
14705 namespace {
14706   // Mark all of the declarations used by a type as referenced.
14707   // FIXME: Not fully implemented yet! We need to have a better understanding
14708   // of when we're entering a context we should not recurse into.
14709   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
14710   // TreeTransforms rebuilding the type in a new context. Rather than
14711   // duplicating the TreeTransform logic, we should consider reusing it here.
14712   // Currently that causes problems when rebuilding LambdaExprs.
14713   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14714     Sema &S;
14715     SourceLocation Loc;
14716 
14717   public:
14718     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14719 
14720     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14721 
14722     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14723   };
14724 }
14725 
14726 bool MarkReferencedDecls::TraverseTemplateArgument(
14727     const TemplateArgument &Arg) {
14728   {
14729     // A non-type template argument is a constant-evaluated context.
14730     EnterExpressionEvaluationContext Evaluated(
14731         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
14732     if (Arg.getKind() == TemplateArgument::Declaration) {
14733       if (Decl *D = Arg.getAsDecl())
14734         S.MarkAnyDeclReferenced(Loc, D, true);
14735     } else if (Arg.getKind() == TemplateArgument::Expression) {
14736       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
14737     }
14738   }
14739 
14740   return Inherited::TraverseTemplateArgument(Arg);
14741 }
14742 
14743 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14744   MarkReferencedDecls Marker(*this, Loc);
14745   Marker.TraverseType(T);
14746 }
14747 
14748 namespace {
14749   /// \brief Helper class that marks all of the declarations referenced by
14750   /// potentially-evaluated subexpressions as "referenced".
14751   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14752     Sema &S;
14753     bool SkipLocalVariables;
14754 
14755   public:
14756     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14757 
14758     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14759       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14760 
14761     void VisitDeclRefExpr(DeclRefExpr *E) {
14762       // If we were asked not to visit local variables, don't.
14763       if (SkipLocalVariables) {
14764         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14765           if (VD->hasLocalStorage())
14766             return;
14767       }
14768 
14769       S.MarkDeclRefReferenced(E);
14770     }
14771 
14772     void VisitMemberExpr(MemberExpr *E) {
14773       S.MarkMemberReferenced(E);
14774       Inherited::VisitMemberExpr(E);
14775     }
14776 
14777     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14778       S.MarkFunctionReferenced(E->getLocStart(),
14779             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14780       Visit(E->getSubExpr());
14781     }
14782 
14783     void VisitCXXNewExpr(CXXNewExpr *E) {
14784       if (E->getOperatorNew())
14785         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14786       if (E->getOperatorDelete())
14787         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14788       Inherited::VisitCXXNewExpr(E);
14789     }
14790 
14791     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14792       if (E->getOperatorDelete())
14793         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14794       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14795       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14796         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14797         S.MarkFunctionReferenced(E->getLocStart(),
14798                                     S.LookupDestructor(Record));
14799       }
14800 
14801       Inherited::VisitCXXDeleteExpr(E);
14802     }
14803 
14804     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14805       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14806       Inherited::VisitCXXConstructExpr(E);
14807     }
14808 
14809     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14810       Visit(E->getExpr());
14811     }
14812 
14813     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14814       Inherited::VisitImplicitCastExpr(E);
14815 
14816       if (E->getCastKind() == CK_LValueToRValue)
14817         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14818     }
14819   };
14820 }
14821 
14822 /// \brief Mark any declarations that appear within this expression or any
14823 /// potentially-evaluated subexpressions as "referenced".
14824 ///
14825 /// \param SkipLocalVariables If true, don't mark local variables as
14826 /// 'referenced'.
14827 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14828                                             bool SkipLocalVariables) {
14829   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14830 }
14831 
14832 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14833 /// of the program being compiled.
14834 ///
14835 /// This routine emits the given diagnostic when the code currently being
14836 /// type-checked is "potentially evaluated", meaning that there is a
14837 /// possibility that the code will actually be executable. Code in sizeof()
14838 /// expressions, code used only during overload resolution, etc., are not
14839 /// potentially evaluated. This routine will suppress such diagnostics or,
14840 /// in the absolutely nutty case of potentially potentially evaluated
14841 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14842 /// later.
14843 ///
14844 /// This routine should be used for all diagnostics that describe the run-time
14845 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14846 /// Failure to do so will likely result in spurious diagnostics or failures
14847 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14848 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14849                                const PartialDiagnostic &PD) {
14850   switch (ExprEvalContexts.back().Context) {
14851   case ExpressionEvaluationContext::Unevaluated:
14852   case ExpressionEvaluationContext::UnevaluatedList:
14853   case ExpressionEvaluationContext::UnevaluatedAbstract:
14854   case ExpressionEvaluationContext::DiscardedStatement:
14855     // The argument will never be evaluated, so don't complain.
14856     break;
14857 
14858   case ExpressionEvaluationContext::ConstantEvaluated:
14859     // Relevant diagnostics should be produced by constant evaluation.
14860     break;
14861 
14862   case ExpressionEvaluationContext::PotentiallyEvaluated:
14863   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14864     if (Statement && getCurFunctionOrMethodDecl()) {
14865       FunctionScopes.back()->PossiblyUnreachableDiags.
14866         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14867     }
14868     else
14869       Diag(Loc, PD);
14870 
14871     return true;
14872   }
14873 
14874   return false;
14875 }
14876 
14877 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14878                                CallExpr *CE, FunctionDecl *FD) {
14879   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14880     return false;
14881 
14882   // If we're inside a decltype's expression, don't check for a valid return
14883   // type or construct temporaries until we know whether this is the last call.
14884   if (ExprEvalContexts.back().IsDecltype) {
14885     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14886     return false;
14887   }
14888 
14889   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14890     FunctionDecl *FD;
14891     CallExpr *CE;
14892 
14893   public:
14894     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14895       : FD(FD), CE(CE) { }
14896 
14897     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14898       if (!FD) {
14899         S.Diag(Loc, diag::err_call_incomplete_return)
14900           << T << CE->getSourceRange();
14901         return;
14902       }
14903 
14904       S.Diag(Loc, diag::err_call_function_incomplete_return)
14905         << CE->getSourceRange() << FD->getDeclName() << T;
14906       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14907           << FD->getDeclName();
14908     }
14909   } Diagnoser(FD, CE);
14910 
14911   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14912     return true;
14913 
14914   return false;
14915 }
14916 
14917 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14918 // will prevent this condition from triggering, which is what we want.
14919 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14920   SourceLocation Loc;
14921 
14922   unsigned diagnostic = diag::warn_condition_is_assignment;
14923   bool IsOrAssign = false;
14924 
14925   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14926     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14927       return;
14928 
14929     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14930 
14931     // Greylist some idioms by putting them into a warning subcategory.
14932     if (ObjCMessageExpr *ME
14933           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14934       Selector Sel = ME->getSelector();
14935 
14936       // self = [<foo> init...]
14937       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14938         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14939 
14940       // <foo> = [<bar> nextObject]
14941       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14942         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14943     }
14944 
14945     Loc = Op->getOperatorLoc();
14946   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14947     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14948       return;
14949 
14950     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14951     Loc = Op->getOperatorLoc();
14952   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14953     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14954   else {
14955     // Not an assignment.
14956     return;
14957   }
14958 
14959   Diag(Loc, diagnostic) << E->getSourceRange();
14960 
14961   SourceLocation Open = E->getLocStart();
14962   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14963   Diag(Loc, diag::note_condition_assign_silence)
14964         << FixItHint::CreateInsertion(Open, "(")
14965         << FixItHint::CreateInsertion(Close, ")");
14966 
14967   if (IsOrAssign)
14968     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14969       << FixItHint::CreateReplacement(Loc, "!=");
14970   else
14971     Diag(Loc, diag::note_condition_assign_to_comparison)
14972       << FixItHint::CreateReplacement(Loc, "==");
14973 }
14974 
14975 /// \brief Redundant parentheses over an equality comparison can indicate
14976 /// that the user intended an assignment used as condition.
14977 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14978   // Don't warn if the parens came from a macro.
14979   SourceLocation parenLoc = ParenE->getLocStart();
14980   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14981     return;
14982   // Don't warn for dependent expressions.
14983   if (ParenE->isTypeDependent())
14984     return;
14985 
14986   Expr *E = ParenE->IgnoreParens();
14987 
14988   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14989     if (opE->getOpcode() == BO_EQ &&
14990         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14991                                                            == Expr::MLV_Valid) {
14992       SourceLocation Loc = opE->getOperatorLoc();
14993 
14994       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14995       SourceRange ParenERange = ParenE->getSourceRange();
14996       Diag(Loc, diag::note_equality_comparison_silence)
14997         << FixItHint::CreateRemoval(ParenERange.getBegin())
14998         << FixItHint::CreateRemoval(ParenERange.getEnd());
14999       Diag(Loc, diag::note_equality_comparison_to_assign)
15000         << FixItHint::CreateReplacement(Loc, "=");
15001     }
15002 }
15003 
15004 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
15005                                        bool IsConstexpr) {
15006   DiagnoseAssignmentAsCondition(E);
15007   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
15008     DiagnoseEqualityWithExtraParens(parenE);
15009 
15010   ExprResult result = CheckPlaceholderExpr(E);
15011   if (result.isInvalid()) return ExprError();
15012   E = result.get();
15013 
15014   if (!E->isTypeDependent()) {
15015     if (getLangOpts().CPlusPlus)
15016       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
15017 
15018     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
15019     if (ERes.isInvalid())
15020       return ExprError();
15021     E = ERes.get();
15022 
15023     QualType T = E->getType();
15024     if (!T->isScalarType()) { // C99 6.8.4.1p1
15025       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
15026         << T << E->getSourceRange();
15027       return ExprError();
15028     }
15029     CheckBoolLikeConversion(E, Loc);
15030   }
15031 
15032   return E;
15033 }
15034 
15035 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
15036                                            Expr *SubExpr, ConditionKind CK) {
15037   // Empty conditions are valid in for-statements.
15038   if (!SubExpr)
15039     return ConditionResult();
15040 
15041   ExprResult Cond;
15042   switch (CK) {
15043   case ConditionKind::Boolean:
15044     Cond = CheckBooleanCondition(Loc, SubExpr);
15045     break;
15046 
15047   case ConditionKind::ConstexprIf:
15048     Cond = CheckBooleanCondition(Loc, SubExpr, true);
15049     break;
15050 
15051   case ConditionKind::Switch:
15052     Cond = CheckSwitchCondition(Loc, SubExpr);
15053     break;
15054   }
15055   if (Cond.isInvalid())
15056     return ConditionError();
15057 
15058   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
15059   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
15060   if (!FullExpr.get())
15061     return ConditionError();
15062 
15063   return ConditionResult(*this, nullptr, FullExpr,
15064                          CK == ConditionKind::ConstexprIf);
15065 }
15066 
15067 namespace {
15068   /// A visitor for rebuilding a call to an __unknown_any expression
15069   /// to have an appropriate type.
15070   struct RebuildUnknownAnyFunction
15071     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
15072 
15073     Sema &S;
15074 
15075     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
15076 
15077     ExprResult VisitStmt(Stmt *S) {
15078       llvm_unreachable("unexpected statement!");
15079     }
15080 
15081     ExprResult VisitExpr(Expr *E) {
15082       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
15083         << E->getSourceRange();
15084       return ExprError();
15085     }
15086 
15087     /// Rebuild an expression which simply semantically wraps another
15088     /// expression which it shares the type and value kind of.
15089     template <class T> ExprResult rebuildSugarExpr(T *E) {
15090       ExprResult SubResult = Visit(E->getSubExpr());
15091       if (SubResult.isInvalid()) return ExprError();
15092 
15093       Expr *SubExpr = SubResult.get();
15094       E->setSubExpr(SubExpr);
15095       E->setType(SubExpr->getType());
15096       E->setValueKind(SubExpr->getValueKind());
15097       assert(E->getObjectKind() == OK_Ordinary);
15098       return E;
15099     }
15100 
15101     ExprResult VisitParenExpr(ParenExpr *E) {
15102       return rebuildSugarExpr(E);
15103     }
15104 
15105     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15106       return rebuildSugarExpr(E);
15107     }
15108 
15109     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15110       ExprResult SubResult = Visit(E->getSubExpr());
15111       if (SubResult.isInvalid()) return ExprError();
15112 
15113       Expr *SubExpr = SubResult.get();
15114       E->setSubExpr(SubExpr);
15115       E->setType(S.Context.getPointerType(SubExpr->getType()));
15116       assert(E->getValueKind() == VK_RValue);
15117       assert(E->getObjectKind() == OK_Ordinary);
15118       return E;
15119     }
15120 
15121     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
15122       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
15123 
15124       E->setType(VD->getType());
15125 
15126       assert(E->getValueKind() == VK_RValue);
15127       if (S.getLangOpts().CPlusPlus &&
15128           !(isa<CXXMethodDecl>(VD) &&
15129             cast<CXXMethodDecl>(VD)->isInstance()))
15130         E->setValueKind(VK_LValue);
15131 
15132       return E;
15133     }
15134 
15135     ExprResult VisitMemberExpr(MemberExpr *E) {
15136       return resolveDecl(E, E->getMemberDecl());
15137     }
15138 
15139     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15140       return resolveDecl(E, E->getDecl());
15141     }
15142   };
15143 }
15144 
15145 /// Given a function expression of unknown-any type, try to rebuild it
15146 /// to have a function type.
15147 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
15148   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
15149   if (Result.isInvalid()) return ExprError();
15150   return S.DefaultFunctionArrayConversion(Result.get());
15151 }
15152 
15153 namespace {
15154   /// A visitor for rebuilding an expression of type __unknown_anytype
15155   /// into one which resolves the type directly on the referring
15156   /// expression.  Strict preservation of the original source
15157   /// structure is not a goal.
15158   struct RebuildUnknownAnyExpr
15159     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
15160 
15161     Sema &S;
15162 
15163     /// The current destination type.
15164     QualType DestType;
15165 
15166     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
15167       : S(S), DestType(CastType) {}
15168 
15169     ExprResult VisitStmt(Stmt *S) {
15170       llvm_unreachable("unexpected statement!");
15171     }
15172 
15173     ExprResult VisitExpr(Expr *E) {
15174       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15175         << E->getSourceRange();
15176       return ExprError();
15177     }
15178 
15179     ExprResult VisitCallExpr(CallExpr *E);
15180     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
15181 
15182     /// Rebuild an expression which simply semantically wraps another
15183     /// expression which it shares the type and value kind of.
15184     template <class T> ExprResult rebuildSugarExpr(T *E) {
15185       ExprResult SubResult = Visit(E->getSubExpr());
15186       if (SubResult.isInvalid()) return ExprError();
15187       Expr *SubExpr = SubResult.get();
15188       E->setSubExpr(SubExpr);
15189       E->setType(SubExpr->getType());
15190       E->setValueKind(SubExpr->getValueKind());
15191       assert(E->getObjectKind() == OK_Ordinary);
15192       return E;
15193     }
15194 
15195     ExprResult VisitParenExpr(ParenExpr *E) {
15196       return rebuildSugarExpr(E);
15197     }
15198 
15199     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15200       return rebuildSugarExpr(E);
15201     }
15202 
15203     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15204       const PointerType *Ptr = DestType->getAs<PointerType>();
15205       if (!Ptr) {
15206         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
15207           << E->getSourceRange();
15208         return ExprError();
15209       }
15210 
15211       if (isa<CallExpr>(E->getSubExpr())) {
15212         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
15213           << E->getSourceRange();
15214         return ExprError();
15215       }
15216 
15217       assert(E->getValueKind() == VK_RValue);
15218       assert(E->getObjectKind() == OK_Ordinary);
15219       E->setType(DestType);
15220 
15221       // Build the sub-expression as if it were an object of the pointee type.
15222       DestType = Ptr->getPointeeType();
15223       ExprResult SubResult = Visit(E->getSubExpr());
15224       if (SubResult.isInvalid()) return ExprError();
15225       E->setSubExpr(SubResult.get());
15226       return E;
15227     }
15228 
15229     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
15230 
15231     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
15232 
15233     ExprResult VisitMemberExpr(MemberExpr *E) {
15234       return resolveDecl(E, E->getMemberDecl());
15235     }
15236 
15237     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15238       return resolveDecl(E, E->getDecl());
15239     }
15240   };
15241 }
15242 
15243 /// Rebuilds a call expression which yielded __unknown_anytype.
15244 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
15245   Expr *CalleeExpr = E->getCallee();
15246 
15247   enum FnKind {
15248     FK_MemberFunction,
15249     FK_FunctionPointer,
15250     FK_BlockPointer
15251   };
15252 
15253   FnKind Kind;
15254   QualType CalleeType = CalleeExpr->getType();
15255   if (CalleeType == S.Context.BoundMemberTy) {
15256     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
15257     Kind = FK_MemberFunction;
15258     CalleeType = Expr::findBoundMemberType(CalleeExpr);
15259   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
15260     CalleeType = Ptr->getPointeeType();
15261     Kind = FK_FunctionPointer;
15262   } else {
15263     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
15264     Kind = FK_BlockPointer;
15265   }
15266   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
15267 
15268   // Verify that this is a legal result type of a function.
15269   if (DestType->isArrayType() || DestType->isFunctionType()) {
15270     unsigned diagID = diag::err_func_returning_array_function;
15271     if (Kind == FK_BlockPointer)
15272       diagID = diag::err_block_returning_array_function;
15273 
15274     S.Diag(E->getExprLoc(), diagID)
15275       << DestType->isFunctionType() << DestType;
15276     return ExprError();
15277   }
15278 
15279   // Otherwise, go ahead and set DestType as the call's result.
15280   E->setType(DestType.getNonLValueExprType(S.Context));
15281   E->setValueKind(Expr::getValueKindForType(DestType));
15282   assert(E->getObjectKind() == OK_Ordinary);
15283 
15284   // Rebuild the function type, replacing the result type with DestType.
15285   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
15286   if (Proto) {
15287     // __unknown_anytype(...) is a special case used by the debugger when
15288     // it has no idea what a function's signature is.
15289     //
15290     // We want to build this call essentially under the K&R
15291     // unprototyped rules, but making a FunctionNoProtoType in C++
15292     // would foul up all sorts of assumptions.  However, we cannot
15293     // simply pass all arguments as variadic arguments, nor can we
15294     // portably just call the function under a non-variadic type; see
15295     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
15296     // However, it turns out that in practice it is generally safe to
15297     // call a function declared as "A foo(B,C,D);" under the prototype
15298     // "A foo(B,C,D,...);".  The only known exception is with the
15299     // Windows ABI, where any variadic function is implicitly cdecl
15300     // regardless of its normal CC.  Therefore we change the parameter
15301     // types to match the types of the arguments.
15302     //
15303     // This is a hack, but it is far superior to moving the
15304     // corresponding target-specific code from IR-gen to Sema/AST.
15305 
15306     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
15307     SmallVector<QualType, 8> ArgTypes;
15308     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
15309       ArgTypes.reserve(E->getNumArgs());
15310       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
15311         Expr *Arg = E->getArg(i);
15312         QualType ArgType = Arg->getType();
15313         if (E->isLValue()) {
15314           ArgType = S.Context.getLValueReferenceType(ArgType);
15315         } else if (E->isXValue()) {
15316           ArgType = S.Context.getRValueReferenceType(ArgType);
15317         }
15318         ArgTypes.push_back(ArgType);
15319       }
15320       ParamTypes = ArgTypes;
15321     }
15322     DestType = S.Context.getFunctionType(DestType, ParamTypes,
15323                                          Proto->getExtProtoInfo());
15324   } else {
15325     DestType = S.Context.getFunctionNoProtoType(DestType,
15326                                                 FnType->getExtInfo());
15327   }
15328 
15329   // Rebuild the appropriate pointer-to-function type.
15330   switch (Kind) {
15331   case FK_MemberFunction:
15332     // Nothing to do.
15333     break;
15334 
15335   case FK_FunctionPointer:
15336     DestType = S.Context.getPointerType(DestType);
15337     break;
15338 
15339   case FK_BlockPointer:
15340     DestType = S.Context.getBlockPointerType(DestType);
15341     break;
15342   }
15343 
15344   // Finally, we can recurse.
15345   ExprResult CalleeResult = Visit(CalleeExpr);
15346   if (!CalleeResult.isUsable()) return ExprError();
15347   E->setCallee(CalleeResult.get());
15348 
15349   // Bind a temporary if necessary.
15350   return S.MaybeBindToTemporary(E);
15351 }
15352 
15353 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
15354   // Verify that this is a legal result type of a call.
15355   if (DestType->isArrayType() || DestType->isFunctionType()) {
15356     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
15357       << DestType->isFunctionType() << DestType;
15358     return ExprError();
15359   }
15360 
15361   // Rewrite the method result type if available.
15362   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
15363     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
15364     Method->setReturnType(DestType);
15365   }
15366 
15367   // Change the type of the message.
15368   E->setType(DestType.getNonReferenceType());
15369   E->setValueKind(Expr::getValueKindForType(DestType));
15370 
15371   return S.MaybeBindToTemporary(E);
15372 }
15373 
15374 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15375   // The only case we should ever see here is a function-to-pointer decay.
15376   if (E->getCastKind() == CK_FunctionToPointerDecay) {
15377     assert(E->getValueKind() == VK_RValue);
15378     assert(E->getObjectKind() == OK_Ordinary);
15379 
15380     E->setType(DestType);
15381 
15382     // Rebuild the sub-expression as the pointee (function) type.
15383     DestType = DestType->castAs<PointerType>()->getPointeeType();
15384 
15385     ExprResult Result = Visit(E->getSubExpr());
15386     if (!Result.isUsable()) return ExprError();
15387 
15388     E->setSubExpr(Result.get());
15389     return E;
15390   } else if (E->getCastKind() == CK_LValueToRValue) {
15391     assert(E->getValueKind() == VK_RValue);
15392     assert(E->getObjectKind() == OK_Ordinary);
15393 
15394     assert(isa<BlockPointerType>(E->getType()));
15395 
15396     E->setType(DestType);
15397 
15398     // The sub-expression has to be a lvalue reference, so rebuild it as such.
15399     DestType = S.Context.getLValueReferenceType(DestType);
15400 
15401     ExprResult Result = Visit(E->getSubExpr());
15402     if (!Result.isUsable()) return ExprError();
15403 
15404     E->setSubExpr(Result.get());
15405     return E;
15406   } else {
15407     llvm_unreachable("Unhandled cast type!");
15408   }
15409 }
15410 
15411 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15412   ExprValueKind ValueKind = VK_LValue;
15413   QualType Type = DestType;
15414 
15415   // We know how to make this work for certain kinds of decls:
15416 
15417   //  - functions
15418   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15419     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15420       DestType = Ptr->getPointeeType();
15421       ExprResult Result = resolveDecl(E, VD);
15422       if (Result.isInvalid()) return ExprError();
15423       return S.ImpCastExprToType(Result.get(), Type,
15424                                  CK_FunctionToPointerDecay, VK_RValue);
15425     }
15426 
15427     if (!Type->isFunctionType()) {
15428       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15429         << VD << E->getSourceRange();
15430       return ExprError();
15431     }
15432     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15433       // We must match the FunctionDecl's type to the hack introduced in
15434       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15435       // type. See the lengthy commentary in that routine.
15436       QualType FDT = FD->getType();
15437       const FunctionType *FnType = FDT->castAs<FunctionType>();
15438       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15439       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15440       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15441         SourceLocation Loc = FD->getLocation();
15442         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15443                                       FD->getDeclContext(),
15444                                       Loc, Loc, FD->getNameInfo().getName(),
15445                                       DestType, FD->getTypeSourceInfo(),
15446                                       SC_None, false/*isInlineSpecified*/,
15447                                       FD->hasPrototype(),
15448                                       false/*isConstexprSpecified*/);
15449 
15450         if (FD->getQualifier())
15451           NewFD->setQualifierInfo(FD->getQualifierLoc());
15452 
15453         SmallVector<ParmVarDecl*, 16> Params;
15454         for (const auto &AI : FT->param_types()) {
15455           ParmVarDecl *Param =
15456             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15457           Param->setScopeInfo(0, Params.size());
15458           Params.push_back(Param);
15459         }
15460         NewFD->setParams(Params);
15461         DRE->setDecl(NewFD);
15462         VD = DRE->getDecl();
15463       }
15464     }
15465 
15466     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15467       if (MD->isInstance()) {
15468         ValueKind = VK_RValue;
15469         Type = S.Context.BoundMemberTy;
15470       }
15471 
15472     // Function references aren't l-values in C.
15473     if (!S.getLangOpts().CPlusPlus)
15474       ValueKind = VK_RValue;
15475 
15476   //  - variables
15477   } else if (isa<VarDecl>(VD)) {
15478     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15479       Type = RefTy->getPointeeType();
15480     } else if (Type->isFunctionType()) {
15481       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15482         << VD << E->getSourceRange();
15483       return ExprError();
15484     }
15485 
15486   //  - nothing else
15487   } else {
15488     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15489       << VD << E->getSourceRange();
15490     return ExprError();
15491   }
15492 
15493   // Modifying the declaration like this is friendly to IR-gen but
15494   // also really dangerous.
15495   VD->setType(DestType);
15496   E->setType(Type);
15497   E->setValueKind(ValueKind);
15498   return E;
15499 }
15500 
15501 /// Check a cast of an unknown-any type.  We intentionally only
15502 /// trigger this for C-style casts.
15503 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15504                                      Expr *CastExpr, CastKind &CastKind,
15505                                      ExprValueKind &VK, CXXCastPath &Path) {
15506   // The type we're casting to must be either void or complete.
15507   if (!CastType->isVoidType() &&
15508       RequireCompleteType(TypeRange.getBegin(), CastType,
15509                           diag::err_typecheck_cast_to_incomplete))
15510     return ExprError();
15511 
15512   // Rewrite the casted expression from scratch.
15513   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15514   if (!result.isUsable()) return ExprError();
15515 
15516   CastExpr = result.get();
15517   VK = CastExpr->getValueKind();
15518   CastKind = CK_NoOp;
15519 
15520   return CastExpr;
15521 }
15522 
15523 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15524   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15525 }
15526 
15527 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15528                                     Expr *arg, QualType &paramType) {
15529   // If the syntactic form of the argument is not an explicit cast of
15530   // any sort, just do default argument promotion.
15531   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15532   if (!castArg) {
15533     ExprResult result = DefaultArgumentPromotion(arg);
15534     if (result.isInvalid()) return ExprError();
15535     paramType = result.get()->getType();
15536     return result;
15537   }
15538 
15539   // Otherwise, use the type that was written in the explicit cast.
15540   assert(!arg->hasPlaceholderType());
15541   paramType = castArg->getTypeAsWritten();
15542 
15543   // Copy-initialize a parameter of that type.
15544   InitializedEntity entity =
15545     InitializedEntity::InitializeParameter(Context, paramType,
15546                                            /*consumed*/ false);
15547   return PerformCopyInitialization(entity, callLoc, arg);
15548 }
15549 
15550 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15551   Expr *orig = E;
15552   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15553   while (true) {
15554     E = E->IgnoreParenImpCasts();
15555     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15556       E = call->getCallee();
15557       diagID = diag::err_uncasted_call_of_unknown_any;
15558     } else {
15559       break;
15560     }
15561   }
15562 
15563   SourceLocation loc;
15564   NamedDecl *d;
15565   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15566     loc = ref->getLocation();
15567     d = ref->getDecl();
15568   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15569     loc = mem->getMemberLoc();
15570     d = mem->getMemberDecl();
15571   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15572     diagID = diag::err_uncasted_call_of_unknown_any;
15573     loc = msg->getSelectorStartLoc();
15574     d = msg->getMethodDecl();
15575     if (!d) {
15576       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15577         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15578         << orig->getSourceRange();
15579       return ExprError();
15580     }
15581   } else {
15582     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15583       << E->getSourceRange();
15584     return ExprError();
15585   }
15586 
15587   S.Diag(loc, diagID) << d << orig->getSourceRange();
15588 
15589   // Never recoverable.
15590   return ExprError();
15591 }
15592 
15593 /// Check for operands with placeholder types and complain if found.
15594 /// Returns ExprError() if there was an error and no recovery was possible.
15595 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15596   if (!getLangOpts().CPlusPlus) {
15597     // C cannot handle TypoExpr nodes on either side of a binop because it
15598     // doesn't handle dependent types properly, so make sure any TypoExprs have
15599     // been dealt with before checking the operands.
15600     ExprResult Result = CorrectDelayedTyposInExpr(E);
15601     if (!Result.isUsable()) return ExprError();
15602     E = Result.get();
15603   }
15604 
15605   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15606   if (!placeholderType) return E;
15607 
15608   switch (placeholderType->getKind()) {
15609 
15610   // Overloaded expressions.
15611   case BuiltinType::Overload: {
15612     // Try to resolve a single function template specialization.
15613     // This is obligatory.
15614     ExprResult Result = E;
15615     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15616       return Result;
15617 
15618     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15619     // leaves Result unchanged on failure.
15620     Result = E;
15621     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15622       return Result;
15623 
15624     // If that failed, try to recover with a call.
15625     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15626                          /*complain*/ true);
15627     return Result;
15628   }
15629 
15630   // Bound member functions.
15631   case BuiltinType::BoundMember: {
15632     ExprResult result = E;
15633     const Expr *BME = E->IgnoreParens();
15634     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15635     // Try to give a nicer diagnostic if it is a bound member that we recognize.
15636     if (isa<CXXPseudoDestructorExpr>(BME)) {
15637       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15638     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15639       if (ME->getMemberNameInfo().getName().getNameKind() ==
15640           DeclarationName::CXXDestructorName)
15641         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15642     }
15643     tryToRecoverWithCall(result, PD,
15644                          /*complain*/ true);
15645     return result;
15646   }
15647 
15648   // ARC unbridged casts.
15649   case BuiltinType::ARCUnbridgedCast: {
15650     Expr *realCast = stripARCUnbridgedCast(E);
15651     diagnoseARCUnbridgedCast(realCast);
15652     return realCast;
15653   }
15654 
15655   // Expressions of unknown type.
15656   case BuiltinType::UnknownAny:
15657     return diagnoseUnknownAnyExpr(*this, E);
15658 
15659   // Pseudo-objects.
15660   case BuiltinType::PseudoObject:
15661     return checkPseudoObjectRValue(E);
15662 
15663   case BuiltinType::BuiltinFn: {
15664     // Accept __noop without parens by implicitly converting it to a call expr.
15665     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15666     if (DRE) {
15667       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15668       if (FD->getBuiltinID() == Builtin::BI__noop) {
15669         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15670                               CK_BuiltinFnToFnPtr).get();
15671         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15672                                       VK_RValue, SourceLocation());
15673       }
15674     }
15675 
15676     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15677     return ExprError();
15678   }
15679 
15680   // Expressions of unknown type.
15681   case BuiltinType::OMPArraySection:
15682     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15683     return ExprError();
15684 
15685   // Everything else should be impossible.
15686 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15687   case BuiltinType::Id:
15688 #include "clang/Basic/OpenCLImageTypes.def"
15689 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15690 #define PLACEHOLDER_TYPE(Id, SingletonId)
15691 #include "clang/AST/BuiltinTypes.def"
15692     break;
15693   }
15694 
15695   llvm_unreachable("invalid placeholder type!");
15696 }
15697 
15698 bool Sema::CheckCaseExpression(Expr *E) {
15699   if (E->isTypeDependent())
15700     return true;
15701   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15702     return E->getType()->isIntegralOrEnumerationType();
15703   return false;
15704 }
15705 
15706 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15707 ExprResult
15708 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15709   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15710          "Unknown Objective-C Boolean value!");
15711   QualType BoolT = Context.ObjCBuiltinBoolTy;
15712   if (!Context.getBOOLDecl()) {
15713     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15714                         Sema::LookupOrdinaryName);
15715     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15716       NamedDecl *ND = Result.getFoundDecl();
15717       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15718         Context.setBOOLDecl(TD);
15719     }
15720   }
15721   if (Context.getBOOLDecl())
15722     BoolT = Context.getBOOLType();
15723   return new (Context)
15724       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15725 }
15726 
15727 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15728     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15729     SourceLocation RParen) {
15730 
15731   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15732 
15733   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15734                            [&](const AvailabilitySpec &Spec) {
15735                              return Spec.getPlatform() == Platform;
15736                            });
15737 
15738   VersionTuple Version;
15739   if (Spec != AvailSpecs.end())
15740     Version = Spec->getVersion();
15741 
15742   // The use of `@available` in the enclosing function should be analyzed to
15743   // warn when it's used inappropriately (i.e. not if(@available)).
15744   if (getCurFunctionOrMethodDecl())
15745     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
15746   else if (getCurBlock() || getCurLambda())
15747     getCurFunction()->HasPotentialAvailabilityViolations = true;
15748 
15749   return new (Context)
15750       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15751 }
15752