1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "TreeTransform.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/ASTMutationListener.h"
20 #include "clang/AST/CXXInheritance.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/ExprOpenMP.h"
28 #include "clang/AST/RecursiveASTVisitor.h"
29 #include "clang/AST/TypeLoc.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/LiteralSupport.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/AnalysisBasedWarnings.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Designator.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaFixItUtils.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/Support/ConvertUTF.h"
47 using namespace clang;
48 using namespace sema;
49 
50 /// \brief Determine whether the use of this declaration is valid, without
51 /// emitting diagnostics.
52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
53   // See if this is an auto-typed variable whose initializer we are parsing.
54   if (ParsingInitForAutoVars.count(D))
55     return false;
56 
57   // See if this is a deleted function.
58   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
59     if (FD->isDeleted())
60       return false;
61 
62     // If the function has a deduced return type, and we can't deduce it,
63     // then we can't use it either.
64     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
65         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
66       return false;
67   }
68 
69   // See if this function is unavailable.
70   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
71       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
72     return false;
73 
74   return true;
75 }
76 
77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
78   // Warn if this is used but marked unused.
79   if (const auto *A = D->getAttr<UnusedAttr>()) {
80     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
81     // should diagnose them.
82     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) {
83       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
84       if (DC && !DC->hasAttr<UnusedAttr>())
85         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
86     }
87   }
88 }
89 
90 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
91   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
92   if (!OMD)
93     return false;
94   const ObjCInterfaceDecl *OID = OMD->getClassInterface();
95   if (!OID)
96     return false;
97 
98   for (const ObjCCategoryDecl *Cat : OID->visible_categories())
99     if (ObjCMethodDecl *CatMeth =
100             Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
101       if (!CatMeth->hasAttr<AvailabilityAttr>())
102         return true;
103   return false;
104 }
105 
106 static AvailabilityResult
107 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
108                            const ObjCInterfaceDecl *UnknownObjCClass,
109                            bool ObjCPropertyAccess) {
110   // See if this declaration is unavailable or deprecated.
111   std::string Message;
112   AvailabilityResult Result = D->getAvailability(&Message);
113 
114   // For typedefs, if the typedef declaration appears available look
115   // to the underlying type to see if it is more restrictive.
116   while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
117     if (Result == AR_Available) {
118       if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
119         D = TT->getDecl();
120         Result = D->getAvailability(&Message);
121         continue;
122       }
123     }
124     break;
125   }
126 
127   // Forward class declarations get their attributes from their definition.
128   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
129     if (IDecl->getDefinition()) {
130       D = IDecl->getDefinition();
131       Result = D->getAvailability(&Message);
132     }
133   }
134 
135   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
136     if (Result == AR_Available) {
137       const DeclContext *DC = ECD->getDeclContext();
138       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
139         Result = TheEnumDecl->getAvailability(&Message);
140     }
141 
142   const ObjCPropertyDecl *ObjCPDecl = nullptr;
143   if (Result == AR_Deprecated || Result == AR_Unavailable ||
144       Result == AR_NotYetIntroduced) {
145     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
146       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
147         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
148         if (PDeclResult == Result)
149           ObjCPDecl = PD;
150       }
151     }
152   }
153 
154   switch (Result) {
155     case AR_Available:
156       break;
157 
158     case AR_Deprecated:
159       if (S.getCurContextAvailability() != AR_Deprecated)
160         S.EmitAvailabilityWarning(Sema::AD_Deprecation,
161                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
162                                   ObjCPropertyAccess);
163       break;
164 
165     case AR_NotYetIntroduced: {
166       // Don't do this for enums, they can't be redeclared.
167       if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
168         break;
169 
170       bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
171       // Objective-C method declarations in categories are not modelled as
172       // redeclarations, so manually look for a redeclaration in a category
173       // if necessary.
174       if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
175         Warn = false;
176       // In general, D will point to the most recent redeclaration. However,
177       // for `@class A;` decls, this isn't true -- manually go through the
178       // redecl chain in that case.
179       if (Warn && isa<ObjCInterfaceDecl>(D))
180         for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
181              Redecl = Redecl->getPreviousDecl())
182           if (!Redecl->hasAttr<AvailabilityAttr>() ||
183               Redecl->getAttr<AvailabilityAttr>()->isInherited())
184             Warn = false;
185 
186       if (Warn)
187         S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc,
188                                   UnknownObjCClass, ObjCPDecl,
189                                   ObjCPropertyAccess);
190       break;
191     }
192 
193     case AR_Unavailable:
194       if (S.getCurContextAvailability() != AR_Unavailable)
195         S.EmitAvailabilityWarning(Sema::AD_Unavailable,
196                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
197                                   ObjCPropertyAccess);
198       break;
199 
200     }
201     return Result;
202 }
203 
204 /// \brief Emit a note explaining that this function is deleted.
205 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
206   assert(Decl->isDeleted());
207 
208   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
209 
210   if (Method && Method->isDeleted() && Method->isDefaulted()) {
211     // If the method was explicitly defaulted, point at that declaration.
212     if (!Method->isImplicit())
213       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
214 
215     // Try to diagnose why this special member function was implicitly
216     // deleted. This might fail, if that reason no longer applies.
217     CXXSpecialMember CSM = getSpecialMember(Method);
218     if (CSM != CXXInvalid)
219       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
220 
221     return;
222   }
223 
224   if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
225     if (CXXConstructorDecl *BaseCD =
226             const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
227       Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
228       if (BaseCD->isDeleted()) {
229         NoteDeletedFunction(BaseCD);
230       } else {
231         // FIXME: An explanation of why exactly it can't be inherited
232         // would be nice.
233         Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
234       }
235       return;
236     }
237   }
238 
239   Diag(Decl->getLocation(), diag::note_availability_specified_here)
240     << Decl << true;
241 }
242 
243 /// \brief Determine whether a FunctionDecl was ever declared with an
244 /// explicit storage class.
245 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
246   for (auto I : D->redecls()) {
247     if (I->getStorageClass() != SC_None)
248       return true;
249   }
250   return false;
251 }
252 
253 /// \brief Check whether we're in an extern inline function and referring to a
254 /// variable or function with internal linkage (C11 6.7.4p3).
255 ///
256 /// This is only a warning because we used to silently accept this code, but
257 /// in many cases it will not behave correctly. This is not enabled in C++ mode
258 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
259 /// and so while there may still be user mistakes, most of the time we can't
260 /// prove that there are errors.
261 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
262                                                       const NamedDecl *D,
263                                                       SourceLocation Loc) {
264   // This is disabled under C++; there are too many ways for this to fire in
265   // contexts where the warning is a false positive, or where it is technically
266   // correct but benign.
267   if (S.getLangOpts().CPlusPlus)
268     return;
269 
270   // Check if this is an inlined function or method.
271   FunctionDecl *Current = S.getCurFunctionDecl();
272   if (!Current)
273     return;
274   if (!Current->isInlined())
275     return;
276   if (!Current->isExternallyVisible())
277     return;
278 
279   // Check if the decl has internal linkage.
280   if (D->getFormalLinkage() != InternalLinkage)
281     return;
282 
283   // Downgrade from ExtWarn to Extension if
284   //  (1) the supposedly external inline function is in the main file,
285   //      and probably won't be included anywhere else.
286   //  (2) the thing we're referencing is a pure function.
287   //  (3) the thing we're referencing is another inline function.
288   // This last can give us false negatives, but it's better than warning on
289   // wrappers for simple C library functions.
290   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
291   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
292   if (!DowngradeWarning && UsedFn)
293     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
294 
295   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
296                                : diag::ext_internal_in_extern_inline)
297     << /*IsVar=*/!UsedFn << D;
298 
299   S.MaybeSuggestAddingStaticToDecl(Current);
300 
301   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
302       << D;
303 }
304 
305 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
306   const FunctionDecl *First = Cur->getFirstDecl();
307 
308   // Suggest "static" on the function, if possible.
309   if (!hasAnyExplicitStorageClass(First)) {
310     SourceLocation DeclBegin = First->getSourceRange().getBegin();
311     Diag(DeclBegin, diag::note_convert_inline_to_static)
312       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
313   }
314 }
315 
316 /// \brief Determine whether the use of this declaration is valid, and
317 /// emit any corresponding diagnostics.
318 ///
319 /// This routine diagnoses various problems with referencing
320 /// declarations that can occur when using a declaration. For example,
321 /// it might warn if a deprecated or unavailable declaration is being
322 /// used, or produce an error (and return true) if a C++0x deleted
323 /// function is being used.
324 ///
325 /// \returns true if there was an error (this declaration cannot be
326 /// referenced), false otherwise.
327 ///
328 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
329                              const ObjCInterfaceDecl *UnknownObjCClass,
330                              bool ObjCPropertyAccess) {
331   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
332     // If there were any diagnostics suppressed by template argument deduction,
333     // emit them now.
334     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
335     if (Pos != SuppressedDiagnostics.end()) {
336       for (const PartialDiagnosticAt &Suppressed : Pos->second)
337         Diag(Suppressed.first, Suppressed.second);
338 
339       // Clear out the list of suppressed diagnostics, so that we don't emit
340       // them again for this specialization. However, we don't obsolete this
341       // entry from the table, because we want to avoid ever emitting these
342       // diagnostics again.
343       Pos->second.clear();
344     }
345 
346     // C++ [basic.start.main]p3:
347     //   The function 'main' shall not be used within a program.
348     if (cast<FunctionDecl>(D)->isMain())
349       Diag(Loc, diag::ext_main_used);
350   }
351 
352   // See if this is an auto-typed variable whose initializer we are parsing.
353   if (ParsingInitForAutoVars.count(D)) {
354     const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
355 
356     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
357       << D->getDeclName() << (unsigned)AT->getKeyword();
358     return true;
359   }
360 
361   // See if this is a deleted function.
362   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
363     if (FD->isDeleted()) {
364       Diag(Loc, diag::err_deleted_function_use);
365       NoteDeletedFunction(FD);
366       return true;
367     }
368 
369     // If the function has a deduced return type, and we can't deduce it,
370     // then we can't use it either.
371     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
372         DeduceReturnType(FD, Loc))
373       return true;
374   }
375 
376   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
377   // Only the variables omp_in and omp_out are allowed in the combiner.
378   // Only the variables omp_priv and omp_orig are allowed in the
379   // initializer-clause.
380   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
381   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
382       isa<VarDecl>(D)) {
383     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
384         << getCurFunction()->HasOMPDeclareReductionCombiner;
385     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
386     return true;
387   }
388   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
389                              ObjCPropertyAccess);
390 
391   DiagnoseUnusedOfDecl(*this, D, Loc);
392 
393   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
394 
395   return false;
396 }
397 
398 /// \brief Retrieve the message suffix that should be added to a
399 /// diagnostic complaining about the given function being deleted or
400 /// unavailable.
401 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
402   std::string Message;
403   if (FD->getAvailability(&Message))
404     return ": " + Message;
405 
406   return std::string();
407 }
408 
409 /// DiagnoseSentinelCalls - This routine checks whether a call or
410 /// message-send is to a declaration with the sentinel attribute, and
411 /// if so, it checks that the requirements of the sentinel are
412 /// satisfied.
413 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
414                                  ArrayRef<Expr *> Args) {
415   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
416   if (!attr)
417     return;
418 
419   // The number of formal parameters of the declaration.
420   unsigned numFormalParams;
421 
422   // The kind of declaration.  This is also an index into a %select in
423   // the diagnostic.
424   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
425 
426   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
427     numFormalParams = MD->param_size();
428     calleeType = CT_Method;
429   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
430     numFormalParams = FD->param_size();
431     calleeType = CT_Function;
432   } else if (isa<VarDecl>(D)) {
433     QualType type = cast<ValueDecl>(D)->getType();
434     const FunctionType *fn = nullptr;
435     if (const PointerType *ptr = type->getAs<PointerType>()) {
436       fn = ptr->getPointeeType()->getAs<FunctionType>();
437       if (!fn) return;
438       calleeType = CT_Function;
439     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
440       fn = ptr->getPointeeType()->castAs<FunctionType>();
441       calleeType = CT_Block;
442     } else {
443       return;
444     }
445 
446     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
447       numFormalParams = proto->getNumParams();
448     } else {
449       numFormalParams = 0;
450     }
451   } else {
452     return;
453   }
454 
455   // "nullPos" is the number of formal parameters at the end which
456   // effectively count as part of the variadic arguments.  This is
457   // useful if you would prefer to not have *any* formal parameters,
458   // but the language forces you to have at least one.
459   unsigned nullPos = attr->getNullPos();
460   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
461   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
462 
463   // The number of arguments which should follow the sentinel.
464   unsigned numArgsAfterSentinel = attr->getSentinel();
465 
466   // If there aren't enough arguments for all the formal parameters,
467   // the sentinel, and the args after the sentinel, complain.
468   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
469     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
470     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
471     return;
472   }
473 
474   // Otherwise, find the sentinel expression.
475   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
476   if (!sentinelExpr) return;
477   if (sentinelExpr->isValueDependent()) return;
478   if (Context.isSentinelNullExpr(sentinelExpr)) return;
479 
480   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
481   // or 'NULL' if those are actually defined in the context.  Only use
482   // 'nil' for ObjC methods, where it's much more likely that the
483   // variadic arguments form a list of object pointers.
484   SourceLocation MissingNilLoc
485     = getLocForEndOfToken(sentinelExpr->getLocEnd());
486   std::string NullValue;
487   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
488     NullValue = "nil";
489   else if (getLangOpts().CPlusPlus11)
490     NullValue = "nullptr";
491   else if (PP.isMacroDefined("NULL"))
492     NullValue = "NULL";
493   else
494     NullValue = "(void*) 0";
495 
496   if (MissingNilLoc.isInvalid())
497     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
498   else
499     Diag(MissingNilLoc, diag::warn_missing_sentinel)
500       << int(calleeType)
501       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
502   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
503 }
504 
505 SourceRange Sema::getExprRange(Expr *E) const {
506   return E ? E->getSourceRange() : SourceRange();
507 }
508 
509 //===----------------------------------------------------------------------===//
510 //  Standard Promotions and Conversions
511 //===----------------------------------------------------------------------===//
512 
513 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
514 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
515   // Handle any placeholder expressions which made it here.
516   if (E->getType()->isPlaceholderType()) {
517     ExprResult result = CheckPlaceholderExpr(E);
518     if (result.isInvalid()) return ExprError();
519     E = result.get();
520   }
521 
522   QualType Ty = E->getType();
523   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
524 
525   if (Ty->isFunctionType()) {
526     // If we are here, we are not calling a function but taking
527     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
528     if (getLangOpts().OpenCL) {
529       if (Diagnose)
530         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
531       return ExprError();
532     }
533 
534     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
535       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
536         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
537           return ExprError();
538 
539     E = ImpCastExprToType(E, Context.getPointerType(Ty),
540                           CK_FunctionToPointerDecay).get();
541   } else if (Ty->isArrayType()) {
542     // In C90 mode, arrays only promote to pointers if the array expression is
543     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
544     // type 'array of type' is converted to an expression that has type 'pointer
545     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
546     // that has type 'array of type' ...".  The relevant change is "an lvalue"
547     // (C90) to "an expression" (C99).
548     //
549     // C++ 4.2p1:
550     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
551     // T" can be converted to an rvalue of type "pointer to T".
552     //
553     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
554       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
555                             CK_ArrayToPointerDecay).get();
556   }
557   return E;
558 }
559 
560 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
561   // Check to see if we are dereferencing a null pointer.  If so,
562   // and if not volatile-qualified, this is undefined behavior that the
563   // optimizer will delete, so warn about it.  People sometimes try to use this
564   // to get a deterministic trap and are surprised by clang's behavior.  This
565   // only handles the pattern "*null", which is a very syntactic check.
566   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
567     if (UO->getOpcode() == UO_Deref &&
568         UO->getSubExpr()->IgnoreParenCasts()->
569           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
570         !UO->getType().isVolatileQualified()) {
571     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
572                           S.PDiag(diag::warn_indirection_through_null)
573                             << UO->getSubExpr()->getSourceRange());
574     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
575                         S.PDiag(diag::note_indirection_through_null));
576   }
577 }
578 
579 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
580                                     SourceLocation AssignLoc,
581                                     const Expr* RHS) {
582   const ObjCIvarDecl *IV = OIRE->getDecl();
583   if (!IV)
584     return;
585 
586   DeclarationName MemberName = IV->getDeclName();
587   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
588   if (!Member || !Member->isStr("isa"))
589     return;
590 
591   const Expr *Base = OIRE->getBase();
592   QualType BaseType = Base->getType();
593   if (OIRE->isArrow())
594     BaseType = BaseType->getPointeeType();
595   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
596     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
597       ObjCInterfaceDecl *ClassDeclared = nullptr;
598       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
599       if (!ClassDeclared->getSuperClass()
600           && (*ClassDeclared->ivar_begin()) == IV) {
601         if (RHS) {
602           NamedDecl *ObjectSetClass =
603             S.LookupSingleName(S.TUScope,
604                                &S.Context.Idents.get("object_setClass"),
605                                SourceLocation(), S.LookupOrdinaryName);
606           if (ObjectSetClass) {
607             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
608             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
609             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
610             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
611                                                      AssignLoc), ",") <<
612             FixItHint::CreateInsertion(RHSLocEnd, ")");
613           }
614           else
615             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
616         } else {
617           NamedDecl *ObjectGetClass =
618             S.LookupSingleName(S.TUScope,
619                                &S.Context.Idents.get("object_getClass"),
620                                SourceLocation(), S.LookupOrdinaryName);
621           if (ObjectGetClass)
622             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
623             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
624             FixItHint::CreateReplacement(
625                                          SourceRange(OIRE->getOpLoc(),
626                                                      OIRE->getLocEnd()), ")");
627           else
628             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
629         }
630         S.Diag(IV->getLocation(), diag::note_ivar_decl);
631       }
632     }
633 }
634 
635 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
636   // Handle any placeholder expressions which made it here.
637   if (E->getType()->isPlaceholderType()) {
638     ExprResult result = CheckPlaceholderExpr(E);
639     if (result.isInvalid()) return ExprError();
640     E = result.get();
641   }
642 
643   // C++ [conv.lval]p1:
644   //   A glvalue of a non-function, non-array type T can be
645   //   converted to a prvalue.
646   if (!E->isGLValue()) return E;
647 
648   QualType T = E->getType();
649   assert(!T.isNull() && "r-value conversion on typeless expression?");
650 
651   // We don't want to throw lvalue-to-rvalue casts on top of
652   // expressions of certain types in C++.
653   if (getLangOpts().CPlusPlus &&
654       (E->getType() == Context.OverloadTy ||
655        T->isDependentType() ||
656        T->isRecordType()))
657     return E;
658 
659   // The C standard is actually really unclear on this point, and
660   // DR106 tells us what the result should be but not why.  It's
661   // generally best to say that void types just doesn't undergo
662   // lvalue-to-rvalue at all.  Note that expressions of unqualified
663   // 'void' type are never l-values, but qualified void can be.
664   if (T->isVoidType())
665     return E;
666 
667   // OpenCL usually rejects direct accesses to values of 'half' type.
668   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
669       T->isHalfType()) {
670     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
671       << 0 << T;
672     return ExprError();
673   }
674 
675   CheckForNullPointerDereference(*this, E);
676   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
677     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
678                                      &Context.Idents.get("object_getClass"),
679                                      SourceLocation(), LookupOrdinaryName);
680     if (ObjectGetClass)
681       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
682         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
683         FixItHint::CreateReplacement(
684                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
685     else
686       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
687   }
688   else if (const ObjCIvarRefExpr *OIRE =
689             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
690     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
691 
692   // C++ [conv.lval]p1:
693   //   [...] If T is a non-class type, the type of the prvalue is the
694   //   cv-unqualified version of T. Otherwise, the type of the
695   //   rvalue is T.
696   //
697   // C99 6.3.2.1p2:
698   //   If the lvalue has qualified type, the value has the unqualified
699   //   version of the type of the lvalue; otherwise, the value has the
700   //   type of the lvalue.
701   if (T.hasQualifiers())
702     T = T.getUnqualifiedType();
703 
704   // Under the MS ABI, lock down the inheritance model now.
705   if (T->isMemberPointerType() &&
706       Context.getTargetInfo().getCXXABI().isMicrosoft())
707     (void)isCompleteType(E->getExprLoc(), T);
708 
709   UpdateMarkingForLValueToRValue(E);
710 
711   // Loading a __weak object implicitly retains the value, so we need a cleanup to
712   // balance that.
713   if (getLangOpts().ObjCAutoRefCount &&
714       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
715     ExprNeedsCleanups = true;
716 
717   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
718                                             nullptr, VK_RValue);
719 
720   // C11 6.3.2.1p2:
721   //   ... if the lvalue has atomic type, the value has the non-atomic version
722   //   of the type of the lvalue ...
723   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
724     T = Atomic->getValueType().getUnqualifiedType();
725     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
726                                    nullptr, VK_RValue);
727   }
728 
729   return Res;
730 }
731 
732 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
733   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
734   if (Res.isInvalid())
735     return ExprError();
736   Res = DefaultLvalueConversion(Res.get());
737   if (Res.isInvalid())
738     return ExprError();
739   return Res;
740 }
741 
742 /// CallExprUnaryConversions - a special case of an unary conversion
743 /// performed on a function designator of a call expression.
744 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
745   QualType Ty = E->getType();
746   ExprResult Res = E;
747   // Only do implicit cast for a function type, but not for a pointer
748   // to function type.
749   if (Ty->isFunctionType()) {
750     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
751                             CK_FunctionToPointerDecay).get();
752     if (Res.isInvalid())
753       return ExprError();
754   }
755   Res = DefaultLvalueConversion(Res.get());
756   if (Res.isInvalid())
757     return ExprError();
758   return Res.get();
759 }
760 
761 /// UsualUnaryConversions - Performs various conversions that are common to most
762 /// operators (C99 6.3). The conversions of array and function types are
763 /// sometimes suppressed. For example, the array->pointer conversion doesn't
764 /// apply if the array is an argument to the sizeof or address (&) operators.
765 /// In these instances, this routine should *not* be called.
766 ExprResult Sema::UsualUnaryConversions(Expr *E) {
767   // First, convert to an r-value.
768   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
769   if (Res.isInvalid())
770     return ExprError();
771   E = Res.get();
772 
773   QualType Ty = E->getType();
774   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
775 
776   // Half FP have to be promoted to float unless it is natively supported
777   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
778     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
779 
780   // Try to perform integral promotions if the object has a theoretically
781   // promotable type.
782   if (Ty->isIntegralOrUnscopedEnumerationType()) {
783     // C99 6.3.1.1p2:
784     //
785     //   The following may be used in an expression wherever an int or
786     //   unsigned int may be used:
787     //     - an object or expression with an integer type whose integer
788     //       conversion rank is less than or equal to the rank of int
789     //       and unsigned int.
790     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
791     //
792     //   If an int can represent all values of the original type, the
793     //   value is converted to an int; otherwise, it is converted to an
794     //   unsigned int. These are called the integer promotions. All
795     //   other types are unchanged by the integer promotions.
796 
797     QualType PTy = Context.isPromotableBitField(E);
798     if (!PTy.isNull()) {
799       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
800       return E;
801     }
802     if (Ty->isPromotableIntegerType()) {
803       QualType PT = Context.getPromotedIntegerType(Ty);
804       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
805       return E;
806     }
807   }
808   return E;
809 }
810 
811 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
812 /// do not have a prototype. Arguments that have type float or __fp16
813 /// are promoted to double. All other argument types are converted by
814 /// UsualUnaryConversions().
815 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
816   QualType Ty = E->getType();
817   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
818 
819   ExprResult Res = UsualUnaryConversions(E);
820   if (Res.isInvalid())
821     return ExprError();
822   E = Res.get();
823 
824   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
825   // double.
826   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
827   if (BTy && (BTy->getKind() == BuiltinType::Half ||
828               BTy->getKind() == BuiltinType::Float))
829     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
830 
831   // C++ performs lvalue-to-rvalue conversion as a default argument
832   // promotion, even on class types, but note:
833   //   C++11 [conv.lval]p2:
834   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
835   //     operand or a subexpression thereof the value contained in the
836   //     referenced object is not accessed. Otherwise, if the glvalue
837   //     has a class type, the conversion copy-initializes a temporary
838   //     of type T from the glvalue and the result of the conversion
839   //     is a prvalue for the temporary.
840   // FIXME: add some way to gate this entire thing for correctness in
841   // potentially potentially evaluated contexts.
842   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
843     ExprResult Temp = PerformCopyInitialization(
844                        InitializedEntity::InitializeTemporary(E->getType()),
845                                                 E->getExprLoc(), E);
846     if (Temp.isInvalid())
847       return ExprError();
848     E = Temp.get();
849   }
850 
851   return E;
852 }
853 
854 /// Determine the degree of POD-ness for an expression.
855 /// Incomplete types are considered POD, since this check can be performed
856 /// when we're in an unevaluated context.
857 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
858   if (Ty->isIncompleteType()) {
859     // C++11 [expr.call]p7:
860     //   After these conversions, if the argument does not have arithmetic,
861     //   enumeration, pointer, pointer to member, or class type, the program
862     //   is ill-formed.
863     //
864     // Since we've already performed array-to-pointer and function-to-pointer
865     // decay, the only such type in C++ is cv void. This also handles
866     // initializer lists as variadic arguments.
867     if (Ty->isVoidType())
868       return VAK_Invalid;
869 
870     if (Ty->isObjCObjectType())
871       return VAK_Invalid;
872     return VAK_Valid;
873   }
874 
875   if (Ty.isCXX98PODType(Context))
876     return VAK_Valid;
877 
878   // C++11 [expr.call]p7:
879   //   Passing a potentially-evaluated argument of class type (Clause 9)
880   //   having a non-trivial copy constructor, a non-trivial move constructor,
881   //   or a non-trivial destructor, with no corresponding parameter,
882   //   is conditionally-supported with implementation-defined semantics.
883   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
884     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
885       if (!Record->hasNonTrivialCopyConstructor() &&
886           !Record->hasNonTrivialMoveConstructor() &&
887           !Record->hasNonTrivialDestructor())
888         return VAK_ValidInCXX11;
889 
890   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
891     return VAK_Valid;
892 
893   if (Ty->isObjCObjectType())
894     return VAK_Invalid;
895 
896   if (getLangOpts().MSVCCompat)
897     return VAK_MSVCUndefined;
898 
899   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
900   // permitted to reject them. We should consider doing so.
901   return VAK_Undefined;
902 }
903 
904 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
905   // Don't allow one to pass an Objective-C interface to a vararg.
906   const QualType &Ty = E->getType();
907   VarArgKind VAK = isValidVarArgType(Ty);
908 
909   // Complain about passing non-POD types through varargs.
910   switch (VAK) {
911   case VAK_ValidInCXX11:
912     DiagRuntimeBehavior(
913         E->getLocStart(), nullptr,
914         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
915           << Ty << CT);
916     // Fall through.
917   case VAK_Valid:
918     if (Ty->isRecordType()) {
919       // This is unlikely to be what the user intended. If the class has a
920       // 'c_str' member function, the user probably meant to call that.
921       DiagRuntimeBehavior(E->getLocStart(), nullptr,
922                           PDiag(diag::warn_pass_class_arg_to_vararg)
923                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
924     }
925     break;
926 
927   case VAK_Undefined:
928   case VAK_MSVCUndefined:
929     DiagRuntimeBehavior(
930         E->getLocStart(), nullptr,
931         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
932           << getLangOpts().CPlusPlus11 << Ty << CT);
933     break;
934 
935   case VAK_Invalid:
936     if (Ty->isObjCObjectType())
937       DiagRuntimeBehavior(
938           E->getLocStart(), nullptr,
939           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
940             << Ty << CT);
941     else
942       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
943         << isa<InitListExpr>(E) << Ty << CT;
944     break;
945   }
946 }
947 
948 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
949 /// will create a trap if the resulting type is not a POD type.
950 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
951                                                   FunctionDecl *FDecl) {
952   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
953     // Strip the unbridged-cast placeholder expression off, if applicable.
954     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
955         (CT == VariadicMethod ||
956          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
957       E = stripARCUnbridgedCast(E);
958 
959     // Otherwise, do normal placeholder checking.
960     } else {
961       ExprResult ExprRes = CheckPlaceholderExpr(E);
962       if (ExprRes.isInvalid())
963         return ExprError();
964       E = ExprRes.get();
965     }
966   }
967 
968   ExprResult ExprRes = DefaultArgumentPromotion(E);
969   if (ExprRes.isInvalid())
970     return ExprError();
971   E = ExprRes.get();
972 
973   // Diagnostics regarding non-POD argument types are
974   // emitted along with format string checking in Sema::CheckFunctionCall().
975   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
976     // Turn this into a trap.
977     CXXScopeSpec SS;
978     SourceLocation TemplateKWLoc;
979     UnqualifiedId Name;
980     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
981                        E->getLocStart());
982     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
983                                           Name, true, false);
984     if (TrapFn.isInvalid())
985       return ExprError();
986 
987     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
988                                     E->getLocStart(), None,
989                                     E->getLocEnd());
990     if (Call.isInvalid())
991       return ExprError();
992 
993     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
994                                   Call.get(), E);
995     if (Comma.isInvalid())
996       return ExprError();
997     return Comma.get();
998   }
999 
1000   if (!getLangOpts().CPlusPlus &&
1001       RequireCompleteType(E->getExprLoc(), E->getType(),
1002                           diag::err_call_incomplete_argument))
1003     return ExprError();
1004 
1005   return E;
1006 }
1007 
1008 /// \brief Converts an integer to complex float type.  Helper function of
1009 /// UsualArithmeticConversions()
1010 ///
1011 /// \return false if the integer expression is an integer type and is
1012 /// successfully converted to the complex type.
1013 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1014                                                   ExprResult &ComplexExpr,
1015                                                   QualType IntTy,
1016                                                   QualType ComplexTy,
1017                                                   bool SkipCast) {
1018   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1019   if (SkipCast) return false;
1020   if (IntTy->isIntegerType()) {
1021     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1022     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1023     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1024                                   CK_FloatingRealToComplex);
1025   } else {
1026     assert(IntTy->isComplexIntegerType());
1027     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1028                                   CK_IntegralComplexToFloatingComplex);
1029   }
1030   return false;
1031 }
1032 
1033 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1034 /// UsualArithmeticConversions()
1035 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1036                                              ExprResult &RHS, QualType LHSType,
1037                                              QualType RHSType,
1038                                              bool IsCompAssign) {
1039   // if we have an integer operand, the result is the complex type.
1040   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1041                                              /*skipCast*/false))
1042     return LHSType;
1043   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1044                                              /*skipCast*/IsCompAssign))
1045     return RHSType;
1046 
1047   // This handles complex/complex, complex/float, or float/complex.
1048   // When both operands are complex, the shorter operand is converted to the
1049   // type of the longer, and that is the type of the result. This corresponds
1050   // to what is done when combining two real floating-point operands.
1051   // The fun begins when size promotion occur across type domains.
1052   // From H&S 6.3.4: When one operand is complex and the other is a real
1053   // floating-point type, the less precise type is converted, within it's
1054   // real or complex domain, to the precision of the other type. For example,
1055   // when combining a "long double" with a "double _Complex", the
1056   // "double _Complex" is promoted to "long double _Complex".
1057 
1058   // Compute the rank of the two types, regardless of whether they are complex.
1059   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1060 
1061   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1062   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1063   QualType LHSElementType =
1064       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1065   QualType RHSElementType =
1066       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1067 
1068   QualType ResultType = S.Context.getComplexType(LHSElementType);
1069   if (Order < 0) {
1070     // Promote the precision of the LHS if not an assignment.
1071     ResultType = S.Context.getComplexType(RHSElementType);
1072     if (!IsCompAssign) {
1073       if (LHSComplexType)
1074         LHS =
1075             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1076       else
1077         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1078     }
1079   } else if (Order > 0) {
1080     // Promote the precision of the RHS.
1081     if (RHSComplexType)
1082       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1083     else
1084       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1085   }
1086   return ResultType;
1087 }
1088 
1089 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1090 /// of UsualArithmeticConversions()
1091 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1092                                            ExprResult &IntExpr,
1093                                            QualType FloatTy, QualType IntTy,
1094                                            bool ConvertFloat, bool ConvertInt) {
1095   if (IntTy->isIntegerType()) {
1096     if (ConvertInt)
1097       // Convert intExpr to the lhs floating point type.
1098       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1099                                     CK_IntegralToFloating);
1100     return FloatTy;
1101   }
1102 
1103   // Convert both sides to the appropriate complex float.
1104   assert(IntTy->isComplexIntegerType());
1105   QualType result = S.Context.getComplexType(FloatTy);
1106 
1107   // _Complex int -> _Complex float
1108   if (ConvertInt)
1109     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1110                                   CK_IntegralComplexToFloatingComplex);
1111 
1112   // float -> _Complex float
1113   if (ConvertFloat)
1114     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1115                                     CK_FloatingRealToComplex);
1116 
1117   return result;
1118 }
1119 
1120 /// \brief Handle arithmethic conversion with floating point types.  Helper
1121 /// function of UsualArithmeticConversions()
1122 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1123                                       ExprResult &RHS, QualType LHSType,
1124                                       QualType RHSType, bool IsCompAssign) {
1125   bool LHSFloat = LHSType->isRealFloatingType();
1126   bool RHSFloat = RHSType->isRealFloatingType();
1127 
1128   // If we have two real floating types, convert the smaller operand
1129   // to the bigger result.
1130   if (LHSFloat && RHSFloat) {
1131     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1132     if (order > 0) {
1133       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1134       return LHSType;
1135     }
1136 
1137     assert(order < 0 && "illegal float comparison");
1138     if (!IsCompAssign)
1139       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1140     return RHSType;
1141   }
1142 
1143   if (LHSFloat) {
1144     // Half FP has to be promoted to float unless it is natively supported
1145     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1146       LHSType = S.Context.FloatTy;
1147 
1148     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1149                                       /*convertFloat=*/!IsCompAssign,
1150                                       /*convertInt=*/ true);
1151   }
1152   assert(RHSFloat);
1153   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1154                                     /*convertInt=*/ true,
1155                                     /*convertFloat=*/!IsCompAssign);
1156 }
1157 
1158 /// \brief Diagnose attempts to convert between __float128 and long double if
1159 /// there is no support for such conversion. Helper function of
1160 /// UsualArithmeticConversions().
1161 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1162                                       QualType RHSType) {
1163   /*  No issue converting if at least one of the types is not a floating point
1164       type or the two types have the same rank.
1165   */
1166   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1167       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1168     return false;
1169 
1170   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1171          "The remaining types must be floating point types.");
1172 
1173   auto *LHSComplex = LHSType->getAs<ComplexType>();
1174   auto *RHSComplex = RHSType->getAs<ComplexType>();
1175 
1176   QualType LHSElemType = LHSComplex ?
1177     LHSComplex->getElementType() : LHSType;
1178   QualType RHSElemType = RHSComplex ?
1179     RHSComplex->getElementType() : RHSType;
1180 
1181   // No issue if the two types have the same representation
1182   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1183       &S.Context.getFloatTypeSemantics(RHSElemType))
1184     return false;
1185 
1186   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1187                                 RHSElemType == S.Context.LongDoubleTy);
1188   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1189                             RHSElemType == S.Context.Float128Ty);
1190 
1191   /* We've handled the situation where __float128 and long double have the same
1192      representation. The only other allowable conversion is if long double is
1193      really just double.
1194   */
1195   return Float128AndLongDouble &&
1196     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1197      &llvm::APFloat::IEEEdouble);
1198 }
1199 
1200 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1201 
1202 namespace {
1203 /// These helper callbacks are placed in an anonymous namespace to
1204 /// permit their use as function template parameters.
1205 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1206   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1207 }
1208 
1209 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1210   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1211                              CK_IntegralComplexCast);
1212 }
1213 }
1214 
1215 /// \brief Handle integer arithmetic conversions.  Helper function of
1216 /// UsualArithmeticConversions()
1217 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1218 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1219                                         ExprResult &RHS, QualType LHSType,
1220                                         QualType RHSType, bool IsCompAssign) {
1221   // The rules for this case are in C99 6.3.1.8
1222   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1223   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1224   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1225   if (LHSSigned == RHSSigned) {
1226     // Same signedness; use the higher-ranked type
1227     if (order >= 0) {
1228       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1229       return LHSType;
1230     } else if (!IsCompAssign)
1231       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1232     return RHSType;
1233   } else if (order != (LHSSigned ? 1 : -1)) {
1234     // The unsigned type has greater than or equal rank to the
1235     // signed type, so use the unsigned type
1236     if (RHSSigned) {
1237       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1238       return LHSType;
1239     } else if (!IsCompAssign)
1240       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1241     return RHSType;
1242   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1243     // The two types are different widths; if we are here, that
1244     // means the signed type is larger than the unsigned type, so
1245     // use the signed type.
1246     if (LHSSigned) {
1247       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1248       return LHSType;
1249     } else if (!IsCompAssign)
1250       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1251     return RHSType;
1252   } else {
1253     // The signed type is higher-ranked than the unsigned type,
1254     // but isn't actually any bigger (like unsigned int and long
1255     // on most 32-bit systems).  Use the unsigned type corresponding
1256     // to the signed type.
1257     QualType result =
1258       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1259     RHS = (*doRHSCast)(S, RHS.get(), result);
1260     if (!IsCompAssign)
1261       LHS = (*doLHSCast)(S, LHS.get(), result);
1262     return result;
1263   }
1264 }
1265 
1266 /// \brief Handle conversions with GCC complex int extension.  Helper function
1267 /// of UsualArithmeticConversions()
1268 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1269                                            ExprResult &RHS, QualType LHSType,
1270                                            QualType RHSType,
1271                                            bool IsCompAssign) {
1272   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1273   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1274 
1275   if (LHSComplexInt && RHSComplexInt) {
1276     QualType LHSEltType = LHSComplexInt->getElementType();
1277     QualType RHSEltType = RHSComplexInt->getElementType();
1278     QualType ScalarType =
1279       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1280         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1281 
1282     return S.Context.getComplexType(ScalarType);
1283   }
1284 
1285   if (LHSComplexInt) {
1286     QualType LHSEltType = LHSComplexInt->getElementType();
1287     QualType ScalarType =
1288       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1289         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1290     QualType ComplexType = S.Context.getComplexType(ScalarType);
1291     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1292                               CK_IntegralRealToComplex);
1293 
1294     return ComplexType;
1295   }
1296 
1297   assert(RHSComplexInt);
1298 
1299   QualType RHSEltType = RHSComplexInt->getElementType();
1300   QualType ScalarType =
1301     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1302       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1303   QualType ComplexType = S.Context.getComplexType(ScalarType);
1304 
1305   if (!IsCompAssign)
1306     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1307                               CK_IntegralRealToComplex);
1308   return ComplexType;
1309 }
1310 
1311 /// UsualArithmeticConversions - Performs various conversions that are common to
1312 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1313 /// routine returns the first non-arithmetic type found. The client is
1314 /// responsible for emitting appropriate error diagnostics.
1315 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1316                                           bool IsCompAssign) {
1317   if (!IsCompAssign) {
1318     LHS = UsualUnaryConversions(LHS.get());
1319     if (LHS.isInvalid())
1320       return QualType();
1321   }
1322 
1323   RHS = UsualUnaryConversions(RHS.get());
1324   if (RHS.isInvalid())
1325     return QualType();
1326 
1327   // For conversion purposes, we ignore any qualifiers.
1328   // For example, "const float" and "float" are equivalent.
1329   QualType LHSType =
1330     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1331   QualType RHSType =
1332     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1333 
1334   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1335   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1336     LHSType = AtomicLHS->getValueType();
1337 
1338   // If both types are identical, no conversion is needed.
1339   if (LHSType == RHSType)
1340     return LHSType;
1341 
1342   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1343   // The caller can deal with this (e.g. pointer + int).
1344   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1345     return QualType();
1346 
1347   // Apply unary and bitfield promotions to the LHS's type.
1348   QualType LHSUnpromotedType = LHSType;
1349   if (LHSType->isPromotableIntegerType())
1350     LHSType = Context.getPromotedIntegerType(LHSType);
1351   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1352   if (!LHSBitfieldPromoteTy.isNull())
1353     LHSType = LHSBitfieldPromoteTy;
1354   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1355     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1356 
1357   // If both types are identical, no conversion is needed.
1358   if (LHSType == RHSType)
1359     return LHSType;
1360 
1361   // At this point, we have two different arithmetic types.
1362 
1363   // Diagnose attempts to convert between __float128 and long double where
1364   // such conversions currently can't be handled.
1365   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1366     return QualType();
1367 
1368   // Handle complex types first (C99 6.3.1.8p1).
1369   if (LHSType->isComplexType() || RHSType->isComplexType())
1370     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1371                                         IsCompAssign);
1372 
1373   // Now handle "real" floating types (i.e. float, double, long double).
1374   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1375     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1376                                  IsCompAssign);
1377 
1378   // Handle GCC complex int extension.
1379   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1380     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1381                                       IsCompAssign);
1382 
1383   // Finally, we have two differing integer types.
1384   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1385            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1386 }
1387 
1388 
1389 //===----------------------------------------------------------------------===//
1390 //  Semantic Analysis for various Expression Types
1391 //===----------------------------------------------------------------------===//
1392 
1393 
1394 ExprResult
1395 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1396                                 SourceLocation DefaultLoc,
1397                                 SourceLocation RParenLoc,
1398                                 Expr *ControllingExpr,
1399                                 ArrayRef<ParsedType> ArgTypes,
1400                                 ArrayRef<Expr *> ArgExprs) {
1401   unsigned NumAssocs = ArgTypes.size();
1402   assert(NumAssocs == ArgExprs.size());
1403 
1404   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1405   for (unsigned i = 0; i < NumAssocs; ++i) {
1406     if (ArgTypes[i])
1407       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1408     else
1409       Types[i] = nullptr;
1410   }
1411 
1412   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1413                                              ControllingExpr,
1414                                              llvm::makeArrayRef(Types, NumAssocs),
1415                                              ArgExprs);
1416   delete [] Types;
1417   return ER;
1418 }
1419 
1420 ExprResult
1421 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1422                                  SourceLocation DefaultLoc,
1423                                  SourceLocation RParenLoc,
1424                                  Expr *ControllingExpr,
1425                                  ArrayRef<TypeSourceInfo *> Types,
1426                                  ArrayRef<Expr *> Exprs) {
1427   unsigned NumAssocs = Types.size();
1428   assert(NumAssocs == Exprs.size());
1429 
1430   // Decay and strip qualifiers for the controlling expression type, and handle
1431   // placeholder type replacement. See committee discussion from WG14 DR423.
1432   {
1433     EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
1434     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1435     if (R.isInvalid())
1436       return ExprError();
1437     ControllingExpr = R.get();
1438   }
1439 
1440   // The controlling expression is an unevaluated operand, so side effects are
1441   // likely unintended.
1442   if (ActiveTemplateInstantiations.empty() &&
1443       ControllingExpr->HasSideEffects(Context, false))
1444     Diag(ControllingExpr->getExprLoc(),
1445          diag::warn_side_effects_unevaluated_context);
1446 
1447   bool TypeErrorFound = false,
1448        IsResultDependent = ControllingExpr->isTypeDependent(),
1449        ContainsUnexpandedParameterPack
1450          = ControllingExpr->containsUnexpandedParameterPack();
1451 
1452   for (unsigned i = 0; i < NumAssocs; ++i) {
1453     if (Exprs[i]->containsUnexpandedParameterPack())
1454       ContainsUnexpandedParameterPack = true;
1455 
1456     if (Types[i]) {
1457       if (Types[i]->getType()->containsUnexpandedParameterPack())
1458         ContainsUnexpandedParameterPack = true;
1459 
1460       if (Types[i]->getType()->isDependentType()) {
1461         IsResultDependent = true;
1462       } else {
1463         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1464         // complete object type other than a variably modified type."
1465         unsigned D = 0;
1466         if (Types[i]->getType()->isIncompleteType())
1467           D = diag::err_assoc_type_incomplete;
1468         else if (!Types[i]->getType()->isObjectType())
1469           D = diag::err_assoc_type_nonobject;
1470         else if (Types[i]->getType()->isVariablyModifiedType())
1471           D = diag::err_assoc_type_variably_modified;
1472 
1473         if (D != 0) {
1474           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1475             << Types[i]->getTypeLoc().getSourceRange()
1476             << Types[i]->getType();
1477           TypeErrorFound = true;
1478         }
1479 
1480         // C11 6.5.1.1p2 "No two generic associations in the same generic
1481         // selection shall specify compatible types."
1482         for (unsigned j = i+1; j < NumAssocs; ++j)
1483           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1484               Context.typesAreCompatible(Types[i]->getType(),
1485                                          Types[j]->getType())) {
1486             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1487                  diag::err_assoc_compatible_types)
1488               << Types[j]->getTypeLoc().getSourceRange()
1489               << Types[j]->getType()
1490               << Types[i]->getType();
1491             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1492                  diag::note_compat_assoc)
1493               << Types[i]->getTypeLoc().getSourceRange()
1494               << Types[i]->getType();
1495             TypeErrorFound = true;
1496           }
1497       }
1498     }
1499   }
1500   if (TypeErrorFound)
1501     return ExprError();
1502 
1503   // If we determined that the generic selection is result-dependent, don't
1504   // try to compute the result expression.
1505   if (IsResultDependent)
1506     return new (Context) GenericSelectionExpr(
1507         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1508         ContainsUnexpandedParameterPack);
1509 
1510   SmallVector<unsigned, 1> CompatIndices;
1511   unsigned DefaultIndex = -1U;
1512   for (unsigned i = 0; i < NumAssocs; ++i) {
1513     if (!Types[i])
1514       DefaultIndex = i;
1515     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1516                                         Types[i]->getType()))
1517       CompatIndices.push_back(i);
1518   }
1519 
1520   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1521   // type compatible with at most one of the types named in its generic
1522   // association list."
1523   if (CompatIndices.size() > 1) {
1524     // We strip parens here because the controlling expression is typically
1525     // parenthesized in macro definitions.
1526     ControllingExpr = ControllingExpr->IgnoreParens();
1527     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1528       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1529       << (unsigned) CompatIndices.size();
1530     for (unsigned I : CompatIndices) {
1531       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1532            diag::note_compat_assoc)
1533         << Types[I]->getTypeLoc().getSourceRange()
1534         << Types[I]->getType();
1535     }
1536     return ExprError();
1537   }
1538 
1539   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1540   // its controlling expression shall have type compatible with exactly one of
1541   // the types named in its generic association list."
1542   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1543     // We strip parens here because the controlling expression is typically
1544     // parenthesized in macro definitions.
1545     ControllingExpr = ControllingExpr->IgnoreParens();
1546     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1547       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1548     return ExprError();
1549   }
1550 
1551   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1552   // type name that is compatible with the type of the controlling expression,
1553   // then the result expression of the generic selection is the expression
1554   // in that generic association. Otherwise, the result expression of the
1555   // generic selection is the expression in the default generic association."
1556   unsigned ResultIndex =
1557     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1558 
1559   return new (Context) GenericSelectionExpr(
1560       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1561       ContainsUnexpandedParameterPack, ResultIndex);
1562 }
1563 
1564 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1565 /// location of the token and the offset of the ud-suffix within it.
1566 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1567                                      unsigned Offset) {
1568   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1569                                         S.getLangOpts());
1570 }
1571 
1572 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1573 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1574 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1575                                                  IdentifierInfo *UDSuffix,
1576                                                  SourceLocation UDSuffixLoc,
1577                                                  ArrayRef<Expr*> Args,
1578                                                  SourceLocation LitEndLoc) {
1579   assert(Args.size() <= 2 && "too many arguments for literal operator");
1580 
1581   QualType ArgTy[2];
1582   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1583     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1584     if (ArgTy[ArgIdx]->isArrayType())
1585       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1586   }
1587 
1588   DeclarationName OpName =
1589     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1590   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1591   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1592 
1593   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1594   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1595                               /*AllowRaw*/false, /*AllowTemplate*/false,
1596                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1597     return ExprError();
1598 
1599   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1600 }
1601 
1602 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1603 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1604 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1605 /// multiple tokens.  However, the common case is that StringToks points to one
1606 /// string.
1607 ///
1608 ExprResult
1609 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1610   assert(!StringToks.empty() && "Must have at least one string!");
1611 
1612   StringLiteralParser Literal(StringToks, PP);
1613   if (Literal.hadError)
1614     return ExprError();
1615 
1616   SmallVector<SourceLocation, 4> StringTokLocs;
1617   for (const Token &Tok : StringToks)
1618     StringTokLocs.push_back(Tok.getLocation());
1619 
1620   QualType CharTy = Context.CharTy;
1621   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1622   if (Literal.isWide()) {
1623     CharTy = Context.getWideCharType();
1624     Kind = StringLiteral::Wide;
1625   } else if (Literal.isUTF8()) {
1626     Kind = StringLiteral::UTF8;
1627   } else if (Literal.isUTF16()) {
1628     CharTy = Context.Char16Ty;
1629     Kind = StringLiteral::UTF16;
1630   } else if (Literal.isUTF32()) {
1631     CharTy = Context.Char32Ty;
1632     Kind = StringLiteral::UTF32;
1633   } else if (Literal.isPascal()) {
1634     CharTy = Context.UnsignedCharTy;
1635   }
1636 
1637   QualType CharTyConst = CharTy;
1638   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1639   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1640     CharTyConst.addConst();
1641 
1642   // Get an array type for the string, according to C99 6.4.5.  This includes
1643   // the nul terminator character as well as the string length for pascal
1644   // strings.
1645   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1646                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1647                                  ArrayType::Normal, 0);
1648 
1649   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1650   if (getLangOpts().OpenCL) {
1651     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1652   }
1653 
1654   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1655   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1656                                              Kind, Literal.Pascal, StrTy,
1657                                              &StringTokLocs[0],
1658                                              StringTokLocs.size());
1659   if (Literal.getUDSuffix().empty())
1660     return Lit;
1661 
1662   // We're building a user-defined literal.
1663   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1664   SourceLocation UDSuffixLoc =
1665     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1666                    Literal.getUDSuffixOffset());
1667 
1668   // Make sure we're allowed user-defined literals here.
1669   if (!UDLScope)
1670     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1671 
1672   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1673   //   operator "" X (str, len)
1674   QualType SizeType = Context.getSizeType();
1675 
1676   DeclarationName OpName =
1677     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1678   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1679   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1680 
1681   QualType ArgTy[] = {
1682     Context.getArrayDecayedType(StrTy), SizeType
1683   };
1684 
1685   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1686   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1687                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1688                                 /*AllowStringTemplate*/true)) {
1689 
1690   case LOLR_Cooked: {
1691     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1692     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1693                                                     StringTokLocs[0]);
1694     Expr *Args[] = { Lit, LenArg };
1695 
1696     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1697   }
1698 
1699   case LOLR_StringTemplate: {
1700     TemplateArgumentListInfo ExplicitArgs;
1701 
1702     unsigned CharBits = Context.getIntWidth(CharTy);
1703     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1704     llvm::APSInt Value(CharBits, CharIsUnsigned);
1705 
1706     TemplateArgument TypeArg(CharTy);
1707     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1708     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1709 
1710     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1711       Value = Lit->getCodeUnit(I);
1712       TemplateArgument Arg(Context, Value, CharTy);
1713       TemplateArgumentLocInfo ArgInfo;
1714       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1715     }
1716     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1717                                     &ExplicitArgs);
1718   }
1719   case LOLR_Raw:
1720   case LOLR_Template:
1721     llvm_unreachable("unexpected literal operator lookup result");
1722   case LOLR_Error:
1723     return ExprError();
1724   }
1725   llvm_unreachable("unexpected literal operator lookup result");
1726 }
1727 
1728 ExprResult
1729 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1730                        SourceLocation Loc,
1731                        const CXXScopeSpec *SS) {
1732   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1733   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1734 }
1735 
1736 /// BuildDeclRefExpr - Build an expression that references a
1737 /// declaration that does not require a closure capture.
1738 ExprResult
1739 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1740                        const DeclarationNameInfo &NameInfo,
1741                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1742                        const TemplateArgumentListInfo *TemplateArgs) {
1743   if (getLangOpts().CUDA)
1744     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1745       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1746         if (CheckCUDATarget(Caller, Callee)) {
1747           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1748             << IdentifyCUDATarget(Callee) << D->getIdentifier()
1749             << IdentifyCUDATarget(Caller);
1750           Diag(D->getLocation(), diag::note_previous_decl)
1751             << D->getIdentifier();
1752           return ExprError();
1753         }
1754       }
1755 
1756   bool RefersToCapturedVariable =
1757       isa<VarDecl>(D) &&
1758       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1759 
1760   DeclRefExpr *E;
1761   if (isa<VarTemplateSpecializationDecl>(D)) {
1762     VarTemplateSpecializationDecl *VarSpec =
1763         cast<VarTemplateSpecializationDecl>(D);
1764 
1765     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1766                                         : NestedNameSpecifierLoc(),
1767                             VarSpec->getTemplateKeywordLoc(), D,
1768                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1769                             FoundD, TemplateArgs);
1770   } else {
1771     assert(!TemplateArgs && "No template arguments for non-variable"
1772                             " template specialization references");
1773     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1774                                         : NestedNameSpecifierLoc(),
1775                             SourceLocation(), D, RefersToCapturedVariable,
1776                             NameInfo, Ty, VK, FoundD);
1777   }
1778 
1779   MarkDeclRefReferenced(E);
1780 
1781   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1782       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1783       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1784       recordUseOfEvaluatedWeak(E);
1785 
1786   if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1787     UnusedPrivateFields.remove(FD);
1788     // Just in case we're building an illegal pointer-to-member.
1789     if (FD->isBitField())
1790       E->setObjectKind(OK_BitField);
1791   }
1792 
1793   return E;
1794 }
1795 
1796 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1797 /// possibly a list of template arguments.
1798 ///
1799 /// If this produces template arguments, it is permitted to call
1800 /// DecomposeTemplateName.
1801 ///
1802 /// This actually loses a lot of source location information for
1803 /// non-standard name kinds; we should consider preserving that in
1804 /// some way.
1805 void
1806 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1807                              TemplateArgumentListInfo &Buffer,
1808                              DeclarationNameInfo &NameInfo,
1809                              const TemplateArgumentListInfo *&TemplateArgs) {
1810   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1811     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1812     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1813 
1814     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1815                                        Id.TemplateId->NumArgs);
1816     translateTemplateArguments(TemplateArgsPtr, Buffer);
1817 
1818     TemplateName TName = Id.TemplateId->Template.get();
1819     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1820     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1821     TemplateArgs = &Buffer;
1822   } else {
1823     NameInfo = GetNameFromUnqualifiedId(Id);
1824     TemplateArgs = nullptr;
1825   }
1826 }
1827 
1828 static void emitEmptyLookupTypoDiagnostic(
1829     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1830     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1831     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1832   DeclContext *Ctx =
1833       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1834   if (!TC) {
1835     // Emit a special diagnostic for failed member lookups.
1836     // FIXME: computing the declaration context might fail here (?)
1837     if (Ctx)
1838       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1839                                                  << SS.getRange();
1840     else
1841       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1842     return;
1843   }
1844 
1845   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1846   bool DroppedSpecifier =
1847       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1848   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1849                         ? diag::note_implicit_param_decl
1850                         : diag::note_previous_decl;
1851   if (!Ctx)
1852     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1853                          SemaRef.PDiag(NoteID));
1854   else
1855     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1856                                  << Typo << Ctx << DroppedSpecifier
1857                                  << SS.getRange(),
1858                          SemaRef.PDiag(NoteID));
1859 }
1860 
1861 /// Diagnose an empty lookup.
1862 ///
1863 /// \return false if new lookup candidates were found
1864 bool
1865 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1866                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1867                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1868                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1869   DeclarationName Name = R.getLookupName();
1870 
1871   unsigned diagnostic = diag::err_undeclared_var_use;
1872   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1873   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1874       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1875       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1876     diagnostic = diag::err_undeclared_use;
1877     diagnostic_suggest = diag::err_undeclared_use_suggest;
1878   }
1879 
1880   // If the original lookup was an unqualified lookup, fake an
1881   // unqualified lookup.  This is useful when (for example) the
1882   // original lookup would not have found something because it was a
1883   // dependent name.
1884   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1885   while (DC) {
1886     if (isa<CXXRecordDecl>(DC)) {
1887       LookupQualifiedName(R, DC);
1888 
1889       if (!R.empty()) {
1890         // Don't give errors about ambiguities in this lookup.
1891         R.suppressDiagnostics();
1892 
1893         // During a default argument instantiation the CurContext points
1894         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1895         // function parameter list, hence add an explicit check.
1896         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1897                               ActiveTemplateInstantiations.back().Kind ==
1898             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1899         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1900         bool isInstance = CurMethod &&
1901                           CurMethod->isInstance() &&
1902                           DC == CurMethod->getParent() && !isDefaultArgument;
1903 
1904         // Give a code modification hint to insert 'this->'.
1905         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1906         // Actually quite difficult!
1907         if (getLangOpts().MSVCCompat)
1908           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1909         if (isInstance) {
1910           Diag(R.getNameLoc(), diagnostic) << Name
1911             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1912           CheckCXXThisCapture(R.getNameLoc());
1913         } else {
1914           Diag(R.getNameLoc(), diagnostic) << Name;
1915         }
1916 
1917         // Do we really want to note all of these?
1918         for (NamedDecl *D : R)
1919           Diag(D->getLocation(), diag::note_dependent_var_use);
1920 
1921         // Return true if we are inside a default argument instantiation
1922         // and the found name refers to an instance member function, otherwise
1923         // the function calling DiagnoseEmptyLookup will try to create an
1924         // implicit member call and this is wrong for default argument.
1925         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1926           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1927           return true;
1928         }
1929 
1930         // Tell the callee to try to recover.
1931         return false;
1932       }
1933 
1934       R.clear();
1935     }
1936 
1937     // In Microsoft mode, if we are performing lookup from within a friend
1938     // function definition declared at class scope then we must set
1939     // DC to the lexical parent to be able to search into the parent
1940     // class.
1941     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1942         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1943         DC->getLexicalParent()->isRecord())
1944       DC = DC->getLexicalParent();
1945     else
1946       DC = DC->getParent();
1947   }
1948 
1949   // We didn't find anything, so try to correct for a typo.
1950   TypoCorrection Corrected;
1951   if (S && Out) {
1952     SourceLocation TypoLoc = R.getNameLoc();
1953     assert(!ExplicitTemplateArgs &&
1954            "Diagnosing an empty lookup with explicit template args!");
1955     *Out = CorrectTypoDelayed(
1956         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1957         [=](const TypoCorrection &TC) {
1958           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1959                                         diagnostic, diagnostic_suggest);
1960         },
1961         nullptr, CTK_ErrorRecovery);
1962     if (*Out)
1963       return true;
1964   } else if (S && (Corrected =
1965                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1966                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1967     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1968     bool DroppedSpecifier =
1969         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1970     R.setLookupName(Corrected.getCorrection());
1971 
1972     bool AcceptableWithRecovery = false;
1973     bool AcceptableWithoutRecovery = false;
1974     NamedDecl *ND = Corrected.getFoundDecl();
1975     if (ND) {
1976       if (Corrected.isOverloaded()) {
1977         OverloadCandidateSet OCS(R.getNameLoc(),
1978                                  OverloadCandidateSet::CSK_Normal);
1979         OverloadCandidateSet::iterator Best;
1980         for (NamedDecl *CD : Corrected) {
1981           if (FunctionTemplateDecl *FTD =
1982                    dyn_cast<FunctionTemplateDecl>(CD))
1983             AddTemplateOverloadCandidate(
1984                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1985                 Args, OCS);
1986           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1987             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1988               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1989                                    Args, OCS);
1990         }
1991         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1992         case OR_Success:
1993           ND = Best->FoundDecl;
1994           Corrected.setCorrectionDecl(ND);
1995           break;
1996         default:
1997           // FIXME: Arbitrarily pick the first declaration for the note.
1998           Corrected.setCorrectionDecl(ND);
1999           break;
2000         }
2001       }
2002       R.addDecl(ND);
2003       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2004         CXXRecordDecl *Record = nullptr;
2005         if (Corrected.getCorrectionSpecifier()) {
2006           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2007           Record = Ty->getAsCXXRecordDecl();
2008         }
2009         if (!Record)
2010           Record = cast<CXXRecordDecl>(
2011               ND->getDeclContext()->getRedeclContext());
2012         R.setNamingClass(Record);
2013       }
2014 
2015       auto *UnderlyingND = ND->getUnderlyingDecl();
2016       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2017                                isa<FunctionTemplateDecl>(UnderlyingND);
2018       // FIXME: If we ended up with a typo for a type name or
2019       // Objective-C class name, we're in trouble because the parser
2020       // is in the wrong place to recover. Suggest the typo
2021       // correction, but don't make it a fix-it since we're not going
2022       // to recover well anyway.
2023       AcceptableWithoutRecovery =
2024           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2025     } else {
2026       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2027       // because we aren't able to recover.
2028       AcceptableWithoutRecovery = true;
2029     }
2030 
2031     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2032       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2033                             ? diag::note_implicit_param_decl
2034                             : diag::note_previous_decl;
2035       if (SS.isEmpty())
2036         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2037                      PDiag(NoteID), AcceptableWithRecovery);
2038       else
2039         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2040                                   << Name << computeDeclContext(SS, false)
2041                                   << DroppedSpecifier << SS.getRange(),
2042                      PDiag(NoteID), AcceptableWithRecovery);
2043 
2044       // Tell the callee whether to try to recover.
2045       return !AcceptableWithRecovery;
2046     }
2047   }
2048   R.clear();
2049 
2050   // Emit a special diagnostic for failed member lookups.
2051   // FIXME: computing the declaration context might fail here (?)
2052   if (!SS.isEmpty()) {
2053     Diag(R.getNameLoc(), diag::err_no_member)
2054       << Name << computeDeclContext(SS, false)
2055       << SS.getRange();
2056     return true;
2057   }
2058 
2059   // Give up, we can't recover.
2060   Diag(R.getNameLoc(), diagnostic) << Name;
2061   return true;
2062 }
2063 
2064 /// In Microsoft mode, if we are inside a template class whose parent class has
2065 /// dependent base classes, and we can't resolve an unqualified identifier, then
2066 /// assume the identifier is a member of a dependent base class.  We can only
2067 /// recover successfully in static methods, instance methods, and other contexts
2068 /// where 'this' is available.  This doesn't precisely match MSVC's
2069 /// instantiation model, but it's close enough.
2070 static Expr *
2071 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2072                                DeclarationNameInfo &NameInfo,
2073                                SourceLocation TemplateKWLoc,
2074                                const TemplateArgumentListInfo *TemplateArgs) {
2075   // Only try to recover from lookup into dependent bases in static methods or
2076   // contexts where 'this' is available.
2077   QualType ThisType = S.getCurrentThisType();
2078   const CXXRecordDecl *RD = nullptr;
2079   if (!ThisType.isNull())
2080     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2081   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2082     RD = MD->getParent();
2083   if (!RD || !RD->hasAnyDependentBases())
2084     return nullptr;
2085 
2086   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2087   // is available, suggest inserting 'this->' as a fixit.
2088   SourceLocation Loc = NameInfo.getLoc();
2089   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2090   DB << NameInfo.getName() << RD;
2091 
2092   if (!ThisType.isNull()) {
2093     DB << FixItHint::CreateInsertion(Loc, "this->");
2094     return CXXDependentScopeMemberExpr::Create(
2095         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2096         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2097         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2098   }
2099 
2100   // Synthesize a fake NNS that points to the derived class.  This will
2101   // perform name lookup during template instantiation.
2102   CXXScopeSpec SS;
2103   auto *NNS =
2104       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2105   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2106   return DependentScopeDeclRefExpr::Create(
2107       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2108       TemplateArgs);
2109 }
2110 
2111 ExprResult
2112 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2113                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2114                         bool HasTrailingLParen, bool IsAddressOfOperand,
2115                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2116                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2117   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2118          "cannot be direct & operand and have a trailing lparen");
2119   if (SS.isInvalid())
2120     return ExprError();
2121 
2122   TemplateArgumentListInfo TemplateArgsBuffer;
2123 
2124   // Decompose the UnqualifiedId into the following data.
2125   DeclarationNameInfo NameInfo;
2126   const TemplateArgumentListInfo *TemplateArgs;
2127   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2128 
2129   DeclarationName Name = NameInfo.getName();
2130   IdentifierInfo *II = Name.getAsIdentifierInfo();
2131   SourceLocation NameLoc = NameInfo.getLoc();
2132 
2133   // C++ [temp.dep.expr]p3:
2134   //   An id-expression is type-dependent if it contains:
2135   //     -- an identifier that was declared with a dependent type,
2136   //        (note: handled after lookup)
2137   //     -- a template-id that is dependent,
2138   //        (note: handled in BuildTemplateIdExpr)
2139   //     -- a conversion-function-id that specifies a dependent type,
2140   //     -- a nested-name-specifier that contains a class-name that
2141   //        names a dependent type.
2142   // Determine whether this is a member of an unknown specialization;
2143   // we need to handle these differently.
2144   bool DependentID = false;
2145   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2146       Name.getCXXNameType()->isDependentType()) {
2147     DependentID = true;
2148   } else if (SS.isSet()) {
2149     if (DeclContext *DC = computeDeclContext(SS, false)) {
2150       if (RequireCompleteDeclContext(SS, DC))
2151         return ExprError();
2152     } else {
2153       DependentID = true;
2154     }
2155   }
2156 
2157   if (DependentID)
2158     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2159                                       IsAddressOfOperand, TemplateArgs);
2160 
2161   // Perform the required lookup.
2162   LookupResult R(*this, NameInfo,
2163                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2164                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2165   if (TemplateArgs) {
2166     // Lookup the template name again to correctly establish the context in
2167     // which it was found. This is really unfortunate as we already did the
2168     // lookup to determine that it was a template name in the first place. If
2169     // this becomes a performance hit, we can work harder to preserve those
2170     // results until we get here but it's likely not worth it.
2171     bool MemberOfUnknownSpecialization;
2172     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2173                        MemberOfUnknownSpecialization);
2174 
2175     if (MemberOfUnknownSpecialization ||
2176         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2177       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2178                                         IsAddressOfOperand, TemplateArgs);
2179   } else {
2180     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2181     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2182 
2183     // If the result might be in a dependent base class, this is a dependent
2184     // id-expression.
2185     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2186       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2187                                         IsAddressOfOperand, TemplateArgs);
2188 
2189     // If this reference is in an Objective-C method, then we need to do
2190     // some special Objective-C lookup, too.
2191     if (IvarLookupFollowUp) {
2192       ExprResult E(LookupInObjCMethod(R, S, II, true));
2193       if (E.isInvalid())
2194         return ExprError();
2195 
2196       if (Expr *Ex = E.getAs<Expr>())
2197         return Ex;
2198     }
2199   }
2200 
2201   if (R.isAmbiguous())
2202     return ExprError();
2203 
2204   // This could be an implicitly declared function reference (legal in C90,
2205   // extension in C99, forbidden in C++).
2206   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2207     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2208     if (D) R.addDecl(D);
2209   }
2210 
2211   // Determine whether this name might be a candidate for
2212   // argument-dependent lookup.
2213   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2214 
2215   if (R.empty() && !ADL) {
2216     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2217       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2218                                                    TemplateKWLoc, TemplateArgs))
2219         return E;
2220     }
2221 
2222     // Don't diagnose an empty lookup for inline assembly.
2223     if (IsInlineAsmIdentifier)
2224       return ExprError();
2225 
2226     // If this name wasn't predeclared and if this is not a function
2227     // call, diagnose the problem.
2228     TypoExpr *TE = nullptr;
2229     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2230         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2231     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2232     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2233            "Typo correction callback misconfigured");
2234     if (CCC) {
2235       // Make sure the callback knows what the typo being diagnosed is.
2236       CCC->setTypoName(II);
2237       if (SS.isValid())
2238         CCC->setTypoNNS(SS.getScopeRep());
2239     }
2240     if (DiagnoseEmptyLookup(S, SS, R,
2241                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2242                             nullptr, None, &TE)) {
2243       if (TE && KeywordReplacement) {
2244         auto &State = getTypoExprState(TE);
2245         auto BestTC = State.Consumer->getNextCorrection();
2246         if (BestTC.isKeyword()) {
2247           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2248           if (State.DiagHandler)
2249             State.DiagHandler(BestTC);
2250           KeywordReplacement->startToken();
2251           KeywordReplacement->setKind(II->getTokenID());
2252           KeywordReplacement->setIdentifierInfo(II);
2253           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2254           // Clean up the state associated with the TypoExpr, since it has
2255           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2256           clearDelayedTypo(TE);
2257           // Signal that a correction to a keyword was performed by returning a
2258           // valid-but-null ExprResult.
2259           return (Expr*)nullptr;
2260         }
2261         State.Consumer->resetCorrectionStream();
2262       }
2263       return TE ? TE : ExprError();
2264     }
2265 
2266     assert(!R.empty() &&
2267            "DiagnoseEmptyLookup returned false but added no results");
2268 
2269     // If we found an Objective-C instance variable, let
2270     // LookupInObjCMethod build the appropriate expression to
2271     // reference the ivar.
2272     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2273       R.clear();
2274       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2275       // In a hopelessly buggy code, Objective-C instance variable
2276       // lookup fails and no expression will be built to reference it.
2277       if (!E.isInvalid() && !E.get())
2278         return ExprError();
2279       return E;
2280     }
2281   }
2282 
2283   // This is guaranteed from this point on.
2284   assert(!R.empty() || ADL);
2285 
2286   // Check whether this might be a C++ implicit instance member access.
2287   // C++ [class.mfct.non-static]p3:
2288   //   When an id-expression that is not part of a class member access
2289   //   syntax and not used to form a pointer to member is used in the
2290   //   body of a non-static member function of class X, if name lookup
2291   //   resolves the name in the id-expression to a non-static non-type
2292   //   member of some class C, the id-expression is transformed into a
2293   //   class member access expression using (*this) as the
2294   //   postfix-expression to the left of the . operator.
2295   //
2296   // But we don't actually need to do this for '&' operands if R
2297   // resolved to a function or overloaded function set, because the
2298   // expression is ill-formed if it actually works out to be a
2299   // non-static member function:
2300   //
2301   // C++ [expr.ref]p4:
2302   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2303   //   [t]he expression can be used only as the left-hand operand of a
2304   //   member function call.
2305   //
2306   // There are other safeguards against such uses, but it's important
2307   // to get this right here so that we don't end up making a
2308   // spuriously dependent expression if we're inside a dependent
2309   // instance method.
2310   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2311     bool MightBeImplicitMember;
2312     if (!IsAddressOfOperand)
2313       MightBeImplicitMember = true;
2314     else if (!SS.isEmpty())
2315       MightBeImplicitMember = false;
2316     else if (R.isOverloadedResult())
2317       MightBeImplicitMember = false;
2318     else if (R.isUnresolvableResult())
2319       MightBeImplicitMember = true;
2320     else
2321       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2322                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2323                               isa<MSPropertyDecl>(R.getFoundDecl());
2324 
2325     if (MightBeImplicitMember)
2326       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2327                                              R, TemplateArgs, S);
2328   }
2329 
2330   if (TemplateArgs || TemplateKWLoc.isValid()) {
2331 
2332     // In C++1y, if this is a variable template id, then check it
2333     // in BuildTemplateIdExpr().
2334     // The single lookup result must be a variable template declaration.
2335     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2336         Id.TemplateId->Kind == TNK_Var_template) {
2337       assert(R.getAsSingle<VarTemplateDecl>() &&
2338              "There should only be one declaration found.");
2339     }
2340 
2341     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2342   }
2343 
2344   return BuildDeclarationNameExpr(SS, R, ADL);
2345 }
2346 
2347 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2348 /// declaration name, generally during template instantiation.
2349 /// There's a large number of things which don't need to be done along
2350 /// this path.
2351 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2352     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2353     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2354   DeclContext *DC = computeDeclContext(SS, false);
2355   if (!DC)
2356     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2357                                      NameInfo, /*TemplateArgs=*/nullptr);
2358 
2359   if (RequireCompleteDeclContext(SS, DC))
2360     return ExprError();
2361 
2362   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2363   LookupQualifiedName(R, DC);
2364 
2365   if (R.isAmbiguous())
2366     return ExprError();
2367 
2368   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2369     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2370                                      NameInfo, /*TemplateArgs=*/nullptr);
2371 
2372   if (R.empty()) {
2373     Diag(NameInfo.getLoc(), diag::err_no_member)
2374       << NameInfo.getName() << DC << SS.getRange();
2375     return ExprError();
2376   }
2377 
2378   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2379     // Diagnose a missing typename if this resolved unambiguously to a type in
2380     // a dependent context.  If we can recover with a type, downgrade this to
2381     // a warning in Microsoft compatibility mode.
2382     unsigned DiagID = diag::err_typename_missing;
2383     if (RecoveryTSI && getLangOpts().MSVCCompat)
2384       DiagID = diag::ext_typename_missing;
2385     SourceLocation Loc = SS.getBeginLoc();
2386     auto D = Diag(Loc, DiagID);
2387     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2388       << SourceRange(Loc, NameInfo.getEndLoc());
2389 
2390     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2391     // context.
2392     if (!RecoveryTSI)
2393       return ExprError();
2394 
2395     // Only issue the fixit if we're prepared to recover.
2396     D << FixItHint::CreateInsertion(Loc, "typename ");
2397 
2398     // Recover by pretending this was an elaborated type.
2399     QualType Ty = Context.getTypeDeclType(TD);
2400     TypeLocBuilder TLB;
2401     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2402 
2403     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2404     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2405     QTL.setElaboratedKeywordLoc(SourceLocation());
2406     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2407 
2408     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2409 
2410     return ExprEmpty();
2411   }
2412 
2413   // Defend against this resolving to an implicit member access. We usually
2414   // won't get here if this might be a legitimate a class member (we end up in
2415   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2416   // a pointer-to-member or in an unevaluated context in C++11.
2417   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2418     return BuildPossibleImplicitMemberExpr(SS,
2419                                            /*TemplateKWLoc=*/SourceLocation(),
2420                                            R, /*TemplateArgs=*/nullptr, S);
2421 
2422   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2423 }
2424 
2425 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2426 /// detected that we're currently inside an ObjC method.  Perform some
2427 /// additional lookup.
2428 ///
2429 /// Ideally, most of this would be done by lookup, but there's
2430 /// actually quite a lot of extra work involved.
2431 ///
2432 /// Returns a null sentinel to indicate trivial success.
2433 ExprResult
2434 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2435                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2436   SourceLocation Loc = Lookup.getNameLoc();
2437   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2438 
2439   // Check for error condition which is already reported.
2440   if (!CurMethod)
2441     return ExprError();
2442 
2443   // There are two cases to handle here.  1) scoped lookup could have failed,
2444   // in which case we should look for an ivar.  2) scoped lookup could have
2445   // found a decl, but that decl is outside the current instance method (i.e.
2446   // a global variable).  In these two cases, we do a lookup for an ivar with
2447   // this name, if the lookup sucedes, we replace it our current decl.
2448 
2449   // If we're in a class method, we don't normally want to look for
2450   // ivars.  But if we don't find anything else, and there's an
2451   // ivar, that's an error.
2452   bool IsClassMethod = CurMethod->isClassMethod();
2453 
2454   bool LookForIvars;
2455   if (Lookup.empty())
2456     LookForIvars = true;
2457   else if (IsClassMethod)
2458     LookForIvars = false;
2459   else
2460     LookForIvars = (Lookup.isSingleResult() &&
2461                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2462   ObjCInterfaceDecl *IFace = nullptr;
2463   if (LookForIvars) {
2464     IFace = CurMethod->getClassInterface();
2465     ObjCInterfaceDecl *ClassDeclared;
2466     ObjCIvarDecl *IV = nullptr;
2467     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2468       // Diagnose using an ivar in a class method.
2469       if (IsClassMethod)
2470         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2471                          << IV->getDeclName());
2472 
2473       // If we're referencing an invalid decl, just return this as a silent
2474       // error node.  The error diagnostic was already emitted on the decl.
2475       if (IV->isInvalidDecl())
2476         return ExprError();
2477 
2478       // Check if referencing a field with __attribute__((deprecated)).
2479       if (DiagnoseUseOfDecl(IV, Loc))
2480         return ExprError();
2481 
2482       // Diagnose the use of an ivar outside of the declaring class.
2483       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2484           !declaresSameEntity(ClassDeclared, IFace) &&
2485           !getLangOpts().DebuggerSupport)
2486         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2487 
2488       // FIXME: This should use a new expr for a direct reference, don't
2489       // turn this into Self->ivar, just return a BareIVarExpr or something.
2490       IdentifierInfo &II = Context.Idents.get("self");
2491       UnqualifiedId SelfName;
2492       SelfName.setIdentifier(&II, SourceLocation());
2493       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2494       CXXScopeSpec SelfScopeSpec;
2495       SourceLocation TemplateKWLoc;
2496       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2497                                               SelfName, false, false);
2498       if (SelfExpr.isInvalid())
2499         return ExprError();
2500 
2501       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2502       if (SelfExpr.isInvalid())
2503         return ExprError();
2504 
2505       MarkAnyDeclReferenced(Loc, IV, true);
2506 
2507       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2508       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2509           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2510         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2511 
2512       ObjCIvarRefExpr *Result = new (Context)
2513           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2514                           IV->getLocation(), SelfExpr.get(), true, true);
2515 
2516       if (getLangOpts().ObjCAutoRefCount) {
2517         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2518           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2519             recordUseOfEvaluatedWeak(Result);
2520         }
2521         if (CurContext->isClosure())
2522           Diag(Loc, diag::warn_implicitly_retains_self)
2523             << FixItHint::CreateInsertion(Loc, "self->");
2524       }
2525 
2526       return Result;
2527     }
2528   } else if (CurMethod->isInstanceMethod()) {
2529     // We should warn if a local variable hides an ivar.
2530     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2531       ObjCInterfaceDecl *ClassDeclared;
2532       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2533         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2534             declaresSameEntity(IFace, ClassDeclared))
2535           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2536       }
2537     }
2538   } else if (Lookup.isSingleResult() &&
2539              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2540     // If accessing a stand-alone ivar in a class method, this is an error.
2541     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2542       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2543                        << IV->getDeclName());
2544   }
2545 
2546   if (Lookup.empty() && II && AllowBuiltinCreation) {
2547     // FIXME. Consolidate this with similar code in LookupName.
2548     if (unsigned BuiltinID = II->getBuiltinID()) {
2549       if (!(getLangOpts().CPlusPlus &&
2550             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2551         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2552                                            S, Lookup.isForRedeclaration(),
2553                                            Lookup.getNameLoc());
2554         if (D) Lookup.addDecl(D);
2555       }
2556     }
2557   }
2558   // Sentinel value saying that we didn't do anything special.
2559   return ExprResult((Expr *)nullptr);
2560 }
2561 
2562 /// \brief Cast a base object to a member's actual type.
2563 ///
2564 /// Logically this happens in three phases:
2565 ///
2566 /// * First we cast from the base type to the naming class.
2567 ///   The naming class is the class into which we were looking
2568 ///   when we found the member;  it's the qualifier type if a
2569 ///   qualifier was provided, and otherwise it's the base type.
2570 ///
2571 /// * Next we cast from the naming class to the declaring class.
2572 ///   If the member we found was brought into a class's scope by
2573 ///   a using declaration, this is that class;  otherwise it's
2574 ///   the class declaring the member.
2575 ///
2576 /// * Finally we cast from the declaring class to the "true"
2577 ///   declaring class of the member.  This conversion does not
2578 ///   obey access control.
2579 ExprResult
2580 Sema::PerformObjectMemberConversion(Expr *From,
2581                                     NestedNameSpecifier *Qualifier,
2582                                     NamedDecl *FoundDecl,
2583                                     NamedDecl *Member) {
2584   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2585   if (!RD)
2586     return From;
2587 
2588   QualType DestRecordType;
2589   QualType DestType;
2590   QualType FromRecordType;
2591   QualType FromType = From->getType();
2592   bool PointerConversions = false;
2593   if (isa<FieldDecl>(Member)) {
2594     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2595 
2596     if (FromType->getAs<PointerType>()) {
2597       DestType = Context.getPointerType(DestRecordType);
2598       FromRecordType = FromType->getPointeeType();
2599       PointerConversions = true;
2600     } else {
2601       DestType = DestRecordType;
2602       FromRecordType = FromType;
2603     }
2604   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2605     if (Method->isStatic())
2606       return From;
2607 
2608     DestType = Method->getThisType(Context);
2609     DestRecordType = DestType->getPointeeType();
2610 
2611     if (FromType->getAs<PointerType>()) {
2612       FromRecordType = FromType->getPointeeType();
2613       PointerConversions = true;
2614     } else {
2615       FromRecordType = FromType;
2616       DestType = DestRecordType;
2617     }
2618   } else {
2619     // No conversion necessary.
2620     return From;
2621   }
2622 
2623   if (DestType->isDependentType() || FromType->isDependentType())
2624     return From;
2625 
2626   // If the unqualified types are the same, no conversion is necessary.
2627   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2628     return From;
2629 
2630   SourceRange FromRange = From->getSourceRange();
2631   SourceLocation FromLoc = FromRange.getBegin();
2632 
2633   ExprValueKind VK = From->getValueKind();
2634 
2635   // C++ [class.member.lookup]p8:
2636   //   [...] Ambiguities can often be resolved by qualifying a name with its
2637   //   class name.
2638   //
2639   // If the member was a qualified name and the qualified referred to a
2640   // specific base subobject type, we'll cast to that intermediate type
2641   // first and then to the object in which the member is declared. That allows
2642   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2643   //
2644   //   class Base { public: int x; };
2645   //   class Derived1 : public Base { };
2646   //   class Derived2 : public Base { };
2647   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2648   //
2649   //   void VeryDerived::f() {
2650   //     x = 17; // error: ambiguous base subobjects
2651   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2652   //   }
2653   if (Qualifier && Qualifier->getAsType()) {
2654     QualType QType = QualType(Qualifier->getAsType(), 0);
2655     assert(QType->isRecordType() && "lookup done with non-record type");
2656 
2657     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2658 
2659     // In C++98, the qualifier type doesn't actually have to be a base
2660     // type of the object type, in which case we just ignore it.
2661     // Otherwise build the appropriate casts.
2662     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2663       CXXCastPath BasePath;
2664       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2665                                        FromLoc, FromRange, &BasePath))
2666         return ExprError();
2667 
2668       if (PointerConversions)
2669         QType = Context.getPointerType(QType);
2670       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2671                                VK, &BasePath).get();
2672 
2673       FromType = QType;
2674       FromRecordType = QRecordType;
2675 
2676       // If the qualifier type was the same as the destination type,
2677       // we're done.
2678       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2679         return From;
2680     }
2681   }
2682 
2683   bool IgnoreAccess = false;
2684 
2685   // If we actually found the member through a using declaration, cast
2686   // down to the using declaration's type.
2687   //
2688   // Pointer equality is fine here because only one declaration of a
2689   // class ever has member declarations.
2690   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2691     assert(isa<UsingShadowDecl>(FoundDecl));
2692     QualType URecordType = Context.getTypeDeclType(
2693                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2694 
2695     // We only need to do this if the naming-class to declaring-class
2696     // conversion is non-trivial.
2697     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2698       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2699       CXXCastPath BasePath;
2700       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2701                                        FromLoc, FromRange, &BasePath))
2702         return ExprError();
2703 
2704       QualType UType = URecordType;
2705       if (PointerConversions)
2706         UType = Context.getPointerType(UType);
2707       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2708                                VK, &BasePath).get();
2709       FromType = UType;
2710       FromRecordType = URecordType;
2711     }
2712 
2713     // We don't do access control for the conversion from the
2714     // declaring class to the true declaring class.
2715     IgnoreAccess = true;
2716   }
2717 
2718   CXXCastPath BasePath;
2719   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2720                                    FromLoc, FromRange, &BasePath,
2721                                    IgnoreAccess))
2722     return ExprError();
2723 
2724   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2725                            VK, &BasePath);
2726 }
2727 
2728 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2729                                       const LookupResult &R,
2730                                       bool HasTrailingLParen) {
2731   // Only when used directly as the postfix-expression of a call.
2732   if (!HasTrailingLParen)
2733     return false;
2734 
2735   // Never if a scope specifier was provided.
2736   if (SS.isSet())
2737     return false;
2738 
2739   // Only in C++ or ObjC++.
2740   if (!getLangOpts().CPlusPlus)
2741     return false;
2742 
2743   // Turn off ADL when we find certain kinds of declarations during
2744   // normal lookup:
2745   for (NamedDecl *D : R) {
2746     // C++0x [basic.lookup.argdep]p3:
2747     //     -- a declaration of a class member
2748     // Since using decls preserve this property, we check this on the
2749     // original decl.
2750     if (D->isCXXClassMember())
2751       return false;
2752 
2753     // C++0x [basic.lookup.argdep]p3:
2754     //     -- a block-scope function declaration that is not a
2755     //        using-declaration
2756     // NOTE: we also trigger this for function templates (in fact, we
2757     // don't check the decl type at all, since all other decl types
2758     // turn off ADL anyway).
2759     if (isa<UsingShadowDecl>(D))
2760       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2761     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2762       return false;
2763 
2764     // C++0x [basic.lookup.argdep]p3:
2765     //     -- a declaration that is neither a function or a function
2766     //        template
2767     // And also for builtin functions.
2768     if (isa<FunctionDecl>(D)) {
2769       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2770 
2771       // But also builtin functions.
2772       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2773         return false;
2774     } else if (!isa<FunctionTemplateDecl>(D))
2775       return false;
2776   }
2777 
2778   return true;
2779 }
2780 
2781 
2782 /// Diagnoses obvious problems with the use of the given declaration
2783 /// as an expression.  This is only actually called for lookups that
2784 /// were not overloaded, and it doesn't promise that the declaration
2785 /// will in fact be used.
2786 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2787   if (isa<TypedefNameDecl>(D)) {
2788     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2789     return true;
2790   }
2791 
2792   if (isa<ObjCInterfaceDecl>(D)) {
2793     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2794     return true;
2795   }
2796 
2797   if (isa<NamespaceDecl>(D)) {
2798     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2799     return true;
2800   }
2801 
2802   return false;
2803 }
2804 
2805 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2806                                           LookupResult &R, bool NeedsADL,
2807                                           bool AcceptInvalidDecl) {
2808   // If this is a single, fully-resolved result and we don't need ADL,
2809   // just build an ordinary singleton decl ref.
2810   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2811     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2812                                     R.getRepresentativeDecl(), nullptr,
2813                                     AcceptInvalidDecl);
2814 
2815   // We only need to check the declaration if there's exactly one
2816   // result, because in the overloaded case the results can only be
2817   // functions and function templates.
2818   if (R.isSingleResult() &&
2819       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2820     return ExprError();
2821 
2822   // Otherwise, just build an unresolved lookup expression.  Suppress
2823   // any lookup-related diagnostics; we'll hash these out later, when
2824   // we've picked a target.
2825   R.suppressDiagnostics();
2826 
2827   UnresolvedLookupExpr *ULE
2828     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2829                                    SS.getWithLocInContext(Context),
2830                                    R.getLookupNameInfo(),
2831                                    NeedsADL, R.isOverloadedResult(),
2832                                    R.begin(), R.end());
2833 
2834   return ULE;
2835 }
2836 
2837 /// \brief Complete semantic analysis for a reference to the given declaration.
2838 ExprResult Sema::BuildDeclarationNameExpr(
2839     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2840     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2841     bool AcceptInvalidDecl) {
2842   assert(D && "Cannot refer to a NULL declaration");
2843   assert(!isa<FunctionTemplateDecl>(D) &&
2844          "Cannot refer unambiguously to a function template");
2845 
2846   SourceLocation Loc = NameInfo.getLoc();
2847   if (CheckDeclInExpr(*this, Loc, D))
2848     return ExprError();
2849 
2850   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2851     // Specifically diagnose references to class templates that are missing
2852     // a template argument list.
2853     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2854                                            << Template << SS.getRange();
2855     Diag(Template->getLocation(), diag::note_template_decl_here);
2856     return ExprError();
2857   }
2858 
2859   // Make sure that we're referring to a value.
2860   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2861   if (!VD) {
2862     Diag(Loc, diag::err_ref_non_value)
2863       << D << SS.getRange();
2864     Diag(D->getLocation(), diag::note_declared_at);
2865     return ExprError();
2866   }
2867 
2868   // Check whether this declaration can be used. Note that we suppress
2869   // this check when we're going to perform argument-dependent lookup
2870   // on this function name, because this might not be the function
2871   // that overload resolution actually selects.
2872   if (DiagnoseUseOfDecl(VD, Loc))
2873     return ExprError();
2874 
2875   // Only create DeclRefExpr's for valid Decl's.
2876   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2877     return ExprError();
2878 
2879   // Handle members of anonymous structs and unions.  If we got here,
2880   // and the reference is to a class member indirect field, then this
2881   // must be the subject of a pointer-to-member expression.
2882   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2883     if (!indirectField->isCXXClassMember())
2884       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2885                                                       indirectField);
2886 
2887   {
2888     QualType type = VD->getType();
2889     ExprValueKind valueKind = VK_RValue;
2890 
2891     switch (D->getKind()) {
2892     // Ignore all the non-ValueDecl kinds.
2893 #define ABSTRACT_DECL(kind)
2894 #define VALUE(type, base)
2895 #define DECL(type, base) \
2896     case Decl::type:
2897 #include "clang/AST/DeclNodes.inc"
2898       llvm_unreachable("invalid value decl kind");
2899 
2900     // These shouldn't make it here.
2901     case Decl::ObjCAtDefsField:
2902     case Decl::ObjCIvar:
2903       llvm_unreachable("forming non-member reference to ivar?");
2904 
2905     // Enum constants are always r-values and never references.
2906     // Unresolved using declarations are dependent.
2907     case Decl::EnumConstant:
2908     case Decl::UnresolvedUsingValue:
2909     case Decl::OMPDeclareReduction:
2910       valueKind = VK_RValue;
2911       break;
2912 
2913     // Fields and indirect fields that got here must be for
2914     // pointer-to-member expressions; we just call them l-values for
2915     // internal consistency, because this subexpression doesn't really
2916     // exist in the high-level semantics.
2917     case Decl::Field:
2918     case Decl::IndirectField:
2919       assert(getLangOpts().CPlusPlus &&
2920              "building reference to field in C?");
2921 
2922       // These can't have reference type in well-formed programs, but
2923       // for internal consistency we do this anyway.
2924       type = type.getNonReferenceType();
2925       valueKind = VK_LValue;
2926       break;
2927 
2928     // Non-type template parameters are either l-values or r-values
2929     // depending on the type.
2930     case Decl::NonTypeTemplateParm: {
2931       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2932         type = reftype->getPointeeType();
2933         valueKind = VK_LValue; // even if the parameter is an r-value reference
2934         break;
2935       }
2936 
2937       // For non-references, we need to strip qualifiers just in case
2938       // the template parameter was declared as 'const int' or whatever.
2939       valueKind = VK_RValue;
2940       type = type.getUnqualifiedType();
2941       break;
2942     }
2943 
2944     case Decl::Var:
2945     case Decl::VarTemplateSpecialization:
2946     case Decl::VarTemplatePartialSpecialization:
2947     case Decl::OMPCapturedExpr:
2948       // In C, "extern void blah;" is valid and is an r-value.
2949       if (!getLangOpts().CPlusPlus &&
2950           !type.hasQualifiers() &&
2951           type->isVoidType()) {
2952         valueKind = VK_RValue;
2953         break;
2954       }
2955       // fallthrough
2956 
2957     case Decl::ImplicitParam:
2958     case Decl::ParmVar: {
2959       // These are always l-values.
2960       valueKind = VK_LValue;
2961       type = type.getNonReferenceType();
2962 
2963       // FIXME: Does the addition of const really only apply in
2964       // potentially-evaluated contexts? Since the variable isn't actually
2965       // captured in an unevaluated context, it seems that the answer is no.
2966       if (!isUnevaluatedContext()) {
2967         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2968         if (!CapturedType.isNull())
2969           type = CapturedType;
2970       }
2971 
2972       break;
2973     }
2974 
2975     case Decl::Function: {
2976       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2977         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2978           type = Context.BuiltinFnTy;
2979           valueKind = VK_RValue;
2980           break;
2981         }
2982       }
2983 
2984       const FunctionType *fty = type->castAs<FunctionType>();
2985 
2986       // If we're referring to a function with an __unknown_anytype
2987       // result type, make the entire expression __unknown_anytype.
2988       if (fty->getReturnType() == Context.UnknownAnyTy) {
2989         type = Context.UnknownAnyTy;
2990         valueKind = VK_RValue;
2991         break;
2992       }
2993 
2994       // Functions are l-values in C++.
2995       if (getLangOpts().CPlusPlus) {
2996         valueKind = VK_LValue;
2997         break;
2998       }
2999 
3000       // C99 DR 316 says that, if a function type comes from a
3001       // function definition (without a prototype), that type is only
3002       // used for checking compatibility. Therefore, when referencing
3003       // the function, we pretend that we don't have the full function
3004       // type.
3005       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3006           isa<FunctionProtoType>(fty))
3007         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3008                                               fty->getExtInfo());
3009 
3010       // Functions are r-values in C.
3011       valueKind = VK_RValue;
3012       break;
3013     }
3014 
3015     case Decl::MSProperty:
3016       valueKind = VK_LValue;
3017       break;
3018 
3019     case Decl::CXXMethod:
3020       // If we're referring to a method with an __unknown_anytype
3021       // result type, make the entire expression __unknown_anytype.
3022       // This should only be possible with a type written directly.
3023       if (const FunctionProtoType *proto
3024             = dyn_cast<FunctionProtoType>(VD->getType()))
3025         if (proto->getReturnType() == Context.UnknownAnyTy) {
3026           type = Context.UnknownAnyTy;
3027           valueKind = VK_RValue;
3028           break;
3029         }
3030 
3031       // C++ methods are l-values if static, r-values if non-static.
3032       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3033         valueKind = VK_LValue;
3034         break;
3035       }
3036       // fallthrough
3037 
3038     case Decl::CXXConversion:
3039     case Decl::CXXDestructor:
3040     case Decl::CXXConstructor:
3041       valueKind = VK_RValue;
3042       break;
3043     }
3044 
3045     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3046                             TemplateArgs);
3047   }
3048 }
3049 
3050 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3051                                     SmallString<32> &Target) {
3052   Target.resize(CharByteWidth * (Source.size() + 1));
3053   char *ResultPtr = &Target[0];
3054   const UTF8 *ErrorPtr;
3055   bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3056   (void)success;
3057   assert(success);
3058   Target.resize(ResultPtr - &Target[0]);
3059 }
3060 
3061 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3062                                      PredefinedExpr::IdentType IT) {
3063   // Pick the current block, lambda, captured statement or function.
3064   Decl *currentDecl = nullptr;
3065   if (const BlockScopeInfo *BSI = getCurBlock())
3066     currentDecl = BSI->TheDecl;
3067   else if (const LambdaScopeInfo *LSI = getCurLambda())
3068     currentDecl = LSI->CallOperator;
3069   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3070     currentDecl = CSI->TheCapturedDecl;
3071   else
3072     currentDecl = getCurFunctionOrMethodDecl();
3073 
3074   if (!currentDecl) {
3075     Diag(Loc, diag::ext_predef_outside_function);
3076     currentDecl = Context.getTranslationUnitDecl();
3077   }
3078 
3079   QualType ResTy;
3080   StringLiteral *SL = nullptr;
3081   if (cast<DeclContext>(currentDecl)->isDependentContext())
3082     ResTy = Context.DependentTy;
3083   else {
3084     // Pre-defined identifiers are of type char[x], where x is the length of
3085     // the string.
3086     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3087     unsigned Length = Str.length();
3088 
3089     llvm::APInt LengthI(32, Length + 1);
3090     if (IT == PredefinedExpr::LFunction) {
3091       ResTy = Context.WideCharTy.withConst();
3092       SmallString<32> RawChars;
3093       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3094                               Str, RawChars);
3095       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3096                                            /*IndexTypeQuals*/ 0);
3097       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3098                                  /*Pascal*/ false, ResTy, Loc);
3099     } else {
3100       ResTy = Context.CharTy.withConst();
3101       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3102                                            /*IndexTypeQuals*/ 0);
3103       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3104                                  /*Pascal*/ false, ResTy, Loc);
3105     }
3106   }
3107 
3108   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3109 }
3110 
3111 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3112   PredefinedExpr::IdentType IT;
3113 
3114   switch (Kind) {
3115   default: llvm_unreachable("Unknown simple primary expr!");
3116   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3117   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3118   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3119   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3120   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3121   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3122   }
3123 
3124   return BuildPredefinedExpr(Loc, IT);
3125 }
3126 
3127 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3128   SmallString<16> CharBuffer;
3129   bool Invalid = false;
3130   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3131   if (Invalid)
3132     return ExprError();
3133 
3134   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3135                             PP, Tok.getKind());
3136   if (Literal.hadError())
3137     return ExprError();
3138 
3139   QualType Ty;
3140   if (Literal.isWide())
3141     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3142   else if (Literal.isUTF16())
3143     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3144   else if (Literal.isUTF32())
3145     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3146   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3147     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3148   else
3149     Ty = Context.CharTy;  // 'x' -> char in C++
3150 
3151   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3152   if (Literal.isWide())
3153     Kind = CharacterLiteral::Wide;
3154   else if (Literal.isUTF16())
3155     Kind = CharacterLiteral::UTF16;
3156   else if (Literal.isUTF32())
3157     Kind = CharacterLiteral::UTF32;
3158   else if (Literal.isUTF8())
3159     Kind = CharacterLiteral::UTF8;
3160 
3161   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3162                                              Tok.getLocation());
3163 
3164   if (Literal.getUDSuffix().empty())
3165     return Lit;
3166 
3167   // We're building a user-defined literal.
3168   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3169   SourceLocation UDSuffixLoc =
3170     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3171 
3172   // Make sure we're allowed user-defined literals here.
3173   if (!UDLScope)
3174     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3175 
3176   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3177   //   operator "" X (ch)
3178   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3179                                         Lit, Tok.getLocation());
3180 }
3181 
3182 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3183   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3184   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3185                                 Context.IntTy, Loc);
3186 }
3187 
3188 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3189                                   QualType Ty, SourceLocation Loc) {
3190   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3191 
3192   using llvm::APFloat;
3193   APFloat Val(Format);
3194 
3195   APFloat::opStatus result = Literal.GetFloatValue(Val);
3196 
3197   // Overflow is always an error, but underflow is only an error if
3198   // we underflowed to zero (APFloat reports denormals as underflow).
3199   if ((result & APFloat::opOverflow) ||
3200       ((result & APFloat::opUnderflow) && Val.isZero())) {
3201     unsigned diagnostic;
3202     SmallString<20> buffer;
3203     if (result & APFloat::opOverflow) {
3204       diagnostic = diag::warn_float_overflow;
3205       APFloat::getLargest(Format).toString(buffer);
3206     } else {
3207       diagnostic = diag::warn_float_underflow;
3208       APFloat::getSmallest(Format).toString(buffer);
3209     }
3210 
3211     S.Diag(Loc, diagnostic)
3212       << Ty
3213       << StringRef(buffer.data(), buffer.size());
3214   }
3215 
3216   bool isExact = (result == APFloat::opOK);
3217   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3218 }
3219 
3220 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3221   assert(E && "Invalid expression");
3222 
3223   if (E->isValueDependent())
3224     return false;
3225 
3226   QualType QT = E->getType();
3227   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3228     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3229     return true;
3230   }
3231 
3232   llvm::APSInt ValueAPS;
3233   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3234 
3235   if (R.isInvalid())
3236     return true;
3237 
3238   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3239   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3240     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3241         << ValueAPS.toString(10) << ValueIsPositive;
3242     return true;
3243   }
3244 
3245   return false;
3246 }
3247 
3248 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3249   // Fast path for a single digit (which is quite common).  A single digit
3250   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3251   if (Tok.getLength() == 1) {
3252     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3253     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3254   }
3255 
3256   SmallString<128> SpellingBuffer;
3257   // NumericLiteralParser wants to overread by one character.  Add padding to
3258   // the buffer in case the token is copied to the buffer.  If getSpelling()
3259   // returns a StringRef to the memory buffer, it should have a null char at
3260   // the EOF, so it is also safe.
3261   SpellingBuffer.resize(Tok.getLength() + 1);
3262 
3263   // Get the spelling of the token, which eliminates trigraphs, etc.
3264   bool Invalid = false;
3265   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3266   if (Invalid)
3267     return ExprError();
3268 
3269   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3270   if (Literal.hadError)
3271     return ExprError();
3272 
3273   if (Literal.hasUDSuffix()) {
3274     // We're building a user-defined literal.
3275     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3276     SourceLocation UDSuffixLoc =
3277       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3278 
3279     // Make sure we're allowed user-defined literals here.
3280     if (!UDLScope)
3281       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3282 
3283     QualType CookedTy;
3284     if (Literal.isFloatingLiteral()) {
3285       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3286       // long double, the literal is treated as a call of the form
3287       //   operator "" X (f L)
3288       CookedTy = Context.LongDoubleTy;
3289     } else {
3290       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3291       // unsigned long long, the literal is treated as a call of the form
3292       //   operator "" X (n ULL)
3293       CookedTy = Context.UnsignedLongLongTy;
3294     }
3295 
3296     DeclarationName OpName =
3297       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3298     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3299     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3300 
3301     SourceLocation TokLoc = Tok.getLocation();
3302 
3303     // Perform literal operator lookup to determine if we're building a raw
3304     // literal or a cooked one.
3305     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3306     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3307                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3308                                   /*AllowStringTemplate*/false)) {
3309     case LOLR_Error:
3310       return ExprError();
3311 
3312     case LOLR_Cooked: {
3313       Expr *Lit;
3314       if (Literal.isFloatingLiteral()) {
3315         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3316       } else {
3317         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3318         if (Literal.GetIntegerValue(ResultVal))
3319           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3320               << /* Unsigned */ 1;
3321         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3322                                      Tok.getLocation());
3323       }
3324       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3325     }
3326 
3327     case LOLR_Raw: {
3328       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3329       // literal is treated as a call of the form
3330       //   operator "" X ("n")
3331       unsigned Length = Literal.getUDSuffixOffset();
3332       QualType StrTy = Context.getConstantArrayType(
3333           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3334           ArrayType::Normal, 0);
3335       Expr *Lit = StringLiteral::Create(
3336           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3337           /*Pascal*/false, StrTy, &TokLoc, 1);
3338       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3339     }
3340 
3341     case LOLR_Template: {
3342       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3343       // template), L is treated as a call fo the form
3344       //   operator "" X <'c1', 'c2', ... 'ck'>()
3345       // where n is the source character sequence c1 c2 ... ck.
3346       TemplateArgumentListInfo ExplicitArgs;
3347       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3348       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3349       llvm::APSInt Value(CharBits, CharIsUnsigned);
3350       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3351         Value = TokSpelling[I];
3352         TemplateArgument Arg(Context, Value, Context.CharTy);
3353         TemplateArgumentLocInfo ArgInfo;
3354         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3355       }
3356       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3357                                       &ExplicitArgs);
3358     }
3359     case LOLR_StringTemplate:
3360       llvm_unreachable("unexpected literal operator lookup result");
3361     }
3362   }
3363 
3364   Expr *Res;
3365 
3366   if (Literal.isFloatingLiteral()) {
3367     QualType Ty;
3368     if (Literal.isHalf){
3369       if (getOpenCLOptions().cl_khr_fp16)
3370         Ty = Context.HalfTy;
3371       else {
3372         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3373         return ExprError();
3374       }
3375     } else if (Literal.isFloat)
3376       Ty = Context.FloatTy;
3377     else if (Literal.isLong)
3378       Ty = Context.LongDoubleTy;
3379     else if (Literal.isFloat128)
3380       Ty = Context.Float128Ty;
3381     else
3382       Ty = Context.DoubleTy;
3383 
3384     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3385 
3386     if (Ty == Context.DoubleTy) {
3387       if (getLangOpts().SinglePrecisionConstants) {
3388         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3389       } else if (getLangOpts().OpenCL &&
3390                  !((getLangOpts().OpenCLVersion >= 120) ||
3391                    getOpenCLOptions().cl_khr_fp64)) {
3392         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3393         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3394       }
3395     }
3396   } else if (!Literal.isIntegerLiteral()) {
3397     return ExprError();
3398   } else {
3399     QualType Ty;
3400 
3401     // 'long long' is a C99 or C++11 feature.
3402     if (!getLangOpts().C99 && Literal.isLongLong) {
3403       if (getLangOpts().CPlusPlus)
3404         Diag(Tok.getLocation(),
3405              getLangOpts().CPlusPlus11 ?
3406              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3407       else
3408         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3409     }
3410 
3411     // Get the value in the widest-possible width.
3412     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3413     llvm::APInt ResultVal(MaxWidth, 0);
3414 
3415     if (Literal.GetIntegerValue(ResultVal)) {
3416       // If this value didn't fit into uintmax_t, error and force to ull.
3417       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3418           << /* Unsigned */ 1;
3419       Ty = Context.UnsignedLongLongTy;
3420       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3421              "long long is not intmax_t?");
3422     } else {
3423       // If this value fits into a ULL, try to figure out what else it fits into
3424       // according to the rules of C99 6.4.4.1p5.
3425 
3426       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3427       // be an unsigned int.
3428       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3429 
3430       // Check from smallest to largest, picking the smallest type we can.
3431       unsigned Width = 0;
3432 
3433       // Microsoft specific integer suffixes are explicitly sized.
3434       if (Literal.MicrosoftInteger) {
3435         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3436           Width = 8;
3437           Ty = Context.CharTy;
3438         } else {
3439           Width = Literal.MicrosoftInteger;
3440           Ty = Context.getIntTypeForBitwidth(Width,
3441                                              /*Signed=*/!Literal.isUnsigned);
3442         }
3443       }
3444 
3445       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3446         // Are int/unsigned possibilities?
3447         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3448 
3449         // Does it fit in a unsigned int?
3450         if (ResultVal.isIntN(IntSize)) {
3451           // Does it fit in a signed int?
3452           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3453             Ty = Context.IntTy;
3454           else if (AllowUnsigned)
3455             Ty = Context.UnsignedIntTy;
3456           Width = IntSize;
3457         }
3458       }
3459 
3460       // Are long/unsigned long possibilities?
3461       if (Ty.isNull() && !Literal.isLongLong) {
3462         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3463 
3464         // Does it fit in a unsigned long?
3465         if (ResultVal.isIntN(LongSize)) {
3466           // Does it fit in a signed long?
3467           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3468             Ty = Context.LongTy;
3469           else if (AllowUnsigned)
3470             Ty = Context.UnsignedLongTy;
3471           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3472           // is compatible.
3473           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3474             const unsigned LongLongSize =
3475                 Context.getTargetInfo().getLongLongWidth();
3476             Diag(Tok.getLocation(),
3477                  getLangOpts().CPlusPlus
3478                      ? Literal.isLong
3479                            ? diag::warn_old_implicitly_unsigned_long_cxx
3480                            : /*C++98 UB*/ diag::
3481                                  ext_old_implicitly_unsigned_long_cxx
3482                      : diag::warn_old_implicitly_unsigned_long)
3483                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3484                                             : /*will be ill-formed*/ 1);
3485             Ty = Context.UnsignedLongTy;
3486           }
3487           Width = LongSize;
3488         }
3489       }
3490 
3491       // Check long long if needed.
3492       if (Ty.isNull()) {
3493         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3494 
3495         // Does it fit in a unsigned long long?
3496         if (ResultVal.isIntN(LongLongSize)) {
3497           // Does it fit in a signed long long?
3498           // To be compatible with MSVC, hex integer literals ending with the
3499           // LL or i64 suffix are always signed in Microsoft mode.
3500           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3501               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3502             Ty = Context.LongLongTy;
3503           else if (AllowUnsigned)
3504             Ty = Context.UnsignedLongLongTy;
3505           Width = LongLongSize;
3506         }
3507       }
3508 
3509       // If we still couldn't decide a type, we probably have something that
3510       // does not fit in a signed long long, but has no U suffix.
3511       if (Ty.isNull()) {
3512         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3513         Ty = Context.UnsignedLongLongTy;
3514         Width = Context.getTargetInfo().getLongLongWidth();
3515       }
3516 
3517       if (ResultVal.getBitWidth() != Width)
3518         ResultVal = ResultVal.trunc(Width);
3519     }
3520     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3521   }
3522 
3523   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3524   if (Literal.isImaginary)
3525     Res = new (Context) ImaginaryLiteral(Res,
3526                                         Context.getComplexType(Res->getType()));
3527 
3528   return Res;
3529 }
3530 
3531 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3532   assert(E && "ActOnParenExpr() missing expr");
3533   return new (Context) ParenExpr(L, R, E);
3534 }
3535 
3536 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3537                                          SourceLocation Loc,
3538                                          SourceRange ArgRange) {
3539   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3540   // scalar or vector data type argument..."
3541   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3542   // type (C99 6.2.5p18) or void.
3543   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3544     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3545       << T << ArgRange;
3546     return true;
3547   }
3548 
3549   assert((T->isVoidType() || !T->isIncompleteType()) &&
3550          "Scalar types should always be complete");
3551   return false;
3552 }
3553 
3554 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3555                                            SourceLocation Loc,
3556                                            SourceRange ArgRange,
3557                                            UnaryExprOrTypeTrait TraitKind) {
3558   // Invalid types must be hard errors for SFINAE in C++.
3559   if (S.LangOpts.CPlusPlus)
3560     return true;
3561 
3562   // C99 6.5.3.4p1:
3563   if (T->isFunctionType() &&
3564       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3565     // sizeof(function)/alignof(function) is allowed as an extension.
3566     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3567       << TraitKind << ArgRange;
3568     return false;
3569   }
3570 
3571   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3572   // this is an error (OpenCL v1.1 s6.3.k)
3573   if (T->isVoidType()) {
3574     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3575                                         : diag::ext_sizeof_alignof_void_type;
3576     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3577     return false;
3578   }
3579 
3580   return true;
3581 }
3582 
3583 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3584                                              SourceLocation Loc,
3585                                              SourceRange ArgRange,
3586                                              UnaryExprOrTypeTrait TraitKind) {
3587   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3588   // runtime doesn't allow it.
3589   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3590     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3591       << T << (TraitKind == UETT_SizeOf)
3592       << ArgRange;
3593     return true;
3594   }
3595 
3596   return false;
3597 }
3598 
3599 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3600 /// pointer type is equal to T) and emit a warning if it is.
3601 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3602                                      Expr *E) {
3603   // Don't warn if the operation changed the type.
3604   if (T != E->getType())
3605     return;
3606 
3607   // Now look for array decays.
3608   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3609   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3610     return;
3611 
3612   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3613                                              << ICE->getType()
3614                                              << ICE->getSubExpr()->getType();
3615 }
3616 
3617 /// \brief Check the constraints on expression operands to unary type expression
3618 /// and type traits.
3619 ///
3620 /// Completes any types necessary and validates the constraints on the operand
3621 /// expression. The logic mostly mirrors the type-based overload, but may modify
3622 /// the expression as it completes the type for that expression through template
3623 /// instantiation, etc.
3624 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3625                                             UnaryExprOrTypeTrait ExprKind) {
3626   QualType ExprTy = E->getType();
3627   assert(!ExprTy->isReferenceType());
3628 
3629   if (ExprKind == UETT_VecStep)
3630     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3631                                         E->getSourceRange());
3632 
3633   // Whitelist some types as extensions
3634   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3635                                       E->getSourceRange(), ExprKind))
3636     return false;
3637 
3638   // 'alignof' applied to an expression only requires the base element type of
3639   // the expression to be complete. 'sizeof' requires the expression's type to
3640   // be complete (and will attempt to complete it if it's an array of unknown
3641   // bound).
3642   if (ExprKind == UETT_AlignOf) {
3643     if (RequireCompleteType(E->getExprLoc(),
3644                             Context.getBaseElementType(E->getType()),
3645                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3646                             E->getSourceRange()))
3647       return true;
3648   } else {
3649     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3650                                 ExprKind, E->getSourceRange()))
3651       return true;
3652   }
3653 
3654   // Completing the expression's type may have changed it.
3655   ExprTy = E->getType();
3656   assert(!ExprTy->isReferenceType());
3657 
3658   if (ExprTy->isFunctionType()) {
3659     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3660       << ExprKind << E->getSourceRange();
3661     return true;
3662   }
3663 
3664   // The operand for sizeof and alignof is in an unevaluated expression context,
3665   // so side effects could result in unintended consequences.
3666   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3667       ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3668     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3669 
3670   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3671                                        E->getSourceRange(), ExprKind))
3672     return true;
3673 
3674   if (ExprKind == UETT_SizeOf) {
3675     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3676       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3677         QualType OType = PVD->getOriginalType();
3678         QualType Type = PVD->getType();
3679         if (Type->isPointerType() && OType->isArrayType()) {
3680           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3681             << Type << OType;
3682           Diag(PVD->getLocation(), diag::note_declared_at);
3683         }
3684       }
3685     }
3686 
3687     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3688     // decays into a pointer and returns an unintended result. This is most
3689     // likely a typo for "sizeof(array) op x".
3690     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3691       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3692                                BO->getLHS());
3693       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3694                                BO->getRHS());
3695     }
3696   }
3697 
3698   return false;
3699 }
3700 
3701 /// \brief Check the constraints on operands to unary expression and type
3702 /// traits.
3703 ///
3704 /// This will complete any types necessary, and validate the various constraints
3705 /// on those operands.
3706 ///
3707 /// The UsualUnaryConversions() function is *not* called by this routine.
3708 /// C99 6.3.2.1p[2-4] all state:
3709 ///   Except when it is the operand of the sizeof operator ...
3710 ///
3711 /// C++ [expr.sizeof]p4
3712 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3713 ///   standard conversions are not applied to the operand of sizeof.
3714 ///
3715 /// This policy is followed for all of the unary trait expressions.
3716 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3717                                             SourceLocation OpLoc,
3718                                             SourceRange ExprRange,
3719                                             UnaryExprOrTypeTrait ExprKind) {
3720   if (ExprType->isDependentType())
3721     return false;
3722 
3723   // C++ [expr.sizeof]p2:
3724   //     When applied to a reference or a reference type, the result
3725   //     is the size of the referenced type.
3726   // C++11 [expr.alignof]p3:
3727   //     When alignof is applied to a reference type, the result
3728   //     shall be the alignment of the referenced type.
3729   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3730     ExprType = Ref->getPointeeType();
3731 
3732   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3733   //   When alignof or _Alignof is applied to an array type, the result
3734   //   is the alignment of the element type.
3735   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3736     ExprType = Context.getBaseElementType(ExprType);
3737 
3738   if (ExprKind == UETT_VecStep)
3739     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3740 
3741   // Whitelist some types as extensions
3742   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3743                                       ExprKind))
3744     return false;
3745 
3746   if (RequireCompleteType(OpLoc, ExprType,
3747                           diag::err_sizeof_alignof_incomplete_type,
3748                           ExprKind, ExprRange))
3749     return true;
3750 
3751   if (ExprType->isFunctionType()) {
3752     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3753       << ExprKind << ExprRange;
3754     return true;
3755   }
3756 
3757   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3758                                        ExprKind))
3759     return true;
3760 
3761   return false;
3762 }
3763 
3764 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3765   E = E->IgnoreParens();
3766 
3767   // Cannot know anything else if the expression is dependent.
3768   if (E->isTypeDependent())
3769     return false;
3770 
3771   if (E->getObjectKind() == OK_BitField) {
3772     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3773        << 1 << E->getSourceRange();
3774     return true;
3775   }
3776 
3777   ValueDecl *D = nullptr;
3778   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3779     D = DRE->getDecl();
3780   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3781     D = ME->getMemberDecl();
3782   }
3783 
3784   // If it's a field, require the containing struct to have a
3785   // complete definition so that we can compute the layout.
3786   //
3787   // This can happen in C++11 onwards, either by naming the member
3788   // in a way that is not transformed into a member access expression
3789   // (in an unevaluated operand, for instance), or by naming the member
3790   // in a trailing-return-type.
3791   //
3792   // For the record, since __alignof__ on expressions is a GCC
3793   // extension, GCC seems to permit this but always gives the
3794   // nonsensical answer 0.
3795   //
3796   // We don't really need the layout here --- we could instead just
3797   // directly check for all the appropriate alignment-lowing
3798   // attributes --- but that would require duplicating a lot of
3799   // logic that just isn't worth duplicating for such a marginal
3800   // use-case.
3801   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3802     // Fast path this check, since we at least know the record has a
3803     // definition if we can find a member of it.
3804     if (!FD->getParent()->isCompleteDefinition()) {
3805       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3806         << E->getSourceRange();
3807       return true;
3808     }
3809 
3810     // Otherwise, if it's a field, and the field doesn't have
3811     // reference type, then it must have a complete type (or be a
3812     // flexible array member, which we explicitly want to
3813     // white-list anyway), which makes the following checks trivial.
3814     if (!FD->getType()->isReferenceType())
3815       return false;
3816   }
3817 
3818   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3819 }
3820 
3821 bool Sema::CheckVecStepExpr(Expr *E) {
3822   E = E->IgnoreParens();
3823 
3824   // Cannot know anything else if the expression is dependent.
3825   if (E->isTypeDependent())
3826     return false;
3827 
3828   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3829 }
3830 
3831 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3832                                         CapturingScopeInfo *CSI) {
3833   assert(T->isVariablyModifiedType());
3834   assert(CSI != nullptr);
3835 
3836   // We're going to walk down into the type and look for VLA expressions.
3837   do {
3838     const Type *Ty = T.getTypePtr();
3839     switch (Ty->getTypeClass()) {
3840 #define TYPE(Class, Base)
3841 #define ABSTRACT_TYPE(Class, Base)
3842 #define NON_CANONICAL_TYPE(Class, Base)
3843 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3844 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3845 #include "clang/AST/TypeNodes.def"
3846       T = QualType();
3847       break;
3848     // These types are never variably-modified.
3849     case Type::Builtin:
3850     case Type::Complex:
3851     case Type::Vector:
3852     case Type::ExtVector:
3853     case Type::Record:
3854     case Type::Enum:
3855     case Type::Elaborated:
3856     case Type::TemplateSpecialization:
3857     case Type::ObjCObject:
3858     case Type::ObjCInterface:
3859     case Type::ObjCObjectPointer:
3860     case Type::Pipe:
3861       llvm_unreachable("type class is never variably-modified!");
3862     case Type::Adjusted:
3863       T = cast<AdjustedType>(Ty)->getOriginalType();
3864       break;
3865     case Type::Decayed:
3866       T = cast<DecayedType>(Ty)->getPointeeType();
3867       break;
3868     case Type::Pointer:
3869       T = cast<PointerType>(Ty)->getPointeeType();
3870       break;
3871     case Type::BlockPointer:
3872       T = cast<BlockPointerType>(Ty)->getPointeeType();
3873       break;
3874     case Type::LValueReference:
3875     case Type::RValueReference:
3876       T = cast<ReferenceType>(Ty)->getPointeeType();
3877       break;
3878     case Type::MemberPointer:
3879       T = cast<MemberPointerType>(Ty)->getPointeeType();
3880       break;
3881     case Type::ConstantArray:
3882     case Type::IncompleteArray:
3883       // Losing element qualification here is fine.
3884       T = cast<ArrayType>(Ty)->getElementType();
3885       break;
3886     case Type::VariableArray: {
3887       // Losing element qualification here is fine.
3888       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3889 
3890       // Unknown size indication requires no size computation.
3891       // Otherwise, evaluate and record it.
3892       if (auto Size = VAT->getSizeExpr()) {
3893         if (!CSI->isVLATypeCaptured(VAT)) {
3894           RecordDecl *CapRecord = nullptr;
3895           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3896             CapRecord = LSI->Lambda;
3897           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3898             CapRecord = CRSI->TheRecordDecl;
3899           }
3900           if (CapRecord) {
3901             auto ExprLoc = Size->getExprLoc();
3902             auto SizeType = Context.getSizeType();
3903             // Build the non-static data member.
3904             auto Field =
3905                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3906                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3907                                   /*BW*/ nullptr, /*Mutable*/ false,
3908                                   /*InitStyle*/ ICIS_NoInit);
3909             Field->setImplicit(true);
3910             Field->setAccess(AS_private);
3911             Field->setCapturedVLAType(VAT);
3912             CapRecord->addDecl(Field);
3913 
3914             CSI->addVLATypeCapture(ExprLoc, SizeType);
3915           }
3916         }
3917       }
3918       T = VAT->getElementType();
3919       break;
3920     }
3921     case Type::FunctionProto:
3922     case Type::FunctionNoProto:
3923       T = cast<FunctionType>(Ty)->getReturnType();
3924       break;
3925     case Type::Paren:
3926     case Type::TypeOf:
3927     case Type::UnaryTransform:
3928     case Type::Attributed:
3929     case Type::SubstTemplateTypeParm:
3930     case Type::PackExpansion:
3931       // Keep walking after single level desugaring.
3932       T = T.getSingleStepDesugaredType(Context);
3933       break;
3934     case Type::Typedef:
3935       T = cast<TypedefType>(Ty)->desugar();
3936       break;
3937     case Type::Decltype:
3938       T = cast<DecltypeType>(Ty)->desugar();
3939       break;
3940     case Type::Auto:
3941       T = cast<AutoType>(Ty)->getDeducedType();
3942       break;
3943     case Type::TypeOfExpr:
3944       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3945       break;
3946     case Type::Atomic:
3947       T = cast<AtomicType>(Ty)->getValueType();
3948       break;
3949     }
3950   } while (!T.isNull() && T->isVariablyModifiedType());
3951 }
3952 
3953 /// \brief Build a sizeof or alignof expression given a type operand.
3954 ExprResult
3955 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3956                                      SourceLocation OpLoc,
3957                                      UnaryExprOrTypeTrait ExprKind,
3958                                      SourceRange R) {
3959   if (!TInfo)
3960     return ExprError();
3961 
3962   QualType T = TInfo->getType();
3963 
3964   if (!T->isDependentType() &&
3965       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3966     return ExprError();
3967 
3968   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3969     if (auto *TT = T->getAs<TypedefType>()) {
3970       for (auto I = FunctionScopes.rbegin(),
3971                 E = std::prev(FunctionScopes.rend());
3972            I != E; ++I) {
3973         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3974         if (CSI == nullptr)
3975           break;
3976         DeclContext *DC = nullptr;
3977         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
3978           DC = LSI->CallOperator;
3979         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
3980           DC = CRSI->TheCapturedDecl;
3981         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
3982           DC = BSI->TheDecl;
3983         if (DC) {
3984           if (DC->containsDecl(TT->getDecl()))
3985             break;
3986           captureVariablyModifiedType(Context, T, CSI);
3987         }
3988       }
3989     }
3990   }
3991 
3992   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3993   return new (Context) UnaryExprOrTypeTraitExpr(
3994       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3995 }
3996 
3997 /// \brief Build a sizeof or alignof expression given an expression
3998 /// operand.
3999 ExprResult
4000 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4001                                      UnaryExprOrTypeTrait ExprKind) {
4002   ExprResult PE = CheckPlaceholderExpr(E);
4003   if (PE.isInvalid())
4004     return ExprError();
4005 
4006   E = PE.get();
4007 
4008   // Verify that the operand is valid.
4009   bool isInvalid = false;
4010   if (E->isTypeDependent()) {
4011     // Delay type-checking for type-dependent expressions.
4012   } else if (ExprKind == UETT_AlignOf) {
4013     isInvalid = CheckAlignOfExpr(*this, E);
4014   } else if (ExprKind == UETT_VecStep) {
4015     isInvalid = CheckVecStepExpr(E);
4016   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4017       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4018       isInvalid = true;
4019   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4020     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4021     isInvalid = true;
4022   } else {
4023     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4024   }
4025 
4026   if (isInvalid)
4027     return ExprError();
4028 
4029   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4030     PE = TransformToPotentiallyEvaluated(E);
4031     if (PE.isInvalid()) return ExprError();
4032     E = PE.get();
4033   }
4034 
4035   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4036   return new (Context) UnaryExprOrTypeTraitExpr(
4037       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4038 }
4039 
4040 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4041 /// expr and the same for @c alignof and @c __alignof
4042 /// Note that the ArgRange is invalid if isType is false.
4043 ExprResult
4044 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4045                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4046                                     void *TyOrEx, SourceRange ArgRange) {
4047   // If error parsing type, ignore.
4048   if (!TyOrEx) return ExprError();
4049 
4050   if (IsType) {
4051     TypeSourceInfo *TInfo;
4052     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4053     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4054   }
4055 
4056   Expr *ArgEx = (Expr *)TyOrEx;
4057   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4058   return Result;
4059 }
4060 
4061 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4062                                      bool IsReal) {
4063   if (V.get()->isTypeDependent())
4064     return S.Context.DependentTy;
4065 
4066   // _Real and _Imag are only l-values for normal l-values.
4067   if (V.get()->getObjectKind() != OK_Ordinary) {
4068     V = S.DefaultLvalueConversion(V.get());
4069     if (V.isInvalid())
4070       return QualType();
4071   }
4072 
4073   // These operators return the element type of a complex type.
4074   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4075     return CT->getElementType();
4076 
4077   // Otherwise they pass through real integer and floating point types here.
4078   if (V.get()->getType()->isArithmeticType())
4079     return V.get()->getType();
4080 
4081   // Test for placeholders.
4082   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4083   if (PR.isInvalid()) return QualType();
4084   if (PR.get() != V.get()) {
4085     V = PR;
4086     return CheckRealImagOperand(S, V, Loc, IsReal);
4087   }
4088 
4089   // Reject anything else.
4090   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4091     << (IsReal ? "__real" : "__imag");
4092   return QualType();
4093 }
4094 
4095 
4096 
4097 ExprResult
4098 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4099                           tok::TokenKind Kind, Expr *Input) {
4100   UnaryOperatorKind Opc;
4101   switch (Kind) {
4102   default: llvm_unreachable("Unknown unary op!");
4103   case tok::plusplus:   Opc = UO_PostInc; break;
4104   case tok::minusminus: Opc = UO_PostDec; break;
4105   }
4106 
4107   // Since this might is a postfix expression, get rid of ParenListExprs.
4108   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4109   if (Result.isInvalid()) return ExprError();
4110   Input = Result.get();
4111 
4112   return BuildUnaryOp(S, OpLoc, Opc, Input);
4113 }
4114 
4115 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4116 ///
4117 /// \return true on error
4118 static bool checkArithmeticOnObjCPointer(Sema &S,
4119                                          SourceLocation opLoc,
4120                                          Expr *op) {
4121   assert(op->getType()->isObjCObjectPointerType());
4122   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4123       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4124     return false;
4125 
4126   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4127     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4128     << op->getSourceRange();
4129   return true;
4130 }
4131 
4132 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4133   auto *BaseNoParens = Base->IgnoreParens();
4134   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4135     return MSProp->getPropertyDecl()->getType()->isArrayType();
4136   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4137 }
4138 
4139 ExprResult
4140 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4141                               Expr *idx, SourceLocation rbLoc) {
4142   if (base && !base->getType().isNull() &&
4143       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4144     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4145                                     /*Length=*/nullptr, rbLoc);
4146 
4147   // Since this might be a postfix expression, get rid of ParenListExprs.
4148   if (isa<ParenListExpr>(base)) {
4149     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4150     if (result.isInvalid()) return ExprError();
4151     base = result.get();
4152   }
4153 
4154   // Handle any non-overload placeholder types in the base and index
4155   // expressions.  We can't handle overloads here because the other
4156   // operand might be an overloadable type, in which case the overload
4157   // resolution for the operator overload should get the first crack
4158   // at the overload.
4159   bool IsMSPropertySubscript = false;
4160   if (base->getType()->isNonOverloadPlaceholderType()) {
4161     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4162     if (!IsMSPropertySubscript) {
4163       ExprResult result = CheckPlaceholderExpr(base);
4164       if (result.isInvalid())
4165         return ExprError();
4166       base = result.get();
4167     }
4168   }
4169   if (idx->getType()->isNonOverloadPlaceholderType()) {
4170     ExprResult result = CheckPlaceholderExpr(idx);
4171     if (result.isInvalid()) return ExprError();
4172     idx = result.get();
4173   }
4174 
4175   // Build an unanalyzed expression if either operand is type-dependent.
4176   if (getLangOpts().CPlusPlus &&
4177       (base->isTypeDependent() || idx->isTypeDependent())) {
4178     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4179                                             VK_LValue, OK_Ordinary, rbLoc);
4180   }
4181 
4182   // MSDN, property (C++)
4183   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4184   // This attribute can also be used in the declaration of an empty array in a
4185   // class or structure definition. For example:
4186   // __declspec(property(get=GetX, put=PutX)) int x[];
4187   // The above statement indicates that x[] can be used with one or more array
4188   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4189   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4190   if (IsMSPropertySubscript) {
4191     // Build MS property subscript expression if base is MS property reference
4192     // or MS property subscript.
4193     return new (Context) MSPropertySubscriptExpr(
4194         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4195   }
4196 
4197   // Use C++ overloaded-operator rules if either operand has record
4198   // type.  The spec says to do this if either type is *overloadable*,
4199   // but enum types can't declare subscript operators or conversion
4200   // operators, so there's nothing interesting for overload resolution
4201   // to do if there aren't any record types involved.
4202   //
4203   // ObjC pointers have their own subscripting logic that is not tied
4204   // to overload resolution and so should not take this path.
4205   if (getLangOpts().CPlusPlus &&
4206       (base->getType()->isRecordType() ||
4207        (!base->getType()->isObjCObjectPointerType() &&
4208         idx->getType()->isRecordType()))) {
4209     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4210   }
4211 
4212   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4213 }
4214 
4215 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4216                                           Expr *LowerBound,
4217                                           SourceLocation ColonLoc, Expr *Length,
4218                                           SourceLocation RBLoc) {
4219   if (Base->getType()->isPlaceholderType() &&
4220       !Base->getType()->isSpecificPlaceholderType(
4221           BuiltinType::OMPArraySection)) {
4222     ExprResult Result = CheckPlaceholderExpr(Base);
4223     if (Result.isInvalid())
4224       return ExprError();
4225     Base = Result.get();
4226   }
4227   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4228     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4229     if (Result.isInvalid())
4230       return ExprError();
4231     Result = DefaultLvalueConversion(Result.get());
4232     if (Result.isInvalid())
4233       return ExprError();
4234     LowerBound = Result.get();
4235   }
4236   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4237     ExprResult Result = CheckPlaceholderExpr(Length);
4238     if (Result.isInvalid())
4239       return ExprError();
4240     Result = DefaultLvalueConversion(Result.get());
4241     if (Result.isInvalid())
4242       return ExprError();
4243     Length = Result.get();
4244   }
4245 
4246   // Build an unanalyzed expression if either operand is type-dependent.
4247   if (Base->isTypeDependent() ||
4248       (LowerBound &&
4249        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4250       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4251     return new (Context)
4252         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4253                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4254   }
4255 
4256   // Perform default conversions.
4257   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4258   QualType ResultTy;
4259   if (OriginalTy->isAnyPointerType()) {
4260     ResultTy = OriginalTy->getPointeeType();
4261   } else if (OriginalTy->isArrayType()) {
4262     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4263   } else {
4264     return ExprError(
4265         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4266         << Base->getSourceRange());
4267   }
4268   // C99 6.5.2.1p1
4269   if (LowerBound) {
4270     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4271                                                       LowerBound);
4272     if (Res.isInvalid())
4273       return ExprError(Diag(LowerBound->getExprLoc(),
4274                             diag::err_omp_typecheck_section_not_integer)
4275                        << 0 << LowerBound->getSourceRange());
4276     LowerBound = Res.get();
4277 
4278     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4279         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4280       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4281           << 0 << LowerBound->getSourceRange();
4282   }
4283   if (Length) {
4284     auto Res =
4285         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4286     if (Res.isInvalid())
4287       return ExprError(Diag(Length->getExprLoc(),
4288                             diag::err_omp_typecheck_section_not_integer)
4289                        << 1 << Length->getSourceRange());
4290     Length = Res.get();
4291 
4292     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4293         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4294       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4295           << 1 << Length->getSourceRange();
4296   }
4297 
4298   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4299   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4300   // type. Note that functions are not objects, and that (in C99 parlance)
4301   // incomplete types are not object types.
4302   if (ResultTy->isFunctionType()) {
4303     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4304         << ResultTy << Base->getSourceRange();
4305     return ExprError();
4306   }
4307 
4308   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4309                           diag::err_omp_section_incomplete_type, Base))
4310     return ExprError();
4311 
4312   if (LowerBound) {
4313     llvm::APSInt LowerBoundValue;
4314     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4315       // OpenMP 4.0, [2.4 Array Sections]
4316       // The lower-bound and length must evaluate to non-negative integers.
4317       if (LowerBoundValue.isNegative()) {
4318         Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative)
4319             << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true)
4320             << LowerBound->getSourceRange();
4321         return ExprError();
4322       }
4323     }
4324   }
4325 
4326   if (Length) {
4327     llvm::APSInt LengthValue;
4328     if (Length->EvaluateAsInt(LengthValue, Context)) {
4329       // OpenMP 4.0, [2.4 Array Sections]
4330       // The lower-bound and length must evaluate to non-negative integers.
4331       if (LengthValue.isNegative()) {
4332         Diag(Length->getExprLoc(), diag::err_omp_section_negative)
4333             << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4334             << Length->getSourceRange();
4335         return ExprError();
4336       }
4337     }
4338   } else if (ColonLoc.isValid() &&
4339              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4340                                       !OriginalTy->isVariableArrayType()))) {
4341     // OpenMP 4.0, [2.4 Array Sections]
4342     // When the size of the array dimension is not known, the length must be
4343     // specified explicitly.
4344     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4345         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4346     return ExprError();
4347   }
4348 
4349   if (!Base->getType()->isSpecificPlaceholderType(
4350           BuiltinType::OMPArraySection)) {
4351     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4352     if (Result.isInvalid())
4353       return ExprError();
4354     Base = Result.get();
4355   }
4356   return new (Context)
4357       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4358                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4359 }
4360 
4361 ExprResult
4362 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4363                                       Expr *Idx, SourceLocation RLoc) {
4364   Expr *LHSExp = Base;
4365   Expr *RHSExp = Idx;
4366 
4367   // Perform default conversions.
4368   if (!LHSExp->getType()->getAs<VectorType>()) {
4369     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4370     if (Result.isInvalid())
4371       return ExprError();
4372     LHSExp = Result.get();
4373   }
4374   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4375   if (Result.isInvalid())
4376     return ExprError();
4377   RHSExp = Result.get();
4378 
4379   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4380   ExprValueKind VK = VK_LValue;
4381   ExprObjectKind OK = OK_Ordinary;
4382 
4383   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4384   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4385   // in the subscript position. As a result, we need to derive the array base
4386   // and index from the expression types.
4387   Expr *BaseExpr, *IndexExpr;
4388   QualType ResultType;
4389   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4390     BaseExpr = LHSExp;
4391     IndexExpr = RHSExp;
4392     ResultType = Context.DependentTy;
4393   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4394     BaseExpr = LHSExp;
4395     IndexExpr = RHSExp;
4396     ResultType = PTy->getPointeeType();
4397   } else if (const ObjCObjectPointerType *PTy =
4398                LHSTy->getAs<ObjCObjectPointerType>()) {
4399     BaseExpr = LHSExp;
4400     IndexExpr = RHSExp;
4401 
4402     // Use custom logic if this should be the pseudo-object subscript
4403     // expression.
4404     if (!LangOpts.isSubscriptPointerArithmetic())
4405       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4406                                           nullptr);
4407 
4408     ResultType = PTy->getPointeeType();
4409   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4410      // Handle the uncommon case of "123[Ptr]".
4411     BaseExpr = RHSExp;
4412     IndexExpr = LHSExp;
4413     ResultType = PTy->getPointeeType();
4414   } else if (const ObjCObjectPointerType *PTy =
4415                RHSTy->getAs<ObjCObjectPointerType>()) {
4416      // Handle the uncommon case of "123[Ptr]".
4417     BaseExpr = RHSExp;
4418     IndexExpr = LHSExp;
4419     ResultType = PTy->getPointeeType();
4420     if (!LangOpts.isSubscriptPointerArithmetic()) {
4421       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4422         << ResultType << BaseExpr->getSourceRange();
4423       return ExprError();
4424     }
4425   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4426     BaseExpr = LHSExp;    // vectors: V[123]
4427     IndexExpr = RHSExp;
4428     VK = LHSExp->getValueKind();
4429     if (VK != VK_RValue)
4430       OK = OK_VectorComponent;
4431 
4432     // FIXME: need to deal with const...
4433     ResultType = VTy->getElementType();
4434   } else if (LHSTy->isArrayType()) {
4435     // If we see an array that wasn't promoted by
4436     // DefaultFunctionArrayLvalueConversion, it must be an array that
4437     // wasn't promoted because of the C90 rule that doesn't
4438     // allow promoting non-lvalue arrays.  Warn, then
4439     // force the promotion here.
4440     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4441         LHSExp->getSourceRange();
4442     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4443                                CK_ArrayToPointerDecay).get();
4444     LHSTy = LHSExp->getType();
4445 
4446     BaseExpr = LHSExp;
4447     IndexExpr = RHSExp;
4448     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4449   } else if (RHSTy->isArrayType()) {
4450     // Same as previous, except for 123[f().a] case
4451     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4452         RHSExp->getSourceRange();
4453     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4454                                CK_ArrayToPointerDecay).get();
4455     RHSTy = RHSExp->getType();
4456 
4457     BaseExpr = RHSExp;
4458     IndexExpr = LHSExp;
4459     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4460   } else {
4461     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4462        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4463   }
4464   // C99 6.5.2.1p1
4465   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4466     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4467                      << IndexExpr->getSourceRange());
4468 
4469   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4470        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4471          && !IndexExpr->isTypeDependent())
4472     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4473 
4474   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4475   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4476   // type. Note that Functions are not objects, and that (in C99 parlance)
4477   // incomplete types are not object types.
4478   if (ResultType->isFunctionType()) {
4479     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4480       << ResultType << BaseExpr->getSourceRange();
4481     return ExprError();
4482   }
4483 
4484   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4485     // GNU extension: subscripting on pointer to void
4486     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4487       << BaseExpr->getSourceRange();
4488 
4489     // C forbids expressions of unqualified void type from being l-values.
4490     // See IsCForbiddenLValueType.
4491     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4492   } else if (!ResultType->isDependentType() &&
4493       RequireCompleteType(LLoc, ResultType,
4494                           diag::err_subscript_incomplete_type, BaseExpr))
4495     return ExprError();
4496 
4497   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4498          !ResultType.isCForbiddenLValueType());
4499 
4500   return new (Context)
4501       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4502 }
4503 
4504 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4505                                         FunctionDecl *FD,
4506                                         ParmVarDecl *Param) {
4507   if (Param->hasUnparsedDefaultArg()) {
4508     Diag(CallLoc,
4509          diag::err_use_of_default_argument_to_function_declared_later) <<
4510       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4511     Diag(UnparsedDefaultArgLocs[Param],
4512          diag::note_default_argument_declared_here);
4513     return ExprError();
4514   }
4515 
4516   if (Param->hasUninstantiatedDefaultArg()) {
4517     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4518 
4519     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4520                                                  Param);
4521 
4522     // Instantiate the expression.
4523     MultiLevelTemplateArgumentList MutiLevelArgList
4524       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4525 
4526     InstantiatingTemplate Inst(*this, CallLoc, Param,
4527                                MutiLevelArgList.getInnermost());
4528     if (Inst.isInvalid())
4529       return ExprError();
4530 
4531     ExprResult Result;
4532     {
4533       // C++ [dcl.fct.default]p5:
4534       //   The names in the [default argument] expression are bound, and
4535       //   the semantic constraints are checked, at the point where the
4536       //   default argument expression appears.
4537       ContextRAII SavedContext(*this, FD);
4538       LocalInstantiationScope Local(*this);
4539       Result = SubstExpr(UninstExpr, MutiLevelArgList);
4540     }
4541     if (Result.isInvalid())
4542       return ExprError();
4543 
4544     // Check the expression as an initializer for the parameter.
4545     InitializedEntity Entity
4546       = InitializedEntity::InitializeParameter(Context, Param);
4547     InitializationKind Kind
4548       = InitializationKind::CreateCopy(Param->getLocation(),
4549              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4550     Expr *ResultE = Result.getAs<Expr>();
4551 
4552     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4553     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4554     if (Result.isInvalid())
4555       return ExprError();
4556 
4557     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4558                                  Param->getOuterLocStart());
4559     if (Result.isInvalid())
4560       return ExprError();
4561 
4562     // Remember the instantiated default argument.
4563     Param->setDefaultArg(Result.getAs<Expr>());
4564     if (ASTMutationListener *L = getASTMutationListener()) {
4565       L->DefaultArgumentInstantiated(Param);
4566     }
4567   }
4568 
4569   // If the default expression creates temporaries, we need to
4570   // push them to the current stack of expression temporaries so they'll
4571   // be properly destroyed.
4572   // FIXME: We should really be rebuilding the default argument with new
4573   // bound temporaries; see the comment in PR5810.
4574   // We don't need to do that with block decls, though, because
4575   // blocks in default argument expression can never capture anything.
4576   if (isa<ExprWithCleanups>(Param->getInit())) {
4577     // Set the "needs cleanups" bit regardless of whether there are
4578     // any explicit objects.
4579     ExprNeedsCleanups = true;
4580 
4581     // Append all the objects to the cleanup list.  Right now, this
4582     // should always be a no-op, because blocks in default argument
4583     // expressions should never be able to capture anything.
4584     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
4585            "default argument expression has capturing blocks?");
4586   }
4587 
4588   // We already type-checked the argument, so we know it works.
4589   // Just mark all of the declarations in this potentially-evaluated expression
4590   // as being "referenced".
4591   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4592                                    /*SkipLocalVariables=*/true);
4593   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4594 }
4595 
4596 
4597 Sema::VariadicCallType
4598 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4599                           Expr *Fn) {
4600   if (Proto && Proto->isVariadic()) {
4601     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4602       return VariadicConstructor;
4603     else if (Fn && Fn->getType()->isBlockPointerType())
4604       return VariadicBlock;
4605     else if (FDecl) {
4606       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4607         if (Method->isInstance())
4608           return VariadicMethod;
4609     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4610       return VariadicMethod;
4611     return VariadicFunction;
4612   }
4613   return VariadicDoesNotApply;
4614 }
4615 
4616 namespace {
4617 class FunctionCallCCC : public FunctionCallFilterCCC {
4618 public:
4619   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4620                   unsigned NumArgs, MemberExpr *ME)
4621       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4622         FunctionName(FuncName) {}
4623 
4624   bool ValidateCandidate(const TypoCorrection &candidate) override {
4625     if (!candidate.getCorrectionSpecifier() ||
4626         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4627       return false;
4628     }
4629 
4630     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4631   }
4632 
4633 private:
4634   const IdentifierInfo *const FunctionName;
4635 };
4636 }
4637 
4638 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4639                                                FunctionDecl *FDecl,
4640                                                ArrayRef<Expr *> Args) {
4641   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4642   DeclarationName FuncName = FDecl->getDeclName();
4643   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4644 
4645   if (TypoCorrection Corrected = S.CorrectTypo(
4646           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4647           S.getScopeForContext(S.CurContext), nullptr,
4648           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4649                                              Args.size(), ME),
4650           Sema::CTK_ErrorRecovery)) {
4651     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4652       if (Corrected.isOverloaded()) {
4653         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4654         OverloadCandidateSet::iterator Best;
4655         for (NamedDecl *CD : Corrected) {
4656           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4657             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4658                                    OCS);
4659         }
4660         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4661         case OR_Success:
4662           ND = Best->FoundDecl;
4663           Corrected.setCorrectionDecl(ND);
4664           break;
4665         default:
4666           break;
4667         }
4668       }
4669       ND = ND->getUnderlyingDecl();
4670       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4671         return Corrected;
4672     }
4673   }
4674   return TypoCorrection();
4675 }
4676 
4677 /// ConvertArgumentsForCall - Converts the arguments specified in
4678 /// Args/NumArgs to the parameter types of the function FDecl with
4679 /// function prototype Proto. Call is the call expression itself, and
4680 /// Fn is the function expression. For a C++ member function, this
4681 /// routine does not attempt to convert the object argument. Returns
4682 /// true if the call is ill-formed.
4683 bool
4684 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4685                               FunctionDecl *FDecl,
4686                               const FunctionProtoType *Proto,
4687                               ArrayRef<Expr *> Args,
4688                               SourceLocation RParenLoc,
4689                               bool IsExecConfig) {
4690   // Bail out early if calling a builtin with custom typechecking.
4691   if (FDecl)
4692     if (unsigned ID = FDecl->getBuiltinID())
4693       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4694         return false;
4695 
4696   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4697   // assignment, to the types of the corresponding parameter, ...
4698   unsigned NumParams = Proto->getNumParams();
4699   bool Invalid = false;
4700   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4701   unsigned FnKind = Fn->getType()->isBlockPointerType()
4702                        ? 1 /* block */
4703                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4704                                        : 0 /* function */);
4705 
4706   // If too few arguments are available (and we don't have default
4707   // arguments for the remaining parameters), don't make the call.
4708   if (Args.size() < NumParams) {
4709     if (Args.size() < MinArgs) {
4710       TypoCorrection TC;
4711       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4712         unsigned diag_id =
4713             MinArgs == NumParams && !Proto->isVariadic()
4714                 ? diag::err_typecheck_call_too_few_args_suggest
4715                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4716         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4717                                         << static_cast<unsigned>(Args.size())
4718                                         << TC.getCorrectionRange());
4719       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4720         Diag(RParenLoc,
4721              MinArgs == NumParams && !Proto->isVariadic()
4722                  ? diag::err_typecheck_call_too_few_args_one
4723                  : diag::err_typecheck_call_too_few_args_at_least_one)
4724             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4725       else
4726         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4727                             ? diag::err_typecheck_call_too_few_args
4728                             : diag::err_typecheck_call_too_few_args_at_least)
4729             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4730             << Fn->getSourceRange();
4731 
4732       // Emit the location of the prototype.
4733       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4734         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4735           << FDecl;
4736 
4737       return true;
4738     }
4739     Call->setNumArgs(Context, NumParams);
4740   }
4741 
4742   // If too many are passed and not variadic, error on the extras and drop
4743   // them.
4744   if (Args.size() > NumParams) {
4745     if (!Proto->isVariadic()) {
4746       TypoCorrection TC;
4747       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4748         unsigned diag_id =
4749             MinArgs == NumParams && !Proto->isVariadic()
4750                 ? diag::err_typecheck_call_too_many_args_suggest
4751                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4752         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4753                                         << static_cast<unsigned>(Args.size())
4754                                         << TC.getCorrectionRange());
4755       } else if (NumParams == 1 && FDecl &&
4756                  FDecl->getParamDecl(0)->getDeclName())
4757         Diag(Args[NumParams]->getLocStart(),
4758              MinArgs == NumParams
4759                  ? diag::err_typecheck_call_too_many_args_one
4760                  : diag::err_typecheck_call_too_many_args_at_most_one)
4761             << FnKind << FDecl->getParamDecl(0)
4762             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4763             << SourceRange(Args[NumParams]->getLocStart(),
4764                            Args.back()->getLocEnd());
4765       else
4766         Diag(Args[NumParams]->getLocStart(),
4767              MinArgs == NumParams
4768                  ? diag::err_typecheck_call_too_many_args
4769                  : diag::err_typecheck_call_too_many_args_at_most)
4770             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4771             << Fn->getSourceRange()
4772             << SourceRange(Args[NumParams]->getLocStart(),
4773                            Args.back()->getLocEnd());
4774 
4775       // Emit the location of the prototype.
4776       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4777         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4778           << FDecl;
4779 
4780       // This deletes the extra arguments.
4781       Call->setNumArgs(Context, NumParams);
4782       return true;
4783     }
4784   }
4785   SmallVector<Expr *, 8> AllArgs;
4786   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4787 
4788   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4789                                    Proto, 0, Args, AllArgs, CallType);
4790   if (Invalid)
4791     return true;
4792   unsigned TotalNumArgs = AllArgs.size();
4793   for (unsigned i = 0; i < TotalNumArgs; ++i)
4794     Call->setArg(i, AllArgs[i]);
4795 
4796   return false;
4797 }
4798 
4799 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4800                                   const FunctionProtoType *Proto,
4801                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4802                                   SmallVectorImpl<Expr *> &AllArgs,
4803                                   VariadicCallType CallType, bool AllowExplicit,
4804                                   bool IsListInitialization) {
4805   unsigned NumParams = Proto->getNumParams();
4806   bool Invalid = false;
4807   size_t ArgIx = 0;
4808   // Continue to check argument types (even if we have too few/many args).
4809   for (unsigned i = FirstParam; i < NumParams; i++) {
4810     QualType ProtoArgType = Proto->getParamType(i);
4811 
4812     Expr *Arg;
4813     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4814     if (ArgIx < Args.size()) {
4815       Arg = Args[ArgIx++];
4816 
4817       if (RequireCompleteType(Arg->getLocStart(),
4818                               ProtoArgType,
4819                               diag::err_call_incomplete_argument, Arg))
4820         return true;
4821 
4822       // Strip the unbridged-cast placeholder expression off, if applicable.
4823       bool CFAudited = false;
4824       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4825           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4826           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4827         Arg = stripARCUnbridgedCast(Arg);
4828       else if (getLangOpts().ObjCAutoRefCount &&
4829                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4830                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4831         CFAudited = true;
4832 
4833       InitializedEntity Entity =
4834           Param ? InitializedEntity::InitializeParameter(Context, Param,
4835                                                          ProtoArgType)
4836                 : InitializedEntity::InitializeParameter(
4837                       Context, ProtoArgType, Proto->isParamConsumed(i));
4838 
4839       // Remember that parameter belongs to a CF audited API.
4840       if (CFAudited)
4841         Entity.setParameterCFAudited();
4842 
4843       ExprResult ArgE = PerformCopyInitialization(
4844           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4845       if (ArgE.isInvalid())
4846         return true;
4847 
4848       Arg = ArgE.getAs<Expr>();
4849     } else {
4850       assert(Param && "can't use default arguments without a known callee");
4851 
4852       ExprResult ArgExpr =
4853         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4854       if (ArgExpr.isInvalid())
4855         return true;
4856 
4857       Arg = ArgExpr.getAs<Expr>();
4858     }
4859 
4860     // Check for array bounds violations for each argument to the call. This
4861     // check only triggers warnings when the argument isn't a more complex Expr
4862     // with its own checking, such as a BinaryOperator.
4863     CheckArrayAccess(Arg);
4864 
4865     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4866     CheckStaticArrayArgument(CallLoc, Param, Arg);
4867 
4868     AllArgs.push_back(Arg);
4869   }
4870 
4871   // If this is a variadic call, handle args passed through "...".
4872   if (CallType != VariadicDoesNotApply) {
4873     // Assume that extern "C" functions with variadic arguments that
4874     // return __unknown_anytype aren't *really* variadic.
4875     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4876         FDecl->isExternC()) {
4877       for (Expr *A : Args.slice(ArgIx)) {
4878         QualType paramType; // ignored
4879         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4880         Invalid |= arg.isInvalid();
4881         AllArgs.push_back(arg.get());
4882       }
4883 
4884     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4885     } else {
4886       for (Expr *A : Args.slice(ArgIx)) {
4887         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4888         Invalid |= Arg.isInvalid();
4889         AllArgs.push_back(Arg.get());
4890       }
4891     }
4892 
4893     // Check for array bounds violations.
4894     for (Expr *A : Args.slice(ArgIx))
4895       CheckArrayAccess(A);
4896   }
4897   return Invalid;
4898 }
4899 
4900 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4901   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4902   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4903     TL = DTL.getOriginalLoc();
4904   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4905     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4906       << ATL.getLocalSourceRange();
4907 }
4908 
4909 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4910 /// array parameter, check that it is non-null, and that if it is formed by
4911 /// array-to-pointer decay, the underlying array is sufficiently large.
4912 ///
4913 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4914 /// array type derivation, then for each call to the function, the value of the
4915 /// corresponding actual argument shall provide access to the first element of
4916 /// an array with at least as many elements as specified by the size expression.
4917 void
4918 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4919                                ParmVarDecl *Param,
4920                                const Expr *ArgExpr) {
4921   // Static array parameters are not supported in C++.
4922   if (!Param || getLangOpts().CPlusPlus)
4923     return;
4924 
4925   QualType OrigTy = Param->getOriginalType();
4926 
4927   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4928   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4929     return;
4930 
4931   if (ArgExpr->isNullPointerConstant(Context,
4932                                      Expr::NPC_NeverValueDependent)) {
4933     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4934     DiagnoseCalleeStaticArrayParam(*this, Param);
4935     return;
4936   }
4937 
4938   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4939   if (!CAT)
4940     return;
4941 
4942   const ConstantArrayType *ArgCAT =
4943     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4944   if (!ArgCAT)
4945     return;
4946 
4947   if (ArgCAT->getSize().ult(CAT->getSize())) {
4948     Diag(CallLoc, diag::warn_static_array_too_small)
4949       << ArgExpr->getSourceRange()
4950       << (unsigned) ArgCAT->getSize().getZExtValue()
4951       << (unsigned) CAT->getSize().getZExtValue();
4952     DiagnoseCalleeStaticArrayParam(*this, Param);
4953   }
4954 }
4955 
4956 /// Given a function expression of unknown-any type, try to rebuild it
4957 /// to have a function type.
4958 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4959 
4960 /// Is the given type a placeholder that we need to lower out
4961 /// immediately during argument processing?
4962 static bool isPlaceholderToRemoveAsArg(QualType type) {
4963   // Placeholders are never sugared.
4964   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4965   if (!placeholder) return false;
4966 
4967   switch (placeholder->getKind()) {
4968   // Ignore all the non-placeholder types.
4969 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4970   case BuiltinType::Id:
4971 #include "clang/Basic/OpenCLImageTypes.def"
4972 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4973 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4974 #include "clang/AST/BuiltinTypes.def"
4975     return false;
4976 
4977   // We cannot lower out overload sets; they might validly be resolved
4978   // by the call machinery.
4979   case BuiltinType::Overload:
4980     return false;
4981 
4982   // Unbridged casts in ARC can be handled in some call positions and
4983   // should be left in place.
4984   case BuiltinType::ARCUnbridgedCast:
4985     return false;
4986 
4987   // Pseudo-objects should be converted as soon as possible.
4988   case BuiltinType::PseudoObject:
4989     return true;
4990 
4991   // The debugger mode could theoretically but currently does not try
4992   // to resolve unknown-typed arguments based on known parameter types.
4993   case BuiltinType::UnknownAny:
4994     return true;
4995 
4996   // These are always invalid as call arguments and should be reported.
4997   case BuiltinType::BoundMember:
4998   case BuiltinType::BuiltinFn:
4999   case BuiltinType::OMPArraySection:
5000     return true;
5001 
5002   }
5003   llvm_unreachable("bad builtin type kind");
5004 }
5005 
5006 /// Check an argument list for placeholders that we won't try to
5007 /// handle later.
5008 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5009   // Apply this processing to all the arguments at once instead of
5010   // dying at the first failure.
5011   bool hasInvalid = false;
5012   for (size_t i = 0, e = args.size(); i != e; i++) {
5013     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5014       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5015       if (result.isInvalid()) hasInvalid = true;
5016       else args[i] = result.get();
5017     } else if (hasInvalid) {
5018       (void)S.CorrectDelayedTyposInExpr(args[i]);
5019     }
5020   }
5021   return hasInvalid;
5022 }
5023 
5024 /// If a builtin function has a pointer argument with no explicit address
5025 /// space, then it should be able to accept a pointer to any address
5026 /// space as input.  In order to do this, we need to replace the
5027 /// standard builtin declaration with one that uses the same address space
5028 /// as the call.
5029 ///
5030 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5031 ///                  it does not contain any pointer arguments without
5032 ///                  an address space qualifer.  Otherwise the rewritten
5033 ///                  FunctionDecl is returned.
5034 /// TODO: Handle pointer return types.
5035 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5036                                                 const FunctionDecl *FDecl,
5037                                                 MultiExprArg ArgExprs) {
5038 
5039   QualType DeclType = FDecl->getType();
5040   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5041 
5042   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5043       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5044     return nullptr;
5045 
5046   bool NeedsNewDecl = false;
5047   unsigned i = 0;
5048   SmallVector<QualType, 8> OverloadParams;
5049 
5050   for (QualType ParamType : FT->param_types()) {
5051 
5052     // Convert array arguments to pointer to simplify type lookup.
5053     Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get();
5054     QualType ArgType = Arg->getType();
5055     if (!ParamType->isPointerType() ||
5056         ParamType.getQualifiers().hasAddressSpace() ||
5057         !ArgType->isPointerType() ||
5058         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5059       OverloadParams.push_back(ParamType);
5060       continue;
5061     }
5062 
5063     NeedsNewDecl = true;
5064     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5065 
5066     QualType PointeeType = ParamType->getPointeeType();
5067     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5068     OverloadParams.push_back(Context.getPointerType(PointeeType));
5069   }
5070 
5071   if (!NeedsNewDecl)
5072     return nullptr;
5073 
5074   FunctionProtoType::ExtProtoInfo EPI;
5075   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5076                                                 OverloadParams, EPI);
5077   DeclContext *Parent = Context.getTranslationUnitDecl();
5078   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5079                                                     FDecl->getLocation(),
5080                                                     FDecl->getLocation(),
5081                                                     FDecl->getIdentifier(),
5082                                                     OverloadTy,
5083                                                     /*TInfo=*/nullptr,
5084                                                     SC_Extern, false,
5085                                                     /*hasPrototype=*/true);
5086   SmallVector<ParmVarDecl*, 16> Params;
5087   FT = cast<FunctionProtoType>(OverloadTy);
5088   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5089     QualType ParamType = FT->getParamType(i);
5090     ParmVarDecl *Parm =
5091         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5092                                 SourceLocation(), nullptr, ParamType,
5093                                 /*TInfo=*/nullptr, SC_None, nullptr);
5094     Parm->setScopeInfo(0, i);
5095     Params.push_back(Parm);
5096   }
5097   OverloadDecl->setParams(Params);
5098   return OverloadDecl;
5099 }
5100 
5101 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee,
5102                                        std::size_t NumArgs) {
5103   if (S.TooManyArguments(Callee->getNumParams(), NumArgs,
5104                          /*PartialOverloading=*/false))
5105     return Callee->isVariadic();
5106   return Callee->getMinRequiredArguments() <= NumArgs;
5107 }
5108 
5109 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5110 /// This provides the location of the left/right parens and a list of comma
5111 /// locations.
5112 ExprResult
5113 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5114                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
5115                     Expr *ExecConfig, bool IsExecConfig) {
5116   // Since this might be a postfix expression, get rid of ParenListExprs.
5117   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
5118   if (Result.isInvalid()) return ExprError();
5119   Fn = Result.get();
5120 
5121   if (checkArgsForPlaceholders(*this, ArgExprs))
5122     return ExprError();
5123 
5124   if (getLangOpts().CPlusPlus) {
5125     // If this is a pseudo-destructor expression, build the call immediately.
5126     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5127       if (!ArgExprs.empty()) {
5128         // Pseudo-destructor calls should not have any arguments.
5129         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5130           << FixItHint::CreateRemoval(
5131                                     SourceRange(ArgExprs.front()->getLocStart(),
5132                                                 ArgExprs.back()->getLocEnd()));
5133       }
5134 
5135       return new (Context)
5136           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5137     }
5138     if (Fn->getType() == Context.PseudoObjectTy) {
5139       ExprResult result = CheckPlaceholderExpr(Fn);
5140       if (result.isInvalid()) return ExprError();
5141       Fn = result.get();
5142     }
5143 
5144     // Determine whether this is a dependent call inside a C++ template,
5145     // in which case we won't do any semantic analysis now.
5146     bool Dependent = false;
5147     if (Fn->isTypeDependent())
5148       Dependent = true;
5149     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5150       Dependent = true;
5151 
5152     if (Dependent) {
5153       if (ExecConfig) {
5154         return new (Context) CUDAKernelCallExpr(
5155             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5156             Context.DependentTy, VK_RValue, RParenLoc);
5157       } else {
5158         return new (Context) CallExpr(
5159             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5160       }
5161     }
5162 
5163     // Determine whether this is a call to an object (C++ [over.call.object]).
5164     if (Fn->getType()->isRecordType())
5165       return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
5166                                           RParenLoc);
5167 
5168     if (Fn->getType() == Context.UnknownAnyTy) {
5169       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5170       if (result.isInvalid()) return ExprError();
5171       Fn = result.get();
5172     }
5173 
5174     if (Fn->getType() == Context.BoundMemberTy) {
5175       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
5176     }
5177   }
5178 
5179   // Check for overloaded calls.  This can happen even in C due to extensions.
5180   if (Fn->getType() == Context.OverloadTy) {
5181     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5182 
5183     // We aren't supposed to apply this logic for if there's an '&' involved.
5184     if (!find.HasFormOfMemberPointer) {
5185       OverloadExpr *ovl = find.Expression;
5186       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5187         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
5188                                        RParenLoc, ExecConfig,
5189                                        /*AllowTypoCorrection=*/true,
5190                                        find.IsAddressOfOperand);
5191       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
5192     }
5193   }
5194 
5195   // If we're directly calling a function, get the appropriate declaration.
5196   if (Fn->getType() == Context.UnknownAnyTy) {
5197     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5198     if (result.isInvalid()) return ExprError();
5199     Fn = result.get();
5200   }
5201 
5202   Expr *NakedFn = Fn->IgnoreParens();
5203 
5204   bool CallingNDeclIndirectly = false;
5205   NamedDecl *NDecl = nullptr;
5206   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5207     if (UnOp->getOpcode() == UO_AddrOf) {
5208       CallingNDeclIndirectly = true;
5209       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5210     }
5211   }
5212 
5213   if (isa<DeclRefExpr>(NakedFn)) {
5214     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5215 
5216     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5217     if (FDecl && FDecl->getBuiltinID()) {
5218       // Rewrite the function decl for this builtin by replacing parameters
5219       // with no explicit address space with the address space of the arguments
5220       // in ArgExprs.
5221       if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5222         NDecl = FDecl;
5223         Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(),
5224                            SourceLocation(), FDecl, false,
5225                            SourceLocation(), FDecl->getType(),
5226                            Fn->getValueKind(), FDecl);
5227       }
5228     }
5229   } else if (isa<MemberExpr>(NakedFn))
5230     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5231 
5232   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5233     if (CallingNDeclIndirectly &&
5234         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5235                                            Fn->getLocStart()))
5236       return ExprError();
5237 
5238     // CheckEnableIf assumes that the we're passing in a sane number of args for
5239     // FD, but that doesn't always hold true here. This is because, in some
5240     // cases, we'll emit a diag about an ill-formed function call, but then
5241     // we'll continue on as if the function call wasn't ill-formed. So, if the
5242     // number of args looks incorrect, don't do enable_if checks; we should've
5243     // already emitted an error about the bad call.
5244     if (FD->hasAttr<EnableIfAttr>() &&
5245         isNumberOfArgsValidForCall(*this, FD, ArgExprs.size())) {
5246       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
5247         Diag(Fn->getLocStart(),
5248              isa<CXXMethodDecl>(FD) ?
5249                  diag::err_ovl_no_viable_member_function_in_call :
5250                  diag::err_ovl_no_viable_function_in_call)
5251           << FD << FD->getSourceRange();
5252         Diag(FD->getLocation(),
5253              diag::note_ovl_candidate_disabled_by_enable_if_attr)
5254             << Attr->getCond()->getSourceRange() << Attr->getMessage();
5255       }
5256     }
5257   }
5258 
5259   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5260                                ExecConfig, IsExecConfig);
5261 }
5262 
5263 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5264 ///
5265 /// __builtin_astype( value, dst type )
5266 ///
5267 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5268                                  SourceLocation BuiltinLoc,
5269                                  SourceLocation RParenLoc) {
5270   ExprValueKind VK = VK_RValue;
5271   ExprObjectKind OK = OK_Ordinary;
5272   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5273   QualType SrcTy = E->getType();
5274   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5275     return ExprError(Diag(BuiltinLoc,
5276                           diag::err_invalid_astype_of_different_size)
5277                      << DstTy
5278                      << SrcTy
5279                      << E->getSourceRange());
5280   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5281 }
5282 
5283 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5284 /// provided arguments.
5285 ///
5286 /// __builtin_convertvector( value, dst type )
5287 ///
5288 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5289                                         SourceLocation BuiltinLoc,
5290                                         SourceLocation RParenLoc) {
5291   TypeSourceInfo *TInfo;
5292   GetTypeFromParser(ParsedDestTy, &TInfo);
5293   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5294 }
5295 
5296 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5297 /// i.e. an expression not of \p OverloadTy.  The expression should
5298 /// unary-convert to an expression of function-pointer or
5299 /// block-pointer type.
5300 ///
5301 /// \param NDecl the declaration being called, if available
5302 ExprResult
5303 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5304                             SourceLocation LParenLoc,
5305                             ArrayRef<Expr *> Args,
5306                             SourceLocation RParenLoc,
5307                             Expr *Config, bool IsExecConfig) {
5308   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5309   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5310 
5311   // Functions with 'interrupt' attribute cannot be called directly.
5312   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5313     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5314     return ExprError();
5315   }
5316 
5317   // Promote the function operand.
5318   // We special-case function promotion here because we only allow promoting
5319   // builtin functions to function pointers in the callee of a call.
5320   ExprResult Result;
5321   if (BuiltinID &&
5322       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5323     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5324                                CK_BuiltinFnToFnPtr).get();
5325   } else {
5326     Result = CallExprUnaryConversions(Fn);
5327   }
5328   if (Result.isInvalid())
5329     return ExprError();
5330   Fn = Result.get();
5331 
5332   // Make the call expr early, before semantic checks.  This guarantees cleanup
5333   // of arguments and function on error.
5334   CallExpr *TheCall;
5335   if (Config)
5336     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5337                                                cast<CallExpr>(Config), Args,
5338                                                Context.BoolTy, VK_RValue,
5339                                                RParenLoc);
5340   else
5341     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5342                                      VK_RValue, RParenLoc);
5343 
5344   if (!getLangOpts().CPlusPlus) {
5345     // C cannot always handle TypoExpr nodes in builtin calls and direct
5346     // function calls as their argument checking don't necessarily handle
5347     // dependent types properly, so make sure any TypoExprs have been
5348     // dealt with.
5349     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5350     if (!Result.isUsable()) return ExprError();
5351     TheCall = dyn_cast<CallExpr>(Result.get());
5352     if (!TheCall) return Result;
5353     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5354   }
5355 
5356   // Bail out early if calling a builtin with custom typechecking.
5357   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5358     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5359 
5360  retry:
5361   const FunctionType *FuncT;
5362   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5363     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5364     // have type pointer to function".
5365     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5366     if (!FuncT)
5367       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5368                          << Fn->getType() << Fn->getSourceRange());
5369   } else if (const BlockPointerType *BPT =
5370                Fn->getType()->getAs<BlockPointerType>()) {
5371     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5372   } else {
5373     // Handle calls to expressions of unknown-any type.
5374     if (Fn->getType() == Context.UnknownAnyTy) {
5375       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5376       if (rewrite.isInvalid()) return ExprError();
5377       Fn = rewrite.get();
5378       TheCall->setCallee(Fn);
5379       goto retry;
5380     }
5381 
5382     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5383       << Fn->getType() << Fn->getSourceRange());
5384   }
5385 
5386   if (getLangOpts().CUDA) {
5387     if (Config) {
5388       // CUDA: Kernel calls must be to global functions
5389       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5390         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5391             << FDecl->getName() << Fn->getSourceRange());
5392 
5393       // CUDA: Kernel function must have 'void' return type
5394       if (!FuncT->getReturnType()->isVoidType())
5395         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5396             << Fn->getType() << Fn->getSourceRange());
5397     } else {
5398       // CUDA: Calls to global functions must be configured
5399       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5400         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5401             << FDecl->getName() << Fn->getSourceRange());
5402     }
5403   }
5404 
5405   // Check for a valid return type
5406   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5407                           FDecl))
5408     return ExprError();
5409 
5410   // We know the result type of the call, set it.
5411   TheCall->setType(FuncT->getCallResultType(Context));
5412   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5413 
5414   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5415   if (Proto) {
5416     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5417                                 IsExecConfig))
5418       return ExprError();
5419   } else {
5420     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5421 
5422     if (FDecl) {
5423       // Check if we have too few/too many template arguments, based
5424       // on our knowledge of the function definition.
5425       const FunctionDecl *Def = nullptr;
5426       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5427         Proto = Def->getType()->getAs<FunctionProtoType>();
5428        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5429           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5430           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5431       }
5432 
5433       // If the function we're calling isn't a function prototype, but we have
5434       // a function prototype from a prior declaratiom, use that prototype.
5435       if (!FDecl->hasPrototype())
5436         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5437     }
5438 
5439     // Promote the arguments (C99 6.5.2.2p6).
5440     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5441       Expr *Arg = Args[i];
5442 
5443       if (Proto && i < Proto->getNumParams()) {
5444         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5445             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5446         ExprResult ArgE =
5447             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5448         if (ArgE.isInvalid())
5449           return true;
5450 
5451         Arg = ArgE.getAs<Expr>();
5452 
5453       } else {
5454         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5455 
5456         if (ArgE.isInvalid())
5457           return true;
5458 
5459         Arg = ArgE.getAs<Expr>();
5460       }
5461 
5462       if (RequireCompleteType(Arg->getLocStart(),
5463                               Arg->getType(),
5464                               diag::err_call_incomplete_argument, Arg))
5465         return ExprError();
5466 
5467       TheCall->setArg(i, Arg);
5468     }
5469   }
5470 
5471   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5472     if (!Method->isStatic())
5473       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5474         << Fn->getSourceRange());
5475 
5476   // Check for sentinels
5477   if (NDecl)
5478     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5479 
5480   // Do special checking on direct calls to functions.
5481   if (FDecl) {
5482     if (CheckFunctionCall(FDecl, TheCall, Proto))
5483       return ExprError();
5484 
5485     if (BuiltinID)
5486       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5487   } else if (NDecl) {
5488     if (CheckPointerCall(NDecl, TheCall, Proto))
5489       return ExprError();
5490   } else {
5491     if (CheckOtherCall(TheCall, Proto))
5492       return ExprError();
5493   }
5494 
5495   return MaybeBindToTemporary(TheCall);
5496 }
5497 
5498 ExprResult
5499 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5500                            SourceLocation RParenLoc, Expr *InitExpr) {
5501   assert(Ty && "ActOnCompoundLiteral(): missing type");
5502   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5503 
5504   TypeSourceInfo *TInfo;
5505   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5506   if (!TInfo)
5507     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5508 
5509   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5510 }
5511 
5512 ExprResult
5513 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5514                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5515   QualType literalType = TInfo->getType();
5516 
5517   if (literalType->isArrayType()) {
5518     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5519           diag::err_illegal_decl_array_incomplete_type,
5520           SourceRange(LParenLoc,
5521                       LiteralExpr->getSourceRange().getEnd())))
5522       return ExprError();
5523     if (literalType->isVariableArrayType())
5524       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5525         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5526   } else if (!literalType->isDependentType() &&
5527              RequireCompleteType(LParenLoc, literalType,
5528                diag::err_typecheck_decl_incomplete_type,
5529                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5530     return ExprError();
5531 
5532   InitializedEntity Entity
5533     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5534   InitializationKind Kind
5535     = InitializationKind::CreateCStyleCast(LParenLoc,
5536                                            SourceRange(LParenLoc, RParenLoc),
5537                                            /*InitList=*/true);
5538   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5539   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5540                                       &literalType);
5541   if (Result.isInvalid())
5542     return ExprError();
5543   LiteralExpr = Result.get();
5544 
5545   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
5546   if (isFileScope &&
5547       !LiteralExpr->isTypeDependent() &&
5548       !LiteralExpr->isValueDependent() &&
5549       !literalType->isDependentType()) { // 6.5.2.5p3
5550     if (CheckForConstantInitializer(LiteralExpr, literalType))
5551       return ExprError();
5552   }
5553 
5554   // In C, compound literals are l-values for some reason.
5555   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
5556 
5557   return MaybeBindToTemporary(
5558            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5559                                              VK, LiteralExpr, isFileScope));
5560 }
5561 
5562 ExprResult
5563 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5564                     SourceLocation RBraceLoc) {
5565   // Immediately handle non-overload placeholders.  Overloads can be
5566   // resolved contextually, but everything else here can't.
5567   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5568     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5569       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5570 
5571       // Ignore failures; dropping the entire initializer list because
5572       // of one failure would be terrible for indexing/etc.
5573       if (result.isInvalid()) continue;
5574 
5575       InitArgList[I] = result.get();
5576     }
5577   }
5578 
5579   // Semantic analysis for initializers is done by ActOnDeclarator() and
5580   // CheckInitializer() - it requires knowledge of the object being intialized.
5581 
5582   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5583                                                RBraceLoc);
5584   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5585   return E;
5586 }
5587 
5588 /// Do an explicit extend of the given block pointer if we're in ARC.
5589 void Sema::maybeExtendBlockObject(ExprResult &E) {
5590   assert(E.get()->getType()->isBlockPointerType());
5591   assert(E.get()->isRValue());
5592 
5593   // Only do this in an r-value context.
5594   if (!getLangOpts().ObjCAutoRefCount) return;
5595 
5596   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5597                                CK_ARCExtendBlockObject, E.get(),
5598                                /*base path*/ nullptr, VK_RValue);
5599   ExprNeedsCleanups = true;
5600 }
5601 
5602 /// Prepare a conversion of the given expression to an ObjC object
5603 /// pointer type.
5604 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5605   QualType type = E.get()->getType();
5606   if (type->isObjCObjectPointerType()) {
5607     return CK_BitCast;
5608   } else if (type->isBlockPointerType()) {
5609     maybeExtendBlockObject(E);
5610     return CK_BlockPointerToObjCPointerCast;
5611   } else {
5612     assert(type->isPointerType());
5613     return CK_CPointerToObjCPointerCast;
5614   }
5615 }
5616 
5617 /// Prepares for a scalar cast, performing all the necessary stages
5618 /// except the final cast and returning the kind required.
5619 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5620   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5621   // Also, callers should have filtered out the invalid cases with
5622   // pointers.  Everything else should be possible.
5623 
5624   QualType SrcTy = Src.get()->getType();
5625   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5626     return CK_NoOp;
5627 
5628   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5629   case Type::STK_MemberPointer:
5630     llvm_unreachable("member pointer type in C");
5631 
5632   case Type::STK_CPointer:
5633   case Type::STK_BlockPointer:
5634   case Type::STK_ObjCObjectPointer:
5635     switch (DestTy->getScalarTypeKind()) {
5636     case Type::STK_CPointer: {
5637       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5638       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5639       if (SrcAS != DestAS)
5640         return CK_AddressSpaceConversion;
5641       return CK_BitCast;
5642     }
5643     case Type::STK_BlockPointer:
5644       return (SrcKind == Type::STK_BlockPointer
5645                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5646     case Type::STK_ObjCObjectPointer:
5647       if (SrcKind == Type::STK_ObjCObjectPointer)
5648         return CK_BitCast;
5649       if (SrcKind == Type::STK_CPointer)
5650         return CK_CPointerToObjCPointerCast;
5651       maybeExtendBlockObject(Src);
5652       return CK_BlockPointerToObjCPointerCast;
5653     case Type::STK_Bool:
5654       return CK_PointerToBoolean;
5655     case Type::STK_Integral:
5656       return CK_PointerToIntegral;
5657     case Type::STK_Floating:
5658     case Type::STK_FloatingComplex:
5659     case Type::STK_IntegralComplex:
5660     case Type::STK_MemberPointer:
5661       llvm_unreachable("illegal cast from pointer");
5662     }
5663     llvm_unreachable("Should have returned before this");
5664 
5665   case Type::STK_Bool: // casting from bool is like casting from an integer
5666   case Type::STK_Integral:
5667     switch (DestTy->getScalarTypeKind()) {
5668     case Type::STK_CPointer:
5669     case Type::STK_ObjCObjectPointer:
5670     case Type::STK_BlockPointer:
5671       if (Src.get()->isNullPointerConstant(Context,
5672                                            Expr::NPC_ValueDependentIsNull))
5673         return CK_NullToPointer;
5674       return CK_IntegralToPointer;
5675     case Type::STK_Bool:
5676       return CK_IntegralToBoolean;
5677     case Type::STK_Integral:
5678       return CK_IntegralCast;
5679     case Type::STK_Floating:
5680       return CK_IntegralToFloating;
5681     case Type::STK_IntegralComplex:
5682       Src = ImpCastExprToType(Src.get(),
5683                       DestTy->castAs<ComplexType>()->getElementType(),
5684                       CK_IntegralCast);
5685       return CK_IntegralRealToComplex;
5686     case Type::STK_FloatingComplex:
5687       Src = ImpCastExprToType(Src.get(),
5688                       DestTy->castAs<ComplexType>()->getElementType(),
5689                       CK_IntegralToFloating);
5690       return CK_FloatingRealToComplex;
5691     case Type::STK_MemberPointer:
5692       llvm_unreachable("member pointer type in C");
5693     }
5694     llvm_unreachable("Should have returned before this");
5695 
5696   case Type::STK_Floating:
5697     switch (DestTy->getScalarTypeKind()) {
5698     case Type::STK_Floating:
5699       return CK_FloatingCast;
5700     case Type::STK_Bool:
5701       return CK_FloatingToBoolean;
5702     case Type::STK_Integral:
5703       return CK_FloatingToIntegral;
5704     case Type::STK_FloatingComplex:
5705       Src = ImpCastExprToType(Src.get(),
5706                               DestTy->castAs<ComplexType>()->getElementType(),
5707                               CK_FloatingCast);
5708       return CK_FloatingRealToComplex;
5709     case Type::STK_IntegralComplex:
5710       Src = ImpCastExprToType(Src.get(),
5711                               DestTy->castAs<ComplexType>()->getElementType(),
5712                               CK_FloatingToIntegral);
5713       return CK_IntegralRealToComplex;
5714     case Type::STK_CPointer:
5715     case Type::STK_ObjCObjectPointer:
5716     case Type::STK_BlockPointer:
5717       llvm_unreachable("valid float->pointer cast?");
5718     case Type::STK_MemberPointer:
5719       llvm_unreachable("member pointer type in C");
5720     }
5721     llvm_unreachable("Should have returned before this");
5722 
5723   case Type::STK_FloatingComplex:
5724     switch (DestTy->getScalarTypeKind()) {
5725     case Type::STK_FloatingComplex:
5726       return CK_FloatingComplexCast;
5727     case Type::STK_IntegralComplex:
5728       return CK_FloatingComplexToIntegralComplex;
5729     case Type::STK_Floating: {
5730       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5731       if (Context.hasSameType(ET, DestTy))
5732         return CK_FloatingComplexToReal;
5733       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5734       return CK_FloatingCast;
5735     }
5736     case Type::STK_Bool:
5737       return CK_FloatingComplexToBoolean;
5738     case Type::STK_Integral:
5739       Src = ImpCastExprToType(Src.get(),
5740                               SrcTy->castAs<ComplexType>()->getElementType(),
5741                               CK_FloatingComplexToReal);
5742       return CK_FloatingToIntegral;
5743     case Type::STK_CPointer:
5744     case Type::STK_ObjCObjectPointer:
5745     case Type::STK_BlockPointer:
5746       llvm_unreachable("valid complex float->pointer cast?");
5747     case Type::STK_MemberPointer:
5748       llvm_unreachable("member pointer type in C");
5749     }
5750     llvm_unreachable("Should have returned before this");
5751 
5752   case Type::STK_IntegralComplex:
5753     switch (DestTy->getScalarTypeKind()) {
5754     case Type::STK_FloatingComplex:
5755       return CK_IntegralComplexToFloatingComplex;
5756     case Type::STK_IntegralComplex:
5757       return CK_IntegralComplexCast;
5758     case Type::STK_Integral: {
5759       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5760       if (Context.hasSameType(ET, DestTy))
5761         return CK_IntegralComplexToReal;
5762       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5763       return CK_IntegralCast;
5764     }
5765     case Type::STK_Bool:
5766       return CK_IntegralComplexToBoolean;
5767     case Type::STK_Floating:
5768       Src = ImpCastExprToType(Src.get(),
5769                               SrcTy->castAs<ComplexType>()->getElementType(),
5770                               CK_IntegralComplexToReal);
5771       return CK_IntegralToFloating;
5772     case Type::STK_CPointer:
5773     case Type::STK_ObjCObjectPointer:
5774     case Type::STK_BlockPointer:
5775       llvm_unreachable("valid complex int->pointer cast?");
5776     case Type::STK_MemberPointer:
5777       llvm_unreachable("member pointer type in C");
5778     }
5779     llvm_unreachable("Should have returned before this");
5780   }
5781 
5782   llvm_unreachable("Unhandled scalar cast");
5783 }
5784 
5785 static bool breakDownVectorType(QualType type, uint64_t &len,
5786                                 QualType &eltType) {
5787   // Vectors are simple.
5788   if (const VectorType *vecType = type->getAs<VectorType>()) {
5789     len = vecType->getNumElements();
5790     eltType = vecType->getElementType();
5791     assert(eltType->isScalarType());
5792     return true;
5793   }
5794 
5795   // We allow lax conversion to and from non-vector types, but only if
5796   // they're real types (i.e. non-complex, non-pointer scalar types).
5797   if (!type->isRealType()) return false;
5798 
5799   len = 1;
5800   eltType = type;
5801   return true;
5802 }
5803 
5804 /// Are the two types lax-compatible vector types?  That is, given
5805 /// that one of them is a vector, do they have equal storage sizes,
5806 /// where the storage size is the number of elements times the element
5807 /// size?
5808 ///
5809 /// This will also return false if either of the types is neither a
5810 /// vector nor a real type.
5811 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5812   assert(destTy->isVectorType() || srcTy->isVectorType());
5813 
5814   // Disallow lax conversions between scalars and ExtVectors (these
5815   // conversions are allowed for other vector types because common headers
5816   // depend on them).  Most scalar OP ExtVector cases are handled by the
5817   // splat path anyway, which does what we want (convert, not bitcast).
5818   // What this rules out for ExtVectors is crazy things like char4*float.
5819   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5820   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5821 
5822   uint64_t srcLen, destLen;
5823   QualType srcEltTy, destEltTy;
5824   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5825   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5826 
5827   // ASTContext::getTypeSize will return the size rounded up to a
5828   // power of 2, so instead of using that, we need to use the raw
5829   // element size multiplied by the element count.
5830   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5831   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5832 
5833   return (srcLen * srcEltSize == destLen * destEltSize);
5834 }
5835 
5836 /// Is this a legal conversion between two types, one of which is
5837 /// known to be a vector type?
5838 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5839   assert(destTy->isVectorType() || srcTy->isVectorType());
5840 
5841   if (!Context.getLangOpts().LaxVectorConversions)
5842     return false;
5843   return areLaxCompatibleVectorTypes(srcTy, destTy);
5844 }
5845 
5846 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5847                            CastKind &Kind) {
5848   assert(VectorTy->isVectorType() && "Not a vector type!");
5849 
5850   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5851     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5852       return Diag(R.getBegin(),
5853                   Ty->isVectorType() ?
5854                   diag::err_invalid_conversion_between_vectors :
5855                   diag::err_invalid_conversion_between_vector_and_integer)
5856         << VectorTy << Ty << R;
5857   } else
5858     return Diag(R.getBegin(),
5859                 diag::err_invalid_conversion_between_vector_and_scalar)
5860       << VectorTy << Ty << R;
5861 
5862   Kind = CK_BitCast;
5863   return false;
5864 }
5865 
5866 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5867   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5868 
5869   if (DestElemTy == SplattedExpr->getType())
5870     return SplattedExpr;
5871 
5872   assert(DestElemTy->isFloatingType() ||
5873          DestElemTy->isIntegralOrEnumerationType());
5874 
5875   CastKind CK;
5876   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5877     // OpenCL requires that we convert `true` boolean expressions to -1, but
5878     // only when splatting vectors.
5879     if (DestElemTy->isFloatingType()) {
5880       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5881       // in two steps: boolean to signed integral, then to floating.
5882       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5883                                                  CK_BooleanToSignedIntegral);
5884       SplattedExpr = CastExprRes.get();
5885       CK = CK_IntegralToFloating;
5886     } else {
5887       CK = CK_BooleanToSignedIntegral;
5888     }
5889   } else {
5890     ExprResult CastExprRes = SplattedExpr;
5891     CK = PrepareScalarCast(CastExprRes, DestElemTy);
5892     if (CastExprRes.isInvalid())
5893       return ExprError();
5894     SplattedExpr = CastExprRes.get();
5895   }
5896   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5897 }
5898 
5899 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5900                                     Expr *CastExpr, CastKind &Kind) {
5901   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5902 
5903   QualType SrcTy = CastExpr->getType();
5904 
5905   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5906   // an ExtVectorType.
5907   // In OpenCL, casts between vectors of different types are not allowed.
5908   // (See OpenCL 6.2).
5909   if (SrcTy->isVectorType()) {
5910     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
5911         || (getLangOpts().OpenCL &&
5912             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5913       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5914         << DestTy << SrcTy << R;
5915       return ExprError();
5916     }
5917     Kind = CK_BitCast;
5918     return CastExpr;
5919   }
5920 
5921   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5922   // conversion will take place first from scalar to elt type, and then
5923   // splat from elt type to vector.
5924   if (SrcTy->isPointerType())
5925     return Diag(R.getBegin(),
5926                 diag::err_invalid_conversion_between_vector_and_scalar)
5927       << DestTy << SrcTy << R;
5928 
5929   Kind = CK_VectorSplat;
5930   return prepareVectorSplat(DestTy, CastExpr);
5931 }
5932 
5933 ExprResult
5934 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5935                     Declarator &D, ParsedType &Ty,
5936                     SourceLocation RParenLoc, Expr *CastExpr) {
5937   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5938          "ActOnCastExpr(): missing type or expr");
5939 
5940   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5941   if (D.isInvalidType())
5942     return ExprError();
5943 
5944   if (getLangOpts().CPlusPlus) {
5945     // Check that there are no default arguments (C++ only).
5946     CheckExtraCXXDefaultArguments(D);
5947   } else {
5948     // Make sure any TypoExprs have been dealt with.
5949     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
5950     if (!Res.isUsable())
5951       return ExprError();
5952     CastExpr = Res.get();
5953   }
5954 
5955   checkUnusedDeclAttributes(D);
5956 
5957   QualType castType = castTInfo->getType();
5958   Ty = CreateParsedType(castType, castTInfo);
5959 
5960   bool isVectorLiteral = false;
5961 
5962   // Check for an altivec or OpenCL literal,
5963   // i.e. all the elements are integer constants.
5964   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5965   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5966   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
5967        && castType->isVectorType() && (PE || PLE)) {
5968     if (PLE && PLE->getNumExprs() == 0) {
5969       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5970       return ExprError();
5971     }
5972     if (PE || PLE->getNumExprs() == 1) {
5973       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5974       if (!E->getType()->isVectorType())
5975         isVectorLiteral = true;
5976     }
5977     else
5978       isVectorLiteral = true;
5979   }
5980 
5981   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5982   // then handle it as such.
5983   if (isVectorLiteral)
5984     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5985 
5986   // If the Expr being casted is a ParenListExpr, handle it specially.
5987   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5988   // sequence of BinOp comma operators.
5989   if (isa<ParenListExpr>(CastExpr)) {
5990     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5991     if (Result.isInvalid()) return ExprError();
5992     CastExpr = Result.get();
5993   }
5994 
5995   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5996       !getSourceManager().isInSystemMacro(LParenLoc))
5997     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
5998 
5999   CheckTollFreeBridgeCast(castType, CastExpr);
6000 
6001   CheckObjCBridgeRelatedCast(castType, CastExpr);
6002 
6003   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6004 }
6005 
6006 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6007                                     SourceLocation RParenLoc, Expr *E,
6008                                     TypeSourceInfo *TInfo) {
6009   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6010          "Expected paren or paren list expression");
6011 
6012   Expr **exprs;
6013   unsigned numExprs;
6014   Expr *subExpr;
6015   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6016   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6017     LiteralLParenLoc = PE->getLParenLoc();
6018     LiteralRParenLoc = PE->getRParenLoc();
6019     exprs = PE->getExprs();
6020     numExprs = PE->getNumExprs();
6021   } else { // isa<ParenExpr> by assertion at function entrance
6022     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6023     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6024     subExpr = cast<ParenExpr>(E)->getSubExpr();
6025     exprs = &subExpr;
6026     numExprs = 1;
6027   }
6028 
6029   QualType Ty = TInfo->getType();
6030   assert(Ty->isVectorType() && "Expected vector type");
6031 
6032   SmallVector<Expr *, 8> initExprs;
6033   const VectorType *VTy = Ty->getAs<VectorType>();
6034   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6035 
6036   // '(...)' form of vector initialization in AltiVec: the number of
6037   // initializers must be one or must match the size of the vector.
6038   // If a single value is specified in the initializer then it will be
6039   // replicated to all the components of the vector
6040   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6041     // The number of initializers must be one or must match the size of the
6042     // vector. If a single value is specified in the initializer then it will
6043     // be replicated to all the components of the vector
6044     if (numExprs == 1) {
6045       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6046       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6047       if (Literal.isInvalid())
6048         return ExprError();
6049       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6050                                   PrepareScalarCast(Literal, ElemTy));
6051       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6052     }
6053     else if (numExprs < numElems) {
6054       Diag(E->getExprLoc(),
6055            diag::err_incorrect_number_of_vector_initializers);
6056       return ExprError();
6057     }
6058     else
6059       initExprs.append(exprs, exprs + numExprs);
6060   }
6061   else {
6062     // For OpenCL, when the number of initializers is a single value,
6063     // it will be replicated to all components of the vector.
6064     if (getLangOpts().OpenCL &&
6065         VTy->getVectorKind() == VectorType::GenericVector &&
6066         numExprs == 1) {
6067         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6068         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6069         if (Literal.isInvalid())
6070           return ExprError();
6071         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6072                                     PrepareScalarCast(Literal, ElemTy));
6073         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6074     }
6075 
6076     initExprs.append(exprs, exprs + numExprs);
6077   }
6078   // FIXME: This means that pretty-printing the final AST will produce curly
6079   // braces instead of the original commas.
6080   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6081                                                    initExprs, LiteralRParenLoc);
6082   initE->setType(Ty);
6083   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6084 }
6085 
6086 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6087 /// the ParenListExpr into a sequence of comma binary operators.
6088 ExprResult
6089 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6090   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6091   if (!E)
6092     return OrigExpr;
6093 
6094   ExprResult Result(E->getExpr(0));
6095 
6096   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6097     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6098                         E->getExpr(i));
6099 
6100   if (Result.isInvalid()) return ExprError();
6101 
6102   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6103 }
6104 
6105 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6106                                     SourceLocation R,
6107                                     MultiExprArg Val) {
6108   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6109   return expr;
6110 }
6111 
6112 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6113 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6114 /// emitted.
6115 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6116                                       SourceLocation QuestionLoc) {
6117   Expr *NullExpr = LHSExpr;
6118   Expr *NonPointerExpr = RHSExpr;
6119   Expr::NullPointerConstantKind NullKind =
6120       NullExpr->isNullPointerConstant(Context,
6121                                       Expr::NPC_ValueDependentIsNotNull);
6122 
6123   if (NullKind == Expr::NPCK_NotNull) {
6124     NullExpr = RHSExpr;
6125     NonPointerExpr = LHSExpr;
6126     NullKind =
6127         NullExpr->isNullPointerConstant(Context,
6128                                         Expr::NPC_ValueDependentIsNotNull);
6129   }
6130 
6131   if (NullKind == Expr::NPCK_NotNull)
6132     return false;
6133 
6134   if (NullKind == Expr::NPCK_ZeroExpression)
6135     return false;
6136 
6137   if (NullKind == Expr::NPCK_ZeroLiteral) {
6138     // In this case, check to make sure that we got here from a "NULL"
6139     // string in the source code.
6140     NullExpr = NullExpr->IgnoreParenImpCasts();
6141     SourceLocation loc = NullExpr->getExprLoc();
6142     if (!findMacroSpelling(loc, "NULL"))
6143       return false;
6144   }
6145 
6146   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6147   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6148       << NonPointerExpr->getType() << DiagType
6149       << NonPointerExpr->getSourceRange();
6150   return true;
6151 }
6152 
6153 /// \brief Return false if the condition expression is valid, true otherwise.
6154 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6155   QualType CondTy = Cond->getType();
6156 
6157   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6158   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6159     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6160       << CondTy << Cond->getSourceRange();
6161     return true;
6162   }
6163 
6164   // C99 6.5.15p2
6165   if (CondTy->isScalarType()) return false;
6166 
6167   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6168     << CondTy << Cond->getSourceRange();
6169   return true;
6170 }
6171 
6172 /// \brief Handle when one or both operands are void type.
6173 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6174                                          ExprResult &RHS) {
6175     Expr *LHSExpr = LHS.get();
6176     Expr *RHSExpr = RHS.get();
6177 
6178     if (!LHSExpr->getType()->isVoidType())
6179       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6180         << RHSExpr->getSourceRange();
6181     if (!RHSExpr->getType()->isVoidType())
6182       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6183         << LHSExpr->getSourceRange();
6184     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6185     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6186     return S.Context.VoidTy;
6187 }
6188 
6189 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6190 /// true otherwise.
6191 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6192                                         QualType PointerTy) {
6193   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6194       !NullExpr.get()->isNullPointerConstant(S.Context,
6195                                             Expr::NPC_ValueDependentIsNull))
6196     return true;
6197 
6198   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6199   return false;
6200 }
6201 
6202 /// \brief Checks compatibility between two pointers and return the resulting
6203 /// type.
6204 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6205                                                      ExprResult &RHS,
6206                                                      SourceLocation Loc) {
6207   QualType LHSTy = LHS.get()->getType();
6208   QualType RHSTy = RHS.get()->getType();
6209 
6210   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6211     // Two identical pointers types are always compatible.
6212     return LHSTy;
6213   }
6214 
6215   QualType lhptee, rhptee;
6216 
6217   // Get the pointee types.
6218   bool IsBlockPointer = false;
6219   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6220     lhptee = LHSBTy->getPointeeType();
6221     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6222     IsBlockPointer = true;
6223   } else {
6224     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6225     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6226   }
6227 
6228   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6229   // differently qualified versions of compatible types, the result type is
6230   // a pointer to an appropriately qualified version of the composite
6231   // type.
6232 
6233   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6234   // clause doesn't make sense for our extensions. E.g. address space 2 should
6235   // be incompatible with address space 3: they may live on different devices or
6236   // anything.
6237   Qualifiers lhQual = lhptee.getQualifiers();
6238   Qualifiers rhQual = rhptee.getQualifiers();
6239 
6240   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6241   lhQual.removeCVRQualifiers();
6242   rhQual.removeCVRQualifiers();
6243 
6244   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6245   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6246 
6247   // For OpenCL:
6248   // 1. If LHS and RHS types match exactly and:
6249   //  (a) AS match => use standard C rules, no bitcast or addrspacecast
6250   //  (b) AS overlap => generate addrspacecast
6251   //  (c) AS don't overlap => give an error
6252   // 2. if LHS and RHS types don't match:
6253   //  (a) AS match => use standard C rules, generate bitcast
6254   //  (b) AS overlap => generate addrspacecast instead of bitcast
6255   //  (c) AS don't overlap => give an error
6256 
6257   // For OpenCL, non-null composite type is returned only for cases 1a and 1b.
6258   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6259 
6260   // OpenCL cases 1c, 2a, 2b, and 2c.
6261   if (CompositeTy.isNull()) {
6262     // In this situation, we assume void* type. No especially good
6263     // reason, but this is what gcc does, and we do have to pick
6264     // to get a consistent AST.
6265     QualType incompatTy;
6266     if (S.getLangOpts().OpenCL) {
6267       // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6268       // spaces is disallowed.
6269       unsigned ResultAddrSpace;
6270       if (lhQual.isAddressSpaceSupersetOf(rhQual)) {
6271         // Cases 2a and 2b.
6272         ResultAddrSpace = lhQual.getAddressSpace();
6273       } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) {
6274         // Cases 2a and 2b.
6275         ResultAddrSpace = rhQual.getAddressSpace();
6276       } else {
6277         // Cases 1c and 2c.
6278         S.Diag(Loc,
6279                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6280             << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6281             << RHS.get()->getSourceRange();
6282         return QualType();
6283       }
6284 
6285       // Continue handling cases 2a and 2b.
6286       incompatTy = S.Context.getPointerType(
6287           S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6288       LHS = S.ImpCastExprToType(LHS.get(), incompatTy,
6289                                 (lhQual.getAddressSpace() != ResultAddrSpace)
6290                                     ? CK_AddressSpaceConversion /* 2b */
6291                                     : CK_BitCast /* 2a */);
6292       RHS = S.ImpCastExprToType(RHS.get(), incompatTy,
6293                                 (rhQual.getAddressSpace() != ResultAddrSpace)
6294                                     ? CK_AddressSpaceConversion /* 2b */
6295                                     : CK_BitCast /* 2a */);
6296     } else {
6297       S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6298           << LHSTy << RHSTy << LHS.get()->getSourceRange()
6299           << RHS.get()->getSourceRange();
6300       incompatTy = S.Context.getPointerType(S.Context.VoidTy);
6301       LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6302       RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6303     }
6304     return incompatTy;
6305   }
6306 
6307   // The pointer types are compatible.
6308   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
6309   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6310   if (IsBlockPointer)
6311     ResultTy = S.Context.getBlockPointerType(ResultTy);
6312   else {
6313     // Cases 1a and 1b for OpenCL.
6314     auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace();
6315     LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace
6316                       ? CK_BitCast /* 1a */
6317                       : CK_AddressSpaceConversion /* 1b */;
6318     RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace
6319                       ? CK_BitCast /* 1a */
6320                       : CK_AddressSpaceConversion /* 1b */;
6321     ResultTy = S.Context.getPointerType(ResultTy);
6322   }
6323 
6324   // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast
6325   // if the target type does not change.
6326   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6327   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6328   return ResultTy;
6329 }
6330 
6331 /// \brief Return the resulting type when the operands are both block pointers.
6332 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6333                                                           ExprResult &LHS,
6334                                                           ExprResult &RHS,
6335                                                           SourceLocation Loc) {
6336   QualType LHSTy = LHS.get()->getType();
6337   QualType RHSTy = RHS.get()->getType();
6338 
6339   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6340     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6341       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6342       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6343       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6344       return destType;
6345     }
6346     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6347       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6348       << RHS.get()->getSourceRange();
6349     return QualType();
6350   }
6351 
6352   // We have 2 block pointer types.
6353   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6354 }
6355 
6356 /// \brief Return the resulting type when the operands are both pointers.
6357 static QualType
6358 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6359                                             ExprResult &RHS,
6360                                             SourceLocation Loc) {
6361   // get the pointer types
6362   QualType LHSTy = LHS.get()->getType();
6363   QualType RHSTy = RHS.get()->getType();
6364 
6365   // get the "pointed to" types
6366   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6367   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6368 
6369   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6370   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6371     // Figure out necessary qualifiers (C99 6.5.15p6)
6372     QualType destPointee
6373       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6374     QualType destType = S.Context.getPointerType(destPointee);
6375     // Add qualifiers if necessary.
6376     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6377     // Promote to void*.
6378     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6379     return destType;
6380   }
6381   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6382     QualType destPointee
6383       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6384     QualType destType = S.Context.getPointerType(destPointee);
6385     // Add qualifiers if necessary.
6386     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6387     // Promote to void*.
6388     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6389     return destType;
6390   }
6391 
6392   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6393 }
6394 
6395 /// \brief Return false if the first expression is not an integer and the second
6396 /// expression is not a pointer, true otherwise.
6397 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6398                                         Expr* PointerExpr, SourceLocation Loc,
6399                                         bool IsIntFirstExpr) {
6400   if (!PointerExpr->getType()->isPointerType() ||
6401       !Int.get()->getType()->isIntegerType())
6402     return false;
6403 
6404   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6405   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6406 
6407   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6408     << Expr1->getType() << Expr2->getType()
6409     << Expr1->getSourceRange() << Expr2->getSourceRange();
6410   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6411                             CK_IntegralToPointer);
6412   return true;
6413 }
6414 
6415 /// \brief Simple conversion between integer and floating point types.
6416 ///
6417 /// Used when handling the OpenCL conditional operator where the
6418 /// condition is a vector while the other operands are scalar.
6419 ///
6420 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6421 /// types are either integer or floating type. Between the two
6422 /// operands, the type with the higher rank is defined as the "result
6423 /// type". The other operand needs to be promoted to the same type. No
6424 /// other type promotion is allowed. We cannot use
6425 /// UsualArithmeticConversions() for this purpose, since it always
6426 /// promotes promotable types.
6427 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6428                                             ExprResult &RHS,
6429                                             SourceLocation QuestionLoc) {
6430   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6431   if (LHS.isInvalid())
6432     return QualType();
6433   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6434   if (RHS.isInvalid())
6435     return QualType();
6436 
6437   // For conversion purposes, we ignore any qualifiers.
6438   // For example, "const float" and "float" are equivalent.
6439   QualType LHSType =
6440     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6441   QualType RHSType =
6442     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6443 
6444   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6445     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6446       << LHSType << LHS.get()->getSourceRange();
6447     return QualType();
6448   }
6449 
6450   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6451     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6452       << RHSType << RHS.get()->getSourceRange();
6453     return QualType();
6454   }
6455 
6456   // If both types are identical, no conversion is needed.
6457   if (LHSType == RHSType)
6458     return LHSType;
6459 
6460   // Now handle "real" floating types (i.e. float, double, long double).
6461   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6462     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6463                                  /*IsCompAssign = */ false);
6464 
6465   // Finally, we have two differing integer types.
6466   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6467   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6468 }
6469 
6470 /// \brief Convert scalar operands to a vector that matches the
6471 ///        condition in length.
6472 ///
6473 /// Used when handling the OpenCL conditional operator where the
6474 /// condition is a vector while the other operands are scalar.
6475 ///
6476 /// We first compute the "result type" for the scalar operands
6477 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6478 /// into a vector of that type where the length matches the condition
6479 /// vector type. s6.11.6 requires that the element types of the result
6480 /// and the condition must have the same number of bits.
6481 static QualType
6482 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6483                               QualType CondTy, SourceLocation QuestionLoc) {
6484   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6485   if (ResTy.isNull()) return QualType();
6486 
6487   const VectorType *CV = CondTy->getAs<VectorType>();
6488   assert(CV);
6489 
6490   // Determine the vector result type
6491   unsigned NumElements = CV->getNumElements();
6492   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6493 
6494   // Ensure that all types have the same number of bits
6495   if (S.Context.getTypeSize(CV->getElementType())
6496       != S.Context.getTypeSize(ResTy)) {
6497     // Since VectorTy is created internally, it does not pretty print
6498     // with an OpenCL name. Instead, we just print a description.
6499     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6500     SmallString<64> Str;
6501     llvm::raw_svector_ostream OS(Str);
6502     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6503     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6504       << CondTy << OS.str();
6505     return QualType();
6506   }
6507 
6508   // Convert operands to the vector result type
6509   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6510   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6511 
6512   return VectorTy;
6513 }
6514 
6515 /// \brief Return false if this is a valid OpenCL condition vector
6516 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6517                                        SourceLocation QuestionLoc) {
6518   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6519   // integral type.
6520   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6521   assert(CondTy);
6522   QualType EleTy = CondTy->getElementType();
6523   if (EleTy->isIntegerType()) return false;
6524 
6525   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6526     << Cond->getType() << Cond->getSourceRange();
6527   return true;
6528 }
6529 
6530 /// \brief Return false if the vector condition type and the vector
6531 ///        result type are compatible.
6532 ///
6533 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6534 /// number of elements, and their element types have the same number
6535 /// of bits.
6536 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6537                               SourceLocation QuestionLoc) {
6538   const VectorType *CV = CondTy->getAs<VectorType>();
6539   const VectorType *RV = VecResTy->getAs<VectorType>();
6540   assert(CV && RV);
6541 
6542   if (CV->getNumElements() != RV->getNumElements()) {
6543     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6544       << CondTy << VecResTy;
6545     return true;
6546   }
6547 
6548   QualType CVE = CV->getElementType();
6549   QualType RVE = RV->getElementType();
6550 
6551   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6552     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6553       << CondTy << VecResTy;
6554     return true;
6555   }
6556 
6557   return false;
6558 }
6559 
6560 /// \brief Return the resulting type for the conditional operator in
6561 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6562 ///        s6.3.i) when the condition is a vector type.
6563 static QualType
6564 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6565                              ExprResult &LHS, ExprResult &RHS,
6566                              SourceLocation QuestionLoc) {
6567   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6568   if (Cond.isInvalid())
6569     return QualType();
6570   QualType CondTy = Cond.get()->getType();
6571 
6572   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6573     return QualType();
6574 
6575   // If either operand is a vector then find the vector type of the
6576   // result as specified in OpenCL v1.1 s6.3.i.
6577   if (LHS.get()->getType()->isVectorType() ||
6578       RHS.get()->getType()->isVectorType()) {
6579     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6580                                               /*isCompAssign*/false,
6581                                               /*AllowBothBool*/true,
6582                                               /*AllowBoolConversions*/false);
6583     if (VecResTy.isNull()) return QualType();
6584     // The result type must match the condition type as specified in
6585     // OpenCL v1.1 s6.11.6.
6586     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6587       return QualType();
6588     return VecResTy;
6589   }
6590 
6591   // Both operands are scalar.
6592   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6593 }
6594 
6595 /// \brief Return true if the Expr is block type
6596 static bool checkBlockType(Sema &S, const Expr *E) {
6597   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6598     QualType Ty = CE->getCallee()->getType();
6599     if (Ty->isBlockPointerType()) {
6600       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6601       return true;
6602     }
6603   }
6604   return false;
6605 }
6606 
6607 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6608 /// In that case, LHS = cond.
6609 /// C99 6.5.15
6610 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6611                                         ExprResult &RHS, ExprValueKind &VK,
6612                                         ExprObjectKind &OK,
6613                                         SourceLocation QuestionLoc) {
6614 
6615   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6616   if (!LHSResult.isUsable()) return QualType();
6617   LHS = LHSResult;
6618 
6619   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6620   if (!RHSResult.isUsable()) return QualType();
6621   RHS = RHSResult;
6622 
6623   // C++ is sufficiently different to merit its own checker.
6624   if (getLangOpts().CPlusPlus)
6625     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6626 
6627   VK = VK_RValue;
6628   OK = OK_Ordinary;
6629 
6630   // The OpenCL operator with a vector condition is sufficiently
6631   // different to merit its own checker.
6632   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6633     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6634 
6635   // First, check the condition.
6636   Cond = UsualUnaryConversions(Cond.get());
6637   if (Cond.isInvalid())
6638     return QualType();
6639   if (checkCondition(*this, Cond.get(), QuestionLoc))
6640     return QualType();
6641 
6642   // Now check the two expressions.
6643   if (LHS.get()->getType()->isVectorType() ||
6644       RHS.get()->getType()->isVectorType())
6645     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6646                                /*AllowBothBool*/true,
6647                                /*AllowBoolConversions*/false);
6648 
6649   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6650   if (LHS.isInvalid() || RHS.isInvalid())
6651     return QualType();
6652 
6653   QualType LHSTy = LHS.get()->getType();
6654   QualType RHSTy = RHS.get()->getType();
6655 
6656   // Diagnose attempts to convert between __float128 and long double where
6657   // such conversions currently can't be handled.
6658   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6659     Diag(QuestionLoc,
6660          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6661       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6662     return QualType();
6663   }
6664 
6665   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6666   // selection operator (?:).
6667   if (getLangOpts().OpenCL &&
6668       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6669     return QualType();
6670   }
6671 
6672   // If both operands have arithmetic type, do the usual arithmetic conversions
6673   // to find a common type: C99 6.5.15p3,5.
6674   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6675     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6676     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6677 
6678     return ResTy;
6679   }
6680 
6681   // If both operands are the same structure or union type, the result is that
6682   // type.
6683   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6684     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6685       if (LHSRT->getDecl() == RHSRT->getDecl())
6686         // "If both the operands have structure or union type, the result has
6687         // that type."  This implies that CV qualifiers are dropped.
6688         return LHSTy.getUnqualifiedType();
6689     // FIXME: Type of conditional expression must be complete in C mode.
6690   }
6691 
6692   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6693   // The following || allows only one side to be void (a GCC-ism).
6694   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6695     return checkConditionalVoidType(*this, LHS, RHS);
6696   }
6697 
6698   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6699   // the type of the other operand."
6700   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6701   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6702 
6703   // All objective-c pointer type analysis is done here.
6704   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6705                                                         QuestionLoc);
6706   if (LHS.isInvalid() || RHS.isInvalid())
6707     return QualType();
6708   if (!compositeType.isNull())
6709     return compositeType;
6710 
6711 
6712   // Handle block pointer types.
6713   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6714     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6715                                                      QuestionLoc);
6716 
6717   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6718   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6719     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6720                                                        QuestionLoc);
6721 
6722   // GCC compatibility: soften pointer/integer mismatch.  Note that
6723   // null pointers have been filtered out by this point.
6724   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6725       /*isIntFirstExpr=*/true))
6726     return RHSTy;
6727   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6728       /*isIntFirstExpr=*/false))
6729     return LHSTy;
6730 
6731   // Emit a better diagnostic if one of the expressions is a null pointer
6732   // constant and the other is not a pointer type. In this case, the user most
6733   // likely forgot to take the address of the other expression.
6734   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6735     return QualType();
6736 
6737   // Otherwise, the operands are not compatible.
6738   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6739     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6740     << RHS.get()->getSourceRange();
6741   return QualType();
6742 }
6743 
6744 /// FindCompositeObjCPointerType - Helper method to find composite type of
6745 /// two objective-c pointer types of the two input expressions.
6746 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6747                                             SourceLocation QuestionLoc) {
6748   QualType LHSTy = LHS.get()->getType();
6749   QualType RHSTy = RHS.get()->getType();
6750 
6751   // Handle things like Class and struct objc_class*.  Here we case the result
6752   // to the pseudo-builtin, because that will be implicitly cast back to the
6753   // redefinition type if an attempt is made to access its fields.
6754   if (LHSTy->isObjCClassType() &&
6755       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6756     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6757     return LHSTy;
6758   }
6759   if (RHSTy->isObjCClassType() &&
6760       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6761     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6762     return RHSTy;
6763   }
6764   // And the same for struct objc_object* / id
6765   if (LHSTy->isObjCIdType() &&
6766       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6767     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6768     return LHSTy;
6769   }
6770   if (RHSTy->isObjCIdType() &&
6771       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6772     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6773     return RHSTy;
6774   }
6775   // And the same for struct objc_selector* / SEL
6776   if (Context.isObjCSelType(LHSTy) &&
6777       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6778     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6779     return LHSTy;
6780   }
6781   if (Context.isObjCSelType(RHSTy) &&
6782       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6783     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6784     return RHSTy;
6785   }
6786   // Check constraints for Objective-C object pointers types.
6787   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6788 
6789     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6790       // Two identical object pointer types are always compatible.
6791       return LHSTy;
6792     }
6793     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6794     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6795     QualType compositeType = LHSTy;
6796 
6797     // If both operands are interfaces and either operand can be
6798     // assigned to the other, use that type as the composite
6799     // type. This allows
6800     //   xxx ? (A*) a : (B*) b
6801     // where B is a subclass of A.
6802     //
6803     // Additionally, as for assignment, if either type is 'id'
6804     // allow silent coercion. Finally, if the types are
6805     // incompatible then make sure to use 'id' as the composite
6806     // type so the result is acceptable for sending messages to.
6807 
6808     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6809     // It could return the composite type.
6810     if (!(compositeType =
6811           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6812       // Nothing more to do.
6813     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6814       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6815     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6816       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6817     } else if ((LHSTy->isObjCQualifiedIdType() ||
6818                 RHSTy->isObjCQualifiedIdType()) &&
6819                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6820       // Need to handle "id<xx>" explicitly.
6821       // GCC allows qualified id and any Objective-C type to devolve to
6822       // id. Currently localizing to here until clear this should be
6823       // part of ObjCQualifiedIdTypesAreCompatible.
6824       compositeType = Context.getObjCIdType();
6825     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6826       compositeType = Context.getObjCIdType();
6827     } else {
6828       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6829       << LHSTy << RHSTy
6830       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6831       QualType incompatTy = Context.getObjCIdType();
6832       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6833       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6834       return incompatTy;
6835     }
6836     // The object pointer types are compatible.
6837     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6838     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6839     return compositeType;
6840   }
6841   // Check Objective-C object pointer types and 'void *'
6842   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6843     if (getLangOpts().ObjCAutoRefCount) {
6844       // ARC forbids the implicit conversion of object pointers to 'void *',
6845       // so these types are not compatible.
6846       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6847           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6848       LHS = RHS = true;
6849       return QualType();
6850     }
6851     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6852     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6853     QualType destPointee
6854     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6855     QualType destType = Context.getPointerType(destPointee);
6856     // Add qualifiers if necessary.
6857     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6858     // Promote to void*.
6859     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6860     return destType;
6861   }
6862   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6863     if (getLangOpts().ObjCAutoRefCount) {
6864       // ARC forbids the implicit conversion of object pointers to 'void *',
6865       // so these types are not compatible.
6866       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6867           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6868       LHS = RHS = true;
6869       return QualType();
6870     }
6871     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6872     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6873     QualType destPointee
6874     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6875     QualType destType = Context.getPointerType(destPointee);
6876     // Add qualifiers if necessary.
6877     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6878     // Promote to void*.
6879     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6880     return destType;
6881   }
6882   return QualType();
6883 }
6884 
6885 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6886 /// ParenRange in parentheses.
6887 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6888                                const PartialDiagnostic &Note,
6889                                SourceRange ParenRange) {
6890   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6891   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6892       EndLoc.isValid()) {
6893     Self.Diag(Loc, Note)
6894       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6895       << FixItHint::CreateInsertion(EndLoc, ")");
6896   } else {
6897     // We can't display the parentheses, so just show the bare note.
6898     Self.Diag(Loc, Note) << ParenRange;
6899   }
6900 }
6901 
6902 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6903   return BinaryOperator::isAdditiveOp(Opc) ||
6904          BinaryOperator::isMultiplicativeOp(Opc) ||
6905          BinaryOperator::isShiftOp(Opc);
6906 }
6907 
6908 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6909 /// expression, either using a built-in or overloaded operator,
6910 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6911 /// expression.
6912 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6913                                    Expr **RHSExprs) {
6914   // Don't strip parenthesis: we should not warn if E is in parenthesis.
6915   E = E->IgnoreImpCasts();
6916   E = E->IgnoreConversionOperator();
6917   E = E->IgnoreImpCasts();
6918 
6919   // Built-in binary operator.
6920   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6921     if (IsArithmeticOp(OP->getOpcode())) {
6922       *Opcode = OP->getOpcode();
6923       *RHSExprs = OP->getRHS();
6924       return true;
6925     }
6926   }
6927 
6928   // Overloaded operator.
6929   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6930     if (Call->getNumArgs() != 2)
6931       return false;
6932 
6933     // Make sure this is really a binary operator that is safe to pass into
6934     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6935     OverloadedOperatorKind OO = Call->getOperator();
6936     if (OO < OO_Plus || OO > OO_Arrow ||
6937         OO == OO_PlusPlus || OO == OO_MinusMinus)
6938       return false;
6939 
6940     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6941     if (IsArithmeticOp(OpKind)) {
6942       *Opcode = OpKind;
6943       *RHSExprs = Call->getArg(1);
6944       return true;
6945     }
6946   }
6947 
6948   return false;
6949 }
6950 
6951 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6952 /// or is a logical expression such as (x==y) which has int type, but is
6953 /// commonly interpreted as boolean.
6954 static bool ExprLooksBoolean(Expr *E) {
6955   E = E->IgnoreParenImpCasts();
6956 
6957   if (E->getType()->isBooleanType())
6958     return true;
6959   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6960     return OP->isComparisonOp() || OP->isLogicalOp();
6961   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6962     return OP->getOpcode() == UO_LNot;
6963   if (E->getType()->isPointerType())
6964     return true;
6965 
6966   return false;
6967 }
6968 
6969 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6970 /// and binary operator are mixed in a way that suggests the programmer assumed
6971 /// the conditional operator has higher precedence, for example:
6972 /// "int x = a + someBinaryCondition ? 1 : 2".
6973 static void DiagnoseConditionalPrecedence(Sema &Self,
6974                                           SourceLocation OpLoc,
6975                                           Expr *Condition,
6976                                           Expr *LHSExpr,
6977                                           Expr *RHSExpr) {
6978   BinaryOperatorKind CondOpcode;
6979   Expr *CondRHS;
6980 
6981   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
6982     return;
6983   if (!ExprLooksBoolean(CondRHS))
6984     return;
6985 
6986   // The condition is an arithmetic binary expression, with a right-
6987   // hand side that looks boolean, so warn.
6988 
6989   Self.Diag(OpLoc, diag::warn_precedence_conditional)
6990       << Condition->getSourceRange()
6991       << BinaryOperator::getOpcodeStr(CondOpcode);
6992 
6993   SuggestParentheses(Self, OpLoc,
6994     Self.PDiag(diag::note_precedence_silence)
6995       << BinaryOperator::getOpcodeStr(CondOpcode),
6996     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
6997 
6998   SuggestParentheses(Self, OpLoc,
6999     Self.PDiag(diag::note_precedence_conditional_first),
7000     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7001 }
7002 
7003 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7004 /// in the case of a the GNU conditional expr extension.
7005 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7006                                     SourceLocation ColonLoc,
7007                                     Expr *CondExpr, Expr *LHSExpr,
7008                                     Expr *RHSExpr) {
7009   if (!getLangOpts().CPlusPlus) {
7010     // C cannot handle TypoExpr nodes in the condition because it
7011     // doesn't handle dependent types properly, so make sure any TypoExprs have
7012     // been dealt with before checking the operands.
7013     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7014     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7015     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7016 
7017     if (!CondResult.isUsable())
7018       return ExprError();
7019 
7020     if (LHSExpr) {
7021       if (!LHSResult.isUsable())
7022         return ExprError();
7023     }
7024 
7025     if (!RHSResult.isUsable())
7026       return ExprError();
7027 
7028     CondExpr = CondResult.get();
7029     LHSExpr = LHSResult.get();
7030     RHSExpr = RHSResult.get();
7031   }
7032 
7033   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7034   // was the condition.
7035   OpaqueValueExpr *opaqueValue = nullptr;
7036   Expr *commonExpr = nullptr;
7037   if (!LHSExpr) {
7038     commonExpr = CondExpr;
7039     // Lower out placeholder types first.  This is important so that we don't
7040     // try to capture a placeholder. This happens in few cases in C++; such
7041     // as Objective-C++'s dictionary subscripting syntax.
7042     if (commonExpr->hasPlaceholderType()) {
7043       ExprResult result = CheckPlaceholderExpr(commonExpr);
7044       if (!result.isUsable()) return ExprError();
7045       commonExpr = result.get();
7046     }
7047     // We usually want to apply unary conversions *before* saving, except
7048     // in the special case of a C++ l-value conditional.
7049     if (!(getLangOpts().CPlusPlus
7050           && !commonExpr->isTypeDependent()
7051           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7052           && commonExpr->isGLValue()
7053           && commonExpr->isOrdinaryOrBitFieldObject()
7054           && RHSExpr->isOrdinaryOrBitFieldObject()
7055           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7056       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7057       if (commonRes.isInvalid())
7058         return ExprError();
7059       commonExpr = commonRes.get();
7060     }
7061 
7062     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7063                                                 commonExpr->getType(),
7064                                                 commonExpr->getValueKind(),
7065                                                 commonExpr->getObjectKind(),
7066                                                 commonExpr);
7067     LHSExpr = CondExpr = opaqueValue;
7068   }
7069 
7070   ExprValueKind VK = VK_RValue;
7071   ExprObjectKind OK = OK_Ordinary;
7072   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7073   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7074                                              VK, OK, QuestionLoc);
7075   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7076       RHS.isInvalid())
7077     return ExprError();
7078 
7079   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7080                                 RHS.get());
7081 
7082   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7083 
7084   if (!commonExpr)
7085     return new (Context)
7086         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7087                             RHS.get(), result, VK, OK);
7088 
7089   return new (Context) BinaryConditionalOperator(
7090       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7091       ColonLoc, result, VK, OK);
7092 }
7093 
7094 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7095 // being closely modeled after the C99 spec:-). The odd characteristic of this
7096 // routine is it effectively iqnores the qualifiers on the top level pointee.
7097 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7098 // FIXME: add a couple examples in this comment.
7099 static Sema::AssignConvertType
7100 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7101   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7102   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7103 
7104   // get the "pointed to" type (ignoring qualifiers at the top level)
7105   const Type *lhptee, *rhptee;
7106   Qualifiers lhq, rhq;
7107   std::tie(lhptee, lhq) =
7108       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7109   std::tie(rhptee, rhq) =
7110       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7111 
7112   Sema::AssignConvertType ConvTy = Sema::Compatible;
7113 
7114   // C99 6.5.16.1p1: This following citation is common to constraints
7115   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7116   // qualifiers of the type *pointed to* by the right;
7117 
7118   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7119   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7120       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7121     // Ignore lifetime for further calculation.
7122     lhq.removeObjCLifetime();
7123     rhq.removeObjCLifetime();
7124   }
7125 
7126   if (!lhq.compatiblyIncludes(rhq)) {
7127     // Treat address-space mismatches as fatal.  TODO: address subspaces
7128     if (!lhq.isAddressSpaceSupersetOf(rhq))
7129       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7130 
7131     // It's okay to add or remove GC or lifetime qualifiers when converting to
7132     // and from void*.
7133     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7134                         .compatiblyIncludes(
7135                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7136              && (lhptee->isVoidType() || rhptee->isVoidType()))
7137       ; // keep old
7138 
7139     // Treat lifetime mismatches as fatal.
7140     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7141       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7142 
7143     // For GCC/MS compatibility, other qualifier mismatches are treated
7144     // as still compatible in C.
7145     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7146   }
7147 
7148   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7149   // incomplete type and the other is a pointer to a qualified or unqualified
7150   // version of void...
7151   if (lhptee->isVoidType()) {
7152     if (rhptee->isIncompleteOrObjectType())
7153       return ConvTy;
7154 
7155     // As an extension, we allow cast to/from void* to function pointer.
7156     assert(rhptee->isFunctionType());
7157     return Sema::FunctionVoidPointer;
7158   }
7159 
7160   if (rhptee->isVoidType()) {
7161     if (lhptee->isIncompleteOrObjectType())
7162       return ConvTy;
7163 
7164     // As an extension, we allow cast to/from void* to function pointer.
7165     assert(lhptee->isFunctionType());
7166     return Sema::FunctionVoidPointer;
7167   }
7168 
7169   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7170   // unqualified versions of compatible types, ...
7171   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7172   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7173     // Check if the pointee types are compatible ignoring the sign.
7174     // We explicitly check for char so that we catch "char" vs
7175     // "unsigned char" on systems where "char" is unsigned.
7176     if (lhptee->isCharType())
7177       ltrans = S.Context.UnsignedCharTy;
7178     else if (lhptee->hasSignedIntegerRepresentation())
7179       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7180 
7181     if (rhptee->isCharType())
7182       rtrans = S.Context.UnsignedCharTy;
7183     else if (rhptee->hasSignedIntegerRepresentation())
7184       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7185 
7186     if (ltrans == rtrans) {
7187       // Types are compatible ignoring the sign. Qualifier incompatibility
7188       // takes priority over sign incompatibility because the sign
7189       // warning can be disabled.
7190       if (ConvTy != Sema::Compatible)
7191         return ConvTy;
7192 
7193       return Sema::IncompatiblePointerSign;
7194     }
7195 
7196     // If we are a multi-level pointer, it's possible that our issue is simply
7197     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7198     // the eventual target type is the same and the pointers have the same
7199     // level of indirection, this must be the issue.
7200     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7201       do {
7202         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7203         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7204       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7205 
7206       if (lhptee == rhptee)
7207         return Sema::IncompatibleNestedPointerQualifiers;
7208     }
7209 
7210     // General pointer incompatibility takes priority over qualifiers.
7211     return Sema::IncompatiblePointer;
7212   }
7213   if (!S.getLangOpts().CPlusPlus &&
7214       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
7215     return Sema::IncompatiblePointer;
7216   return ConvTy;
7217 }
7218 
7219 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7220 /// block pointer types are compatible or whether a block and normal pointer
7221 /// are compatible. It is more restrict than comparing two function pointer
7222 // types.
7223 static Sema::AssignConvertType
7224 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7225                                     QualType RHSType) {
7226   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7227   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7228 
7229   QualType lhptee, rhptee;
7230 
7231   // get the "pointed to" type (ignoring qualifiers at the top level)
7232   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7233   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7234 
7235   // In C++, the types have to match exactly.
7236   if (S.getLangOpts().CPlusPlus)
7237     return Sema::IncompatibleBlockPointer;
7238 
7239   Sema::AssignConvertType ConvTy = Sema::Compatible;
7240 
7241   // For blocks we enforce that qualifiers are identical.
7242   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
7243     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7244 
7245   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7246     return Sema::IncompatibleBlockPointer;
7247 
7248   return ConvTy;
7249 }
7250 
7251 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7252 /// for assignment compatibility.
7253 static Sema::AssignConvertType
7254 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7255                                    QualType RHSType) {
7256   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7257   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7258 
7259   if (LHSType->isObjCBuiltinType()) {
7260     // Class is not compatible with ObjC object pointers.
7261     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7262         !RHSType->isObjCQualifiedClassType())
7263       return Sema::IncompatiblePointer;
7264     return Sema::Compatible;
7265   }
7266   if (RHSType->isObjCBuiltinType()) {
7267     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7268         !LHSType->isObjCQualifiedClassType())
7269       return Sema::IncompatiblePointer;
7270     return Sema::Compatible;
7271   }
7272   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7273   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7274 
7275   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7276       // make an exception for id<P>
7277       !LHSType->isObjCQualifiedIdType())
7278     return Sema::CompatiblePointerDiscardsQualifiers;
7279 
7280   if (S.Context.typesAreCompatible(LHSType, RHSType))
7281     return Sema::Compatible;
7282   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7283     return Sema::IncompatibleObjCQualifiedId;
7284   return Sema::IncompatiblePointer;
7285 }
7286 
7287 Sema::AssignConvertType
7288 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7289                                  QualType LHSType, QualType RHSType) {
7290   // Fake up an opaque expression.  We don't actually care about what
7291   // cast operations are required, so if CheckAssignmentConstraints
7292   // adds casts to this they'll be wasted, but fortunately that doesn't
7293   // usually happen on valid code.
7294   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7295   ExprResult RHSPtr = &RHSExpr;
7296   CastKind K = CK_Invalid;
7297 
7298   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7299 }
7300 
7301 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7302 /// has code to accommodate several GCC extensions when type checking
7303 /// pointers. Here are some objectionable examples that GCC considers warnings:
7304 ///
7305 ///  int a, *pint;
7306 ///  short *pshort;
7307 ///  struct foo *pfoo;
7308 ///
7309 ///  pint = pshort; // warning: assignment from incompatible pointer type
7310 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7311 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7312 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7313 ///
7314 /// As a result, the code for dealing with pointers is more complex than the
7315 /// C99 spec dictates.
7316 ///
7317 /// Sets 'Kind' for any result kind except Incompatible.
7318 Sema::AssignConvertType
7319 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7320                                  CastKind &Kind, bool ConvertRHS) {
7321   QualType RHSType = RHS.get()->getType();
7322   QualType OrigLHSType = LHSType;
7323 
7324   // Get canonical types.  We're not formatting these types, just comparing
7325   // them.
7326   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7327   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7328 
7329   // Common case: no conversion required.
7330   if (LHSType == RHSType) {
7331     Kind = CK_NoOp;
7332     return Compatible;
7333   }
7334 
7335   // If we have an atomic type, try a non-atomic assignment, then just add an
7336   // atomic qualification step.
7337   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7338     Sema::AssignConvertType result =
7339       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7340     if (result != Compatible)
7341       return result;
7342     if (Kind != CK_NoOp && ConvertRHS)
7343       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7344     Kind = CK_NonAtomicToAtomic;
7345     return Compatible;
7346   }
7347 
7348   // If the left-hand side is a reference type, then we are in a
7349   // (rare!) case where we've allowed the use of references in C,
7350   // e.g., as a parameter type in a built-in function. In this case,
7351   // just make sure that the type referenced is compatible with the
7352   // right-hand side type. The caller is responsible for adjusting
7353   // LHSType so that the resulting expression does not have reference
7354   // type.
7355   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7356     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7357       Kind = CK_LValueBitCast;
7358       return Compatible;
7359     }
7360     return Incompatible;
7361   }
7362 
7363   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7364   // to the same ExtVector type.
7365   if (LHSType->isExtVectorType()) {
7366     if (RHSType->isExtVectorType())
7367       return Incompatible;
7368     if (RHSType->isArithmeticType()) {
7369       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7370       if (ConvertRHS)
7371         RHS = prepareVectorSplat(LHSType, RHS.get());
7372       Kind = CK_VectorSplat;
7373       return Compatible;
7374     }
7375   }
7376 
7377   // Conversions to or from vector type.
7378   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7379     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7380       // Allow assignments of an AltiVec vector type to an equivalent GCC
7381       // vector type and vice versa
7382       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7383         Kind = CK_BitCast;
7384         return Compatible;
7385       }
7386 
7387       // If we are allowing lax vector conversions, and LHS and RHS are both
7388       // vectors, the total size only needs to be the same. This is a bitcast;
7389       // no bits are changed but the result type is different.
7390       if (isLaxVectorConversion(RHSType, LHSType)) {
7391         Kind = CK_BitCast;
7392         return IncompatibleVectors;
7393       }
7394     }
7395     return Incompatible;
7396   }
7397 
7398   // Diagnose attempts to convert between __float128 and long double where
7399   // such conversions currently can't be handled.
7400   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7401     return Incompatible;
7402 
7403   // Arithmetic conversions.
7404   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7405       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7406     if (ConvertRHS)
7407       Kind = PrepareScalarCast(RHS, LHSType);
7408     return Compatible;
7409   }
7410 
7411   // Conversions to normal pointers.
7412   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7413     // U* -> T*
7414     if (isa<PointerType>(RHSType)) {
7415       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7416       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7417       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7418       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7419     }
7420 
7421     // int -> T*
7422     if (RHSType->isIntegerType()) {
7423       Kind = CK_IntegralToPointer; // FIXME: null?
7424       return IntToPointer;
7425     }
7426 
7427     // C pointers are not compatible with ObjC object pointers,
7428     // with two exceptions:
7429     if (isa<ObjCObjectPointerType>(RHSType)) {
7430       //  - conversions to void*
7431       if (LHSPointer->getPointeeType()->isVoidType()) {
7432         Kind = CK_BitCast;
7433         return Compatible;
7434       }
7435 
7436       //  - conversions from 'Class' to the redefinition type
7437       if (RHSType->isObjCClassType() &&
7438           Context.hasSameType(LHSType,
7439                               Context.getObjCClassRedefinitionType())) {
7440         Kind = CK_BitCast;
7441         return Compatible;
7442       }
7443 
7444       Kind = CK_BitCast;
7445       return IncompatiblePointer;
7446     }
7447 
7448     // U^ -> void*
7449     if (RHSType->getAs<BlockPointerType>()) {
7450       if (LHSPointer->getPointeeType()->isVoidType()) {
7451         Kind = CK_BitCast;
7452         return Compatible;
7453       }
7454     }
7455 
7456     return Incompatible;
7457   }
7458 
7459   // Conversions to block pointers.
7460   if (isa<BlockPointerType>(LHSType)) {
7461     // U^ -> T^
7462     if (RHSType->isBlockPointerType()) {
7463       Kind = CK_BitCast;
7464       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7465     }
7466 
7467     // int or null -> T^
7468     if (RHSType->isIntegerType()) {
7469       Kind = CK_IntegralToPointer; // FIXME: null
7470       return IntToBlockPointer;
7471     }
7472 
7473     // id -> T^
7474     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7475       Kind = CK_AnyPointerToBlockPointerCast;
7476       return Compatible;
7477     }
7478 
7479     // void* -> T^
7480     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7481       if (RHSPT->getPointeeType()->isVoidType()) {
7482         Kind = CK_AnyPointerToBlockPointerCast;
7483         return Compatible;
7484       }
7485 
7486     return Incompatible;
7487   }
7488 
7489   // Conversions to Objective-C pointers.
7490   if (isa<ObjCObjectPointerType>(LHSType)) {
7491     // A* -> B*
7492     if (RHSType->isObjCObjectPointerType()) {
7493       Kind = CK_BitCast;
7494       Sema::AssignConvertType result =
7495         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7496       if (getLangOpts().ObjCAutoRefCount &&
7497           result == Compatible &&
7498           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7499         result = IncompatibleObjCWeakRef;
7500       return result;
7501     }
7502 
7503     // int or null -> A*
7504     if (RHSType->isIntegerType()) {
7505       Kind = CK_IntegralToPointer; // FIXME: null
7506       return IntToPointer;
7507     }
7508 
7509     // In general, C pointers are not compatible with ObjC object pointers,
7510     // with two exceptions:
7511     if (isa<PointerType>(RHSType)) {
7512       Kind = CK_CPointerToObjCPointerCast;
7513 
7514       //  - conversions from 'void*'
7515       if (RHSType->isVoidPointerType()) {
7516         return Compatible;
7517       }
7518 
7519       //  - conversions to 'Class' from its redefinition type
7520       if (LHSType->isObjCClassType() &&
7521           Context.hasSameType(RHSType,
7522                               Context.getObjCClassRedefinitionType())) {
7523         return Compatible;
7524       }
7525 
7526       return IncompatiblePointer;
7527     }
7528 
7529     // Only under strict condition T^ is compatible with an Objective-C pointer.
7530     if (RHSType->isBlockPointerType() &&
7531         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7532       if (ConvertRHS)
7533         maybeExtendBlockObject(RHS);
7534       Kind = CK_BlockPointerToObjCPointerCast;
7535       return Compatible;
7536     }
7537 
7538     return Incompatible;
7539   }
7540 
7541   // Conversions from pointers that are not covered by the above.
7542   if (isa<PointerType>(RHSType)) {
7543     // T* -> _Bool
7544     if (LHSType == Context.BoolTy) {
7545       Kind = CK_PointerToBoolean;
7546       return Compatible;
7547     }
7548 
7549     // T* -> int
7550     if (LHSType->isIntegerType()) {
7551       Kind = CK_PointerToIntegral;
7552       return PointerToInt;
7553     }
7554 
7555     return Incompatible;
7556   }
7557 
7558   // Conversions from Objective-C pointers that are not covered by the above.
7559   if (isa<ObjCObjectPointerType>(RHSType)) {
7560     // T* -> _Bool
7561     if (LHSType == Context.BoolTy) {
7562       Kind = CK_PointerToBoolean;
7563       return Compatible;
7564     }
7565 
7566     // T* -> int
7567     if (LHSType->isIntegerType()) {
7568       Kind = CK_PointerToIntegral;
7569       return PointerToInt;
7570     }
7571 
7572     return Incompatible;
7573   }
7574 
7575   // struct A -> struct B
7576   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7577     if (Context.typesAreCompatible(LHSType, RHSType)) {
7578       Kind = CK_NoOp;
7579       return Compatible;
7580     }
7581   }
7582 
7583   return Incompatible;
7584 }
7585 
7586 /// \brief Constructs a transparent union from an expression that is
7587 /// used to initialize the transparent union.
7588 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7589                                       ExprResult &EResult, QualType UnionType,
7590                                       FieldDecl *Field) {
7591   // Build an initializer list that designates the appropriate member
7592   // of the transparent union.
7593   Expr *E = EResult.get();
7594   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7595                                                    E, SourceLocation());
7596   Initializer->setType(UnionType);
7597   Initializer->setInitializedFieldInUnion(Field);
7598 
7599   // Build a compound literal constructing a value of the transparent
7600   // union type from this initializer list.
7601   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7602   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7603                                         VK_RValue, Initializer, false);
7604 }
7605 
7606 Sema::AssignConvertType
7607 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7608                                                ExprResult &RHS) {
7609   QualType RHSType = RHS.get()->getType();
7610 
7611   // If the ArgType is a Union type, we want to handle a potential
7612   // transparent_union GCC extension.
7613   const RecordType *UT = ArgType->getAsUnionType();
7614   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7615     return Incompatible;
7616 
7617   // The field to initialize within the transparent union.
7618   RecordDecl *UD = UT->getDecl();
7619   FieldDecl *InitField = nullptr;
7620   // It's compatible if the expression matches any of the fields.
7621   for (auto *it : UD->fields()) {
7622     if (it->getType()->isPointerType()) {
7623       // If the transparent union contains a pointer type, we allow:
7624       // 1) void pointer
7625       // 2) null pointer constant
7626       if (RHSType->isPointerType())
7627         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7628           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7629           InitField = it;
7630           break;
7631         }
7632 
7633       if (RHS.get()->isNullPointerConstant(Context,
7634                                            Expr::NPC_ValueDependentIsNull)) {
7635         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7636                                 CK_NullToPointer);
7637         InitField = it;
7638         break;
7639       }
7640     }
7641 
7642     CastKind Kind = CK_Invalid;
7643     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7644           == Compatible) {
7645       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7646       InitField = it;
7647       break;
7648     }
7649   }
7650 
7651   if (!InitField)
7652     return Incompatible;
7653 
7654   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7655   return Compatible;
7656 }
7657 
7658 Sema::AssignConvertType
7659 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7660                                        bool Diagnose,
7661                                        bool DiagnoseCFAudited,
7662                                        bool ConvertRHS) {
7663   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7664   // we can't avoid *all* modifications at the moment, so we need some somewhere
7665   // to put the updated value.
7666   ExprResult LocalRHS = CallerRHS;
7667   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7668 
7669   if (getLangOpts().CPlusPlus) {
7670     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7671       // C++ 5.17p3: If the left operand is not of class type, the
7672       // expression is implicitly converted (C++ 4) to the
7673       // cv-unqualified type of the left operand.
7674       ExprResult Res;
7675       if (Diagnose) {
7676         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7677                                         AA_Assigning);
7678       } else {
7679         ImplicitConversionSequence ICS =
7680             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7681                                   /*SuppressUserConversions=*/false,
7682                                   /*AllowExplicit=*/false,
7683                                   /*InOverloadResolution=*/false,
7684                                   /*CStyle=*/false,
7685                                   /*AllowObjCWritebackConversion=*/false);
7686         if (ICS.isFailure())
7687           return Incompatible;
7688         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7689                                         ICS, AA_Assigning);
7690       }
7691       if (Res.isInvalid())
7692         return Incompatible;
7693       Sema::AssignConvertType result = Compatible;
7694       if (getLangOpts().ObjCAutoRefCount &&
7695           !CheckObjCARCUnavailableWeakConversion(LHSType,
7696                                                  RHS.get()->getType()))
7697         result = IncompatibleObjCWeakRef;
7698       RHS = Res;
7699       return result;
7700     }
7701 
7702     // FIXME: Currently, we fall through and treat C++ classes like C
7703     // structures.
7704     // FIXME: We also fall through for atomics; not sure what should
7705     // happen there, though.
7706   } else if (RHS.get()->getType() == Context.OverloadTy) {
7707     // As a set of extensions to C, we support overloading on functions. These
7708     // functions need to be resolved here.
7709     DeclAccessPair DAP;
7710     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7711             RHS.get(), LHSType, /*Complain=*/false, DAP))
7712       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7713     else
7714       return Incompatible;
7715   }
7716 
7717   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7718   // a null pointer constant.
7719   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7720        LHSType->isBlockPointerType()) &&
7721       RHS.get()->isNullPointerConstant(Context,
7722                                        Expr::NPC_ValueDependentIsNull)) {
7723     if (Diagnose || ConvertRHS) {
7724       CastKind Kind;
7725       CXXCastPath Path;
7726       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7727                              /*IgnoreBaseAccess=*/false, Diagnose);
7728       if (ConvertRHS)
7729         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7730     }
7731     return Compatible;
7732   }
7733 
7734   // This check seems unnatural, however it is necessary to ensure the proper
7735   // conversion of functions/arrays. If the conversion were done for all
7736   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7737   // expressions that suppress this implicit conversion (&, sizeof).
7738   //
7739   // Suppress this for references: C++ 8.5.3p5.
7740   if (!LHSType->isReferenceType()) {
7741     // FIXME: We potentially allocate here even if ConvertRHS is false.
7742     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7743     if (RHS.isInvalid())
7744       return Incompatible;
7745   }
7746 
7747   Expr *PRE = RHS.get()->IgnoreParenCasts();
7748   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7749     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7750     if (PDecl && !PDecl->hasDefinition()) {
7751       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7752       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7753     }
7754   }
7755 
7756   CastKind Kind = CK_Invalid;
7757   Sema::AssignConvertType result =
7758     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7759 
7760   // C99 6.5.16.1p2: The value of the right operand is converted to the
7761   // type of the assignment expression.
7762   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7763   // so that we can use references in built-in functions even in C.
7764   // The getNonReferenceType() call makes sure that the resulting expression
7765   // does not have reference type.
7766   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7767     QualType Ty = LHSType.getNonLValueExprType(Context);
7768     Expr *E = RHS.get();
7769 
7770     // Check for various Objective-C errors. If we are not reporting
7771     // diagnostics and just checking for errors, e.g., during overload
7772     // resolution, return Incompatible to indicate the failure.
7773     if (getLangOpts().ObjCAutoRefCount &&
7774         CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7775                                Diagnose, DiagnoseCFAudited) != ACR_okay) {
7776       if (!Diagnose)
7777         return Incompatible;
7778     }
7779     if (getLangOpts().ObjC1 &&
7780         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7781                                            E->getType(), E, Diagnose) ||
7782          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7783       if (!Diagnose)
7784         return Incompatible;
7785       // Replace the expression with a corrected version and continue so we
7786       // can find further errors.
7787       RHS = E;
7788       return Compatible;
7789     }
7790 
7791     if (ConvertRHS)
7792       RHS = ImpCastExprToType(E, Ty, Kind);
7793   }
7794   return result;
7795 }
7796 
7797 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7798                                ExprResult &RHS) {
7799   Diag(Loc, diag::err_typecheck_invalid_operands)
7800     << LHS.get()->getType() << RHS.get()->getType()
7801     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7802   return QualType();
7803 }
7804 
7805 /// Try to convert a value of non-vector type to a vector type by converting
7806 /// the type to the element type of the vector and then performing a splat.
7807 /// If the language is OpenCL, we only use conversions that promote scalar
7808 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7809 /// for float->int.
7810 ///
7811 /// \param scalar - if non-null, actually perform the conversions
7812 /// \return true if the operation fails (but without diagnosing the failure)
7813 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7814                                      QualType scalarTy,
7815                                      QualType vectorEltTy,
7816                                      QualType vectorTy) {
7817   // The conversion to apply to the scalar before splatting it,
7818   // if necessary.
7819   CastKind scalarCast = CK_Invalid;
7820 
7821   if (vectorEltTy->isIntegralType(S.Context)) {
7822     if (!scalarTy->isIntegralType(S.Context))
7823       return true;
7824     if (S.getLangOpts().OpenCL &&
7825         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7826       return true;
7827     scalarCast = CK_IntegralCast;
7828   } else if (vectorEltTy->isRealFloatingType()) {
7829     if (scalarTy->isRealFloatingType()) {
7830       if (S.getLangOpts().OpenCL &&
7831           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7832         return true;
7833       scalarCast = CK_FloatingCast;
7834     }
7835     else if (scalarTy->isIntegralType(S.Context))
7836       scalarCast = CK_IntegralToFloating;
7837     else
7838       return true;
7839   } else {
7840     return true;
7841   }
7842 
7843   // Adjust scalar if desired.
7844   if (scalar) {
7845     if (scalarCast != CK_Invalid)
7846       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
7847     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
7848   }
7849   return false;
7850 }
7851 
7852 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7853                                    SourceLocation Loc, bool IsCompAssign,
7854                                    bool AllowBothBool,
7855                                    bool AllowBoolConversions) {
7856   if (!IsCompAssign) {
7857     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
7858     if (LHS.isInvalid())
7859       return QualType();
7860   }
7861   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
7862   if (RHS.isInvalid())
7863     return QualType();
7864 
7865   // For conversion purposes, we ignore any qualifiers.
7866   // For example, "const float" and "float" are equivalent.
7867   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
7868   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
7869 
7870   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
7871   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
7872   assert(LHSVecType || RHSVecType);
7873 
7874   // AltiVec-style "vector bool op vector bool" combinations are allowed
7875   // for some operators but not others.
7876   if (!AllowBothBool &&
7877       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7878       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
7879     return InvalidOperands(Loc, LHS, RHS);
7880 
7881   // If the vector types are identical, return.
7882   if (Context.hasSameType(LHSType, RHSType))
7883     return LHSType;
7884 
7885   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
7886   if (LHSVecType && RHSVecType &&
7887       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7888     if (isa<ExtVectorType>(LHSVecType)) {
7889       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7890       return LHSType;
7891     }
7892 
7893     if (!IsCompAssign)
7894       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7895     return RHSType;
7896   }
7897 
7898   // AllowBoolConversions says that bool and non-bool AltiVec vectors
7899   // can be mixed, with the result being the non-bool type.  The non-bool
7900   // operand must have integer element type.
7901   if (AllowBoolConversions && LHSVecType && RHSVecType &&
7902       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
7903       (Context.getTypeSize(LHSVecType->getElementType()) ==
7904        Context.getTypeSize(RHSVecType->getElementType()))) {
7905     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
7906         LHSVecType->getElementType()->isIntegerType() &&
7907         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
7908       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7909       return LHSType;
7910     }
7911     if (!IsCompAssign &&
7912         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7913         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
7914         RHSVecType->getElementType()->isIntegerType()) {
7915       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7916       return RHSType;
7917     }
7918   }
7919 
7920   // If there's an ext-vector type and a scalar, try to convert the scalar to
7921   // the vector element type and splat.
7922   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
7923     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
7924                                   LHSVecType->getElementType(), LHSType))
7925       return LHSType;
7926   }
7927   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
7928     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
7929                                   LHSType, RHSVecType->getElementType(),
7930                                   RHSType))
7931       return RHSType;
7932   }
7933 
7934   // If we're allowing lax vector conversions, only the total (data) size needs
7935   // to be the same. If one of the types is scalar, the result is always the
7936   // vector type. Don't allow this if the scalar operand is an lvalue.
7937   QualType VecType = LHSVecType ? LHSType : RHSType;
7938   QualType ScalarType = LHSVecType ? RHSType : LHSType;
7939   ExprResult *ScalarExpr = LHSVecType ? &RHS : &LHS;
7940   if (isLaxVectorConversion(ScalarType, VecType) &&
7941       !ScalarExpr->get()->isLValue()) {
7942     *ScalarExpr = ImpCastExprToType(ScalarExpr->get(), VecType, CK_BitCast);
7943     return VecType;
7944   }
7945 
7946   // Okay, the expression is invalid.
7947 
7948   // If there's a non-vector, non-real operand, diagnose that.
7949   if ((!RHSVecType && !RHSType->isRealType()) ||
7950       (!LHSVecType && !LHSType->isRealType())) {
7951     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
7952       << LHSType << RHSType
7953       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7954     return QualType();
7955   }
7956 
7957   // OpenCL V1.1 6.2.6.p1:
7958   // If the operands are of more than one vector type, then an error shall
7959   // occur. Implicit conversions between vector types are not permitted, per
7960   // section 6.2.1.
7961   if (getLangOpts().OpenCL &&
7962       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
7963       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
7964     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
7965                                                            << RHSType;
7966     return QualType();
7967   }
7968 
7969   // Otherwise, use the generic diagnostic.
7970   Diag(Loc, diag::err_typecheck_vector_not_convertable)
7971     << LHSType << RHSType
7972     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7973   return QualType();
7974 }
7975 
7976 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
7977 // expression.  These are mainly cases where the null pointer is used as an
7978 // integer instead of a pointer.
7979 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
7980                                 SourceLocation Loc, bool IsCompare) {
7981   // The canonical way to check for a GNU null is with isNullPointerConstant,
7982   // but we use a bit of a hack here for speed; this is a relatively
7983   // hot path, and isNullPointerConstant is slow.
7984   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
7985   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
7986 
7987   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
7988 
7989   // Avoid analyzing cases where the result will either be invalid (and
7990   // diagnosed as such) or entirely valid and not something to warn about.
7991   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
7992       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
7993     return;
7994 
7995   // Comparison operations would not make sense with a null pointer no matter
7996   // what the other expression is.
7997   if (!IsCompare) {
7998     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
7999         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8000         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8001     return;
8002   }
8003 
8004   // The rest of the operations only make sense with a null pointer
8005   // if the other expression is a pointer.
8006   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8007       NonNullType->canDecayToPointerType())
8008     return;
8009 
8010   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8011       << LHSNull /* LHS is NULL */ << NonNullType
8012       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8013 }
8014 
8015 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8016                                                ExprResult &RHS,
8017                                                SourceLocation Loc, bool IsDiv) {
8018   // Check for division/remainder by zero.
8019   llvm::APSInt RHSValue;
8020   if (!RHS.get()->isValueDependent() &&
8021       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8022     S.DiagRuntimeBehavior(Loc, RHS.get(),
8023                           S.PDiag(diag::warn_remainder_division_by_zero)
8024                             << IsDiv << RHS.get()->getSourceRange());
8025 }
8026 
8027 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8028                                            SourceLocation Loc,
8029                                            bool IsCompAssign, bool IsDiv) {
8030   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8031 
8032   if (LHS.get()->getType()->isVectorType() ||
8033       RHS.get()->getType()->isVectorType())
8034     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8035                                /*AllowBothBool*/getLangOpts().AltiVec,
8036                                /*AllowBoolConversions*/false);
8037 
8038   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8039   if (LHS.isInvalid() || RHS.isInvalid())
8040     return QualType();
8041 
8042 
8043   if (compType.isNull() || !compType->isArithmeticType())
8044     return InvalidOperands(Loc, LHS, RHS);
8045   if (IsDiv)
8046     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8047   return compType;
8048 }
8049 
8050 QualType Sema::CheckRemainderOperands(
8051   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8052   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8053 
8054   if (LHS.get()->getType()->isVectorType() ||
8055       RHS.get()->getType()->isVectorType()) {
8056     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8057         RHS.get()->getType()->hasIntegerRepresentation())
8058       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8059                                  /*AllowBothBool*/getLangOpts().AltiVec,
8060                                  /*AllowBoolConversions*/false);
8061     return InvalidOperands(Loc, LHS, RHS);
8062   }
8063 
8064   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8065   if (LHS.isInvalid() || RHS.isInvalid())
8066     return QualType();
8067 
8068   if (compType.isNull() || !compType->isIntegerType())
8069     return InvalidOperands(Loc, LHS, RHS);
8070   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8071   return compType;
8072 }
8073 
8074 /// \brief Diagnose invalid arithmetic on two void pointers.
8075 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8076                                                 Expr *LHSExpr, Expr *RHSExpr) {
8077   S.Diag(Loc, S.getLangOpts().CPlusPlus
8078                 ? diag::err_typecheck_pointer_arith_void_type
8079                 : diag::ext_gnu_void_ptr)
8080     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8081                             << RHSExpr->getSourceRange();
8082 }
8083 
8084 /// \brief Diagnose invalid arithmetic on a void pointer.
8085 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8086                                             Expr *Pointer) {
8087   S.Diag(Loc, S.getLangOpts().CPlusPlus
8088                 ? diag::err_typecheck_pointer_arith_void_type
8089                 : diag::ext_gnu_void_ptr)
8090     << 0 /* one pointer */ << Pointer->getSourceRange();
8091 }
8092 
8093 /// \brief Diagnose invalid arithmetic on two function pointers.
8094 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8095                                                     Expr *LHS, Expr *RHS) {
8096   assert(LHS->getType()->isAnyPointerType());
8097   assert(RHS->getType()->isAnyPointerType());
8098   S.Diag(Loc, S.getLangOpts().CPlusPlus
8099                 ? diag::err_typecheck_pointer_arith_function_type
8100                 : diag::ext_gnu_ptr_func_arith)
8101     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8102     // We only show the second type if it differs from the first.
8103     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8104                                                    RHS->getType())
8105     << RHS->getType()->getPointeeType()
8106     << LHS->getSourceRange() << RHS->getSourceRange();
8107 }
8108 
8109 /// \brief Diagnose invalid arithmetic on a function pointer.
8110 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8111                                                 Expr *Pointer) {
8112   assert(Pointer->getType()->isAnyPointerType());
8113   S.Diag(Loc, S.getLangOpts().CPlusPlus
8114                 ? diag::err_typecheck_pointer_arith_function_type
8115                 : diag::ext_gnu_ptr_func_arith)
8116     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8117     << 0 /* one pointer, so only one type */
8118     << Pointer->getSourceRange();
8119 }
8120 
8121 /// \brief Emit error if Operand is incomplete pointer type
8122 ///
8123 /// \returns True if pointer has incomplete type
8124 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8125                                                  Expr *Operand) {
8126   QualType ResType = Operand->getType();
8127   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8128     ResType = ResAtomicType->getValueType();
8129 
8130   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8131   QualType PointeeTy = ResType->getPointeeType();
8132   return S.RequireCompleteType(Loc, PointeeTy,
8133                                diag::err_typecheck_arithmetic_incomplete_type,
8134                                PointeeTy, Operand->getSourceRange());
8135 }
8136 
8137 /// \brief Check the validity of an arithmetic pointer operand.
8138 ///
8139 /// If the operand has pointer type, this code will check for pointer types
8140 /// which are invalid in arithmetic operations. These will be diagnosed
8141 /// appropriately, including whether or not the use is supported as an
8142 /// extension.
8143 ///
8144 /// \returns True when the operand is valid to use (even if as an extension).
8145 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8146                                             Expr *Operand) {
8147   QualType ResType = Operand->getType();
8148   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8149     ResType = ResAtomicType->getValueType();
8150 
8151   if (!ResType->isAnyPointerType()) return true;
8152 
8153   QualType PointeeTy = ResType->getPointeeType();
8154   if (PointeeTy->isVoidType()) {
8155     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8156     return !S.getLangOpts().CPlusPlus;
8157   }
8158   if (PointeeTy->isFunctionType()) {
8159     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8160     return !S.getLangOpts().CPlusPlus;
8161   }
8162 
8163   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8164 
8165   return true;
8166 }
8167 
8168 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8169 /// operands.
8170 ///
8171 /// This routine will diagnose any invalid arithmetic on pointer operands much
8172 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8173 /// for emitting a single diagnostic even for operations where both LHS and RHS
8174 /// are (potentially problematic) pointers.
8175 ///
8176 /// \returns True when the operand is valid to use (even if as an extension).
8177 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8178                                                 Expr *LHSExpr, Expr *RHSExpr) {
8179   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8180   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8181   if (!isLHSPointer && !isRHSPointer) return true;
8182 
8183   QualType LHSPointeeTy, RHSPointeeTy;
8184   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8185   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8186 
8187   // if both are pointers check if operation is valid wrt address spaces
8188   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8189     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8190     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8191     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8192       S.Diag(Loc,
8193              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8194           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8195           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8196       return false;
8197     }
8198   }
8199 
8200   // Check for arithmetic on pointers to incomplete types.
8201   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8202   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8203   if (isLHSVoidPtr || isRHSVoidPtr) {
8204     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8205     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8206     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8207 
8208     return !S.getLangOpts().CPlusPlus;
8209   }
8210 
8211   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8212   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8213   if (isLHSFuncPtr || isRHSFuncPtr) {
8214     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8215     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8216                                                                 RHSExpr);
8217     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8218 
8219     return !S.getLangOpts().CPlusPlus;
8220   }
8221 
8222   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8223     return false;
8224   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8225     return false;
8226 
8227   return true;
8228 }
8229 
8230 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8231 /// literal.
8232 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8233                                   Expr *LHSExpr, Expr *RHSExpr) {
8234   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8235   Expr* IndexExpr = RHSExpr;
8236   if (!StrExpr) {
8237     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8238     IndexExpr = LHSExpr;
8239   }
8240 
8241   bool IsStringPlusInt = StrExpr &&
8242       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8243   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8244     return;
8245 
8246   llvm::APSInt index;
8247   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8248     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8249     if (index.isNonNegative() &&
8250         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8251                               index.isUnsigned()))
8252       return;
8253   }
8254 
8255   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8256   Self.Diag(OpLoc, diag::warn_string_plus_int)
8257       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8258 
8259   // Only print a fixit for "str" + int, not for int + "str".
8260   if (IndexExpr == RHSExpr) {
8261     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8262     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8263         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8264         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8265         << FixItHint::CreateInsertion(EndLoc, "]");
8266   } else
8267     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8268 }
8269 
8270 /// \brief Emit a warning when adding a char literal to a string.
8271 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8272                                    Expr *LHSExpr, Expr *RHSExpr) {
8273   const Expr *StringRefExpr = LHSExpr;
8274   const CharacterLiteral *CharExpr =
8275       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8276 
8277   if (!CharExpr) {
8278     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8279     StringRefExpr = RHSExpr;
8280   }
8281 
8282   if (!CharExpr || !StringRefExpr)
8283     return;
8284 
8285   const QualType StringType = StringRefExpr->getType();
8286 
8287   // Return if not a PointerType.
8288   if (!StringType->isAnyPointerType())
8289     return;
8290 
8291   // Return if not a CharacterType.
8292   if (!StringType->getPointeeType()->isAnyCharacterType())
8293     return;
8294 
8295   ASTContext &Ctx = Self.getASTContext();
8296   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8297 
8298   const QualType CharType = CharExpr->getType();
8299   if (!CharType->isAnyCharacterType() &&
8300       CharType->isIntegerType() &&
8301       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8302     Self.Diag(OpLoc, diag::warn_string_plus_char)
8303         << DiagRange << Ctx.CharTy;
8304   } else {
8305     Self.Diag(OpLoc, diag::warn_string_plus_char)
8306         << DiagRange << CharExpr->getType();
8307   }
8308 
8309   // Only print a fixit for str + char, not for char + str.
8310   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8311     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8312     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8313         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8314         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8315         << FixItHint::CreateInsertion(EndLoc, "]");
8316   } else {
8317     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8318   }
8319 }
8320 
8321 /// \brief Emit error when two pointers are incompatible.
8322 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8323                                            Expr *LHSExpr, Expr *RHSExpr) {
8324   assert(LHSExpr->getType()->isAnyPointerType());
8325   assert(RHSExpr->getType()->isAnyPointerType());
8326   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8327     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8328     << RHSExpr->getSourceRange();
8329 }
8330 
8331 // C99 6.5.6
8332 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8333                                      SourceLocation Loc, BinaryOperatorKind Opc,
8334                                      QualType* CompLHSTy) {
8335   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8336 
8337   if (LHS.get()->getType()->isVectorType() ||
8338       RHS.get()->getType()->isVectorType()) {
8339     QualType compType = CheckVectorOperands(
8340         LHS, RHS, Loc, CompLHSTy,
8341         /*AllowBothBool*/getLangOpts().AltiVec,
8342         /*AllowBoolConversions*/getLangOpts().ZVector);
8343     if (CompLHSTy) *CompLHSTy = compType;
8344     return compType;
8345   }
8346 
8347   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8348   if (LHS.isInvalid() || RHS.isInvalid())
8349     return QualType();
8350 
8351   // Diagnose "string literal" '+' int and string '+' "char literal".
8352   if (Opc == BO_Add) {
8353     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8354     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8355   }
8356 
8357   // handle the common case first (both operands are arithmetic).
8358   if (!compType.isNull() && compType->isArithmeticType()) {
8359     if (CompLHSTy) *CompLHSTy = compType;
8360     return compType;
8361   }
8362 
8363   // Type-checking.  Ultimately the pointer's going to be in PExp;
8364   // note that we bias towards the LHS being the pointer.
8365   Expr *PExp = LHS.get(), *IExp = RHS.get();
8366 
8367   bool isObjCPointer;
8368   if (PExp->getType()->isPointerType()) {
8369     isObjCPointer = false;
8370   } else if (PExp->getType()->isObjCObjectPointerType()) {
8371     isObjCPointer = true;
8372   } else {
8373     std::swap(PExp, IExp);
8374     if (PExp->getType()->isPointerType()) {
8375       isObjCPointer = false;
8376     } else if (PExp->getType()->isObjCObjectPointerType()) {
8377       isObjCPointer = true;
8378     } else {
8379       return InvalidOperands(Loc, LHS, RHS);
8380     }
8381   }
8382   assert(PExp->getType()->isAnyPointerType());
8383 
8384   if (!IExp->getType()->isIntegerType())
8385     return InvalidOperands(Loc, LHS, RHS);
8386 
8387   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8388     return QualType();
8389 
8390   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8391     return QualType();
8392 
8393   // Check array bounds for pointer arithemtic
8394   CheckArrayAccess(PExp, IExp);
8395 
8396   if (CompLHSTy) {
8397     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8398     if (LHSTy.isNull()) {
8399       LHSTy = LHS.get()->getType();
8400       if (LHSTy->isPromotableIntegerType())
8401         LHSTy = Context.getPromotedIntegerType(LHSTy);
8402     }
8403     *CompLHSTy = LHSTy;
8404   }
8405 
8406   return PExp->getType();
8407 }
8408 
8409 // C99 6.5.6
8410 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8411                                         SourceLocation Loc,
8412                                         QualType* CompLHSTy) {
8413   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8414 
8415   if (LHS.get()->getType()->isVectorType() ||
8416       RHS.get()->getType()->isVectorType()) {
8417     QualType compType = CheckVectorOperands(
8418         LHS, RHS, Loc, CompLHSTy,
8419         /*AllowBothBool*/getLangOpts().AltiVec,
8420         /*AllowBoolConversions*/getLangOpts().ZVector);
8421     if (CompLHSTy) *CompLHSTy = compType;
8422     return compType;
8423   }
8424 
8425   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8426   if (LHS.isInvalid() || RHS.isInvalid())
8427     return QualType();
8428 
8429   // Enforce type constraints: C99 6.5.6p3.
8430 
8431   // Handle the common case first (both operands are arithmetic).
8432   if (!compType.isNull() && compType->isArithmeticType()) {
8433     if (CompLHSTy) *CompLHSTy = compType;
8434     return compType;
8435   }
8436 
8437   // Either ptr - int   or   ptr - ptr.
8438   if (LHS.get()->getType()->isAnyPointerType()) {
8439     QualType lpointee = LHS.get()->getType()->getPointeeType();
8440 
8441     // Diagnose bad cases where we step over interface counts.
8442     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8443         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8444       return QualType();
8445 
8446     // The result type of a pointer-int computation is the pointer type.
8447     if (RHS.get()->getType()->isIntegerType()) {
8448       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8449         return QualType();
8450 
8451       // Check array bounds for pointer arithemtic
8452       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8453                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8454 
8455       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8456       return LHS.get()->getType();
8457     }
8458 
8459     // Handle pointer-pointer subtractions.
8460     if (const PointerType *RHSPTy
8461           = RHS.get()->getType()->getAs<PointerType>()) {
8462       QualType rpointee = RHSPTy->getPointeeType();
8463 
8464       if (getLangOpts().CPlusPlus) {
8465         // Pointee types must be the same: C++ [expr.add]
8466         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8467           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8468         }
8469       } else {
8470         // Pointee types must be compatible C99 6.5.6p3
8471         if (!Context.typesAreCompatible(
8472                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8473                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8474           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8475           return QualType();
8476         }
8477       }
8478 
8479       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8480                                                LHS.get(), RHS.get()))
8481         return QualType();
8482 
8483       // The pointee type may have zero size.  As an extension, a structure or
8484       // union may have zero size or an array may have zero length.  In this
8485       // case subtraction does not make sense.
8486       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8487         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8488         if (ElementSize.isZero()) {
8489           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8490             << rpointee.getUnqualifiedType()
8491             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8492         }
8493       }
8494 
8495       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8496       return Context.getPointerDiffType();
8497     }
8498   }
8499 
8500   return InvalidOperands(Loc, LHS, RHS);
8501 }
8502 
8503 static bool isScopedEnumerationType(QualType T) {
8504   if (const EnumType *ET = T->getAs<EnumType>())
8505     return ET->getDecl()->isScoped();
8506   return false;
8507 }
8508 
8509 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8510                                    SourceLocation Loc, BinaryOperatorKind Opc,
8511                                    QualType LHSType) {
8512   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8513   // so skip remaining warnings as we don't want to modify values within Sema.
8514   if (S.getLangOpts().OpenCL)
8515     return;
8516 
8517   llvm::APSInt Right;
8518   // Check right/shifter operand
8519   if (RHS.get()->isValueDependent() ||
8520       !RHS.get()->EvaluateAsInt(Right, S.Context))
8521     return;
8522 
8523   if (Right.isNegative()) {
8524     S.DiagRuntimeBehavior(Loc, RHS.get(),
8525                           S.PDiag(diag::warn_shift_negative)
8526                             << RHS.get()->getSourceRange());
8527     return;
8528   }
8529   llvm::APInt LeftBits(Right.getBitWidth(),
8530                        S.Context.getTypeSize(LHS.get()->getType()));
8531   if (Right.uge(LeftBits)) {
8532     S.DiagRuntimeBehavior(Loc, RHS.get(),
8533                           S.PDiag(diag::warn_shift_gt_typewidth)
8534                             << RHS.get()->getSourceRange());
8535     return;
8536   }
8537   if (Opc != BO_Shl)
8538     return;
8539 
8540   // When left shifting an ICE which is signed, we can check for overflow which
8541   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8542   // integers have defined behavior modulo one more than the maximum value
8543   // representable in the result type, so never warn for those.
8544   llvm::APSInt Left;
8545   if (LHS.get()->isValueDependent() ||
8546       LHSType->hasUnsignedIntegerRepresentation() ||
8547       !LHS.get()->EvaluateAsInt(Left, S.Context))
8548     return;
8549 
8550   // If LHS does not have a signed type and non-negative value
8551   // then, the behavior is undefined. Warn about it.
8552   if (Left.isNegative()) {
8553     S.DiagRuntimeBehavior(Loc, LHS.get(),
8554                           S.PDiag(diag::warn_shift_lhs_negative)
8555                             << LHS.get()->getSourceRange());
8556     return;
8557   }
8558 
8559   llvm::APInt ResultBits =
8560       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8561   if (LeftBits.uge(ResultBits))
8562     return;
8563   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8564   Result = Result.shl(Right);
8565 
8566   // Print the bit representation of the signed integer as an unsigned
8567   // hexadecimal number.
8568   SmallString<40> HexResult;
8569   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8570 
8571   // If we are only missing a sign bit, this is less likely to result in actual
8572   // bugs -- if the result is cast back to an unsigned type, it will have the
8573   // expected value. Thus we place this behind a different warning that can be
8574   // turned off separately if needed.
8575   if (LeftBits == ResultBits - 1) {
8576     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8577         << HexResult << LHSType
8578         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8579     return;
8580   }
8581 
8582   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8583     << HexResult.str() << Result.getMinSignedBits() << LHSType
8584     << Left.getBitWidth() << LHS.get()->getSourceRange()
8585     << RHS.get()->getSourceRange();
8586 }
8587 
8588 /// \brief Return the resulting type when an OpenCL vector is shifted
8589 ///        by a scalar or vector shift amount.
8590 static QualType checkOpenCLVectorShift(Sema &S,
8591                                        ExprResult &LHS, ExprResult &RHS,
8592                                        SourceLocation Loc, bool IsCompAssign) {
8593   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8594   if (!LHS.get()->getType()->isVectorType()) {
8595     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8596       << RHS.get()->getType() << LHS.get()->getType()
8597       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8598     return QualType();
8599   }
8600 
8601   if (!IsCompAssign) {
8602     LHS = S.UsualUnaryConversions(LHS.get());
8603     if (LHS.isInvalid()) return QualType();
8604   }
8605 
8606   RHS = S.UsualUnaryConversions(RHS.get());
8607   if (RHS.isInvalid()) return QualType();
8608 
8609   QualType LHSType = LHS.get()->getType();
8610   const VectorType *LHSVecTy = LHSType->castAs<VectorType>();
8611   QualType LHSEleType = LHSVecTy->getElementType();
8612 
8613   // Note that RHS might not be a vector.
8614   QualType RHSType = RHS.get()->getType();
8615   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8616   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8617 
8618   // OpenCL v1.1 s6.3.j says that the operands need to be integers.
8619   if (!LHSEleType->isIntegerType()) {
8620     S.Diag(Loc, diag::err_typecheck_expect_int)
8621       << LHS.get()->getType() << LHS.get()->getSourceRange();
8622     return QualType();
8623   }
8624 
8625   if (!RHSEleType->isIntegerType()) {
8626     S.Diag(Loc, diag::err_typecheck_expect_int)
8627       << RHS.get()->getType() << RHS.get()->getSourceRange();
8628     return QualType();
8629   }
8630 
8631   if (RHSVecTy) {
8632     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8633     // are applied component-wise. So if RHS is a vector, then ensure
8634     // that the number of elements is the same as LHS...
8635     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8636       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8637         << LHS.get()->getType() << RHS.get()->getType()
8638         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8639       return QualType();
8640     }
8641   } else {
8642     // ...else expand RHS to match the number of elements in LHS.
8643     QualType VecTy =
8644       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8645     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8646   }
8647 
8648   return LHSType;
8649 }
8650 
8651 // C99 6.5.7
8652 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8653                                   SourceLocation Loc, BinaryOperatorKind Opc,
8654                                   bool IsCompAssign) {
8655   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8656 
8657   // Vector shifts promote their scalar inputs to vector type.
8658   if (LHS.get()->getType()->isVectorType() ||
8659       RHS.get()->getType()->isVectorType()) {
8660     if (LangOpts.OpenCL)
8661       return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8662     if (LangOpts.ZVector) {
8663       // The shift operators for the z vector extensions work basically
8664       // like OpenCL shifts, except that neither the LHS nor the RHS is
8665       // allowed to be a "vector bool".
8666       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8667         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8668           return InvalidOperands(Loc, LHS, RHS);
8669       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8670         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8671           return InvalidOperands(Loc, LHS, RHS);
8672       return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8673     }
8674     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8675                                /*AllowBothBool*/true,
8676                                /*AllowBoolConversions*/false);
8677   }
8678 
8679   // Shifts don't perform usual arithmetic conversions, they just do integer
8680   // promotions on each operand. C99 6.5.7p3
8681 
8682   // For the LHS, do usual unary conversions, but then reset them away
8683   // if this is a compound assignment.
8684   ExprResult OldLHS = LHS;
8685   LHS = UsualUnaryConversions(LHS.get());
8686   if (LHS.isInvalid())
8687     return QualType();
8688   QualType LHSType = LHS.get()->getType();
8689   if (IsCompAssign) LHS = OldLHS;
8690 
8691   // The RHS is simpler.
8692   RHS = UsualUnaryConversions(RHS.get());
8693   if (RHS.isInvalid())
8694     return QualType();
8695   QualType RHSType = RHS.get()->getType();
8696 
8697   // C99 6.5.7p2: Each of the operands shall have integer type.
8698   if (!LHSType->hasIntegerRepresentation() ||
8699       !RHSType->hasIntegerRepresentation())
8700     return InvalidOperands(Loc, LHS, RHS);
8701 
8702   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8703   // hasIntegerRepresentation() above instead of this.
8704   if (isScopedEnumerationType(LHSType) ||
8705       isScopedEnumerationType(RHSType)) {
8706     return InvalidOperands(Loc, LHS, RHS);
8707   }
8708   // Sanity-check shift operands
8709   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8710 
8711   // "The type of the result is that of the promoted left operand."
8712   return LHSType;
8713 }
8714 
8715 static bool IsWithinTemplateSpecialization(Decl *D) {
8716   if (DeclContext *DC = D->getDeclContext()) {
8717     if (isa<ClassTemplateSpecializationDecl>(DC))
8718       return true;
8719     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8720       return FD->isFunctionTemplateSpecialization();
8721   }
8722   return false;
8723 }
8724 
8725 /// If two different enums are compared, raise a warning.
8726 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8727                                 Expr *RHS) {
8728   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8729   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8730 
8731   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8732   if (!LHSEnumType)
8733     return;
8734   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8735   if (!RHSEnumType)
8736     return;
8737 
8738   // Ignore anonymous enums.
8739   if (!LHSEnumType->getDecl()->getIdentifier())
8740     return;
8741   if (!RHSEnumType->getDecl()->getIdentifier())
8742     return;
8743 
8744   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8745     return;
8746 
8747   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8748       << LHSStrippedType << RHSStrippedType
8749       << LHS->getSourceRange() << RHS->getSourceRange();
8750 }
8751 
8752 /// \brief Diagnose bad pointer comparisons.
8753 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8754                                               ExprResult &LHS, ExprResult &RHS,
8755                                               bool IsError) {
8756   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8757                       : diag::ext_typecheck_comparison_of_distinct_pointers)
8758     << LHS.get()->getType() << RHS.get()->getType()
8759     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8760 }
8761 
8762 /// \brief Returns false if the pointers are converted to a composite type,
8763 /// true otherwise.
8764 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8765                                            ExprResult &LHS, ExprResult &RHS) {
8766   // C++ [expr.rel]p2:
8767   //   [...] Pointer conversions (4.10) and qualification
8768   //   conversions (4.4) are performed on pointer operands (or on
8769   //   a pointer operand and a null pointer constant) to bring
8770   //   them to their composite pointer type. [...]
8771   //
8772   // C++ [expr.eq]p1 uses the same notion for (in)equality
8773   // comparisons of pointers.
8774 
8775   // C++ [expr.eq]p2:
8776   //   In addition, pointers to members can be compared, or a pointer to
8777   //   member and a null pointer constant. Pointer to member conversions
8778   //   (4.11) and qualification conversions (4.4) are performed to bring
8779   //   them to a common type. If one operand is a null pointer constant,
8780   //   the common type is the type of the other operand. Otherwise, the
8781   //   common type is a pointer to member type similar (4.4) to the type
8782   //   of one of the operands, with a cv-qualification signature (4.4)
8783   //   that is the union of the cv-qualification signatures of the operand
8784   //   types.
8785 
8786   QualType LHSType = LHS.get()->getType();
8787   QualType RHSType = RHS.get()->getType();
8788   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
8789          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
8790 
8791   bool NonStandardCompositeType = false;
8792   bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
8793   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
8794   if (T.isNull()) {
8795     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8796     return true;
8797   }
8798 
8799   if (NonStandardCompositeType)
8800     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
8801       << LHSType << RHSType << T << LHS.get()->getSourceRange()
8802       << RHS.get()->getSourceRange();
8803 
8804   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8805   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
8806   return false;
8807 }
8808 
8809 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
8810                                                     ExprResult &LHS,
8811                                                     ExprResult &RHS,
8812                                                     bool IsError) {
8813   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8814                       : diag::ext_typecheck_comparison_of_fptr_to_void)
8815     << LHS.get()->getType() << RHS.get()->getType()
8816     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8817 }
8818 
8819 static bool isObjCObjectLiteral(ExprResult &E) {
8820   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
8821   case Stmt::ObjCArrayLiteralClass:
8822   case Stmt::ObjCDictionaryLiteralClass:
8823   case Stmt::ObjCStringLiteralClass:
8824   case Stmt::ObjCBoxedExprClass:
8825     return true;
8826   default:
8827     // Note that ObjCBoolLiteral is NOT an object literal!
8828     return false;
8829   }
8830 }
8831 
8832 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
8833   const ObjCObjectPointerType *Type =
8834     LHS->getType()->getAs<ObjCObjectPointerType>();
8835 
8836   // If this is not actually an Objective-C object, bail out.
8837   if (!Type)
8838     return false;
8839 
8840   // Get the LHS object's interface type.
8841   QualType InterfaceType = Type->getPointeeType();
8842 
8843   // If the RHS isn't an Objective-C object, bail out.
8844   if (!RHS->getType()->isObjCObjectPointerType())
8845     return false;
8846 
8847   // Try to find the -isEqual: method.
8848   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
8849   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
8850                                                       InterfaceType,
8851                                                       /*instance=*/true);
8852   if (!Method) {
8853     if (Type->isObjCIdType()) {
8854       // For 'id', just check the global pool.
8855       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
8856                                                   /*receiverId=*/true);
8857     } else {
8858       // Check protocols.
8859       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
8860                                              /*instance=*/true);
8861     }
8862   }
8863 
8864   if (!Method)
8865     return false;
8866 
8867   QualType T = Method->parameters()[0]->getType();
8868   if (!T->isObjCObjectPointerType())
8869     return false;
8870 
8871   QualType R = Method->getReturnType();
8872   if (!R->isScalarType())
8873     return false;
8874 
8875   return true;
8876 }
8877 
8878 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
8879   FromE = FromE->IgnoreParenImpCasts();
8880   switch (FromE->getStmtClass()) {
8881     default:
8882       break;
8883     case Stmt::ObjCStringLiteralClass:
8884       // "string literal"
8885       return LK_String;
8886     case Stmt::ObjCArrayLiteralClass:
8887       // "array literal"
8888       return LK_Array;
8889     case Stmt::ObjCDictionaryLiteralClass:
8890       // "dictionary literal"
8891       return LK_Dictionary;
8892     case Stmt::BlockExprClass:
8893       return LK_Block;
8894     case Stmt::ObjCBoxedExprClass: {
8895       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
8896       switch (Inner->getStmtClass()) {
8897         case Stmt::IntegerLiteralClass:
8898         case Stmt::FloatingLiteralClass:
8899         case Stmt::CharacterLiteralClass:
8900         case Stmt::ObjCBoolLiteralExprClass:
8901         case Stmt::CXXBoolLiteralExprClass:
8902           // "numeric literal"
8903           return LK_Numeric;
8904         case Stmt::ImplicitCastExprClass: {
8905           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
8906           // Boolean literals can be represented by implicit casts.
8907           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
8908             return LK_Numeric;
8909           break;
8910         }
8911         default:
8912           break;
8913       }
8914       return LK_Boxed;
8915     }
8916   }
8917   return LK_None;
8918 }
8919 
8920 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
8921                                           ExprResult &LHS, ExprResult &RHS,
8922                                           BinaryOperator::Opcode Opc){
8923   Expr *Literal;
8924   Expr *Other;
8925   if (isObjCObjectLiteral(LHS)) {
8926     Literal = LHS.get();
8927     Other = RHS.get();
8928   } else {
8929     Literal = RHS.get();
8930     Other = LHS.get();
8931   }
8932 
8933   // Don't warn on comparisons against nil.
8934   Other = Other->IgnoreParenCasts();
8935   if (Other->isNullPointerConstant(S.getASTContext(),
8936                                    Expr::NPC_ValueDependentIsNotNull))
8937     return;
8938 
8939   // This should be kept in sync with warn_objc_literal_comparison.
8940   // LK_String should always be after the other literals, since it has its own
8941   // warning flag.
8942   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
8943   assert(LiteralKind != Sema::LK_Block);
8944   if (LiteralKind == Sema::LK_None) {
8945     llvm_unreachable("Unknown Objective-C object literal kind");
8946   }
8947 
8948   if (LiteralKind == Sema::LK_String)
8949     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
8950       << Literal->getSourceRange();
8951   else
8952     S.Diag(Loc, diag::warn_objc_literal_comparison)
8953       << LiteralKind << Literal->getSourceRange();
8954 
8955   if (BinaryOperator::isEqualityOp(Opc) &&
8956       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
8957     SourceLocation Start = LHS.get()->getLocStart();
8958     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
8959     CharSourceRange OpRange =
8960       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
8961 
8962     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
8963       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
8964       << FixItHint::CreateReplacement(OpRange, " isEqual:")
8965       << FixItHint::CreateInsertion(End, "]");
8966   }
8967 }
8968 
8969 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
8970                                                 ExprResult &RHS,
8971                                                 SourceLocation Loc,
8972                                                 BinaryOperatorKind Opc) {
8973   // Check that left hand side is !something.
8974   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
8975   if (!UO || UO->getOpcode() != UO_LNot) return;
8976 
8977   // Only check if the right hand side is non-bool arithmetic type.
8978   if (RHS.get()->isKnownToHaveBooleanValue()) return;
8979 
8980   // Make sure that the something in !something is not bool.
8981   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
8982   if (SubExpr->isKnownToHaveBooleanValue()) return;
8983 
8984   // Emit warning.
8985   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
8986       << Loc;
8987 
8988   // First note suggest !(x < y)
8989   SourceLocation FirstOpen = SubExpr->getLocStart();
8990   SourceLocation FirstClose = RHS.get()->getLocEnd();
8991   FirstClose = S.getLocForEndOfToken(FirstClose);
8992   if (FirstClose.isInvalid())
8993     FirstOpen = SourceLocation();
8994   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
8995       << FixItHint::CreateInsertion(FirstOpen, "(")
8996       << FixItHint::CreateInsertion(FirstClose, ")");
8997 
8998   // Second note suggests (!x) < y
8999   SourceLocation SecondOpen = LHS.get()->getLocStart();
9000   SourceLocation SecondClose = LHS.get()->getLocEnd();
9001   SecondClose = S.getLocForEndOfToken(SecondClose);
9002   if (SecondClose.isInvalid())
9003     SecondOpen = SourceLocation();
9004   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9005       << FixItHint::CreateInsertion(SecondOpen, "(")
9006       << FixItHint::CreateInsertion(SecondClose, ")");
9007 }
9008 
9009 // Get the decl for a simple expression: a reference to a variable,
9010 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9011 static ValueDecl *getCompareDecl(Expr *E) {
9012   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9013     return DR->getDecl();
9014   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9015     if (Ivar->isFreeIvar())
9016       return Ivar->getDecl();
9017   }
9018   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9019     if (Mem->isImplicitAccess())
9020       return Mem->getMemberDecl();
9021   }
9022   return nullptr;
9023 }
9024 
9025 // C99 6.5.8, C++ [expr.rel]
9026 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9027                                     SourceLocation Loc, BinaryOperatorKind Opc,
9028                                     bool IsRelational) {
9029   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9030 
9031   // Handle vector comparisons separately.
9032   if (LHS.get()->getType()->isVectorType() ||
9033       RHS.get()->getType()->isVectorType())
9034     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9035 
9036   QualType LHSType = LHS.get()->getType();
9037   QualType RHSType = RHS.get()->getType();
9038 
9039   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9040   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9041 
9042   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9043   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc);
9044 
9045   if (!LHSType->hasFloatingRepresentation() &&
9046       !(LHSType->isBlockPointerType() && IsRelational) &&
9047       !LHS.get()->getLocStart().isMacroID() &&
9048       !RHS.get()->getLocStart().isMacroID() &&
9049       ActiveTemplateInstantiations.empty()) {
9050     // For non-floating point types, check for self-comparisons of the form
9051     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9052     // often indicate logic errors in the program.
9053     //
9054     // NOTE: Don't warn about comparison expressions resulting from macro
9055     // expansion. Also don't warn about comparisons which are only self
9056     // comparisons within a template specialization. The warnings should catch
9057     // obvious cases in the definition of the template anyways. The idea is to
9058     // warn when the typed comparison operator will always evaluate to the same
9059     // result.
9060     ValueDecl *DL = getCompareDecl(LHSStripped);
9061     ValueDecl *DR = getCompareDecl(RHSStripped);
9062     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9063       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9064                           << 0 // self-
9065                           << (Opc == BO_EQ
9066                               || Opc == BO_LE
9067                               || Opc == BO_GE));
9068     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9069                !DL->getType()->isReferenceType() &&
9070                !DR->getType()->isReferenceType()) {
9071         // what is it always going to eval to?
9072         char always_evals_to;
9073         switch(Opc) {
9074         case BO_EQ: // e.g. array1 == array2
9075           always_evals_to = 0; // false
9076           break;
9077         case BO_NE: // e.g. array1 != array2
9078           always_evals_to = 1; // true
9079           break;
9080         default:
9081           // best we can say is 'a constant'
9082           always_evals_to = 2; // e.g. array1 <= array2
9083           break;
9084         }
9085         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9086                             << 1 // array
9087                             << always_evals_to);
9088     }
9089 
9090     if (isa<CastExpr>(LHSStripped))
9091       LHSStripped = LHSStripped->IgnoreParenCasts();
9092     if (isa<CastExpr>(RHSStripped))
9093       RHSStripped = RHSStripped->IgnoreParenCasts();
9094 
9095     // Warn about comparisons against a string constant (unless the other
9096     // operand is null), the user probably wants strcmp.
9097     Expr *literalString = nullptr;
9098     Expr *literalStringStripped = nullptr;
9099     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9100         !RHSStripped->isNullPointerConstant(Context,
9101                                             Expr::NPC_ValueDependentIsNull)) {
9102       literalString = LHS.get();
9103       literalStringStripped = LHSStripped;
9104     } else if ((isa<StringLiteral>(RHSStripped) ||
9105                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9106                !LHSStripped->isNullPointerConstant(Context,
9107                                             Expr::NPC_ValueDependentIsNull)) {
9108       literalString = RHS.get();
9109       literalStringStripped = RHSStripped;
9110     }
9111 
9112     if (literalString) {
9113       DiagRuntimeBehavior(Loc, nullptr,
9114         PDiag(diag::warn_stringcompare)
9115           << isa<ObjCEncodeExpr>(literalStringStripped)
9116           << literalString->getSourceRange());
9117     }
9118   }
9119 
9120   // C99 6.5.8p3 / C99 6.5.9p4
9121   UsualArithmeticConversions(LHS, RHS);
9122   if (LHS.isInvalid() || RHS.isInvalid())
9123     return QualType();
9124 
9125   LHSType = LHS.get()->getType();
9126   RHSType = RHS.get()->getType();
9127 
9128   // The result of comparisons is 'bool' in C++, 'int' in C.
9129   QualType ResultTy = Context.getLogicalOperationType();
9130 
9131   if (IsRelational) {
9132     if (LHSType->isRealType() && RHSType->isRealType())
9133       return ResultTy;
9134   } else {
9135     // Check for comparisons of floating point operands using != and ==.
9136     if (LHSType->hasFloatingRepresentation())
9137       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9138 
9139     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9140       return ResultTy;
9141   }
9142 
9143   const Expr::NullPointerConstantKind LHSNullKind =
9144       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9145   const Expr::NullPointerConstantKind RHSNullKind =
9146       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9147   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9148   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9149 
9150   if (!IsRelational && LHSIsNull != RHSIsNull) {
9151     bool IsEquality = Opc == BO_EQ;
9152     if (RHSIsNull)
9153       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9154                                    RHS.get()->getSourceRange());
9155     else
9156       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9157                                    LHS.get()->getSourceRange());
9158   }
9159 
9160   // All of the following pointer-related warnings are GCC extensions, except
9161   // when handling null pointer constants.
9162   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
9163     QualType LCanPointeeTy =
9164       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9165     QualType RCanPointeeTy =
9166       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9167 
9168     if (getLangOpts().CPlusPlus) {
9169       if (LCanPointeeTy == RCanPointeeTy)
9170         return ResultTy;
9171       if (!IsRelational &&
9172           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9173         // Valid unless comparison between non-null pointer and function pointer
9174         // This is a gcc extension compatibility comparison.
9175         // In a SFINAE context, we treat this as a hard error to maintain
9176         // conformance with the C++ standard.
9177         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9178             && !LHSIsNull && !RHSIsNull) {
9179           diagnoseFunctionPointerToVoidComparison(
9180               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9181 
9182           if (isSFINAEContext())
9183             return QualType();
9184 
9185           RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9186           return ResultTy;
9187         }
9188       }
9189 
9190       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9191         return QualType();
9192       else
9193         return ResultTy;
9194     }
9195     // C99 6.5.9p2 and C99 6.5.8p2
9196     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9197                                    RCanPointeeTy.getUnqualifiedType())) {
9198       // Valid unless a relational comparison of function pointers
9199       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9200         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9201           << LHSType << RHSType << LHS.get()->getSourceRange()
9202           << RHS.get()->getSourceRange();
9203       }
9204     } else if (!IsRelational &&
9205                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9206       // Valid unless comparison between non-null pointer and function pointer
9207       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9208           && !LHSIsNull && !RHSIsNull)
9209         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9210                                                 /*isError*/false);
9211     } else {
9212       // Invalid
9213       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9214     }
9215     if (LCanPointeeTy != RCanPointeeTy) {
9216       // Treat NULL constant as a special case in OpenCL.
9217       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9218         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9219         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9220           Diag(Loc,
9221                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9222               << LHSType << RHSType << 0 /* comparison */
9223               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9224         }
9225       }
9226       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9227       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9228       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9229                                                : CK_BitCast;
9230       if (LHSIsNull && !RHSIsNull)
9231         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9232       else
9233         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9234     }
9235     return ResultTy;
9236   }
9237 
9238   if (getLangOpts().CPlusPlus) {
9239     // Comparison of nullptr_t with itself.
9240     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
9241       return ResultTy;
9242 
9243     // Comparison of pointers with null pointer constants and equality
9244     // comparisons of member pointers to null pointer constants.
9245     if (RHSIsNull &&
9246         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
9247          (!IsRelational &&
9248           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
9249       RHS = ImpCastExprToType(RHS.get(), LHSType,
9250                         LHSType->isMemberPointerType()
9251                           ? CK_NullToMemberPointer
9252                           : CK_NullToPointer);
9253       return ResultTy;
9254     }
9255     if (LHSIsNull &&
9256         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
9257          (!IsRelational &&
9258           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
9259       LHS = ImpCastExprToType(LHS.get(), RHSType,
9260                         RHSType->isMemberPointerType()
9261                           ? CK_NullToMemberPointer
9262                           : CK_NullToPointer);
9263       return ResultTy;
9264     }
9265 
9266     // Comparison of member pointers.
9267     if (!IsRelational &&
9268         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
9269       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9270         return QualType();
9271       else
9272         return ResultTy;
9273     }
9274 
9275     // Handle scoped enumeration types specifically, since they don't promote
9276     // to integers.
9277     if (LHS.get()->getType()->isEnumeralType() &&
9278         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9279                                        RHS.get()->getType()))
9280       return ResultTy;
9281   }
9282 
9283   // Handle block pointer types.
9284   if (!IsRelational && LHSType->isBlockPointerType() &&
9285       RHSType->isBlockPointerType()) {
9286     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9287     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9288 
9289     if (!LHSIsNull && !RHSIsNull &&
9290         !Context.typesAreCompatible(lpointee, rpointee)) {
9291       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9292         << LHSType << RHSType << LHS.get()->getSourceRange()
9293         << RHS.get()->getSourceRange();
9294     }
9295     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9296     return ResultTy;
9297   }
9298 
9299   // Allow block pointers to be compared with null pointer constants.
9300   if (!IsRelational
9301       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9302           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9303     if (!LHSIsNull && !RHSIsNull) {
9304       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9305              ->getPointeeType()->isVoidType())
9306             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9307                 ->getPointeeType()->isVoidType())))
9308         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9309           << LHSType << RHSType << LHS.get()->getSourceRange()
9310           << RHS.get()->getSourceRange();
9311     }
9312     if (LHSIsNull && !RHSIsNull)
9313       LHS = ImpCastExprToType(LHS.get(), RHSType,
9314                               RHSType->isPointerType() ? CK_BitCast
9315                                 : CK_AnyPointerToBlockPointerCast);
9316     else
9317       RHS = ImpCastExprToType(RHS.get(), LHSType,
9318                               LHSType->isPointerType() ? CK_BitCast
9319                                 : CK_AnyPointerToBlockPointerCast);
9320     return ResultTy;
9321   }
9322 
9323   if (LHSType->isObjCObjectPointerType() ||
9324       RHSType->isObjCObjectPointerType()) {
9325     const PointerType *LPT = LHSType->getAs<PointerType>();
9326     const PointerType *RPT = RHSType->getAs<PointerType>();
9327     if (LPT || RPT) {
9328       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9329       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9330 
9331       if (!LPtrToVoid && !RPtrToVoid &&
9332           !Context.typesAreCompatible(LHSType, RHSType)) {
9333         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9334                                           /*isError*/false);
9335       }
9336       if (LHSIsNull && !RHSIsNull) {
9337         Expr *E = LHS.get();
9338         if (getLangOpts().ObjCAutoRefCount)
9339           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
9340         LHS = ImpCastExprToType(E, RHSType,
9341                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9342       }
9343       else {
9344         Expr *E = RHS.get();
9345         if (getLangOpts().ObjCAutoRefCount)
9346           CheckObjCARCConversion(SourceRange(), LHSType, E,
9347                                  CCK_ImplicitConversion, /*Diagnose=*/true,
9348                                  /*DiagnoseCFAudited=*/false, Opc);
9349         RHS = ImpCastExprToType(E, LHSType,
9350                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9351       }
9352       return ResultTy;
9353     }
9354     if (LHSType->isObjCObjectPointerType() &&
9355         RHSType->isObjCObjectPointerType()) {
9356       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9357         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9358                                           /*isError*/false);
9359       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9360         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9361 
9362       if (LHSIsNull && !RHSIsNull)
9363         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9364       else
9365         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9366       return ResultTy;
9367     }
9368   }
9369   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9370       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9371     unsigned DiagID = 0;
9372     bool isError = false;
9373     if (LangOpts.DebuggerSupport) {
9374       // Under a debugger, allow the comparison of pointers to integers,
9375       // since users tend to want to compare addresses.
9376     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9377         (RHSIsNull && RHSType->isIntegerType())) {
9378       if (IsRelational && !getLangOpts().CPlusPlus)
9379         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9380     } else if (IsRelational && !getLangOpts().CPlusPlus)
9381       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9382     else if (getLangOpts().CPlusPlus) {
9383       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9384       isError = true;
9385     } else
9386       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9387 
9388     if (DiagID) {
9389       Diag(Loc, DiagID)
9390         << LHSType << RHSType << LHS.get()->getSourceRange()
9391         << RHS.get()->getSourceRange();
9392       if (isError)
9393         return QualType();
9394     }
9395 
9396     if (LHSType->isIntegerType())
9397       LHS = ImpCastExprToType(LHS.get(), RHSType,
9398                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9399     else
9400       RHS = ImpCastExprToType(RHS.get(), LHSType,
9401                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9402     return ResultTy;
9403   }
9404 
9405   // Handle block pointers.
9406   if (!IsRelational && RHSIsNull
9407       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9408     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9409     return ResultTy;
9410   }
9411   if (!IsRelational && LHSIsNull
9412       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9413     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9414     return ResultTy;
9415   }
9416 
9417   return InvalidOperands(Loc, LHS, RHS);
9418 }
9419 
9420 
9421 // Return a signed type that is of identical size and number of elements.
9422 // For floating point vectors, return an integer type of identical size
9423 // and number of elements.
9424 QualType Sema::GetSignedVectorType(QualType V) {
9425   const VectorType *VTy = V->getAs<VectorType>();
9426   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9427   if (TypeSize == Context.getTypeSize(Context.CharTy))
9428     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9429   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9430     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9431   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9432     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9433   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9434     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9435   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9436          "Unhandled vector element size in vector compare");
9437   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9438 }
9439 
9440 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9441 /// operates on extended vector types.  Instead of producing an IntTy result,
9442 /// like a scalar comparison, a vector comparison produces a vector of integer
9443 /// types.
9444 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9445                                           SourceLocation Loc,
9446                                           bool IsRelational) {
9447   // Check to make sure we're operating on vectors of the same type and width,
9448   // Allowing one side to be a scalar of element type.
9449   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9450                               /*AllowBothBool*/true,
9451                               /*AllowBoolConversions*/getLangOpts().ZVector);
9452   if (vType.isNull())
9453     return vType;
9454 
9455   QualType LHSType = LHS.get()->getType();
9456 
9457   // If AltiVec, the comparison results in a numeric type, i.e.
9458   // bool for C++, int for C
9459   if (getLangOpts().AltiVec &&
9460       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9461     return Context.getLogicalOperationType();
9462 
9463   // For non-floating point types, check for self-comparisons of the form
9464   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9465   // often indicate logic errors in the program.
9466   if (!LHSType->hasFloatingRepresentation() &&
9467       ActiveTemplateInstantiations.empty()) {
9468     if (DeclRefExpr* DRL
9469           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9470       if (DeclRefExpr* DRR
9471             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9472         if (DRL->getDecl() == DRR->getDecl())
9473           DiagRuntimeBehavior(Loc, nullptr,
9474                               PDiag(diag::warn_comparison_always)
9475                                 << 0 // self-
9476                                 << 2 // "a constant"
9477                               );
9478   }
9479 
9480   // Check for comparisons of floating point operands using != and ==.
9481   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9482     assert (RHS.get()->getType()->hasFloatingRepresentation());
9483     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9484   }
9485 
9486   // Return a signed type for the vector.
9487   return GetSignedVectorType(vType);
9488 }
9489 
9490 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9491                                           SourceLocation Loc) {
9492   // Ensure that either both operands are of the same vector type, or
9493   // one operand is of a vector type and the other is of its element type.
9494   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9495                                        /*AllowBothBool*/true,
9496                                        /*AllowBoolConversions*/false);
9497   if (vType.isNull())
9498     return InvalidOperands(Loc, LHS, RHS);
9499   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9500       vType->hasFloatingRepresentation())
9501     return InvalidOperands(Loc, LHS, RHS);
9502 
9503   return GetSignedVectorType(LHS.get()->getType());
9504 }
9505 
9506 inline QualType Sema::CheckBitwiseOperands(
9507   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9508   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9509 
9510   if (LHS.get()->getType()->isVectorType() ||
9511       RHS.get()->getType()->isVectorType()) {
9512     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9513         RHS.get()->getType()->hasIntegerRepresentation())
9514       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9515                         /*AllowBothBool*/true,
9516                         /*AllowBoolConversions*/getLangOpts().ZVector);
9517     return InvalidOperands(Loc, LHS, RHS);
9518   }
9519 
9520   ExprResult LHSResult = LHS, RHSResult = RHS;
9521   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9522                                                  IsCompAssign);
9523   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9524     return QualType();
9525   LHS = LHSResult.get();
9526   RHS = RHSResult.get();
9527 
9528   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9529     return compType;
9530   return InvalidOperands(Loc, LHS, RHS);
9531 }
9532 
9533 // C99 6.5.[13,14]
9534 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9535                                            SourceLocation Loc,
9536                                            BinaryOperatorKind Opc) {
9537   // Check vector operands differently.
9538   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9539     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9540 
9541   // Diagnose cases where the user write a logical and/or but probably meant a
9542   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9543   // is a constant.
9544   if (LHS.get()->getType()->isIntegerType() &&
9545       !LHS.get()->getType()->isBooleanType() &&
9546       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9547       // Don't warn in macros or template instantiations.
9548       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
9549     // If the RHS can be constant folded, and if it constant folds to something
9550     // that isn't 0 or 1 (which indicate a potential logical operation that
9551     // happened to fold to true/false) then warn.
9552     // Parens on the RHS are ignored.
9553     llvm::APSInt Result;
9554     if (RHS.get()->EvaluateAsInt(Result, Context))
9555       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9556            !RHS.get()->getExprLoc().isMacroID()) ||
9557           (Result != 0 && Result != 1)) {
9558         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9559           << RHS.get()->getSourceRange()
9560           << (Opc == BO_LAnd ? "&&" : "||");
9561         // Suggest replacing the logical operator with the bitwise version
9562         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9563             << (Opc == BO_LAnd ? "&" : "|")
9564             << FixItHint::CreateReplacement(SourceRange(
9565                                                  Loc, getLocForEndOfToken(Loc)),
9566                                             Opc == BO_LAnd ? "&" : "|");
9567         if (Opc == BO_LAnd)
9568           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9569           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9570               << FixItHint::CreateRemoval(
9571                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9572                               RHS.get()->getLocEnd()));
9573       }
9574   }
9575 
9576   if (!Context.getLangOpts().CPlusPlus) {
9577     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9578     // not operate on the built-in scalar and vector float types.
9579     if (Context.getLangOpts().OpenCL &&
9580         Context.getLangOpts().OpenCLVersion < 120) {
9581       if (LHS.get()->getType()->isFloatingType() ||
9582           RHS.get()->getType()->isFloatingType())
9583         return InvalidOperands(Loc, LHS, RHS);
9584     }
9585 
9586     LHS = UsualUnaryConversions(LHS.get());
9587     if (LHS.isInvalid())
9588       return QualType();
9589 
9590     RHS = UsualUnaryConversions(RHS.get());
9591     if (RHS.isInvalid())
9592       return QualType();
9593 
9594     if (!LHS.get()->getType()->isScalarType() ||
9595         !RHS.get()->getType()->isScalarType())
9596       return InvalidOperands(Loc, LHS, RHS);
9597 
9598     return Context.IntTy;
9599   }
9600 
9601   // The following is safe because we only use this method for
9602   // non-overloadable operands.
9603 
9604   // C++ [expr.log.and]p1
9605   // C++ [expr.log.or]p1
9606   // The operands are both contextually converted to type bool.
9607   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9608   if (LHSRes.isInvalid())
9609     return InvalidOperands(Loc, LHS, RHS);
9610   LHS = LHSRes;
9611 
9612   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9613   if (RHSRes.isInvalid())
9614     return InvalidOperands(Loc, LHS, RHS);
9615   RHS = RHSRes;
9616 
9617   // C++ [expr.log.and]p2
9618   // C++ [expr.log.or]p2
9619   // The result is a bool.
9620   return Context.BoolTy;
9621 }
9622 
9623 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9624   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9625   if (!ME) return false;
9626   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9627   ObjCMessageExpr *Base =
9628     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
9629   if (!Base) return false;
9630   return Base->getMethodDecl() != nullptr;
9631 }
9632 
9633 /// Is the given expression (which must be 'const') a reference to a
9634 /// variable which was originally non-const, but which has become
9635 /// 'const' due to being captured within a block?
9636 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9637 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9638   assert(E->isLValue() && E->getType().isConstQualified());
9639   E = E->IgnoreParens();
9640 
9641   // Must be a reference to a declaration from an enclosing scope.
9642   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9643   if (!DRE) return NCCK_None;
9644   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9645 
9646   // The declaration must be a variable which is not declared 'const'.
9647   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9648   if (!var) return NCCK_None;
9649   if (var->getType().isConstQualified()) return NCCK_None;
9650   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9651 
9652   // Decide whether the first capture was for a block or a lambda.
9653   DeclContext *DC = S.CurContext, *Prev = nullptr;
9654   while (DC != var->getDeclContext()) {
9655     Prev = DC;
9656     DC = DC->getParent();
9657   }
9658   // Unless we have an init-capture, we've gone one step too far.
9659   if (!var->isInitCapture())
9660     DC = Prev;
9661   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9662 }
9663 
9664 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9665   Ty = Ty.getNonReferenceType();
9666   if (IsDereference && Ty->isPointerType())
9667     Ty = Ty->getPointeeType();
9668   return !Ty.isConstQualified();
9669 }
9670 
9671 /// Emit the "read-only variable not assignable" error and print notes to give
9672 /// more information about why the variable is not assignable, such as pointing
9673 /// to the declaration of a const variable, showing that a method is const, or
9674 /// that the function is returning a const reference.
9675 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9676                                     SourceLocation Loc) {
9677   // Update err_typecheck_assign_const and note_typecheck_assign_const
9678   // when this enum is changed.
9679   enum {
9680     ConstFunction,
9681     ConstVariable,
9682     ConstMember,
9683     ConstMethod,
9684     ConstUnknown,  // Keep as last element
9685   };
9686 
9687   SourceRange ExprRange = E->getSourceRange();
9688 
9689   // Only emit one error on the first const found.  All other consts will emit
9690   // a note to the error.
9691   bool DiagnosticEmitted = false;
9692 
9693   // Track if the current expression is the result of a derefence, and if the
9694   // next checked expression is the result of a derefence.
9695   bool IsDereference = false;
9696   bool NextIsDereference = false;
9697 
9698   // Loop to process MemberExpr chains.
9699   while (true) {
9700     IsDereference = NextIsDereference;
9701     NextIsDereference = false;
9702 
9703     E = E->IgnoreParenImpCasts();
9704     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9705       NextIsDereference = ME->isArrow();
9706       const ValueDecl *VD = ME->getMemberDecl();
9707       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9708         // Mutable fields can be modified even if the class is const.
9709         if (Field->isMutable()) {
9710           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9711           break;
9712         }
9713 
9714         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9715           if (!DiagnosticEmitted) {
9716             S.Diag(Loc, diag::err_typecheck_assign_const)
9717                 << ExprRange << ConstMember << false /*static*/ << Field
9718                 << Field->getType();
9719             DiagnosticEmitted = true;
9720           }
9721           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9722               << ConstMember << false /*static*/ << Field << Field->getType()
9723               << Field->getSourceRange();
9724         }
9725         E = ME->getBase();
9726         continue;
9727       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9728         if (VDecl->getType().isConstQualified()) {
9729           if (!DiagnosticEmitted) {
9730             S.Diag(Loc, diag::err_typecheck_assign_const)
9731                 << ExprRange << ConstMember << true /*static*/ << VDecl
9732                 << VDecl->getType();
9733             DiagnosticEmitted = true;
9734           }
9735           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9736               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9737               << VDecl->getSourceRange();
9738         }
9739         // Static fields do not inherit constness from parents.
9740         break;
9741       }
9742       break;
9743     } // End MemberExpr
9744     break;
9745   }
9746 
9747   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9748     // Function calls
9749     const FunctionDecl *FD = CE->getDirectCallee();
9750     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
9751       if (!DiagnosticEmitted) {
9752         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9753                                                       << ConstFunction << FD;
9754         DiagnosticEmitted = true;
9755       }
9756       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
9757              diag::note_typecheck_assign_const)
9758           << ConstFunction << FD << FD->getReturnType()
9759           << FD->getReturnTypeSourceRange();
9760     }
9761   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9762     // Point to variable declaration.
9763     if (const ValueDecl *VD = DRE->getDecl()) {
9764       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
9765         if (!DiagnosticEmitted) {
9766           S.Diag(Loc, diag::err_typecheck_assign_const)
9767               << ExprRange << ConstVariable << VD << VD->getType();
9768           DiagnosticEmitted = true;
9769         }
9770         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9771             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
9772       }
9773     }
9774   } else if (isa<CXXThisExpr>(E)) {
9775     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
9776       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
9777         if (MD->isConst()) {
9778           if (!DiagnosticEmitted) {
9779             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9780                                                           << ConstMethod << MD;
9781             DiagnosticEmitted = true;
9782           }
9783           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
9784               << ConstMethod << MD << MD->getSourceRange();
9785         }
9786       }
9787     }
9788   }
9789 
9790   if (DiagnosticEmitted)
9791     return;
9792 
9793   // Can't determine a more specific message, so display the generic error.
9794   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
9795 }
9796 
9797 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
9798 /// emit an error and return true.  If so, return false.
9799 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
9800   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
9801 
9802   S.CheckShadowingDeclModification(E, Loc);
9803 
9804   SourceLocation OrigLoc = Loc;
9805   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
9806                                                               &Loc);
9807   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
9808     IsLV = Expr::MLV_InvalidMessageExpression;
9809   if (IsLV == Expr::MLV_Valid)
9810     return false;
9811 
9812   unsigned DiagID = 0;
9813   bool NeedType = false;
9814   switch (IsLV) { // C99 6.5.16p2
9815   case Expr::MLV_ConstQualified:
9816     // Use a specialized diagnostic when we're assigning to an object
9817     // from an enclosing function or block.
9818     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
9819       if (NCCK == NCCK_Block)
9820         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
9821       else
9822         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
9823       break;
9824     }
9825 
9826     // In ARC, use some specialized diagnostics for occasions where we
9827     // infer 'const'.  These are always pseudo-strong variables.
9828     if (S.getLangOpts().ObjCAutoRefCount) {
9829       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
9830       if (declRef && isa<VarDecl>(declRef->getDecl())) {
9831         VarDecl *var = cast<VarDecl>(declRef->getDecl());
9832 
9833         // Use the normal diagnostic if it's pseudo-__strong but the
9834         // user actually wrote 'const'.
9835         if (var->isARCPseudoStrong() &&
9836             (!var->getTypeSourceInfo() ||
9837              !var->getTypeSourceInfo()->getType().isConstQualified())) {
9838           // There are two pseudo-strong cases:
9839           //  - self
9840           ObjCMethodDecl *method = S.getCurMethodDecl();
9841           if (method && var == method->getSelfDecl())
9842             DiagID = method->isClassMethod()
9843               ? diag::err_typecheck_arc_assign_self_class_method
9844               : diag::err_typecheck_arc_assign_self;
9845 
9846           //  - fast enumeration variables
9847           else
9848             DiagID = diag::err_typecheck_arr_assign_enumeration;
9849 
9850           SourceRange Assign;
9851           if (Loc != OrigLoc)
9852             Assign = SourceRange(OrigLoc, OrigLoc);
9853           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9854           // We need to preserve the AST regardless, so migration tool
9855           // can do its job.
9856           return false;
9857         }
9858       }
9859     }
9860 
9861     // If none of the special cases above are triggered, then this is a
9862     // simple const assignment.
9863     if (DiagID == 0) {
9864       DiagnoseConstAssignment(S, E, Loc);
9865       return true;
9866     }
9867 
9868     break;
9869   case Expr::MLV_ConstAddrSpace:
9870     DiagnoseConstAssignment(S, E, Loc);
9871     return true;
9872   case Expr::MLV_ArrayType:
9873   case Expr::MLV_ArrayTemporary:
9874     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
9875     NeedType = true;
9876     break;
9877   case Expr::MLV_NotObjectType:
9878     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
9879     NeedType = true;
9880     break;
9881   case Expr::MLV_LValueCast:
9882     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
9883     break;
9884   case Expr::MLV_Valid:
9885     llvm_unreachable("did not take early return for MLV_Valid");
9886   case Expr::MLV_InvalidExpression:
9887   case Expr::MLV_MemberFunction:
9888   case Expr::MLV_ClassTemporary:
9889     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
9890     break;
9891   case Expr::MLV_IncompleteType:
9892   case Expr::MLV_IncompleteVoidType:
9893     return S.RequireCompleteType(Loc, E->getType(),
9894              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
9895   case Expr::MLV_DuplicateVectorComponents:
9896     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
9897     break;
9898   case Expr::MLV_NoSetterProperty:
9899     llvm_unreachable("readonly properties should be processed differently");
9900   case Expr::MLV_InvalidMessageExpression:
9901     DiagID = diag::error_readonly_message_assignment;
9902     break;
9903   case Expr::MLV_SubObjCPropertySetting:
9904     DiagID = diag::error_no_subobject_property_setting;
9905     break;
9906   }
9907 
9908   SourceRange Assign;
9909   if (Loc != OrigLoc)
9910     Assign = SourceRange(OrigLoc, OrigLoc);
9911   if (NeedType)
9912     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
9913   else
9914     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9915   return true;
9916 }
9917 
9918 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
9919                                          SourceLocation Loc,
9920                                          Sema &Sema) {
9921   // C / C++ fields
9922   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
9923   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
9924   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
9925     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
9926       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
9927   }
9928 
9929   // Objective-C instance variables
9930   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
9931   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
9932   if (OL && OR && OL->getDecl() == OR->getDecl()) {
9933     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
9934     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
9935     if (RL && RR && RL->getDecl() == RR->getDecl())
9936       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
9937   }
9938 }
9939 
9940 // C99 6.5.16.1
9941 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
9942                                        SourceLocation Loc,
9943                                        QualType CompoundType) {
9944   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
9945 
9946   // Verify that LHS is a modifiable lvalue, and emit error if not.
9947   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
9948     return QualType();
9949 
9950   QualType LHSType = LHSExpr->getType();
9951   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
9952                                              CompoundType;
9953   AssignConvertType ConvTy;
9954   if (CompoundType.isNull()) {
9955     Expr *RHSCheck = RHS.get();
9956 
9957     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
9958 
9959     QualType LHSTy(LHSType);
9960     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
9961     if (RHS.isInvalid())
9962       return QualType();
9963     // Special case of NSObject attributes on c-style pointer types.
9964     if (ConvTy == IncompatiblePointer &&
9965         ((Context.isObjCNSObjectType(LHSType) &&
9966           RHSType->isObjCObjectPointerType()) ||
9967          (Context.isObjCNSObjectType(RHSType) &&
9968           LHSType->isObjCObjectPointerType())))
9969       ConvTy = Compatible;
9970 
9971     if (ConvTy == Compatible &&
9972         LHSType->isObjCObjectType())
9973         Diag(Loc, diag::err_objc_object_assignment)
9974           << LHSType;
9975 
9976     // If the RHS is a unary plus or minus, check to see if they = and + are
9977     // right next to each other.  If so, the user may have typo'd "x =+ 4"
9978     // instead of "x += 4".
9979     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
9980       RHSCheck = ICE->getSubExpr();
9981     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
9982       if ((UO->getOpcode() == UO_Plus ||
9983            UO->getOpcode() == UO_Minus) &&
9984           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
9985           // Only if the two operators are exactly adjacent.
9986           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
9987           // And there is a space or other character before the subexpr of the
9988           // unary +/-.  We don't want to warn on "x=-1".
9989           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
9990           UO->getSubExpr()->getLocStart().isFileID()) {
9991         Diag(Loc, diag::warn_not_compound_assign)
9992           << (UO->getOpcode() == UO_Plus ? "+" : "-")
9993           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
9994       }
9995     }
9996 
9997     if (ConvTy == Compatible) {
9998       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
9999         // Warn about retain cycles where a block captures the LHS, but
10000         // not if the LHS is a simple variable into which the block is
10001         // being stored...unless that variable can be captured by reference!
10002         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10003         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10004         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10005           checkRetainCycles(LHSExpr, RHS.get());
10006 
10007         // It is safe to assign a weak reference into a strong variable.
10008         // Although this code can still have problems:
10009         //   id x = self.weakProp;
10010         //   id y = self.weakProp;
10011         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10012         // paths through the function. This should be revisited if
10013         // -Wrepeated-use-of-weak is made flow-sensitive.
10014         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10015                              RHS.get()->getLocStart()))
10016           getCurFunction()->markSafeWeakUse(RHS.get());
10017 
10018       } else if (getLangOpts().ObjCAutoRefCount) {
10019         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10020       }
10021     }
10022   } else {
10023     // Compound assignment "x += y"
10024     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10025   }
10026 
10027   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10028                                RHS.get(), AA_Assigning))
10029     return QualType();
10030 
10031   CheckForNullPointerDereference(*this, LHSExpr);
10032 
10033   // C99 6.5.16p3: The type of an assignment expression is the type of the
10034   // left operand unless the left operand has qualified type, in which case
10035   // it is the unqualified version of the type of the left operand.
10036   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10037   // is converted to the type of the assignment expression (above).
10038   // C++ 5.17p1: the type of the assignment expression is that of its left
10039   // operand.
10040   return (getLangOpts().CPlusPlus
10041           ? LHSType : LHSType.getUnqualifiedType());
10042 }
10043 
10044 // Only ignore explicit casts to void.
10045 static bool IgnoreCommaOperand(const Expr *E) {
10046   E = E->IgnoreParens();
10047 
10048   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10049     if (CE->getCastKind() == CK_ToVoid) {
10050       return true;
10051     }
10052   }
10053 
10054   return false;
10055 }
10056 
10057 // Look for instances where it is likely the comma operator is confused with
10058 // another operator.  There is a whitelist of acceptable expressions for the
10059 // left hand side of the comma operator, otherwise emit a warning.
10060 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10061   // No warnings in macros
10062   if (Loc.isMacroID())
10063     return;
10064 
10065   // Don't warn in template instantiations.
10066   if (!ActiveTemplateInstantiations.empty())
10067     return;
10068 
10069   // Scope isn't fine-grained enough to whitelist the specific cases, so
10070   // instead, skip more than needed, then call back into here with the
10071   // CommaVisitor in SemaStmt.cpp.
10072   // The whitelisted locations are the initialization and increment portions
10073   // of a for loop.  The additional checks are on the condition of
10074   // if statements, do/while loops, and for loops.
10075   const unsigned ForIncrementFlags =
10076       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10077   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10078   const unsigned ScopeFlags = getCurScope()->getFlags();
10079   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10080       (ScopeFlags & ForInitFlags) == ForInitFlags)
10081     return;
10082 
10083   // If there are multiple comma operators used together, get the RHS of the
10084   // of the comma operator as the LHS.
10085   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10086     if (BO->getOpcode() != BO_Comma)
10087       break;
10088     LHS = BO->getRHS();
10089   }
10090 
10091   // Only allow some expressions on LHS to not warn.
10092   if (IgnoreCommaOperand(LHS))
10093     return;
10094 
10095   Diag(Loc, diag::warn_comma_operator);
10096   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10097       << LHS->getSourceRange()
10098       << FixItHint::CreateInsertion(LHS->getLocStart(),
10099                                     LangOpts.CPlusPlus ? "static_cast<void>("
10100                                                        : "(void)(")
10101       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10102                                     ")");
10103 }
10104 
10105 // C99 6.5.17
10106 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10107                                    SourceLocation Loc) {
10108   LHS = S.CheckPlaceholderExpr(LHS.get());
10109   RHS = S.CheckPlaceholderExpr(RHS.get());
10110   if (LHS.isInvalid() || RHS.isInvalid())
10111     return QualType();
10112 
10113   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10114   // operands, but not unary promotions.
10115   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10116 
10117   // So we treat the LHS as a ignored value, and in C++ we allow the
10118   // containing site to determine what should be done with the RHS.
10119   LHS = S.IgnoredValueConversions(LHS.get());
10120   if (LHS.isInvalid())
10121     return QualType();
10122 
10123   S.DiagnoseUnusedExprResult(LHS.get());
10124 
10125   if (!S.getLangOpts().CPlusPlus) {
10126     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10127     if (RHS.isInvalid())
10128       return QualType();
10129     if (!RHS.get()->getType()->isVoidType())
10130       S.RequireCompleteType(Loc, RHS.get()->getType(),
10131                             diag::err_incomplete_type);
10132   }
10133 
10134   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10135     S.DiagnoseCommaOperator(LHS.get(), Loc);
10136 
10137   return RHS.get()->getType();
10138 }
10139 
10140 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10141 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10142 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10143                                                ExprValueKind &VK,
10144                                                ExprObjectKind &OK,
10145                                                SourceLocation OpLoc,
10146                                                bool IsInc, bool IsPrefix) {
10147   if (Op->isTypeDependent())
10148     return S.Context.DependentTy;
10149 
10150   QualType ResType = Op->getType();
10151   // Atomic types can be used for increment / decrement where the non-atomic
10152   // versions can, so ignore the _Atomic() specifier for the purpose of
10153   // checking.
10154   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10155     ResType = ResAtomicType->getValueType();
10156 
10157   assert(!ResType.isNull() && "no type for increment/decrement expression");
10158 
10159   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10160     // Decrement of bool is not allowed.
10161     if (!IsInc) {
10162       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10163       return QualType();
10164     }
10165     // Increment of bool sets it to true, but is deprecated.
10166     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10167                                               : diag::warn_increment_bool)
10168       << Op->getSourceRange();
10169   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10170     // Error on enum increments and decrements in C++ mode
10171     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10172     return QualType();
10173   } else if (ResType->isRealType()) {
10174     // OK!
10175   } else if (ResType->isPointerType()) {
10176     // C99 6.5.2.4p2, 6.5.6p2
10177     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10178       return QualType();
10179   } else if (ResType->isObjCObjectPointerType()) {
10180     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10181     // Otherwise, we just need a complete type.
10182     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10183         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10184       return QualType();
10185   } else if (ResType->isAnyComplexType()) {
10186     // C99 does not support ++/-- on complex types, we allow as an extension.
10187     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10188       << ResType << Op->getSourceRange();
10189   } else if (ResType->isPlaceholderType()) {
10190     ExprResult PR = S.CheckPlaceholderExpr(Op);
10191     if (PR.isInvalid()) return QualType();
10192     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10193                                           IsInc, IsPrefix);
10194   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10195     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10196   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10197              (ResType->getAs<VectorType>()->getVectorKind() !=
10198               VectorType::AltiVecBool)) {
10199     // The z vector extensions allow ++ and -- for non-bool vectors.
10200   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10201             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10202     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10203   } else {
10204     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10205       << ResType << int(IsInc) << Op->getSourceRange();
10206     return QualType();
10207   }
10208   // At this point, we know we have a real, complex or pointer type.
10209   // Now make sure the operand is a modifiable lvalue.
10210   if (CheckForModifiableLvalue(Op, OpLoc, S))
10211     return QualType();
10212   // In C++, a prefix increment is the same type as the operand. Otherwise
10213   // (in C or with postfix), the increment is the unqualified type of the
10214   // operand.
10215   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10216     VK = VK_LValue;
10217     OK = Op->getObjectKind();
10218     return ResType;
10219   } else {
10220     VK = VK_RValue;
10221     return ResType.getUnqualifiedType();
10222   }
10223 }
10224 
10225 
10226 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10227 /// This routine allows us to typecheck complex/recursive expressions
10228 /// where the declaration is needed for type checking. We only need to
10229 /// handle cases when the expression references a function designator
10230 /// or is an lvalue. Here are some examples:
10231 ///  - &(x) => x
10232 ///  - &*****f => f for f a function designator.
10233 ///  - &s.xx => s
10234 ///  - &s.zz[1].yy -> s, if zz is an array
10235 ///  - *(x + 1) -> x, if x is an array
10236 ///  - &"123"[2] -> 0
10237 ///  - & __real__ x -> x
10238 static ValueDecl *getPrimaryDecl(Expr *E) {
10239   switch (E->getStmtClass()) {
10240   case Stmt::DeclRefExprClass:
10241     return cast<DeclRefExpr>(E)->getDecl();
10242   case Stmt::MemberExprClass:
10243     // If this is an arrow operator, the address is an offset from
10244     // the base's value, so the object the base refers to is
10245     // irrelevant.
10246     if (cast<MemberExpr>(E)->isArrow())
10247       return nullptr;
10248     // Otherwise, the expression refers to a part of the base
10249     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10250   case Stmt::ArraySubscriptExprClass: {
10251     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10252     // promotion of register arrays earlier.
10253     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10254     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10255       if (ICE->getSubExpr()->getType()->isArrayType())
10256         return getPrimaryDecl(ICE->getSubExpr());
10257     }
10258     return nullptr;
10259   }
10260   case Stmt::UnaryOperatorClass: {
10261     UnaryOperator *UO = cast<UnaryOperator>(E);
10262 
10263     switch(UO->getOpcode()) {
10264     case UO_Real:
10265     case UO_Imag:
10266     case UO_Extension:
10267       return getPrimaryDecl(UO->getSubExpr());
10268     default:
10269       return nullptr;
10270     }
10271   }
10272   case Stmt::ParenExprClass:
10273     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10274   case Stmt::ImplicitCastExprClass:
10275     // If the result of an implicit cast is an l-value, we care about
10276     // the sub-expression; otherwise, the result here doesn't matter.
10277     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10278   default:
10279     return nullptr;
10280   }
10281 }
10282 
10283 namespace {
10284   enum {
10285     AO_Bit_Field = 0,
10286     AO_Vector_Element = 1,
10287     AO_Property_Expansion = 2,
10288     AO_Register_Variable = 3,
10289     AO_No_Error = 4
10290   };
10291 }
10292 /// \brief Diagnose invalid operand for address of operations.
10293 ///
10294 /// \param Type The type of operand which cannot have its address taken.
10295 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10296                                          Expr *E, unsigned Type) {
10297   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10298 }
10299 
10300 /// CheckAddressOfOperand - The operand of & must be either a function
10301 /// designator or an lvalue designating an object. If it is an lvalue, the
10302 /// object cannot be declared with storage class register or be a bit field.
10303 /// Note: The usual conversions are *not* applied to the operand of the &
10304 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10305 /// In C++, the operand might be an overloaded function name, in which case
10306 /// we allow the '&' but retain the overloaded-function type.
10307 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10308   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10309     if (PTy->getKind() == BuiltinType::Overload) {
10310       Expr *E = OrigOp.get()->IgnoreParens();
10311       if (!isa<OverloadExpr>(E)) {
10312         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10313         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10314           << OrigOp.get()->getSourceRange();
10315         return QualType();
10316       }
10317 
10318       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10319       if (isa<UnresolvedMemberExpr>(Ovl))
10320         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10321           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10322             << OrigOp.get()->getSourceRange();
10323           return QualType();
10324         }
10325 
10326       return Context.OverloadTy;
10327     }
10328 
10329     if (PTy->getKind() == BuiltinType::UnknownAny)
10330       return Context.UnknownAnyTy;
10331 
10332     if (PTy->getKind() == BuiltinType::BoundMember) {
10333       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10334         << OrigOp.get()->getSourceRange();
10335       return QualType();
10336     }
10337 
10338     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10339     if (OrigOp.isInvalid()) return QualType();
10340   }
10341 
10342   if (OrigOp.get()->isTypeDependent())
10343     return Context.DependentTy;
10344 
10345   assert(!OrigOp.get()->getType()->isPlaceholderType());
10346 
10347   // Make sure to ignore parentheses in subsequent checks
10348   Expr *op = OrigOp.get()->IgnoreParens();
10349 
10350   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10351   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10352     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10353     return QualType();
10354   }
10355 
10356   if (getLangOpts().C99) {
10357     // Implement C99-only parts of addressof rules.
10358     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10359       if (uOp->getOpcode() == UO_Deref)
10360         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10361         // (assuming the deref expression is valid).
10362         return uOp->getSubExpr()->getType();
10363     }
10364     // Technically, there should be a check for array subscript
10365     // expressions here, but the result of one is always an lvalue anyway.
10366   }
10367   ValueDecl *dcl = getPrimaryDecl(op);
10368 
10369   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10370     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10371                                            op->getLocStart()))
10372       return QualType();
10373 
10374   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10375   unsigned AddressOfError = AO_No_Error;
10376 
10377   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10378     bool sfinae = (bool)isSFINAEContext();
10379     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10380                                   : diag::ext_typecheck_addrof_temporary)
10381       << op->getType() << op->getSourceRange();
10382     if (sfinae)
10383       return QualType();
10384     // Materialize the temporary as an lvalue so that we can take its address.
10385     OrigOp = op = new (Context)
10386         MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10387   } else if (isa<ObjCSelectorExpr>(op)) {
10388     return Context.getPointerType(op->getType());
10389   } else if (lval == Expr::LV_MemberFunction) {
10390     // If it's an instance method, make a member pointer.
10391     // The expression must have exactly the form &A::foo.
10392 
10393     // If the underlying expression isn't a decl ref, give up.
10394     if (!isa<DeclRefExpr>(op)) {
10395       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10396         << OrigOp.get()->getSourceRange();
10397       return QualType();
10398     }
10399     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10400     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10401 
10402     // The id-expression was parenthesized.
10403     if (OrigOp.get() != DRE) {
10404       Diag(OpLoc, diag::err_parens_pointer_member_function)
10405         << OrigOp.get()->getSourceRange();
10406 
10407     // The method was named without a qualifier.
10408     } else if (!DRE->getQualifier()) {
10409       if (MD->getParent()->getName().empty())
10410         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10411           << op->getSourceRange();
10412       else {
10413         SmallString<32> Str;
10414         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10415         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10416           << op->getSourceRange()
10417           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10418       }
10419     }
10420 
10421     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10422     if (isa<CXXDestructorDecl>(MD))
10423       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10424 
10425     QualType MPTy = Context.getMemberPointerType(
10426         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10427     // Under the MS ABI, lock down the inheritance model now.
10428     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10429       (void)isCompleteType(OpLoc, MPTy);
10430     return MPTy;
10431   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10432     // C99 6.5.3.2p1
10433     // The operand must be either an l-value or a function designator
10434     if (!op->getType()->isFunctionType()) {
10435       // Use a special diagnostic for loads from property references.
10436       if (isa<PseudoObjectExpr>(op)) {
10437         AddressOfError = AO_Property_Expansion;
10438       } else {
10439         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10440           << op->getType() << op->getSourceRange();
10441         return QualType();
10442       }
10443     }
10444   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10445     // The operand cannot be a bit-field
10446     AddressOfError = AO_Bit_Field;
10447   } else if (op->getObjectKind() == OK_VectorComponent) {
10448     // The operand cannot be an element of a vector
10449     AddressOfError = AO_Vector_Element;
10450   } else if (dcl) { // C99 6.5.3.2p1
10451     // We have an lvalue with a decl. Make sure the decl is not declared
10452     // with the register storage-class specifier.
10453     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10454       // in C++ it is not error to take address of a register
10455       // variable (c++03 7.1.1P3)
10456       if (vd->getStorageClass() == SC_Register &&
10457           !getLangOpts().CPlusPlus) {
10458         AddressOfError = AO_Register_Variable;
10459       }
10460     } else if (isa<MSPropertyDecl>(dcl)) {
10461       AddressOfError = AO_Property_Expansion;
10462     } else if (isa<FunctionTemplateDecl>(dcl)) {
10463       return Context.OverloadTy;
10464     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10465       // Okay: we can take the address of a field.
10466       // Could be a pointer to member, though, if there is an explicit
10467       // scope qualifier for the class.
10468       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10469         DeclContext *Ctx = dcl->getDeclContext();
10470         if (Ctx && Ctx->isRecord()) {
10471           if (dcl->getType()->isReferenceType()) {
10472             Diag(OpLoc,
10473                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10474               << dcl->getDeclName() << dcl->getType();
10475             return QualType();
10476           }
10477 
10478           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10479             Ctx = Ctx->getParent();
10480 
10481           QualType MPTy = Context.getMemberPointerType(
10482               op->getType(),
10483               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10484           // Under the MS ABI, lock down the inheritance model now.
10485           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10486             (void)isCompleteType(OpLoc, MPTy);
10487           return MPTy;
10488         }
10489       }
10490     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
10491       llvm_unreachable("Unknown/unexpected decl type");
10492   }
10493 
10494   if (AddressOfError != AO_No_Error) {
10495     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10496     return QualType();
10497   }
10498 
10499   if (lval == Expr::LV_IncompleteVoidType) {
10500     // Taking the address of a void variable is technically illegal, but we
10501     // allow it in cases which are otherwise valid.
10502     // Example: "extern void x; void* y = &x;".
10503     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10504   }
10505 
10506   // If the operand has type "type", the result has type "pointer to type".
10507   if (op->getType()->isObjCObjectType())
10508     return Context.getObjCObjectPointerType(op->getType());
10509 
10510   // OpenCL v2.0 s6.12.5 - The unary operators & cannot be used with a block.
10511   if (getLangOpts().OpenCL && OrigOp.get()->getType()->isBlockPointerType()) {
10512     Diag(OpLoc, diag::err_typecheck_unary_expr) << OrigOp.get()->getType()
10513                                                 << op->getSourceRange();
10514     return QualType();
10515   }
10516 
10517   return Context.getPointerType(op->getType());
10518 }
10519 
10520 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10521   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10522   if (!DRE)
10523     return;
10524   const Decl *D = DRE->getDecl();
10525   if (!D)
10526     return;
10527   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10528   if (!Param)
10529     return;
10530   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10531     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10532       return;
10533   if (FunctionScopeInfo *FD = S.getCurFunction())
10534     if (!FD->ModifiedNonNullParams.count(Param))
10535       FD->ModifiedNonNullParams.insert(Param);
10536 }
10537 
10538 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10539 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10540                                         SourceLocation OpLoc) {
10541   if (Op->isTypeDependent())
10542     return S.Context.DependentTy;
10543 
10544   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10545   if (ConvResult.isInvalid())
10546     return QualType();
10547   Op = ConvResult.get();
10548   QualType OpTy = Op->getType();
10549   QualType Result;
10550 
10551   if (isa<CXXReinterpretCastExpr>(Op)) {
10552     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10553     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10554                                      Op->getSourceRange());
10555   }
10556 
10557   if (const PointerType *PT = OpTy->getAs<PointerType>())
10558   {
10559     Result = PT->getPointeeType();
10560     // OpenCL v2.0 s6.12.5 - The unary operators * cannot be used with a block.
10561     if (S.getLangOpts().OpenCLVersion >= 200 && Result->isBlockPointerType()) {
10562       S.Diag(OpLoc, diag::err_opencl_dereferencing) << OpTy
10563                                                     << Op->getSourceRange();
10564       return QualType();
10565     }
10566   }
10567   else if (const ObjCObjectPointerType *OPT =
10568              OpTy->getAs<ObjCObjectPointerType>())
10569     Result = OPT->getPointeeType();
10570   else {
10571     ExprResult PR = S.CheckPlaceholderExpr(Op);
10572     if (PR.isInvalid()) return QualType();
10573     if (PR.get() != Op)
10574       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10575   }
10576 
10577   if (Result.isNull()) {
10578     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10579       << OpTy << Op->getSourceRange();
10580     return QualType();
10581   }
10582 
10583   // Note that per both C89 and C99, indirection is always legal, even if Result
10584   // is an incomplete type or void.  It would be possible to warn about
10585   // dereferencing a void pointer, but it's completely well-defined, and such a
10586   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10587   // for pointers to 'void' but is fine for any other pointer type:
10588   //
10589   // C++ [expr.unary.op]p1:
10590   //   [...] the expression to which [the unary * operator] is applied shall
10591   //   be a pointer to an object type, or a pointer to a function type
10592   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10593     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10594       << OpTy << Op->getSourceRange();
10595 
10596   // Dereferences are usually l-values...
10597   VK = VK_LValue;
10598 
10599   // ...except that certain expressions are never l-values in C.
10600   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10601     VK = VK_RValue;
10602 
10603   return Result;
10604 }
10605 
10606 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10607   BinaryOperatorKind Opc;
10608   switch (Kind) {
10609   default: llvm_unreachable("Unknown binop!");
10610   case tok::periodstar:           Opc = BO_PtrMemD; break;
10611   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10612   case tok::star:                 Opc = BO_Mul; break;
10613   case tok::slash:                Opc = BO_Div; break;
10614   case tok::percent:              Opc = BO_Rem; break;
10615   case tok::plus:                 Opc = BO_Add; break;
10616   case tok::minus:                Opc = BO_Sub; break;
10617   case tok::lessless:             Opc = BO_Shl; break;
10618   case tok::greatergreater:       Opc = BO_Shr; break;
10619   case tok::lessequal:            Opc = BO_LE; break;
10620   case tok::less:                 Opc = BO_LT; break;
10621   case tok::greaterequal:         Opc = BO_GE; break;
10622   case tok::greater:              Opc = BO_GT; break;
10623   case tok::exclaimequal:         Opc = BO_NE; break;
10624   case tok::equalequal:           Opc = BO_EQ; break;
10625   case tok::amp:                  Opc = BO_And; break;
10626   case tok::caret:                Opc = BO_Xor; break;
10627   case tok::pipe:                 Opc = BO_Or; break;
10628   case tok::ampamp:               Opc = BO_LAnd; break;
10629   case tok::pipepipe:             Opc = BO_LOr; break;
10630   case tok::equal:                Opc = BO_Assign; break;
10631   case tok::starequal:            Opc = BO_MulAssign; break;
10632   case tok::slashequal:           Opc = BO_DivAssign; break;
10633   case tok::percentequal:         Opc = BO_RemAssign; break;
10634   case tok::plusequal:            Opc = BO_AddAssign; break;
10635   case tok::minusequal:           Opc = BO_SubAssign; break;
10636   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10637   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10638   case tok::ampequal:             Opc = BO_AndAssign; break;
10639   case tok::caretequal:           Opc = BO_XorAssign; break;
10640   case tok::pipeequal:            Opc = BO_OrAssign; break;
10641   case tok::comma:                Opc = BO_Comma; break;
10642   }
10643   return Opc;
10644 }
10645 
10646 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10647   tok::TokenKind Kind) {
10648   UnaryOperatorKind Opc;
10649   switch (Kind) {
10650   default: llvm_unreachable("Unknown unary op!");
10651   case tok::plusplus:     Opc = UO_PreInc; break;
10652   case tok::minusminus:   Opc = UO_PreDec; break;
10653   case tok::amp:          Opc = UO_AddrOf; break;
10654   case tok::star:         Opc = UO_Deref; break;
10655   case tok::plus:         Opc = UO_Plus; break;
10656   case tok::minus:        Opc = UO_Minus; break;
10657   case tok::tilde:        Opc = UO_Not; break;
10658   case tok::exclaim:      Opc = UO_LNot; break;
10659   case tok::kw___real:    Opc = UO_Real; break;
10660   case tok::kw___imag:    Opc = UO_Imag; break;
10661   case tok::kw___extension__: Opc = UO_Extension; break;
10662   }
10663   return Opc;
10664 }
10665 
10666 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10667 /// This warning is only emitted for builtin assignment operations. It is also
10668 /// suppressed in the event of macro expansions.
10669 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10670                                    SourceLocation OpLoc) {
10671   if (!S.ActiveTemplateInstantiations.empty())
10672     return;
10673   if (OpLoc.isInvalid() || OpLoc.isMacroID())
10674     return;
10675   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10676   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10677   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10678   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10679   if (!LHSDeclRef || !RHSDeclRef ||
10680       LHSDeclRef->getLocation().isMacroID() ||
10681       RHSDeclRef->getLocation().isMacroID())
10682     return;
10683   const ValueDecl *LHSDecl =
10684     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10685   const ValueDecl *RHSDecl =
10686     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10687   if (LHSDecl != RHSDecl)
10688     return;
10689   if (LHSDecl->getType().isVolatileQualified())
10690     return;
10691   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10692     if (RefTy->getPointeeType().isVolatileQualified())
10693       return;
10694 
10695   S.Diag(OpLoc, diag::warn_self_assignment)
10696       << LHSDeclRef->getType()
10697       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10698 }
10699 
10700 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
10701 /// is usually indicative of introspection within the Objective-C pointer.
10702 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10703                                           SourceLocation OpLoc) {
10704   if (!S.getLangOpts().ObjC1)
10705     return;
10706 
10707   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10708   const Expr *LHS = L.get();
10709   const Expr *RHS = R.get();
10710 
10711   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10712     ObjCPointerExpr = LHS;
10713     OtherExpr = RHS;
10714   }
10715   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10716     ObjCPointerExpr = RHS;
10717     OtherExpr = LHS;
10718   }
10719 
10720   // This warning is deliberately made very specific to reduce false
10721   // positives with logic that uses '&' for hashing.  This logic mainly
10722   // looks for code trying to introspect into tagged pointers, which
10723   // code should generally never do.
10724   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
10725     unsigned Diag = diag::warn_objc_pointer_masking;
10726     // Determine if we are introspecting the result of performSelectorXXX.
10727     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
10728     // Special case messages to -performSelector and friends, which
10729     // can return non-pointer values boxed in a pointer value.
10730     // Some clients may wish to silence warnings in this subcase.
10731     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
10732       Selector S = ME->getSelector();
10733       StringRef SelArg0 = S.getNameForSlot(0);
10734       if (SelArg0.startswith("performSelector"))
10735         Diag = diag::warn_objc_pointer_masking_performSelector;
10736     }
10737 
10738     S.Diag(OpLoc, Diag)
10739       << ObjCPointerExpr->getSourceRange();
10740   }
10741 }
10742 
10743 static NamedDecl *getDeclFromExpr(Expr *E) {
10744   if (!E)
10745     return nullptr;
10746   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
10747     return DRE->getDecl();
10748   if (auto *ME = dyn_cast<MemberExpr>(E))
10749     return ME->getMemberDecl();
10750   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
10751     return IRE->getDecl();
10752   return nullptr;
10753 }
10754 
10755 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
10756 /// operator @p Opc at location @c TokLoc. This routine only supports
10757 /// built-in operations; ActOnBinOp handles overloaded operators.
10758 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
10759                                     BinaryOperatorKind Opc,
10760                                     Expr *LHSExpr, Expr *RHSExpr) {
10761   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
10762     // The syntax only allows initializer lists on the RHS of assignment,
10763     // so we don't need to worry about accepting invalid code for
10764     // non-assignment operators.
10765     // C++11 5.17p9:
10766     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
10767     //   of x = {} is x = T().
10768     InitializationKind Kind =
10769         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
10770     InitializedEntity Entity =
10771         InitializedEntity::InitializeTemporary(LHSExpr->getType());
10772     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
10773     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
10774     if (Init.isInvalid())
10775       return Init;
10776     RHSExpr = Init.get();
10777   }
10778 
10779   ExprResult LHS = LHSExpr, RHS = RHSExpr;
10780   QualType ResultTy;     // Result type of the binary operator.
10781   // The following two variables are used for compound assignment operators
10782   QualType CompLHSTy;    // Type of LHS after promotions for computation
10783   QualType CompResultTy; // Type of computation result
10784   ExprValueKind VK = VK_RValue;
10785   ExprObjectKind OK = OK_Ordinary;
10786 
10787   if (!getLangOpts().CPlusPlus) {
10788     // C cannot handle TypoExpr nodes on either side of a binop because it
10789     // doesn't handle dependent types properly, so make sure any TypoExprs have
10790     // been dealt with before checking the operands.
10791     LHS = CorrectDelayedTyposInExpr(LHSExpr);
10792     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
10793       if (Opc != BO_Assign)
10794         return ExprResult(E);
10795       // Avoid correcting the RHS to the same Expr as the LHS.
10796       Decl *D = getDeclFromExpr(E);
10797       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
10798     });
10799     if (!LHS.isUsable() || !RHS.isUsable())
10800       return ExprError();
10801   }
10802 
10803   if (getLangOpts().OpenCL) {
10804     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
10805     // the ATOMIC_VAR_INIT macro.
10806     if (LHSExpr->getType()->isAtomicType() ||
10807         RHSExpr->getType()->isAtomicType()) {
10808       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
10809       if (BO_Assign == Opc)
10810         Diag(OpLoc, diag::err_atomic_init_constant) << SR;
10811       else
10812         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
10813       return ExprError();
10814     }
10815   }
10816 
10817   switch (Opc) {
10818   case BO_Assign:
10819     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
10820     if (getLangOpts().CPlusPlus &&
10821         LHS.get()->getObjectKind() != OK_ObjCProperty) {
10822       VK = LHS.get()->getValueKind();
10823       OK = LHS.get()->getObjectKind();
10824     }
10825     if (!ResultTy.isNull()) {
10826       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10827       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
10828     }
10829     RecordModifiableNonNullParam(*this, LHS.get());
10830     break;
10831   case BO_PtrMemD:
10832   case BO_PtrMemI:
10833     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
10834                                             Opc == BO_PtrMemI);
10835     break;
10836   case BO_Mul:
10837   case BO_Div:
10838     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
10839                                            Opc == BO_Div);
10840     break;
10841   case BO_Rem:
10842     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
10843     break;
10844   case BO_Add:
10845     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
10846     break;
10847   case BO_Sub:
10848     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
10849     break;
10850   case BO_Shl:
10851   case BO_Shr:
10852     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
10853     break;
10854   case BO_LE:
10855   case BO_LT:
10856   case BO_GE:
10857   case BO_GT:
10858     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
10859     break;
10860   case BO_EQ:
10861   case BO_NE:
10862     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
10863     break;
10864   case BO_And:
10865     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
10866   case BO_Xor:
10867   case BO_Or:
10868     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
10869     break;
10870   case BO_LAnd:
10871   case BO_LOr:
10872     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
10873     break;
10874   case BO_MulAssign:
10875   case BO_DivAssign:
10876     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
10877                                                Opc == BO_DivAssign);
10878     CompLHSTy = CompResultTy;
10879     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10880       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10881     break;
10882   case BO_RemAssign:
10883     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
10884     CompLHSTy = CompResultTy;
10885     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10886       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10887     break;
10888   case BO_AddAssign:
10889     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
10890     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10891       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10892     break;
10893   case BO_SubAssign:
10894     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
10895     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10896       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10897     break;
10898   case BO_ShlAssign:
10899   case BO_ShrAssign:
10900     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
10901     CompLHSTy = CompResultTy;
10902     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10903       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10904     break;
10905   case BO_AndAssign:
10906   case BO_OrAssign: // fallthrough
10907     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10908   case BO_XorAssign:
10909     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
10910     CompLHSTy = CompResultTy;
10911     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10912       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10913     break;
10914   case BO_Comma:
10915     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
10916     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
10917       VK = RHS.get()->getValueKind();
10918       OK = RHS.get()->getObjectKind();
10919     }
10920     break;
10921   }
10922   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
10923     return ExprError();
10924 
10925   // Check for array bounds violations for both sides of the BinaryOperator
10926   CheckArrayAccess(LHS.get());
10927   CheckArrayAccess(RHS.get());
10928 
10929   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
10930     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
10931                                                  &Context.Idents.get("object_setClass"),
10932                                                  SourceLocation(), LookupOrdinaryName);
10933     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
10934       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
10935       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
10936       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
10937       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
10938       FixItHint::CreateInsertion(RHSLocEnd, ")");
10939     }
10940     else
10941       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
10942   }
10943   else if (const ObjCIvarRefExpr *OIRE =
10944            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
10945     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
10946 
10947   if (CompResultTy.isNull())
10948     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
10949                                         OK, OpLoc, FPFeatures.fp_contract);
10950   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
10951       OK_ObjCProperty) {
10952     VK = VK_LValue;
10953     OK = LHS.get()->getObjectKind();
10954   }
10955   return new (Context) CompoundAssignOperator(
10956       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
10957       OpLoc, FPFeatures.fp_contract);
10958 }
10959 
10960 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
10961 /// operators are mixed in a way that suggests that the programmer forgot that
10962 /// comparison operators have higher precedence. The most typical example of
10963 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
10964 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
10965                                       SourceLocation OpLoc, Expr *LHSExpr,
10966                                       Expr *RHSExpr) {
10967   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
10968   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
10969 
10970   // Check that one of the sides is a comparison operator and the other isn't.
10971   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
10972   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
10973   if (isLeftComp == isRightComp)
10974     return;
10975 
10976   // Bitwise operations are sometimes used as eager logical ops.
10977   // Don't diagnose this.
10978   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
10979   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
10980   if (isLeftBitwise || isRightBitwise)
10981     return;
10982 
10983   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
10984                                                    OpLoc)
10985                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
10986   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
10987   SourceRange ParensRange = isLeftComp ?
10988       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
10989     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
10990 
10991   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
10992     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
10993   SuggestParentheses(Self, OpLoc,
10994     Self.PDiag(diag::note_precedence_silence) << OpStr,
10995     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
10996   SuggestParentheses(Self, OpLoc,
10997     Self.PDiag(diag::note_precedence_bitwise_first)
10998       << BinaryOperator::getOpcodeStr(Opc),
10999     ParensRange);
11000 }
11001 
11002 /// \brief It accepts a '&&' expr that is inside a '||' one.
11003 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11004 /// in parentheses.
11005 static void
11006 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11007                                        BinaryOperator *Bop) {
11008   assert(Bop->getOpcode() == BO_LAnd);
11009   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11010       << Bop->getSourceRange() << OpLoc;
11011   SuggestParentheses(Self, Bop->getOperatorLoc(),
11012     Self.PDiag(diag::note_precedence_silence)
11013       << Bop->getOpcodeStr(),
11014     Bop->getSourceRange());
11015 }
11016 
11017 /// \brief Returns true if the given expression can be evaluated as a constant
11018 /// 'true'.
11019 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11020   bool Res;
11021   return !E->isValueDependent() &&
11022          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11023 }
11024 
11025 /// \brief Returns true if the given expression can be evaluated as a constant
11026 /// 'false'.
11027 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11028   bool Res;
11029   return !E->isValueDependent() &&
11030          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11031 }
11032 
11033 /// \brief Look for '&&' in the left hand of a '||' expr.
11034 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11035                                              Expr *LHSExpr, Expr *RHSExpr) {
11036   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11037     if (Bop->getOpcode() == BO_LAnd) {
11038       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11039       if (EvaluatesAsFalse(S, RHSExpr))
11040         return;
11041       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11042       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11043         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11044     } else if (Bop->getOpcode() == BO_LOr) {
11045       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11046         // If it's "a || b && 1 || c" we didn't warn earlier for
11047         // "a || b && 1", but warn now.
11048         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11049           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11050       }
11051     }
11052   }
11053 }
11054 
11055 /// \brief Look for '&&' in the right hand of a '||' expr.
11056 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11057                                              Expr *LHSExpr, Expr *RHSExpr) {
11058   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11059     if (Bop->getOpcode() == BO_LAnd) {
11060       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11061       if (EvaluatesAsFalse(S, LHSExpr))
11062         return;
11063       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11064       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11065         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11066     }
11067   }
11068 }
11069 
11070 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11071 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11072 /// the '&' expression in parentheses.
11073 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11074                                          SourceLocation OpLoc, Expr *SubExpr) {
11075   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11076     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11077       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11078         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11079         << Bop->getSourceRange() << OpLoc;
11080       SuggestParentheses(S, Bop->getOperatorLoc(),
11081         S.PDiag(diag::note_precedence_silence)
11082           << Bop->getOpcodeStr(),
11083         Bop->getSourceRange());
11084     }
11085   }
11086 }
11087 
11088 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11089                                     Expr *SubExpr, StringRef Shift) {
11090   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11091     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11092       StringRef Op = Bop->getOpcodeStr();
11093       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11094           << Bop->getSourceRange() << OpLoc << Shift << Op;
11095       SuggestParentheses(S, Bop->getOperatorLoc(),
11096           S.PDiag(diag::note_precedence_silence) << Op,
11097           Bop->getSourceRange());
11098     }
11099   }
11100 }
11101 
11102 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11103                                  Expr *LHSExpr, Expr *RHSExpr) {
11104   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11105   if (!OCE)
11106     return;
11107 
11108   FunctionDecl *FD = OCE->getDirectCallee();
11109   if (!FD || !FD->isOverloadedOperator())
11110     return;
11111 
11112   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11113   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11114     return;
11115 
11116   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11117       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11118       << (Kind == OO_LessLess);
11119   SuggestParentheses(S, OCE->getOperatorLoc(),
11120                      S.PDiag(diag::note_precedence_silence)
11121                          << (Kind == OO_LessLess ? "<<" : ">>"),
11122                      OCE->getSourceRange());
11123   SuggestParentheses(S, OpLoc,
11124                      S.PDiag(diag::note_evaluate_comparison_first),
11125                      SourceRange(OCE->getArg(1)->getLocStart(),
11126                                  RHSExpr->getLocEnd()));
11127 }
11128 
11129 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11130 /// precedence.
11131 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11132                                     SourceLocation OpLoc, Expr *LHSExpr,
11133                                     Expr *RHSExpr){
11134   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11135   if (BinaryOperator::isBitwiseOp(Opc))
11136     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11137 
11138   // Diagnose "arg1 & arg2 | arg3"
11139   if ((Opc == BO_Or || Opc == BO_Xor) &&
11140       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11141     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11142     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11143   }
11144 
11145   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11146   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11147   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11148     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11149     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11150   }
11151 
11152   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11153       || Opc == BO_Shr) {
11154     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11155     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11156     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11157   }
11158 
11159   // Warn on overloaded shift operators and comparisons, such as:
11160   // cout << 5 == 4;
11161   if (BinaryOperator::isComparisonOp(Opc))
11162     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11163 }
11164 
11165 // Binary Operators.  'Tok' is the token for the operator.
11166 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11167                             tok::TokenKind Kind,
11168                             Expr *LHSExpr, Expr *RHSExpr) {
11169   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11170   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11171   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11172 
11173   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11174   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11175 
11176   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11177 }
11178 
11179 /// Build an overloaded binary operator expression in the given scope.
11180 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11181                                        BinaryOperatorKind Opc,
11182                                        Expr *LHS, Expr *RHS) {
11183   // Find all of the overloaded operators visible from this
11184   // point. We perform both an operator-name lookup from the local
11185   // scope and an argument-dependent lookup based on the types of
11186   // the arguments.
11187   UnresolvedSet<16> Functions;
11188   OverloadedOperatorKind OverOp
11189     = BinaryOperator::getOverloadedOperator(Opc);
11190   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11191     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11192                                    RHS->getType(), Functions);
11193 
11194   // Build the (potentially-overloaded, potentially-dependent)
11195   // binary operation.
11196   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11197 }
11198 
11199 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11200                             BinaryOperatorKind Opc,
11201                             Expr *LHSExpr, Expr *RHSExpr) {
11202   // We want to end up calling one of checkPseudoObjectAssignment
11203   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11204   // both expressions are overloadable or either is type-dependent),
11205   // or CreateBuiltinBinOp (in any other case).  We also want to get
11206   // any placeholder types out of the way.
11207 
11208   // Handle pseudo-objects in the LHS.
11209   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11210     // Assignments with a pseudo-object l-value need special analysis.
11211     if (pty->getKind() == BuiltinType::PseudoObject &&
11212         BinaryOperator::isAssignmentOp(Opc))
11213       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11214 
11215     // Don't resolve overloads if the other type is overloadable.
11216     if (pty->getKind() == BuiltinType::Overload) {
11217       // We can't actually test that if we still have a placeholder,
11218       // though.  Fortunately, none of the exceptions we see in that
11219       // code below are valid when the LHS is an overload set.  Note
11220       // that an overload set can be dependently-typed, but it never
11221       // instantiates to having an overloadable type.
11222       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11223       if (resolvedRHS.isInvalid()) return ExprError();
11224       RHSExpr = resolvedRHS.get();
11225 
11226       if (RHSExpr->isTypeDependent() ||
11227           RHSExpr->getType()->isOverloadableType())
11228         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11229     }
11230 
11231     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11232     if (LHS.isInvalid()) return ExprError();
11233     LHSExpr = LHS.get();
11234   }
11235 
11236   // Handle pseudo-objects in the RHS.
11237   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11238     // An overload in the RHS can potentially be resolved by the type
11239     // being assigned to.
11240     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11241       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11242         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11243 
11244       if (LHSExpr->getType()->isOverloadableType())
11245         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11246 
11247       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11248     }
11249 
11250     // Don't resolve overloads if the other type is overloadable.
11251     if (pty->getKind() == BuiltinType::Overload &&
11252         LHSExpr->getType()->isOverloadableType())
11253       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11254 
11255     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11256     if (!resolvedRHS.isUsable()) return ExprError();
11257     RHSExpr = resolvedRHS.get();
11258   }
11259 
11260   if (getLangOpts().CPlusPlus) {
11261     // If either expression is type-dependent, always build an
11262     // overloaded op.
11263     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11264       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11265 
11266     // Otherwise, build an overloaded op if either expression has an
11267     // overloadable type.
11268     if (LHSExpr->getType()->isOverloadableType() ||
11269         RHSExpr->getType()->isOverloadableType())
11270       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11271   }
11272 
11273   // Build a built-in binary operation.
11274   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11275 }
11276 
11277 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11278                                       UnaryOperatorKind Opc,
11279                                       Expr *InputExpr) {
11280   ExprResult Input = InputExpr;
11281   ExprValueKind VK = VK_RValue;
11282   ExprObjectKind OK = OK_Ordinary;
11283   QualType resultType;
11284   if (getLangOpts().OpenCL) {
11285     // The only legal unary operation for atomics is '&'.
11286     if (Opc != UO_AddrOf && InputExpr->getType()->isAtomicType()) {
11287       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11288                        << InputExpr->getType()
11289                        << Input.get()->getSourceRange());
11290     }
11291   }
11292   switch (Opc) {
11293   case UO_PreInc:
11294   case UO_PreDec:
11295   case UO_PostInc:
11296   case UO_PostDec:
11297     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11298                                                 OpLoc,
11299                                                 Opc == UO_PreInc ||
11300                                                 Opc == UO_PostInc,
11301                                                 Opc == UO_PreInc ||
11302                                                 Opc == UO_PreDec);
11303     break;
11304   case UO_AddrOf:
11305     resultType = CheckAddressOfOperand(Input, OpLoc);
11306     RecordModifiableNonNullParam(*this, InputExpr);
11307     break;
11308   case UO_Deref: {
11309     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11310     if (Input.isInvalid()) return ExprError();
11311     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11312     break;
11313   }
11314   case UO_Plus:
11315   case UO_Minus:
11316     Input = UsualUnaryConversions(Input.get());
11317     if (Input.isInvalid()) return ExprError();
11318     resultType = Input.get()->getType();
11319     if (resultType->isDependentType())
11320       break;
11321     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11322       break;
11323     else if (resultType->isVectorType() &&
11324              // The z vector extensions don't allow + or - with bool vectors.
11325              (!Context.getLangOpts().ZVector ||
11326               resultType->getAs<VectorType>()->getVectorKind() !=
11327               VectorType::AltiVecBool))
11328       break;
11329     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11330              Opc == UO_Plus &&
11331              resultType->isPointerType())
11332       break;
11333 
11334     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11335       << resultType << Input.get()->getSourceRange());
11336 
11337   case UO_Not: // bitwise complement
11338     Input = UsualUnaryConversions(Input.get());
11339     if (Input.isInvalid())
11340       return ExprError();
11341     resultType = Input.get()->getType();
11342     if (resultType->isDependentType())
11343       break;
11344     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11345     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11346       // C99 does not support '~' for complex conjugation.
11347       Diag(OpLoc, diag::ext_integer_complement_complex)
11348           << resultType << Input.get()->getSourceRange();
11349     else if (resultType->hasIntegerRepresentation())
11350       break;
11351     else if (resultType->isExtVectorType()) {
11352       if (Context.getLangOpts().OpenCL) {
11353         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11354         // on vector float types.
11355         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11356         if (!T->isIntegerType())
11357           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11358                            << resultType << Input.get()->getSourceRange());
11359       }
11360       break;
11361     } else {
11362       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11363                        << resultType << Input.get()->getSourceRange());
11364     }
11365     break;
11366 
11367   case UO_LNot: // logical negation
11368     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11369     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11370     if (Input.isInvalid()) return ExprError();
11371     resultType = Input.get()->getType();
11372 
11373     // Though we still have to promote half FP to float...
11374     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11375       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11376       resultType = Context.FloatTy;
11377     }
11378 
11379     if (resultType->isDependentType())
11380       break;
11381     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11382       // C99 6.5.3.3p1: ok, fallthrough;
11383       if (Context.getLangOpts().CPlusPlus) {
11384         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11385         // operand contextually converted to bool.
11386         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11387                                   ScalarTypeToBooleanCastKind(resultType));
11388       } else if (Context.getLangOpts().OpenCL &&
11389                  Context.getLangOpts().OpenCLVersion < 120) {
11390         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11391         // operate on scalar float types.
11392         if (!resultType->isIntegerType())
11393           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11394                            << resultType << Input.get()->getSourceRange());
11395       }
11396     } else if (resultType->isExtVectorType()) {
11397       if (Context.getLangOpts().OpenCL &&
11398           Context.getLangOpts().OpenCLVersion < 120) {
11399         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11400         // operate on vector float types.
11401         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11402         if (!T->isIntegerType())
11403           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11404                            << resultType << Input.get()->getSourceRange());
11405       }
11406       // Vector logical not returns the signed variant of the operand type.
11407       resultType = GetSignedVectorType(resultType);
11408       break;
11409     } else {
11410       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11411         << resultType << Input.get()->getSourceRange());
11412     }
11413 
11414     // LNot always has type int. C99 6.5.3.3p5.
11415     // In C++, it's bool. C++ 5.3.1p8
11416     resultType = Context.getLogicalOperationType();
11417     break;
11418   case UO_Real:
11419   case UO_Imag:
11420     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11421     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11422     // complex l-values to ordinary l-values and all other values to r-values.
11423     if (Input.isInvalid()) return ExprError();
11424     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11425       if (Input.get()->getValueKind() != VK_RValue &&
11426           Input.get()->getObjectKind() == OK_Ordinary)
11427         VK = Input.get()->getValueKind();
11428     } else if (!getLangOpts().CPlusPlus) {
11429       // In C, a volatile scalar is read by __imag. In C++, it is not.
11430       Input = DefaultLvalueConversion(Input.get());
11431     }
11432     break;
11433   case UO_Extension:
11434   case UO_Coawait:
11435     resultType = Input.get()->getType();
11436     VK = Input.get()->getValueKind();
11437     OK = Input.get()->getObjectKind();
11438     break;
11439   }
11440   if (resultType.isNull() || Input.isInvalid())
11441     return ExprError();
11442 
11443   // Check for array bounds violations in the operand of the UnaryOperator,
11444   // except for the '*' and '&' operators that have to be handled specially
11445   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11446   // that are explicitly defined as valid by the standard).
11447   if (Opc != UO_AddrOf && Opc != UO_Deref)
11448     CheckArrayAccess(Input.get());
11449 
11450   return new (Context)
11451       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11452 }
11453 
11454 /// \brief Determine whether the given expression is a qualified member
11455 /// access expression, of a form that could be turned into a pointer to member
11456 /// with the address-of operator.
11457 static bool isQualifiedMemberAccess(Expr *E) {
11458   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11459     if (!DRE->getQualifier())
11460       return false;
11461 
11462     ValueDecl *VD = DRE->getDecl();
11463     if (!VD->isCXXClassMember())
11464       return false;
11465 
11466     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11467       return true;
11468     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11469       return Method->isInstance();
11470 
11471     return false;
11472   }
11473 
11474   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11475     if (!ULE->getQualifier())
11476       return false;
11477 
11478     for (NamedDecl *D : ULE->decls()) {
11479       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11480         if (Method->isInstance())
11481           return true;
11482       } else {
11483         // Overload set does not contain methods.
11484         break;
11485       }
11486     }
11487 
11488     return false;
11489   }
11490 
11491   return false;
11492 }
11493 
11494 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11495                               UnaryOperatorKind Opc, Expr *Input) {
11496   // First things first: handle placeholders so that the
11497   // overloaded-operator check considers the right type.
11498   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11499     // Increment and decrement of pseudo-object references.
11500     if (pty->getKind() == BuiltinType::PseudoObject &&
11501         UnaryOperator::isIncrementDecrementOp(Opc))
11502       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11503 
11504     // extension is always a builtin operator.
11505     if (Opc == UO_Extension)
11506       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11507 
11508     // & gets special logic for several kinds of placeholder.
11509     // The builtin code knows what to do.
11510     if (Opc == UO_AddrOf &&
11511         (pty->getKind() == BuiltinType::Overload ||
11512          pty->getKind() == BuiltinType::UnknownAny ||
11513          pty->getKind() == BuiltinType::BoundMember))
11514       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11515 
11516     // Anything else needs to be handled now.
11517     ExprResult Result = CheckPlaceholderExpr(Input);
11518     if (Result.isInvalid()) return ExprError();
11519     Input = Result.get();
11520   }
11521 
11522   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11523       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11524       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11525     // Find all of the overloaded operators visible from this
11526     // point. We perform both an operator-name lookup from the local
11527     // scope and an argument-dependent lookup based on the types of
11528     // the arguments.
11529     UnresolvedSet<16> Functions;
11530     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11531     if (S && OverOp != OO_None)
11532       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11533                                    Functions);
11534 
11535     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11536   }
11537 
11538   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11539 }
11540 
11541 // Unary Operators.  'Tok' is the token for the operator.
11542 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11543                               tok::TokenKind Op, Expr *Input) {
11544   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11545 }
11546 
11547 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11548 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11549                                 LabelDecl *TheDecl) {
11550   TheDecl->markUsed(Context);
11551   // Create the AST node.  The address of a label always has type 'void*'.
11552   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11553                                      Context.getPointerType(Context.VoidTy));
11554 }
11555 
11556 /// Given the last statement in a statement-expression, check whether
11557 /// the result is a producing expression (like a call to an
11558 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11559 /// release out of the full-expression.  Otherwise, return null.
11560 /// Cannot fail.
11561 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11562   // Should always be wrapped with one of these.
11563   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11564   if (!cleanups) return nullptr;
11565 
11566   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11567   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11568     return nullptr;
11569 
11570   // Splice out the cast.  This shouldn't modify any interesting
11571   // features of the statement.
11572   Expr *producer = cast->getSubExpr();
11573   assert(producer->getType() == cast->getType());
11574   assert(producer->getValueKind() == cast->getValueKind());
11575   cleanups->setSubExpr(producer);
11576   return cleanups;
11577 }
11578 
11579 void Sema::ActOnStartStmtExpr() {
11580   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11581 }
11582 
11583 void Sema::ActOnStmtExprError() {
11584   // Note that function is also called by TreeTransform when leaving a
11585   // StmtExpr scope without rebuilding anything.
11586 
11587   DiscardCleanupsInEvaluationContext();
11588   PopExpressionEvaluationContext();
11589 }
11590 
11591 ExprResult
11592 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11593                     SourceLocation RPLoc) { // "({..})"
11594   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11595   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11596 
11597   if (hasAnyUnrecoverableErrorsInThisFunction())
11598     DiscardCleanupsInEvaluationContext();
11599   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
11600   PopExpressionEvaluationContext();
11601 
11602   // FIXME: there are a variety of strange constraints to enforce here, for
11603   // example, it is not possible to goto into a stmt expression apparently.
11604   // More semantic analysis is needed.
11605 
11606   // If there are sub-stmts in the compound stmt, take the type of the last one
11607   // as the type of the stmtexpr.
11608   QualType Ty = Context.VoidTy;
11609   bool StmtExprMayBindToTemp = false;
11610   if (!Compound->body_empty()) {
11611     Stmt *LastStmt = Compound->body_back();
11612     LabelStmt *LastLabelStmt = nullptr;
11613     // If LastStmt is a label, skip down through into the body.
11614     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11615       LastLabelStmt = Label;
11616       LastStmt = Label->getSubStmt();
11617     }
11618 
11619     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11620       // Do function/array conversion on the last expression, but not
11621       // lvalue-to-rvalue.  However, initialize an unqualified type.
11622       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11623       if (LastExpr.isInvalid())
11624         return ExprError();
11625       Ty = LastExpr.get()->getType().getUnqualifiedType();
11626 
11627       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11628         // In ARC, if the final expression ends in a consume, splice
11629         // the consume out and bind it later.  In the alternate case
11630         // (when dealing with a retainable type), the result
11631         // initialization will create a produce.  In both cases the
11632         // result will be +1, and we'll need to balance that out with
11633         // a bind.
11634         if (Expr *rebuiltLastStmt
11635               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11636           LastExpr = rebuiltLastStmt;
11637         } else {
11638           LastExpr = PerformCopyInitialization(
11639                             InitializedEntity::InitializeResult(LPLoc,
11640                                                                 Ty,
11641                                                                 false),
11642                                                    SourceLocation(),
11643                                                LastExpr);
11644         }
11645 
11646         if (LastExpr.isInvalid())
11647           return ExprError();
11648         if (LastExpr.get() != nullptr) {
11649           if (!LastLabelStmt)
11650             Compound->setLastStmt(LastExpr.get());
11651           else
11652             LastLabelStmt->setSubStmt(LastExpr.get());
11653           StmtExprMayBindToTemp = true;
11654         }
11655       }
11656     }
11657   }
11658 
11659   // FIXME: Check that expression type is complete/non-abstract; statement
11660   // expressions are not lvalues.
11661   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11662   if (StmtExprMayBindToTemp)
11663     return MaybeBindToTemporary(ResStmtExpr);
11664   return ResStmtExpr;
11665 }
11666 
11667 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11668                                       TypeSourceInfo *TInfo,
11669                                       ArrayRef<OffsetOfComponent> Components,
11670                                       SourceLocation RParenLoc) {
11671   QualType ArgTy = TInfo->getType();
11672   bool Dependent = ArgTy->isDependentType();
11673   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11674 
11675   // We must have at least one component that refers to the type, and the first
11676   // one is known to be a field designator.  Verify that the ArgTy represents
11677   // a struct/union/class.
11678   if (!Dependent && !ArgTy->isRecordType())
11679     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11680                        << ArgTy << TypeRange);
11681 
11682   // Type must be complete per C99 7.17p3 because a declaring a variable
11683   // with an incomplete type would be ill-formed.
11684   if (!Dependent
11685       && RequireCompleteType(BuiltinLoc, ArgTy,
11686                              diag::err_offsetof_incomplete_type, TypeRange))
11687     return ExprError();
11688 
11689   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11690   // GCC extension, diagnose them.
11691   // FIXME: This diagnostic isn't actually visible because the location is in
11692   // a system header!
11693   if (Components.size() != 1)
11694     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11695       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11696 
11697   bool DidWarnAboutNonPOD = false;
11698   QualType CurrentType = ArgTy;
11699   SmallVector<OffsetOfNode, 4> Comps;
11700   SmallVector<Expr*, 4> Exprs;
11701   for (const OffsetOfComponent &OC : Components) {
11702     if (OC.isBrackets) {
11703       // Offset of an array sub-field.  TODO: Should we allow vector elements?
11704       if (!CurrentType->isDependentType()) {
11705         const ArrayType *AT = Context.getAsArrayType(CurrentType);
11706         if(!AT)
11707           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11708                            << CurrentType);
11709         CurrentType = AT->getElementType();
11710       } else
11711         CurrentType = Context.DependentTy;
11712 
11713       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
11714       if (IdxRval.isInvalid())
11715         return ExprError();
11716       Expr *Idx = IdxRval.get();
11717 
11718       // The expression must be an integral expression.
11719       // FIXME: An integral constant expression?
11720       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
11721           !Idx->getType()->isIntegerType())
11722         return ExprError(Diag(Idx->getLocStart(),
11723                               diag::err_typecheck_subscript_not_integer)
11724                          << Idx->getSourceRange());
11725 
11726       // Record this array index.
11727       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
11728       Exprs.push_back(Idx);
11729       continue;
11730     }
11731 
11732     // Offset of a field.
11733     if (CurrentType->isDependentType()) {
11734       // We have the offset of a field, but we can't look into the dependent
11735       // type. Just record the identifier of the field.
11736       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
11737       CurrentType = Context.DependentTy;
11738       continue;
11739     }
11740 
11741     // We need to have a complete type to look into.
11742     if (RequireCompleteType(OC.LocStart, CurrentType,
11743                             diag::err_offsetof_incomplete_type))
11744       return ExprError();
11745 
11746     // Look for the designated field.
11747     const RecordType *RC = CurrentType->getAs<RecordType>();
11748     if (!RC)
11749       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
11750                        << CurrentType);
11751     RecordDecl *RD = RC->getDecl();
11752 
11753     // C++ [lib.support.types]p5:
11754     //   The macro offsetof accepts a restricted set of type arguments in this
11755     //   International Standard. type shall be a POD structure or a POD union
11756     //   (clause 9).
11757     // C++11 [support.types]p4:
11758     //   If type is not a standard-layout class (Clause 9), the results are
11759     //   undefined.
11760     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11761       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
11762       unsigned DiagID =
11763         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
11764                             : diag::ext_offsetof_non_pod_type;
11765 
11766       if (!IsSafe && !DidWarnAboutNonPOD &&
11767           DiagRuntimeBehavior(BuiltinLoc, nullptr,
11768                               PDiag(DiagID)
11769                               << SourceRange(Components[0].LocStart, OC.LocEnd)
11770                               << CurrentType))
11771         DidWarnAboutNonPOD = true;
11772     }
11773 
11774     // Look for the field.
11775     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
11776     LookupQualifiedName(R, RD);
11777     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
11778     IndirectFieldDecl *IndirectMemberDecl = nullptr;
11779     if (!MemberDecl) {
11780       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
11781         MemberDecl = IndirectMemberDecl->getAnonField();
11782     }
11783 
11784     if (!MemberDecl)
11785       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
11786                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
11787                                                               OC.LocEnd));
11788 
11789     // C99 7.17p3:
11790     //   (If the specified member is a bit-field, the behavior is undefined.)
11791     //
11792     // We diagnose this as an error.
11793     if (MemberDecl->isBitField()) {
11794       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
11795         << MemberDecl->getDeclName()
11796         << SourceRange(BuiltinLoc, RParenLoc);
11797       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
11798       return ExprError();
11799     }
11800 
11801     RecordDecl *Parent = MemberDecl->getParent();
11802     if (IndirectMemberDecl)
11803       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
11804 
11805     // If the member was found in a base class, introduce OffsetOfNodes for
11806     // the base class indirections.
11807     CXXBasePaths Paths;
11808     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
11809                       Paths)) {
11810       if (Paths.getDetectedVirtual()) {
11811         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
11812           << MemberDecl->getDeclName()
11813           << SourceRange(BuiltinLoc, RParenLoc);
11814         return ExprError();
11815       }
11816 
11817       CXXBasePath &Path = Paths.front();
11818       for (const CXXBasePathElement &B : Path)
11819         Comps.push_back(OffsetOfNode(B.Base));
11820     }
11821 
11822     if (IndirectMemberDecl) {
11823       for (auto *FI : IndirectMemberDecl->chain()) {
11824         assert(isa<FieldDecl>(FI));
11825         Comps.push_back(OffsetOfNode(OC.LocStart,
11826                                      cast<FieldDecl>(FI), OC.LocEnd));
11827       }
11828     } else
11829       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
11830 
11831     CurrentType = MemberDecl->getType().getNonReferenceType();
11832   }
11833 
11834   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
11835                               Comps, Exprs, RParenLoc);
11836 }
11837 
11838 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
11839                                       SourceLocation BuiltinLoc,
11840                                       SourceLocation TypeLoc,
11841                                       ParsedType ParsedArgTy,
11842                                       ArrayRef<OffsetOfComponent> Components,
11843                                       SourceLocation RParenLoc) {
11844 
11845   TypeSourceInfo *ArgTInfo;
11846   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
11847   if (ArgTy.isNull())
11848     return ExprError();
11849 
11850   if (!ArgTInfo)
11851     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
11852 
11853   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
11854 }
11855 
11856 
11857 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
11858                                  Expr *CondExpr,
11859                                  Expr *LHSExpr, Expr *RHSExpr,
11860                                  SourceLocation RPLoc) {
11861   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
11862 
11863   ExprValueKind VK = VK_RValue;
11864   ExprObjectKind OK = OK_Ordinary;
11865   QualType resType;
11866   bool ValueDependent = false;
11867   bool CondIsTrue = false;
11868   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
11869     resType = Context.DependentTy;
11870     ValueDependent = true;
11871   } else {
11872     // The conditional expression is required to be a constant expression.
11873     llvm::APSInt condEval(32);
11874     ExprResult CondICE
11875       = VerifyIntegerConstantExpression(CondExpr, &condEval,
11876           diag::err_typecheck_choose_expr_requires_constant, false);
11877     if (CondICE.isInvalid())
11878       return ExprError();
11879     CondExpr = CondICE.get();
11880     CondIsTrue = condEval.getZExtValue();
11881 
11882     // If the condition is > zero, then the AST type is the same as the LSHExpr.
11883     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
11884 
11885     resType = ActiveExpr->getType();
11886     ValueDependent = ActiveExpr->isValueDependent();
11887     VK = ActiveExpr->getValueKind();
11888     OK = ActiveExpr->getObjectKind();
11889   }
11890 
11891   return new (Context)
11892       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
11893                  CondIsTrue, resType->isDependentType(), ValueDependent);
11894 }
11895 
11896 //===----------------------------------------------------------------------===//
11897 // Clang Extensions.
11898 //===----------------------------------------------------------------------===//
11899 
11900 /// ActOnBlockStart - This callback is invoked when a block literal is started.
11901 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
11902   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
11903 
11904   if (LangOpts.CPlusPlus) {
11905     Decl *ManglingContextDecl;
11906     if (MangleNumberingContext *MCtx =
11907             getCurrentMangleNumberContext(Block->getDeclContext(),
11908                                           ManglingContextDecl)) {
11909       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
11910       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
11911     }
11912   }
11913 
11914   PushBlockScope(CurScope, Block);
11915   CurContext->addDecl(Block);
11916   if (CurScope)
11917     PushDeclContext(CurScope, Block);
11918   else
11919     CurContext = Block;
11920 
11921   getCurBlock()->HasImplicitReturnType = true;
11922 
11923   // Enter a new evaluation context to insulate the block from any
11924   // cleanups from the enclosing full-expression.
11925   PushExpressionEvaluationContext(PotentiallyEvaluated);
11926 }
11927 
11928 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
11929                                Scope *CurScope) {
11930   assert(ParamInfo.getIdentifier() == nullptr &&
11931          "block-id should have no identifier!");
11932   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
11933   BlockScopeInfo *CurBlock = getCurBlock();
11934 
11935   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
11936   QualType T = Sig->getType();
11937 
11938   // FIXME: We should allow unexpanded parameter packs here, but that would,
11939   // in turn, make the block expression contain unexpanded parameter packs.
11940   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
11941     // Drop the parameters.
11942     FunctionProtoType::ExtProtoInfo EPI;
11943     EPI.HasTrailingReturn = false;
11944     EPI.TypeQuals |= DeclSpec::TQ_const;
11945     T = Context.getFunctionType(Context.DependentTy, None, EPI);
11946     Sig = Context.getTrivialTypeSourceInfo(T);
11947   }
11948 
11949   // GetTypeForDeclarator always produces a function type for a block
11950   // literal signature.  Furthermore, it is always a FunctionProtoType
11951   // unless the function was written with a typedef.
11952   assert(T->isFunctionType() &&
11953          "GetTypeForDeclarator made a non-function block signature");
11954 
11955   // Look for an explicit signature in that function type.
11956   FunctionProtoTypeLoc ExplicitSignature;
11957 
11958   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
11959   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
11960 
11961     // Check whether that explicit signature was synthesized by
11962     // GetTypeForDeclarator.  If so, don't save that as part of the
11963     // written signature.
11964     if (ExplicitSignature.getLocalRangeBegin() ==
11965         ExplicitSignature.getLocalRangeEnd()) {
11966       // This would be much cheaper if we stored TypeLocs instead of
11967       // TypeSourceInfos.
11968       TypeLoc Result = ExplicitSignature.getReturnLoc();
11969       unsigned Size = Result.getFullDataSize();
11970       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
11971       Sig->getTypeLoc().initializeFullCopy(Result, Size);
11972 
11973       ExplicitSignature = FunctionProtoTypeLoc();
11974     }
11975   }
11976 
11977   CurBlock->TheDecl->setSignatureAsWritten(Sig);
11978   CurBlock->FunctionType = T;
11979 
11980   const FunctionType *Fn = T->getAs<FunctionType>();
11981   QualType RetTy = Fn->getReturnType();
11982   bool isVariadic =
11983     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
11984 
11985   CurBlock->TheDecl->setIsVariadic(isVariadic);
11986 
11987   // Context.DependentTy is used as a placeholder for a missing block
11988   // return type.  TODO:  what should we do with declarators like:
11989   //   ^ * { ... }
11990   // If the answer is "apply template argument deduction"....
11991   if (RetTy != Context.DependentTy) {
11992     CurBlock->ReturnType = RetTy;
11993     CurBlock->TheDecl->setBlockMissingReturnType(false);
11994     CurBlock->HasImplicitReturnType = false;
11995   }
11996 
11997   // Push block parameters from the declarator if we had them.
11998   SmallVector<ParmVarDecl*, 8> Params;
11999   if (ExplicitSignature) {
12000     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12001       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12002       if (Param->getIdentifier() == nullptr &&
12003           !Param->isImplicit() &&
12004           !Param->isInvalidDecl() &&
12005           !getLangOpts().CPlusPlus)
12006         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12007       Params.push_back(Param);
12008     }
12009 
12010   // Fake up parameter variables if we have a typedef, like
12011   //   ^ fntype { ... }
12012   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12013     for (const auto &I : Fn->param_types()) {
12014       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12015           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12016       Params.push_back(Param);
12017     }
12018   }
12019 
12020   // Set the parameters on the block decl.
12021   if (!Params.empty()) {
12022     CurBlock->TheDecl->setParams(Params);
12023     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
12024                              CurBlock->TheDecl->param_end(),
12025                              /*CheckParameterNames=*/false);
12026   }
12027 
12028   // Finally we can process decl attributes.
12029   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12030 
12031   // Put the parameter variables in scope.
12032   for (auto AI : CurBlock->TheDecl->params()) {
12033     AI->setOwningFunction(CurBlock->TheDecl);
12034 
12035     // If this has an identifier, add it to the scope stack.
12036     if (AI->getIdentifier()) {
12037       CheckShadow(CurBlock->TheScope, AI);
12038 
12039       PushOnScopeChains(AI, CurBlock->TheScope);
12040     }
12041   }
12042 }
12043 
12044 /// ActOnBlockError - If there is an error parsing a block, this callback
12045 /// is invoked to pop the information about the block from the action impl.
12046 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12047   // Leave the expression-evaluation context.
12048   DiscardCleanupsInEvaluationContext();
12049   PopExpressionEvaluationContext();
12050 
12051   // Pop off CurBlock, handle nested blocks.
12052   PopDeclContext();
12053   PopFunctionScopeInfo();
12054 }
12055 
12056 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12057 /// literal was successfully completed.  ^(int x){...}
12058 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12059                                     Stmt *Body, Scope *CurScope) {
12060   // If blocks are disabled, emit an error.
12061   if (!LangOpts.Blocks)
12062     Diag(CaretLoc, diag::err_blocks_disable);
12063 
12064   // Leave the expression-evaluation context.
12065   if (hasAnyUnrecoverableErrorsInThisFunction())
12066     DiscardCleanupsInEvaluationContext();
12067   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
12068   PopExpressionEvaluationContext();
12069 
12070   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12071 
12072   if (BSI->HasImplicitReturnType)
12073     deduceClosureReturnType(*BSI);
12074 
12075   PopDeclContext();
12076 
12077   QualType RetTy = Context.VoidTy;
12078   if (!BSI->ReturnType.isNull())
12079     RetTy = BSI->ReturnType;
12080 
12081   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12082   QualType BlockTy;
12083 
12084   // Set the captured variables on the block.
12085   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12086   SmallVector<BlockDecl::Capture, 4> Captures;
12087   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12088     if (Cap.isThisCapture())
12089       continue;
12090     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12091                               Cap.isNested(), Cap.getInitExpr());
12092     Captures.push_back(NewCap);
12093   }
12094   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12095 
12096   // If the user wrote a function type in some form, try to use that.
12097   if (!BSI->FunctionType.isNull()) {
12098     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12099 
12100     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12101     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12102 
12103     // Turn protoless block types into nullary block types.
12104     if (isa<FunctionNoProtoType>(FTy)) {
12105       FunctionProtoType::ExtProtoInfo EPI;
12106       EPI.ExtInfo = Ext;
12107       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12108 
12109     // Otherwise, if we don't need to change anything about the function type,
12110     // preserve its sugar structure.
12111     } else if (FTy->getReturnType() == RetTy &&
12112                (!NoReturn || FTy->getNoReturnAttr())) {
12113       BlockTy = BSI->FunctionType;
12114 
12115     // Otherwise, make the minimal modifications to the function type.
12116     } else {
12117       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12118       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12119       EPI.TypeQuals = 0; // FIXME: silently?
12120       EPI.ExtInfo = Ext;
12121       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12122     }
12123 
12124   // If we don't have a function type, just build one from nothing.
12125   } else {
12126     FunctionProtoType::ExtProtoInfo EPI;
12127     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12128     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12129   }
12130 
12131   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
12132                            BSI->TheDecl->param_end());
12133   BlockTy = Context.getBlockPointerType(BlockTy);
12134 
12135   // If needed, diagnose invalid gotos and switches in the block.
12136   if (getCurFunction()->NeedsScopeChecking() &&
12137       !PP.isCodeCompletionEnabled())
12138     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12139 
12140   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12141 
12142   // Try to apply the named return value optimization. We have to check again
12143   // if we can do this, though, because blocks keep return statements around
12144   // to deduce an implicit return type.
12145   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12146       !BSI->TheDecl->isDependentContext())
12147     computeNRVO(Body, BSI);
12148 
12149   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12150   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12151   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12152 
12153   // If the block isn't obviously global, i.e. it captures anything at
12154   // all, then we need to do a few things in the surrounding context:
12155   if (Result->getBlockDecl()->hasCaptures()) {
12156     // First, this expression has a new cleanup object.
12157     ExprCleanupObjects.push_back(Result->getBlockDecl());
12158     ExprNeedsCleanups = true;
12159 
12160     // It also gets a branch-protected scope if any of the captured
12161     // variables needs destruction.
12162     for (const auto &CI : Result->getBlockDecl()->captures()) {
12163       const VarDecl *var = CI.getVariable();
12164       if (var->getType().isDestructedType() != QualType::DK_none) {
12165         getCurFunction()->setHasBranchProtectedScope();
12166         break;
12167       }
12168     }
12169   }
12170 
12171   return Result;
12172 }
12173 
12174 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12175                             SourceLocation RPLoc) {
12176   TypeSourceInfo *TInfo;
12177   GetTypeFromParser(Ty, &TInfo);
12178   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12179 }
12180 
12181 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12182                                 Expr *E, TypeSourceInfo *TInfo,
12183                                 SourceLocation RPLoc) {
12184   Expr *OrigExpr = E;
12185   bool IsMS = false;
12186 
12187   // CUDA device code does not support varargs.
12188   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12189     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12190       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12191       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12192         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12193     }
12194   }
12195 
12196   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12197   // as Microsoft ABI on an actual Microsoft platform, where
12198   // __builtin_ms_va_list and __builtin_va_list are the same.)
12199   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12200       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12201     QualType MSVaListType = Context.getBuiltinMSVaListType();
12202     if (Context.hasSameType(MSVaListType, E->getType())) {
12203       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12204         return ExprError();
12205       IsMS = true;
12206     }
12207   }
12208 
12209   // Get the va_list type
12210   QualType VaListType = Context.getBuiltinVaListType();
12211   if (!IsMS) {
12212     if (VaListType->isArrayType()) {
12213       // Deal with implicit array decay; for example, on x86-64,
12214       // va_list is an array, but it's supposed to decay to
12215       // a pointer for va_arg.
12216       VaListType = Context.getArrayDecayedType(VaListType);
12217       // Make sure the input expression also decays appropriately.
12218       ExprResult Result = UsualUnaryConversions(E);
12219       if (Result.isInvalid())
12220         return ExprError();
12221       E = Result.get();
12222     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12223       // If va_list is a record type and we are compiling in C++ mode,
12224       // check the argument using reference binding.
12225       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12226           Context, Context.getLValueReferenceType(VaListType), false);
12227       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12228       if (Init.isInvalid())
12229         return ExprError();
12230       E = Init.getAs<Expr>();
12231     } else {
12232       // Otherwise, the va_list argument must be an l-value because
12233       // it is modified by va_arg.
12234       if (!E->isTypeDependent() &&
12235           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12236         return ExprError();
12237     }
12238   }
12239 
12240   if (!IsMS && !E->isTypeDependent() &&
12241       !Context.hasSameType(VaListType, E->getType()))
12242     return ExprError(Diag(E->getLocStart(),
12243                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12244       << OrigExpr->getType() << E->getSourceRange());
12245 
12246   if (!TInfo->getType()->isDependentType()) {
12247     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12248                             diag::err_second_parameter_to_va_arg_incomplete,
12249                             TInfo->getTypeLoc()))
12250       return ExprError();
12251 
12252     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12253                                TInfo->getType(),
12254                                diag::err_second_parameter_to_va_arg_abstract,
12255                                TInfo->getTypeLoc()))
12256       return ExprError();
12257 
12258     if (!TInfo->getType().isPODType(Context)) {
12259       Diag(TInfo->getTypeLoc().getBeginLoc(),
12260            TInfo->getType()->isObjCLifetimeType()
12261              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12262              : diag::warn_second_parameter_to_va_arg_not_pod)
12263         << TInfo->getType()
12264         << TInfo->getTypeLoc().getSourceRange();
12265     }
12266 
12267     // Check for va_arg where arguments of the given type will be promoted
12268     // (i.e. this va_arg is guaranteed to have undefined behavior).
12269     QualType PromoteType;
12270     if (TInfo->getType()->isPromotableIntegerType()) {
12271       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12272       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12273         PromoteType = QualType();
12274     }
12275     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12276       PromoteType = Context.DoubleTy;
12277     if (!PromoteType.isNull())
12278       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12279                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12280                           << TInfo->getType()
12281                           << PromoteType
12282                           << TInfo->getTypeLoc().getSourceRange());
12283   }
12284 
12285   QualType T = TInfo->getType().getNonLValueExprType(Context);
12286   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12287 }
12288 
12289 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12290   // The type of __null will be int or long, depending on the size of
12291   // pointers on the target.
12292   QualType Ty;
12293   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12294   if (pw == Context.getTargetInfo().getIntWidth())
12295     Ty = Context.IntTy;
12296   else if (pw == Context.getTargetInfo().getLongWidth())
12297     Ty = Context.LongTy;
12298   else if (pw == Context.getTargetInfo().getLongLongWidth())
12299     Ty = Context.LongLongTy;
12300   else {
12301     llvm_unreachable("I don't know size of pointer!");
12302   }
12303 
12304   return new (Context) GNUNullExpr(Ty, TokenLoc);
12305 }
12306 
12307 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12308                                               bool Diagnose) {
12309   if (!getLangOpts().ObjC1)
12310     return false;
12311 
12312   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12313   if (!PT)
12314     return false;
12315 
12316   if (!PT->isObjCIdType()) {
12317     // Check if the destination is the 'NSString' interface.
12318     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12319     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12320       return false;
12321   }
12322 
12323   // Ignore any parens, implicit casts (should only be
12324   // array-to-pointer decays), and not-so-opaque values.  The last is
12325   // important for making this trigger for property assignments.
12326   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12327   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12328     if (OV->getSourceExpr())
12329       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12330 
12331   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12332   if (!SL || !SL->isAscii())
12333     return false;
12334   if (Diagnose) {
12335     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12336       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12337     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12338   }
12339   return true;
12340 }
12341 
12342 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12343                                               const Expr *SrcExpr) {
12344   if (!DstType->isFunctionPointerType() ||
12345       !SrcExpr->getType()->isFunctionType())
12346     return false;
12347 
12348   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12349   if (!DRE)
12350     return false;
12351 
12352   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12353   if (!FD)
12354     return false;
12355 
12356   return !S.checkAddressOfFunctionIsAvailable(FD,
12357                                               /*Complain=*/true,
12358                                               SrcExpr->getLocStart());
12359 }
12360 
12361 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12362                                     SourceLocation Loc,
12363                                     QualType DstType, QualType SrcType,
12364                                     Expr *SrcExpr, AssignmentAction Action,
12365                                     bool *Complained) {
12366   if (Complained)
12367     *Complained = false;
12368 
12369   // Decode the result (notice that AST's are still created for extensions).
12370   bool CheckInferredResultType = false;
12371   bool isInvalid = false;
12372   unsigned DiagKind = 0;
12373   FixItHint Hint;
12374   ConversionFixItGenerator ConvHints;
12375   bool MayHaveConvFixit = false;
12376   bool MayHaveFunctionDiff = false;
12377   const ObjCInterfaceDecl *IFace = nullptr;
12378   const ObjCProtocolDecl *PDecl = nullptr;
12379 
12380   switch (ConvTy) {
12381   case Compatible:
12382       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12383       return false;
12384 
12385   case PointerToInt:
12386     DiagKind = diag::ext_typecheck_convert_pointer_int;
12387     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12388     MayHaveConvFixit = true;
12389     break;
12390   case IntToPointer:
12391     DiagKind = diag::ext_typecheck_convert_int_pointer;
12392     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12393     MayHaveConvFixit = true;
12394     break;
12395   case IncompatiblePointer:
12396       DiagKind =
12397         (Action == AA_Passing_CFAudited ?
12398           diag::err_arc_typecheck_convert_incompatible_pointer :
12399           diag::ext_typecheck_convert_incompatible_pointer);
12400     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12401       SrcType->isObjCObjectPointerType();
12402     if (Hint.isNull() && !CheckInferredResultType) {
12403       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12404     }
12405     else if (CheckInferredResultType) {
12406       SrcType = SrcType.getUnqualifiedType();
12407       DstType = DstType.getUnqualifiedType();
12408     }
12409     MayHaveConvFixit = true;
12410     break;
12411   case IncompatiblePointerSign:
12412     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12413     break;
12414   case FunctionVoidPointer:
12415     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12416     break;
12417   case IncompatiblePointerDiscardsQualifiers: {
12418     // Perform array-to-pointer decay if necessary.
12419     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12420 
12421     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12422     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12423     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12424       DiagKind = diag::err_typecheck_incompatible_address_space;
12425       break;
12426 
12427 
12428     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12429       DiagKind = diag::err_typecheck_incompatible_ownership;
12430       break;
12431     }
12432 
12433     llvm_unreachable("unknown error case for discarding qualifiers!");
12434     // fallthrough
12435   }
12436   case CompatiblePointerDiscardsQualifiers:
12437     // If the qualifiers lost were because we were applying the
12438     // (deprecated) C++ conversion from a string literal to a char*
12439     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12440     // Ideally, this check would be performed in
12441     // checkPointerTypesForAssignment. However, that would require a
12442     // bit of refactoring (so that the second argument is an
12443     // expression, rather than a type), which should be done as part
12444     // of a larger effort to fix checkPointerTypesForAssignment for
12445     // C++ semantics.
12446     if (getLangOpts().CPlusPlus &&
12447         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12448       return false;
12449     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12450     break;
12451   case IncompatibleNestedPointerQualifiers:
12452     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12453     break;
12454   case IntToBlockPointer:
12455     DiagKind = diag::err_int_to_block_pointer;
12456     break;
12457   case IncompatibleBlockPointer:
12458     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12459     break;
12460   case IncompatibleObjCQualifiedId: {
12461     if (SrcType->isObjCQualifiedIdType()) {
12462       const ObjCObjectPointerType *srcOPT =
12463                 SrcType->getAs<ObjCObjectPointerType>();
12464       for (auto *srcProto : srcOPT->quals()) {
12465         PDecl = srcProto;
12466         break;
12467       }
12468       if (const ObjCInterfaceType *IFaceT =
12469             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12470         IFace = IFaceT->getDecl();
12471     }
12472     else if (DstType->isObjCQualifiedIdType()) {
12473       const ObjCObjectPointerType *dstOPT =
12474         DstType->getAs<ObjCObjectPointerType>();
12475       for (auto *dstProto : dstOPT->quals()) {
12476         PDecl = dstProto;
12477         break;
12478       }
12479       if (const ObjCInterfaceType *IFaceT =
12480             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12481         IFace = IFaceT->getDecl();
12482     }
12483     DiagKind = diag::warn_incompatible_qualified_id;
12484     break;
12485   }
12486   case IncompatibleVectors:
12487     DiagKind = diag::warn_incompatible_vectors;
12488     break;
12489   case IncompatibleObjCWeakRef:
12490     DiagKind = diag::err_arc_weak_unavailable_assign;
12491     break;
12492   case Incompatible:
12493     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12494       if (Complained)
12495         *Complained = true;
12496       return true;
12497     }
12498 
12499     DiagKind = diag::err_typecheck_convert_incompatible;
12500     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12501     MayHaveConvFixit = true;
12502     isInvalid = true;
12503     MayHaveFunctionDiff = true;
12504     break;
12505   }
12506 
12507   QualType FirstType, SecondType;
12508   switch (Action) {
12509   case AA_Assigning:
12510   case AA_Initializing:
12511     // The destination type comes first.
12512     FirstType = DstType;
12513     SecondType = SrcType;
12514     break;
12515 
12516   case AA_Returning:
12517   case AA_Passing:
12518   case AA_Passing_CFAudited:
12519   case AA_Converting:
12520   case AA_Sending:
12521   case AA_Casting:
12522     // The source type comes first.
12523     FirstType = SrcType;
12524     SecondType = DstType;
12525     break;
12526   }
12527 
12528   PartialDiagnostic FDiag = PDiag(DiagKind);
12529   if (Action == AA_Passing_CFAudited)
12530     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12531   else
12532     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12533 
12534   // If we can fix the conversion, suggest the FixIts.
12535   assert(ConvHints.isNull() || Hint.isNull());
12536   if (!ConvHints.isNull()) {
12537     for (FixItHint &H : ConvHints.Hints)
12538       FDiag << H;
12539   } else {
12540     FDiag << Hint;
12541   }
12542   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12543 
12544   if (MayHaveFunctionDiff)
12545     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12546 
12547   Diag(Loc, FDiag);
12548   if (DiagKind == diag::warn_incompatible_qualified_id &&
12549       PDecl && IFace && !IFace->hasDefinition())
12550       Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
12551         << IFace->getName() << PDecl->getName();
12552 
12553   if (SecondType == Context.OverloadTy)
12554     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12555                               FirstType, /*TakingAddress=*/true);
12556 
12557   if (CheckInferredResultType)
12558     EmitRelatedResultTypeNote(SrcExpr);
12559 
12560   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12561     EmitRelatedResultTypeNoteForReturn(DstType);
12562 
12563   if (Complained)
12564     *Complained = true;
12565   return isInvalid;
12566 }
12567 
12568 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12569                                                  llvm::APSInt *Result) {
12570   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12571   public:
12572     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12573       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12574     }
12575   } Diagnoser;
12576 
12577   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12578 }
12579 
12580 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12581                                                  llvm::APSInt *Result,
12582                                                  unsigned DiagID,
12583                                                  bool AllowFold) {
12584   class IDDiagnoser : public VerifyICEDiagnoser {
12585     unsigned DiagID;
12586 
12587   public:
12588     IDDiagnoser(unsigned DiagID)
12589       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12590 
12591     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12592       S.Diag(Loc, DiagID) << SR;
12593     }
12594   } Diagnoser(DiagID);
12595 
12596   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12597 }
12598 
12599 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12600                                             SourceRange SR) {
12601   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12602 }
12603 
12604 ExprResult
12605 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12606                                       VerifyICEDiagnoser &Diagnoser,
12607                                       bool AllowFold) {
12608   SourceLocation DiagLoc = E->getLocStart();
12609 
12610   if (getLangOpts().CPlusPlus11) {
12611     // C++11 [expr.const]p5:
12612     //   If an expression of literal class type is used in a context where an
12613     //   integral constant expression is required, then that class type shall
12614     //   have a single non-explicit conversion function to an integral or
12615     //   unscoped enumeration type
12616     ExprResult Converted;
12617     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12618     public:
12619       CXX11ConvertDiagnoser(bool Silent)
12620           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12621                                 Silent, true) {}
12622 
12623       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12624                                            QualType T) override {
12625         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12626       }
12627 
12628       SemaDiagnosticBuilder diagnoseIncomplete(
12629           Sema &S, SourceLocation Loc, QualType T) override {
12630         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12631       }
12632 
12633       SemaDiagnosticBuilder diagnoseExplicitConv(
12634           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12635         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12636       }
12637 
12638       SemaDiagnosticBuilder noteExplicitConv(
12639           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12640         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12641                  << ConvTy->isEnumeralType() << ConvTy;
12642       }
12643 
12644       SemaDiagnosticBuilder diagnoseAmbiguous(
12645           Sema &S, SourceLocation Loc, QualType T) override {
12646         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12647       }
12648 
12649       SemaDiagnosticBuilder noteAmbiguous(
12650           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12651         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12652                  << ConvTy->isEnumeralType() << ConvTy;
12653       }
12654 
12655       SemaDiagnosticBuilder diagnoseConversion(
12656           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12657         llvm_unreachable("conversion functions are permitted");
12658       }
12659     } ConvertDiagnoser(Diagnoser.Suppress);
12660 
12661     Converted = PerformContextualImplicitConversion(DiagLoc, E,
12662                                                     ConvertDiagnoser);
12663     if (Converted.isInvalid())
12664       return Converted;
12665     E = Converted.get();
12666     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12667       return ExprError();
12668   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12669     // An ICE must be of integral or unscoped enumeration type.
12670     if (!Diagnoser.Suppress)
12671       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12672     return ExprError();
12673   }
12674 
12675   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12676   // in the non-ICE case.
12677   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12678     if (Result)
12679       *Result = E->EvaluateKnownConstInt(Context);
12680     return E;
12681   }
12682 
12683   Expr::EvalResult EvalResult;
12684   SmallVector<PartialDiagnosticAt, 8> Notes;
12685   EvalResult.Diag = &Notes;
12686 
12687   // Try to evaluate the expression, and produce diagnostics explaining why it's
12688   // not a constant expression as a side-effect.
12689   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12690                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12691 
12692   // In C++11, we can rely on diagnostics being produced for any expression
12693   // which is not a constant expression. If no diagnostics were produced, then
12694   // this is a constant expression.
12695   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12696     if (Result)
12697       *Result = EvalResult.Val.getInt();
12698     return E;
12699   }
12700 
12701   // If our only note is the usual "invalid subexpression" note, just point
12702   // the caret at its location rather than producing an essentially
12703   // redundant note.
12704   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12705         diag::note_invalid_subexpr_in_const_expr) {
12706     DiagLoc = Notes[0].first;
12707     Notes.clear();
12708   }
12709 
12710   if (!Folded || !AllowFold) {
12711     if (!Diagnoser.Suppress) {
12712       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12713       for (const PartialDiagnosticAt &Note : Notes)
12714         Diag(Note.first, Note.second);
12715     }
12716 
12717     return ExprError();
12718   }
12719 
12720   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
12721   for (const PartialDiagnosticAt &Note : Notes)
12722     Diag(Note.first, Note.second);
12723 
12724   if (Result)
12725     *Result = EvalResult.Val.getInt();
12726   return E;
12727 }
12728 
12729 namespace {
12730   // Handle the case where we conclude a expression which we speculatively
12731   // considered to be unevaluated is actually evaluated.
12732   class TransformToPE : public TreeTransform<TransformToPE> {
12733     typedef TreeTransform<TransformToPE> BaseTransform;
12734 
12735   public:
12736     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
12737 
12738     // Make sure we redo semantic analysis
12739     bool AlwaysRebuild() { return true; }
12740 
12741     // Make sure we handle LabelStmts correctly.
12742     // FIXME: This does the right thing, but maybe we need a more general
12743     // fix to TreeTransform?
12744     StmtResult TransformLabelStmt(LabelStmt *S) {
12745       S->getDecl()->setStmt(nullptr);
12746       return BaseTransform::TransformLabelStmt(S);
12747     }
12748 
12749     // We need to special-case DeclRefExprs referring to FieldDecls which
12750     // are not part of a member pointer formation; normal TreeTransforming
12751     // doesn't catch this case because of the way we represent them in the AST.
12752     // FIXME: This is a bit ugly; is it really the best way to handle this
12753     // case?
12754     //
12755     // Error on DeclRefExprs referring to FieldDecls.
12756     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
12757       if (isa<FieldDecl>(E->getDecl()) &&
12758           !SemaRef.isUnevaluatedContext())
12759         return SemaRef.Diag(E->getLocation(),
12760                             diag::err_invalid_non_static_member_use)
12761             << E->getDecl() << E->getSourceRange();
12762 
12763       return BaseTransform::TransformDeclRefExpr(E);
12764     }
12765 
12766     // Exception: filter out member pointer formation
12767     ExprResult TransformUnaryOperator(UnaryOperator *E) {
12768       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
12769         return E;
12770 
12771       return BaseTransform::TransformUnaryOperator(E);
12772     }
12773 
12774     ExprResult TransformLambdaExpr(LambdaExpr *E) {
12775       // Lambdas never need to be transformed.
12776       return E;
12777     }
12778   };
12779 }
12780 
12781 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
12782   assert(isUnevaluatedContext() &&
12783          "Should only transform unevaluated expressions");
12784   ExprEvalContexts.back().Context =
12785       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
12786   if (isUnevaluatedContext())
12787     return E;
12788   return TransformToPE(*this).TransformExpr(E);
12789 }
12790 
12791 void
12792 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12793                                       Decl *LambdaContextDecl,
12794                                       bool IsDecltype) {
12795   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(),
12796                                 ExprNeedsCleanups, LambdaContextDecl,
12797                                 IsDecltype);
12798   ExprNeedsCleanups = false;
12799   if (!MaybeODRUseExprs.empty())
12800     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
12801 }
12802 
12803 void
12804 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12805                                       ReuseLambdaContextDecl_t,
12806                                       bool IsDecltype) {
12807   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
12808   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
12809 }
12810 
12811 void Sema::PopExpressionEvaluationContext() {
12812   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
12813   unsigned NumTypos = Rec.NumTypos;
12814 
12815   if (!Rec.Lambdas.empty()) {
12816     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12817       unsigned D;
12818       if (Rec.isUnevaluated()) {
12819         // C++11 [expr.prim.lambda]p2:
12820         //   A lambda-expression shall not appear in an unevaluated operand
12821         //   (Clause 5).
12822         D = diag::err_lambda_unevaluated_operand;
12823       } else {
12824         // C++1y [expr.const]p2:
12825         //   A conditional-expression e is a core constant expression unless the
12826         //   evaluation of e, following the rules of the abstract machine, would
12827         //   evaluate [...] a lambda-expression.
12828         D = diag::err_lambda_in_constant_expression;
12829       }
12830       for (const auto *L : Rec.Lambdas)
12831         Diag(L->getLocStart(), D);
12832     } else {
12833       // Mark the capture expressions odr-used. This was deferred
12834       // during lambda expression creation.
12835       for (auto *Lambda : Rec.Lambdas) {
12836         for (auto *C : Lambda->capture_inits())
12837           MarkDeclarationsReferencedInExpr(C);
12838       }
12839     }
12840   }
12841 
12842   // When are coming out of an unevaluated context, clear out any
12843   // temporaries that we may have created as part of the evaluation of
12844   // the expression in that context: they aren't relevant because they
12845   // will never be constructed.
12846   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12847     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
12848                              ExprCleanupObjects.end());
12849     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
12850     CleanupVarDeclMarking();
12851     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
12852   // Otherwise, merge the contexts together.
12853   } else {
12854     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
12855     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
12856                             Rec.SavedMaybeODRUseExprs.end());
12857   }
12858 
12859   // Pop the current expression evaluation context off the stack.
12860   ExprEvalContexts.pop_back();
12861 
12862   if (!ExprEvalContexts.empty())
12863     ExprEvalContexts.back().NumTypos += NumTypos;
12864   else
12865     assert(NumTypos == 0 && "There are outstanding typos after popping the "
12866                             "last ExpressionEvaluationContextRecord");
12867 }
12868 
12869 void Sema::DiscardCleanupsInEvaluationContext() {
12870   ExprCleanupObjects.erase(
12871          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
12872          ExprCleanupObjects.end());
12873   ExprNeedsCleanups = false;
12874   MaybeODRUseExprs.clear();
12875 }
12876 
12877 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
12878   if (!E->getType()->isVariablyModifiedType())
12879     return E;
12880   return TransformToPotentiallyEvaluated(E);
12881 }
12882 
12883 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
12884   // Do not mark anything as "used" within a dependent context; wait for
12885   // an instantiation.
12886   if (SemaRef.CurContext->isDependentContext())
12887     return false;
12888 
12889   switch (SemaRef.ExprEvalContexts.back().Context) {
12890     case Sema::Unevaluated:
12891     case Sema::UnevaluatedAbstract:
12892       // We are in an expression that is not potentially evaluated; do nothing.
12893       // (Depending on how you read the standard, we actually do need to do
12894       // something here for null pointer constants, but the standard's
12895       // definition of a null pointer constant is completely crazy.)
12896       return false;
12897 
12898     case Sema::ConstantEvaluated:
12899     case Sema::PotentiallyEvaluated:
12900       // We are in a potentially evaluated expression (or a constant-expression
12901       // in C++03); we need to do implicit template instantiation, implicitly
12902       // define class members, and mark most declarations as used.
12903       return true;
12904 
12905     case Sema::PotentiallyEvaluatedIfUsed:
12906       // Referenced declarations will only be used if the construct in the
12907       // containing expression is used.
12908       return false;
12909   }
12910   llvm_unreachable("Invalid context");
12911 }
12912 
12913 /// \brief Mark a function referenced, and check whether it is odr-used
12914 /// (C++ [basic.def.odr]p2, C99 6.9p3)
12915 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
12916                                   bool MightBeOdrUse) {
12917   assert(Func && "No function?");
12918 
12919   Func->setReferenced();
12920 
12921   // C++11 [basic.def.odr]p3:
12922   //   A function whose name appears as a potentially-evaluated expression is
12923   //   odr-used if it is the unique lookup result or the selected member of a
12924   //   set of overloaded functions [...].
12925   //
12926   // We (incorrectly) mark overload resolution as an unevaluated context, so we
12927   // can just check that here.
12928   bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this);
12929 
12930   // Determine whether we require a function definition to exist, per
12931   // C++11 [temp.inst]p3:
12932   //   Unless a function template specialization has been explicitly
12933   //   instantiated or explicitly specialized, the function template
12934   //   specialization is implicitly instantiated when the specialization is
12935   //   referenced in a context that requires a function definition to exist.
12936   //
12937   // We consider constexpr function templates to be referenced in a context
12938   // that requires a definition to exist whenever they are referenced.
12939   //
12940   // FIXME: This instantiates constexpr functions too frequently. If this is
12941   // really an unevaluated context (and we're not just in the definition of a
12942   // function template or overload resolution or other cases which we
12943   // incorrectly consider to be unevaluated contexts), and we're not in a
12944   // subexpression which we actually need to evaluate (for instance, a
12945   // template argument, array bound or an expression in a braced-init-list),
12946   // we are not permitted to instantiate this constexpr function definition.
12947   //
12948   // FIXME: This also implicitly defines special members too frequently. They
12949   // are only supposed to be implicitly defined if they are odr-used, but they
12950   // are not odr-used from constant expressions in unevaluated contexts.
12951   // However, they cannot be referenced if they are deleted, and they are
12952   // deleted whenever the implicit definition of the special member would
12953   // fail (with very few exceptions).
12954   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
12955   bool NeedDefinition =
12956       OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() ||
12957                                          (MD && !MD->isUserProvided())));
12958 
12959   // C++14 [temp.expl.spec]p6:
12960   //   If a template [...] is explicitly specialized then that specialization
12961   //   shall be declared before the first use of that specialization that would
12962   //   cause an implicit instantiation to take place, in every translation unit
12963   //   in which such a use occurs
12964   if (NeedDefinition &&
12965       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
12966        Func->getMemberSpecializationInfo()))
12967     checkSpecializationVisibility(Loc, Func);
12968 
12969   // If we don't need to mark the function as used, and we don't need to
12970   // try to provide a definition, there's nothing more to do.
12971   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
12972       (!NeedDefinition || Func->getBody()))
12973     return;
12974 
12975   // Note that this declaration has been used.
12976   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
12977     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
12978     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
12979       if (Constructor->isDefaultConstructor()) {
12980         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
12981           return;
12982         DefineImplicitDefaultConstructor(Loc, Constructor);
12983       } else if (Constructor->isCopyConstructor()) {
12984         DefineImplicitCopyConstructor(Loc, Constructor);
12985       } else if (Constructor->isMoveConstructor()) {
12986         DefineImplicitMoveConstructor(Loc, Constructor);
12987       }
12988     } else if (Constructor->getInheritedConstructor()) {
12989       DefineInheritingConstructor(Loc, Constructor);
12990     }
12991   } else if (CXXDestructorDecl *Destructor =
12992                  dyn_cast<CXXDestructorDecl>(Func)) {
12993     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
12994     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
12995       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
12996         return;
12997       DefineImplicitDestructor(Loc, Destructor);
12998     }
12999     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13000       MarkVTableUsed(Loc, Destructor->getParent());
13001   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13002     if (MethodDecl->isOverloadedOperator() &&
13003         MethodDecl->getOverloadedOperator() == OO_Equal) {
13004       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13005       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13006         if (MethodDecl->isCopyAssignmentOperator())
13007           DefineImplicitCopyAssignment(Loc, MethodDecl);
13008         else
13009           DefineImplicitMoveAssignment(Loc, MethodDecl);
13010       }
13011     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13012                MethodDecl->getParent()->isLambda()) {
13013       CXXConversionDecl *Conversion =
13014           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13015       if (Conversion->isLambdaToBlockPointerConversion())
13016         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13017       else
13018         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13019     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13020       MarkVTableUsed(Loc, MethodDecl->getParent());
13021   }
13022 
13023   // Recursive functions should be marked when used from another function.
13024   // FIXME: Is this really right?
13025   if (CurContext == Func) return;
13026 
13027   // Resolve the exception specification for any function which is
13028   // used: CodeGen will need it.
13029   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13030   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13031     ResolveExceptionSpec(Loc, FPT);
13032 
13033   // Implicit instantiation of function templates and member functions of
13034   // class templates.
13035   if (Func->isImplicitlyInstantiable()) {
13036     bool AlreadyInstantiated = false;
13037     SourceLocation PointOfInstantiation = Loc;
13038     if (FunctionTemplateSpecializationInfo *SpecInfo
13039                               = Func->getTemplateSpecializationInfo()) {
13040       if (SpecInfo->getPointOfInstantiation().isInvalid())
13041         SpecInfo->setPointOfInstantiation(Loc);
13042       else if (SpecInfo->getTemplateSpecializationKind()
13043                  == TSK_ImplicitInstantiation) {
13044         AlreadyInstantiated = true;
13045         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13046       }
13047     } else if (MemberSpecializationInfo *MSInfo
13048                                 = Func->getMemberSpecializationInfo()) {
13049       if (MSInfo->getPointOfInstantiation().isInvalid())
13050         MSInfo->setPointOfInstantiation(Loc);
13051       else if (MSInfo->getTemplateSpecializationKind()
13052                  == TSK_ImplicitInstantiation) {
13053         AlreadyInstantiated = true;
13054         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13055       }
13056     }
13057 
13058     if (!AlreadyInstantiated || Func->isConstexpr()) {
13059       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13060           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13061           ActiveTemplateInstantiations.size())
13062         PendingLocalImplicitInstantiations.push_back(
13063             std::make_pair(Func, PointOfInstantiation));
13064       else if (Func->isConstexpr())
13065         // Do not defer instantiations of constexpr functions, to avoid the
13066         // expression evaluator needing to call back into Sema if it sees a
13067         // call to such a function.
13068         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13069       else {
13070         PendingInstantiations.push_back(std::make_pair(Func,
13071                                                        PointOfInstantiation));
13072         // Notify the consumer that a function was implicitly instantiated.
13073         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13074       }
13075     }
13076   } else {
13077     // Walk redefinitions, as some of them may be instantiable.
13078     for (auto i : Func->redecls()) {
13079       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13080         MarkFunctionReferenced(Loc, i, OdrUse);
13081     }
13082   }
13083 
13084   if (!OdrUse) return;
13085 
13086   // Keep track of used but undefined functions.
13087   if (!Func->isDefined()) {
13088     if (mightHaveNonExternalLinkage(Func))
13089       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13090     else if (Func->getMostRecentDecl()->isInlined() &&
13091              !LangOpts.GNUInline &&
13092              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13093       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13094   }
13095 
13096   Func->markUsed(Context);
13097 }
13098 
13099 static void
13100 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13101                                    VarDecl *var, DeclContext *DC) {
13102   DeclContext *VarDC = var->getDeclContext();
13103 
13104   //  If the parameter still belongs to the translation unit, then
13105   //  we're actually just using one parameter in the declaration of
13106   //  the next.
13107   if (isa<ParmVarDecl>(var) &&
13108       isa<TranslationUnitDecl>(VarDC))
13109     return;
13110 
13111   // For C code, don't diagnose about capture if we're not actually in code
13112   // right now; it's impossible to write a non-constant expression outside of
13113   // function context, so we'll get other (more useful) diagnostics later.
13114   //
13115   // For C++, things get a bit more nasty... it would be nice to suppress this
13116   // diagnostic for certain cases like using a local variable in an array bound
13117   // for a member of a local class, but the correct predicate is not obvious.
13118   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13119     return;
13120 
13121   if (isa<CXXMethodDecl>(VarDC) &&
13122       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13123     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
13124       << var->getIdentifier();
13125   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
13126     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
13127       << var->getIdentifier() << fn->getDeclName();
13128   } else if (isa<BlockDecl>(VarDC)) {
13129     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
13130       << var->getIdentifier();
13131   } else {
13132     // FIXME: Is there any other context where a local variable can be
13133     // declared?
13134     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
13135       << var->getIdentifier();
13136   }
13137 
13138   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13139       << var->getIdentifier();
13140 
13141   // FIXME: Add additional diagnostic info about class etc. which prevents
13142   // capture.
13143 }
13144 
13145 
13146 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13147                                       bool &SubCapturesAreNested,
13148                                       QualType &CaptureType,
13149                                       QualType &DeclRefType) {
13150    // Check whether we've already captured it.
13151   if (CSI->CaptureMap.count(Var)) {
13152     // If we found a capture, any subcaptures are nested.
13153     SubCapturesAreNested = true;
13154 
13155     // Retrieve the capture type for this variable.
13156     CaptureType = CSI->getCapture(Var).getCaptureType();
13157 
13158     // Compute the type of an expression that refers to this variable.
13159     DeclRefType = CaptureType.getNonReferenceType();
13160 
13161     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13162     // are mutable in the sense that user can change their value - they are
13163     // private instances of the captured declarations.
13164     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13165     if (Cap.isCopyCapture() &&
13166         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13167         !(isa<CapturedRegionScopeInfo>(CSI) &&
13168           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13169       DeclRefType.addConst();
13170     return true;
13171   }
13172   return false;
13173 }
13174 
13175 // Only block literals, captured statements, and lambda expressions can
13176 // capture; other scopes don't work.
13177 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13178                                  SourceLocation Loc,
13179                                  const bool Diagnose, Sema &S) {
13180   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13181     return getLambdaAwareParentOfDeclContext(DC);
13182   else if (Var->hasLocalStorage()) {
13183     if (Diagnose)
13184        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13185   }
13186   return nullptr;
13187 }
13188 
13189 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13190 // certain types of variables (unnamed, variably modified types etc.)
13191 // so check for eligibility.
13192 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13193                                  SourceLocation Loc,
13194                                  const bool Diagnose, Sema &S) {
13195 
13196   bool IsBlock = isa<BlockScopeInfo>(CSI);
13197   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13198 
13199   // Lambdas are not allowed to capture unnamed variables
13200   // (e.g. anonymous unions).
13201   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13202   // assuming that's the intent.
13203   if (IsLambda && !Var->getDeclName()) {
13204     if (Diagnose) {
13205       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13206       S.Diag(Var->getLocation(), diag::note_declared_at);
13207     }
13208     return false;
13209   }
13210 
13211   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13212   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13213     if (Diagnose) {
13214       S.Diag(Loc, diag::err_ref_vm_type);
13215       S.Diag(Var->getLocation(), diag::note_previous_decl)
13216         << Var->getDeclName();
13217     }
13218     return false;
13219   }
13220   // Prohibit structs with flexible array members too.
13221   // We cannot capture what is in the tail end of the struct.
13222   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13223     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13224       if (Diagnose) {
13225         if (IsBlock)
13226           S.Diag(Loc, diag::err_ref_flexarray_type);
13227         else
13228           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13229             << Var->getDeclName();
13230         S.Diag(Var->getLocation(), diag::note_previous_decl)
13231           << Var->getDeclName();
13232       }
13233       return false;
13234     }
13235   }
13236   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13237   // Lambdas and captured statements are not allowed to capture __block
13238   // variables; they don't support the expected semantics.
13239   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13240     if (Diagnose) {
13241       S.Diag(Loc, diag::err_capture_block_variable)
13242         << Var->getDeclName() << !IsLambda;
13243       S.Diag(Var->getLocation(), diag::note_previous_decl)
13244         << Var->getDeclName();
13245     }
13246     return false;
13247   }
13248 
13249   return true;
13250 }
13251 
13252 // Returns true if the capture by block was successful.
13253 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13254                                  SourceLocation Loc,
13255                                  const bool BuildAndDiagnose,
13256                                  QualType &CaptureType,
13257                                  QualType &DeclRefType,
13258                                  const bool Nested,
13259                                  Sema &S) {
13260   Expr *CopyExpr = nullptr;
13261   bool ByRef = false;
13262 
13263   // Blocks are not allowed to capture arrays.
13264   if (CaptureType->isArrayType()) {
13265     if (BuildAndDiagnose) {
13266       S.Diag(Loc, diag::err_ref_array_type);
13267       S.Diag(Var->getLocation(), diag::note_previous_decl)
13268       << Var->getDeclName();
13269     }
13270     return false;
13271   }
13272 
13273   // Forbid the block-capture of autoreleasing variables.
13274   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13275     if (BuildAndDiagnose) {
13276       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13277         << /*block*/ 0;
13278       S.Diag(Var->getLocation(), diag::note_previous_decl)
13279         << Var->getDeclName();
13280     }
13281     return false;
13282   }
13283   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13284   if (HasBlocksAttr || CaptureType->isReferenceType()) {
13285     // Block capture by reference does not change the capture or
13286     // declaration reference types.
13287     ByRef = true;
13288   } else {
13289     // Block capture by copy introduces 'const'.
13290     CaptureType = CaptureType.getNonReferenceType().withConst();
13291     DeclRefType = CaptureType;
13292 
13293     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13294       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13295         // The capture logic needs the destructor, so make sure we mark it.
13296         // Usually this is unnecessary because most local variables have
13297         // their destructors marked at declaration time, but parameters are
13298         // an exception because it's technically only the call site that
13299         // actually requires the destructor.
13300         if (isa<ParmVarDecl>(Var))
13301           S.FinalizeVarWithDestructor(Var, Record);
13302 
13303         // Enter a new evaluation context to insulate the copy
13304         // full-expression.
13305         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
13306 
13307         // According to the blocks spec, the capture of a variable from
13308         // the stack requires a const copy constructor.  This is not true
13309         // of the copy/move done to move a __block variable to the heap.
13310         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13311                                                   DeclRefType.withConst(),
13312                                                   VK_LValue, Loc);
13313 
13314         ExprResult Result
13315           = S.PerformCopyInitialization(
13316               InitializedEntity::InitializeBlock(Var->getLocation(),
13317                                                   CaptureType, false),
13318               Loc, DeclRef);
13319 
13320         // Build a full-expression copy expression if initialization
13321         // succeeded and used a non-trivial constructor.  Recover from
13322         // errors by pretending that the copy isn't necessary.
13323         if (!Result.isInvalid() &&
13324             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13325                 ->isTrivial()) {
13326           Result = S.MaybeCreateExprWithCleanups(Result);
13327           CopyExpr = Result.get();
13328         }
13329       }
13330     }
13331   }
13332 
13333   // Actually capture the variable.
13334   if (BuildAndDiagnose)
13335     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13336                     SourceLocation(), CaptureType, CopyExpr);
13337 
13338   return true;
13339 
13340 }
13341 
13342 
13343 /// \brief Capture the given variable in the captured region.
13344 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13345                                     VarDecl *Var,
13346                                     SourceLocation Loc,
13347                                     const bool BuildAndDiagnose,
13348                                     QualType &CaptureType,
13349                                     QualType &DeclRefType,
13350                                     const bool RefersToCapturedVariable,
13351                                     Sema &S) {
13352 
13353   // By default, capture variables by reference.
13354   bool ByRef = true;
13355   // Using an LValue reference type is consistent with Lambdas (see below).
13356   if (S.getLangOpts().OpenMP) {
13357     ByRef = S.IsOpenMPCapturedByRef(Var, RSI);
13358     if (S.IsOpenMPCapturedDecl(Var))
13359       DeclRefType = DeclRefType.getUnqualifiedType();
13360   }
13361 
13362   if (ByRef)
13363     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13364   else
13365     CaptureType = DeclRefType;
13366 
13367   Expr *CopyExpr = nullptr;
13368   if (BuildAndDiagnose) {
13369     // The current implementation assumes that all variables are captured
13370     // by references. Since there is no capture by copy, no expression
13371     // evaluation will be needed.
13372     RecordDecl *RD = RSI->TheRecordDecl;
13373 
13374     FieldDecl *Field
13375       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13376                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13377                           nullptr, false, ICIS_NoInit);
13378     Field->setImplicit(true);
13379     Field->setAccess(AS_private);
13380     RD->addDecl(Field);
13381 
13382     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13383                                             DeclRefType, VK_LValue, Loc);
13384     Var->setReferenced(true);
13385     Var->markUsed(S.Context);
13386   }
13387 
13388   // Actually capture the variable.
13389   if (BuildAndDiagnose)
13390     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13391                     SourceLocation(), CaptureType, CopyExpr);
13392 
13393 
13394   return true;
13395 }
13396 
13397 /// \brief Create a field within the lambda class for the variable
13398 /// being captured.
13399 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
13400                                     QualType FieldType, QualType DeclRefType,
13401                                     SourceLocation Loc,
13402                                     bool RefersToCapturedVariable) {
13403   CXXRecordDecl *Lambda = LSI->Lambda;
13404 
13405   // Build the non-static data member.
13406   FieldDecl *Field
13407     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13408                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13409                         nullptr, false, ICIS_NoInit);
13410   Field->setImplicit(true);
13411   Field->setAccess(AS_private);
13412   Lambda->addDecl(Field);
13413 }
13414 
13415 /// \brief Capture the given variable in the lambda.
13416 static bool captureInLambda(LambdaScopeInfo *LSI,
13417                             VarDecl *Var,
13418                             SourceLocation Loc,
13419                             const bool BuildAndDiagnose,
13420                             QualType &CaptureType,
13421                             QualType &DeclRefType,
13422                             const bool RefersToCapturedVariable,
13423                             const Sema::TryCaptureKind Kind,
13424                             SourceLocation EllipsisLoc,
13425                             const bool IsTopScope,
13426                             Sema &S) {
13427 
13428   // Determine whether we are capturing by reference or by value.
13429   bool ByRef = false;
13430   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13431     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13432   } else {
13433     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13434   }
13435 
13436   // Compute the type of the field that will capture this variable.
13437   if (ByRef) {
13438     // C++11 [expr.prim.lambda]p15:
13439     //   An entity is captured by reference if it is implicitly or
13440     //   explicitly captured but not captured by copy. It is
13441     //   unspecified whether additional unnamed non-static data
13442     //   members are declared in the closure type for entities
13443     //   captured by reference.
13444     //
13445     // FIXME: It is not clear whether we want to build an lvalue reference
13446     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13447     // to do the former, while EDG does the latter. Core issue 1249 will
13448     // clarify, but for now we follow GCC because it's a more permissive and
13449     // easily defensible position.
13450     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13451   } else {
13452     // C++11 [expr.prim.lambda]p14:
13453     //   For each entity captured by copy, an unnamed non-static
13454     //   data member is declared in the closure type. The
13455     //   declaration order of these members is unspecified. The type
13456     //   of such a data member is the type of the corresponding
13457     //   captured entity if the entity is not a reference to an
13458     //   object, or the referenced type otherwise. [Note: If the
13459     //   captured entity is a reference to a function, the
13460     //   corresponding data member is also a reference to a
13461     //   function. - end note ]
13462     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13463       if (!RefType->getPointeeType()->isFunctionType())
13464         CaptureType = RefType->getPointeeType();
13465     }
13466 
13467     // Forbid the lambda copy-capture of autoreleasing variables.
13468     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13469       if (BuildAndDiagnose) {
13470         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13471         S.Diag(Var->getLocation(), diag::note_previous_decl)
13472           << Var->getDeclName();
13473       }
13474       return false;
13475     }
13476 
13477     // Make sure that by-copy captures are of a complete and non-abstract type.
13478     if (BuildAndDiagnose) {
13479       if (!CaptureType->isDependentType() &&
13480           S.RequireCompleteType(Loc, CaptureType,
13481                                 diag::err_capture_of_incomplete_type,
13482                                 Var->getDeclName()))
13483         return false;
13484 
13485       if (S.RequireNonAbstractType(Loc, CaptureType,
13486                                    diag::err_capture_of_abstract_type))
13487         return false;
13488     }
13489   }
13490 
13491   // Capture this variable in the lambda.
13492   if (BuildAndDiagnose)
13493     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13494                             RefersToCapturedVariable);
13495 
13496   // Compute the type of a reference to this captured variable.
13497   if (ByRef)
13498     DeclRefType = CaptureType.getNonReferenceType();
13499   else {
13500     // C++ [expr.prim.lambda]p5:
13501     //   The closure type for a lambda-expression has a public inline
13502     //   function call operator [...]. This function call operator is
13503     //   declared const (9.3.1) if and only if the lambda-expression’s
13504     //   parameter-declaration-clause is not followed by mutable.
13505     DeclRefType = CaptureType.getNonReferenceType();
13506     if (!LSI->Mutable && !CaptureType->isReferenceType())
13507       DeclRefType.addConst();
13508   }
13509 
13510   // Add the capture.
13511   if (BuildAndDiagnose)
13512     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13513                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13514 
13515   return true;
13516 }
13517 
13518 bool Sema::tryCaptureVariable(
13519     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13520     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13521     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13522   // An init-capture is notionally from the context surrounding its
13523   // declaration, but its parent DC is the lambda class.
13524   DeclContext *VarDC = Var->getDeclContext();
13525   if (Var->isInitCapture())
13526     VarDC = VarDC->getParent();
13527 
13528   DeclContext *DC = CurContext;
13529   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13530       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13531   // We need to sync up the Declaration Context with the
13532   // FunctionScopeIndexToStopAt
13533   if (FunctionScopeIndexToStopAt) {
13534     unsigned FSIndex = FunctionScopes.size() - 1;
13535     while (FSIndex != MaxFunctionScopesIndex) {
13536       DC = getLambdaAwareParentOfDeclContext(DC);
13537       --FSIndex;
13538     }
13539   }
13540 
13541 
13542   // If the variable is declared in the current context, there is no need to
13543   // capture it.
13544   if (VarDC == DC) return true;
13545 
13546   // Capture global variables if it is required to use private copy of this
13547   // variable.
13548   bool IsGlobal = !Var->hasLocalStorage();
13549   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
13550     return true;
13551 
13552   // Walk up the stack to determine whether we can capture the variable,
13553   // performing the "simple" checks that don't depend on type. We stop when
13554   // we've either hit the declared scope of the variable or find an existing
13555   // capture of that variable.  We start from the innermost capturing-entity
13556   // (the DC) and ensure that all intervening capturing-entities
13557   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13558   // declcontext can either capture the variable or have already captured
13559   // the variable.
13560   CaptureType = Var->getType();
13561   DeclRefType = CaptureType.getNonReferenceType();
13562   bool Nested = false;
13563   bool Explicit = (Kind != TryCapture_Implicit);
13564   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13565   unsigned OpenMPLevel = 0;
13566   do {
13567     // Only block literals, captured statements, and lambda expressions can
13568     // capture; other scopes don't work.
13569     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13570                                                               ExprLoc,
13571                                                               BuildAndDiagnose,
13572                                                               *this);
13573     // We need to check for the parent *first* because, if we *have*
13574     // private-captured a global variable, we need to recursively capture it in
13575     // intermediate blocks, lambdas, etc.
13576     if (!ParentDC) {
13577       if (IsGlobal) {
13578         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13579         break;
13580       }
13581       return true;
13582     }
13583 
13584     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
13585     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13586 
13587 
13588     // Check whether we've already captured it.
13589     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13590                                              DeclRefType))
13591       break;
13592     // If we are instantiating a generic lambda call operator body,
13593     // we do not want to capture new variables.  What was captured
13594     // during either a lambdas transformation or initial parsing
13595     // should be used.
13596     if (isGenericLambdaCallOperatorSpecialization(DC)) {
13597       if (BuildAndDiagnose) {
13598         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13599         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13600           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13601           Diag(Var->getLocation(), diag::note_previous_decl)
13602              << Var->getDeclName();
13603           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13604         } else
13605           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13606       }
13607       return true;
13608     }
13609     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13610     // certain types of variables (unnamed, variably modified types etc.)
13611     // so check for eligibility.
13612     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
13613        return true;
13614 
13615     // Try to capture variable-length arrays types.
13616     if (Var->getType()->isVariablyModifiedType()) {
13617       // We're going to walk down into the type and look for VLA
13618       // expressions.
13619       QualType QTy = Var->getType();
13620       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13621         QTy = PVD->getOriginalType();
13622       captureVariablyModifiedType(Context, QTy, CSI);
13623     }
13624 
13625     if (getLangOpts().OpenMP) {
13626       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13627         // OpenMP private variables should not be captured in outer scope, so
13628         // just break here. Similarly, global variables that are captured in a
13629         // target region should not be captured outside the scope of the region.
13630         if (RSI->CapRegionKind == CR_OpenMP) {
13631           auto isTargetCap = isOpenMPTargetCapturedDecl(Var, OpenMPLevel);
13632           // When we detect target captures we are looking from inside the
13633           // target region, therefore we need to propagate the capture from the
13634           // enclosing region. Therefore, the capture is not initially nested.
13635           if (isTargetCap)
13636             FunctionScopesIndex--;
13637 
13638           if (isTargetCap || isOpenMPPrivateDecl(Var, OpenMPLevel)) {
13639             Nested = !isTargetCap;
13640             DeclRefType = DeclRefType.getUnqualifiedType();
13641             CaptureType = Context.getLValueReferenceType(DeclRefType);
13642             break;
13643           }
13644           ++OpenMPLevel;
13645         }
13646       }
13647     }
13648     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
13649       // No capture-default, and this is not an explicit capture
13650       // so cannot capture this variable.
13651       if (BuildAndDiagnose) {
13652         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13653         Diag(Var->getLocation(), diag::note_previous_decl)
13654           << Var->getDeclName();
13655         if (cast<LambdaScopeInfo>(CSI)->Lambda)
13656           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13657                diag::note_lambda_decl);
13658         // FIXME: If we error out because an outer lambda can not implicitly
13659         // capture a variable that an inner lambda explicitly captures, we
13660         // should have the inner lambda do the explicit capture - because
13661         // it makes for cleaner diagnostics later.  This would purely be done
13662         // so that the diagnostic does not misleadingly claim that a variable
13663         // can not be captured by a lambda implicitly even though it is captured
13664         // explicitly.  Suggestion:
13665         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
13666         //    at the function head
13667         //  - cache the StartingDeclContext - this must be a lambda
13668         //  - captureInLambda in the innermost lambda the variable.
13669       }
13670       return true;
13671     }
13672 
13673     FunctionScopesIndex--;
13674     DC = ParentDC;
13675     Explicit = false;
13676   } while (!VarDC->Equals(DC));
13677 
13678   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13679   // computing the type of the capture at each step, checking type-specific
13680   // requirements, and adding captures if requested.
13681   // If the variable had already been captured previously, we start capturing
13682   // at the lambda nested within that one.
13683   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
13684        ++I) {
13685     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
13686 
13687     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13688       if (!captureInBlock(BSI, Var, ExprLoc,
13689                           BuildAndDiagnose, CaptureType,
13690                           DeclRefType, Nested, *this))
13691         return true;
13692       Nested = true;
13693     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13694       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
13695                                    BuildAndDiagnose, CaptureType,
13696                                    DeclRefType, Nested, *this))
13697         return true;
13698       Nested = true;
13699     } else {
13700       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13701       if (!captureInLambda(LSI, Var, ExprLoc,
13702                            BuildAndDiagnose, CaptureType,
13703                            DeclRefType, Nested, Kind, EllipsisLoc,
13704                             /*IsTopScope*/I == N - 1, *this))
13705         return true;
13706       Nested = true;
13707     }
13708   }
13709   return false;
13710 }
13711 
13712 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
13713                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
13714   QualType CaptureType;
13715   QualType DeclRefType;
13716   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
13717                             /*BuildAndDiagnose=*/true, CaptureType,
13718                             DeclRefType, nullptr);
13719 }
13720 
13721 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
13722   QualType CaptureType;
13723   QualType DeclRefType;
13724   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13725                              /*BuildAndDiagnose=*/false, CaptureType,
13726                              DeclRefType, nullptr);
13727 }
13728 
13729 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
13730   QualType CaptureType;
13731   QualType DeclRefType;
13732 
13733   // Determine whether we can capture this variable.
13734   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13735                          /*BuildAndDiagnose=*/false, CaptureType,
13736                          DeclRefType, nullptr))
13737     return QualType();
13738 
13739   return DeclRefType;
13740 }
13741 
13742 
13743 
13744 // If either the type of the variable or the initializer is dependent,
13745 // return false. Otherwise, determine whether the variable is a constant
13746 // expression. Use this if you need to know if a variable that might or
13747 // might not be dependent is truly a constant expression.
13748 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
13749     ASTContext &Context) {
13750 
13751   if (Var->getType()->isDependentType())
13752     return false;
13753   const VarDecl *DefVD = nullptr;
13754   Var->getAnyInitializer(DefVD);
13755   if (!DefVD)
13756     return false;
13757   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
13758   Expr *Init = cast<Expr>(Eval->Value);
13759   if (Init->isValueDependent())
13760     return false;
13761   return IsVariableAConstantExpression(Var, Context);
13762 }
13763 
13764 
13765 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
13766   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
13767   // an object that satisfies the requirements for appearing in a
13768   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
13769   // is immediately applied."  This function handles the lvalue-to-rvalue
13770   // conversion part.
13771   MaybeODRUseExprs.erase(E->IgnoreParens());
13772 
13773   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
13774   // to a variable that is a constant expression, and if so, identify it as
13775   // a reference to a variable that does not involve an odr-use of that
13776   // variable.
13777   if (LambdaScopeInfo *LSI = getCurLambda()) {
13778     Expr *SansParensExpr = E->IgnoreParens();
13779     VarDecl *Var = nullptr;
13780     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
13781       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
13782     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
13783       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
13784 
13785     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
13786       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
13787   }
13788 }
13789 
13790 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
13791   Res = CorrectDelayedTyposInExpr(Res);
13792 
13793   if (!Res.isUsable())
13794     return Res;
13795 
13796   // If a constant-expression is a reference to a variable where we delay
13797   // deciding whether it is an odr-use, just assume we will apply the
13798   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
13799   // (a non-type template argument), we have special handling anyway.
13800   UpdateMarkingForLValueToRValue(Res.get());
13801   return Res;
13802 }
13803 
13804 void Sema::CleanupVarDeclMarking() {
13805   for (Expr *E : MaybeODRUseExprs) {
13806     VarDecl *Var;
13807     SourceLocation Loc;
13808     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13809       Var = cast<VarDecl>(DRE->getDecl());
13810       Loc = DRE->getLocation();
13811     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13812       Var = cast<VarDecl>(ME->getMemberDecl());
13813       Loc = ME->getMemberLoc();
13814     } else {
13815       llvm_unreachable("Unexpected expression");
13816     }
13817 
13818     MarkVarDeclODRUsed(Var, Loc, *this,
13819                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
13820   }
13821 
13822   MaybeODRUseExprs.clear();
13823 }
13824 
13825 
13826 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
13827                                     VarDecl *Var, Expr *E) {
13828   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
13829          "Invalid Expr argument to DoMarkVarDeclReferenced");
13830   Var->setReferenced();
13831 
13832   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
13833   bool MarkODRUsed = true;
13834 
13835   // If the context is not potentially evaluated, this is not an odr-use and
13836   // does not trigger instantiation.
13837   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
13838     if (SemaRef.isUnevaluatedContext())
13839       return;
13840 
13841     // If we don't yet know whether this context is going to end up being an
13842     // evaluated context, and we're referencing a variable from an enclosing
13843     // scope, add a potential capture.
13844     //
13845     // FIXME: Is this necessary? These contexts are only used for default
13846     // arguments, where local variables can't be used.
13847     const bool RefersToEnclosingScope =
13848         (SemaRef.CurContext != Var->getDeclContext() &&
13849          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
13850     if (RefersToEnclosingScope) {
13851       if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
13852         // If a variable could potentially be odr-used, defer marking it so
13853         // until we finish analyzing the full expression for any
13854         // lvalue-to-rvalue
13855         // or discarded value conversions that would obviate odr-use.
13856         // Add it to the list of potential captures that will be analyzed
13857         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
13858         // unless the variable is a reference that was initialized by a constant
13859         // expression (this will never need to be captured or odr-used).
13860         assert(E && "Capture variable should be used in an expression.");
13861         if (!Var->getType()->isReferenceType() ||
13862             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
13863           LSI->addPotentialCapture(E->IgnoreParens());
13864       }
13865     }
13866 
13867     if (!isTemplateInstantiation(TSK))
13868       return;
13869 
13870     // Instantiate, but do not mark as odr-used, variable templates.
13871     MarkODRUsed = false;
13872   }
13873 
13874   VarTemplateSpecializationDecl *VarSpec =
13875       dyn_cast<VarTemplateSpecializationDecl>(Var);
13876   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
13877          "Can't instantiate a partial template specialization.");
13878 
13879   // If this might be a member specialization of a static data member, check
13880   // the specialization is visible. We already did the checks for variable
13881   // template specializations when we created them.
13882   if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var))
13883     SemaRef.checkSpecializationVisibility(Loc, Var);
13884 
13885   // Perform implicit instantiation of static data members, static data member
13886   // templates of class templates, and variable template specializations. Delay
13887   // instantiations of variable templates, except for those that could be used
13888   // in a constant expression.
13889   if (isTemplateInstantiation(TSK)) {
13890     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
13891 
13892     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
13893       if (Var->getPointOfInstantiation().isInvalid()) {
13894         // This is a modification of an existing AST node. Notify listeners.
13895         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
13896           L->StaticDataMemberInstantiated(Var);
13897       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
13898         // Don't bother trying to instantiate it again, unless we might need
13899         // its initializer before we get to the end of the TU.
13900         TryInstantiating = false;
13901     }
13902 
13903     if (Var->getPointOfInstantiation().isInvalid())
13904       Var->setTemplateSpecializationKind(TSK, Loc);
13905 
13906     if (TryInstantiating) {
13907       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
13908       bool InstantiationDependent = false;
13909       bool IsNonDependent =
13910           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
13911                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
13912                   : true;
13913 
13914       // Do not instantiate specializations that are still type-dependent.
13915       if (IsNonDependent) {
13916         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
13917           // Do not defer instantiations of variables which could be used in a
13918           // constant expression.
13919           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
13920         } else {
13921           SemaRef.PendingInstantiations
13922               .push_back(std::make_pair(Var, PointOfInstantiation));
13923         }
13924       }
13925     }
13926   }
13927 
13928   if (!MarkODRUsed)
13929     return;
13930 
13931   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
13932   // the requirements for appearing in a constant expression (5.19) and, if
13933   // it is an object, the lvalue-to-rvalue conversion (4.1)
13934   // is immediately applied."  We check the first part here, and
13935   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
13936   // Note that we use the C++11 definition everywhere because nothing in
13937   // C++03 depends on whether we get the C++03 version correct. The second
13938   // part does not apply to references, since they are not objects.
13939   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
13940     // A reference initialized by a constant expression can never be
13941     // odr-used, so simply ignore it.
13942     if (!Var->getType()->isReferenceType())
13943       SemaRef.MaybeODRUseExprs.insert(E);
13944   } else
13945     MarkVarDeclODRUsed(Var, Loc, SemaRef,
13946                        /*MaxFunctionScopeIndex ptr*/ nullptr);
13947 }
13948 
13949 /// \brief Mark a variable referenced, and check whether it is odr-used
13950 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
13951 /// used directly for normal expressions referring to VarDecl.
13952 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
13953   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
13954 }
13955 
13956 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
13957                                Decl *D, Expr *E, bool MightBeOdrUse) {
13958   if (SemaRef.isInOpenMPDeclareTargetContext())
13959     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
13960 
13961   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
13962     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
13963     return;
13964   }
13965 
13966   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
13967 
13968   // If this is a call to a method via a cast, also mark the method in the
13969   // derived class used in case codegen can devirtualize the call.
13970   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13971   if (!ME)
13972     return;
13973   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
13974   if (!MD)
13975     return;
13976   // Only attempt to devirtualize if this is truly a virtual call.
13977   bool IsVirtualCall = MD->isVirtual() &&
13978                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
13979   if (!IsVirtualCall)
13980     return;
13981   const Expr *Base = ME->getBase();
13982   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
13983   if (!MostDerivedClassDecl)
13984     return;
13985   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
13986   if (!DM || DM->isPure())
13987     return;
13988   SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
13989 }
13990 
13991 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
13992 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
13993   // TODO: update this with DR# once a defect report is filed.
13994   // C++11 defect. The address of a pure member should not be an ODR use, even
13995   // if it's a qualified reference.
13996   bool OdrUse = true;
13997   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
13998     if (Method->isVirtual())
13999       OdrUse = false;
14000   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14001 }
14002 
14003 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14004 void Sema::MarkMemberReferenced(MemberExpr *E) {
14005   // C++11 [basic.def.odr]p2:
14006   //   A non-overloaded function whose name appears as a potentially-evaluated
14007   //   expression or a member of a set of candidate functions, if selected by
14008   //   overload resolution when referred to from a potentially-evaluated
14009   //   expression, is odr-used, unless it is a pure virtual function and its
14010   //   name is not explicitly qualified.
14011   bool MightBeOdrUse = true;
14012   if (E->performsVirtualDispatch(getLangOpts())) {
14013     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14014       if (Method->isPure())
14015         MightBeOdrUse = false;
14016   }
14017   SourceLocation Loc = E->getMemberLoc().isValid() ?
14018                             E->getMemberLoc() : E->getLocStart();
14019   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14020 }
14021 
14022 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14023 /// marks the declaration referenced, and performs odr-use checking for
14024 /// functions and variables. This method should not be used when building a
14025 /// normal expression which refers to a variable.
14026 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14027                                  bool MightBeOdrUse) {
14028   if (MightBeOdrUse) {
14029     if (auto *VD = dyn_cast<VarDecl>(D)) {
14030       MarkVariableReferenced(Loc, VD);
14031       return;
14032     }
14033   }
14034   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14035     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14036     return;
14037   }
14038   D->setReferenced();
14039 }
14040 
14041 namespace {
14042   // Mark all of the declarations referenced
14043   // FIXME: Not fully implemented yet! We need to have a better understanding
14044   // of when we're entering
14045   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14046     Sema &S;
14047     SourceLocation Loc;
14048 
14049   public:
14050     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14051 
14052     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14053 
14054     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14055     bool TraverseRecordType(RecordType *T);
14056   };
14057 }
14058 
14059 bool MarkReferencedDecls::TraverseTemplateArgument(
14060     const TemplateArgument &Arg) {
14061   if (Arg.getKind() == TemplateArgument::Declaration) {
14062     if (Decl *D = Arg.getAsDecl())
14063       S.MarkAnyDeclReferenced(Loc, D, true);
14064   }
14065 
14066   return Inherited::TraverseTemplateArgument(Arg);
14067 }
14068 
14069 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
14070   if (ClassTemplateSpecializationDecl *Spec
14071                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
14072     const TemplateArgumentList &Args = Spec->getTemplateArgs();
14073     return TraverseTemplateArguments(Args.data(), Args.size());
14074   }
14075 
14076   return true;
14077 }
14078 
14079 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14080   MarkReferencedDecls Marker(*this, Loc);
14081   Marker.TraverseType(Context.getCanonicalType(T));
14082 }
14083 
14084 namespace {
14085   /// \brief Helper class that marks all of the declarations referenced by
14086   /// potentially-evaluated subexpressions as "referenced".
14087   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14088     Sema &S;
14089     bool SkipLocalVariables;
14090 
14091   public:
14092     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14093 
14094     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14095       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14096 
14097     void VisitDeclRefExpr(DeclRefExpr *E) {
14098       // If we were asked not to visit local variables, don't.
14099       if (SkipLocalVariables) {
14100         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14101           if (VD->hasLocalStorage())
14102             return;
14103       }
14104 
14105       S.MarkDeclRefReferenced(E);
14106     }
14107 
14108     void VisitMemberExpr(MemberExpr *E) {
14109       S.MarkMemberReferenced(E);
14110       Inherited::VisitMemberExpr(E);
14111     }
14112 
14113     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14114       S.MarkFunctionReferenced(E->getLocStart(),
14115             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14116       Visit(E->getSubExpr());
14117     }
14118 
14119     void VisitCXXNewExpr(CXXNewExpr *E) {
14120       if (E->getOperatorNew())
14121         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14122       if (E->getOperatorDelete())
14123         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14124       Inherited::VisitCXXNewExpr(E);
14125     }
14126 
14127     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14128       if (E->getOperatorDelete())
14129         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14130       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14131       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14132         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14133         S.MarkFunctionReferenced(E->getLocStart(),
14134                                     S.LookupDestructor(Record));
14135       }
14136 
14137       Inherited::VisitCXXDeleteExpr(E);
14138     }
14139 
14140     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14141       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14142       Inherited::VisitCXXConstructExpr(E);
14143     }
14144 
14145     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14146       Visit(E->getExpr());
14147     }
14148 
14149     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14150       Inherited::VisitImplicitCastExpr(E);
14151 
14152       if (E->getCastKind() == CK_LValueToRValue)
14153         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14154     }
14155   };
14156 }
14157 
14158 /// \brief Mark any declarations that appear within this expression or any
14159 /// potentially-evaluated subexpressions as "referenced".
14160 ///
14161 /// \param SkipLocalVariables If true, don't mark local variables as
14162 /// 'referenced'.
14163 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14164                                             bool SkipLocalVariables) {
14165   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14166 }
14167 
14168 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14169 /// of the program being compiled.
14170 ///
14171 /// This routine emits the given diagnostic when the code currently being
14172 /// type-checked is "potentially evaluated", meaning that there is a
14173 /// possibility that the code will actually be executable. Code in sizeof()
14174 /// expressions, code used only during overload resolution, etc., are not
14175 /// potentially evaluated. This routine will suppress such diagnostics or,
14176 /// in the absolutely nutty case of potentially potentially evaluated
14177 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14178 /// later.
14179 ///
14180 /// This routine should be used for all diagnostics that describe the run-time
14181 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14182 /// Failure to do so will likely result in spurious diagnostics or failures
14183 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14184 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14185                                const PartialDiagnostic &PD) {
14186   switch (ExprEvalContexts.back().Context) {
14187   case Unevaluated:
14188   case UnevaluatedAbstract:
14189     // The argument will never be evaluated, so don't complain.
14190     break;
14191 
14192   case ConstantEvaluated:
14193     // Relevant diagnostics should be produced by constant evaluation.
14194     break;
14195 
14196   case PotentiallyEvaluated:
14197   case PotentiallyEvaluatedIfUsed:
14198     if (Statement && getCurFunctionOrMethodDecl()) {
14199       FunctionScopes.back()->PossiblyUnreachableDiags.
14200         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14201     }
14202     else
14203       Diag(Loc, PD);
14204 
14205     return true;
14206   }
14207 
14208   return false;
14209 }
14210 
14211 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14212                                CallExpr *CE, FunctionDecl *FD) {
14213   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14214     return false;
14215 
14216   // If we're inside a decltype's expression, don't check for a valid return
14217   // type or construct temporaries until we know whether this is the last call.
14218   if (ExprEvalContexts.back().IsDecltype) {
14219     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14220     return false;
14221   }
14222 
14223   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14224     FunctionDecl *FD;
14225     CallExpr *CE;
14226 
14227   public:
14228     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14229       : FD(FD), CE(CE) { }
14230 
14231     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14232       if (!FD) {
14233         S.Diag(Loc, diag::err_call_incomplete_return)
14234           << T << CE->getSourceRange();
14235         return;
14236       }
14237 
14238       S.Diag(Loc, diag::err_call_function_incomplete_return)
14239         << CE->getSourceRange() << FD->getDeclName() << T;
14240       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14241           << FD->getDeclName();
14242     }
14243   } Diagnoser(FD, CE);
14244 
14245   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14246     return true;
14247 
14248   return false;
14249 }
14250 
14251 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14252 // will prevent this condition from triggering, which is what we want.
14253 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14254   SourceLocation Loc;
14255 
14256   unsigned diagnostic = diag::warn_condition_is_assignment;
14257   bool IsOrAssign = false;
14258 
14259   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14260     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14261       return;
14262 
14263     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14264 
14265     // Greylist some idioms by putting them into a warning subcategory.
14266     if (ObjCMessageExpr *ME
14267           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14268       Selector Sel = ME->getSelector();
14269 
14270       // self = [<foo> init...]
14271       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14272         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14273 
14274       // <foo> = [<bar> nextObject]
14275       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14276         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14277     }
14278 
14279     Loc = Op->getOperatorLoc();
14280   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14281     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14282       return;
14283 
14284     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14285     Loc = Op->getOperatorLoc();
14286   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14287     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14288   else {
14289     // Not an assignment.
14290     return;
14291   }
14292 
14293   Diag(Loc, diagnostic) << E->getSourceRange();
14294 
14295   SourceLocation Open = E->getLocStart();
14296   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14297   Diag(Loc, diag::note_condition_assign_silence)
14298         << FixItHint::CreateInsertion(Open, "(")
14299         << FixItHint::CreateInsertion(Close, ")");
14300 
14301   if (IsOrAssign)
14302     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14303       << FixItHint::CreateReplacement(Loc, "!=");
14304   else
14305     Diag(Loc, diag::note_condition_assign_to_comparison)
14306       << FixItHint::CreateReplacement(Loc, "==");
14307 }
14308 
14309 /// \brief Redundant parentheses over an equality comparison can indicate
14310 /// that the user intended an assignment used as condition.
14311 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14312   // Don't warn if the parens came from a macro.
14313   SourceLocation parenLoc = ParenE->getLocStart();
14314   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14315     return;
14316   // Don't warn for dependent expressions.
14317   if (ParenE->isTypeDependent())
14318     return;
14319 
14320   Expr *E = ParenE->IgnoreParens();
14321 
14322   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14323     if (opE->getOpcode() == BO_EQ &&
14324         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14325                                                            == Expr::MLV_Valid) {
14326       SourceLocation Loc = opE->getOperatorLoc();
14327 
14328       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14329       SourceRange ParenERange = ParenE->getSourceRange();
14330       Diag(Loc, diag::note_equality_comparison_silence)
14331         << FixItHint::CreateRemoval(ParenERange.getBegin())
14332         << FixItHint::CreateRemoval(ParenERange.getEnd());
14333       Diag(Loc, diag::note_equality_comparison_to_assign)
14334         << FixItHint::CreateReplacement(Loc, "=");
14335     }
14336 }
14337 
14338 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
14339   DiagnoseAssignmentAsCondition(E);
14340   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14341     DiagnoseEqualityWithExtraParens(parenE);
14342 
14343   ExprResult result = CheckPlaceholderExpr(E);
14344   if (result.isInvalid()) return ExprError();
14345   E = result.get();
14346 
14347   if (!E->isTypeDependent()) {
14348     if (getLangOpts().CPlusPlus)
14349       return CheckCXXBooleanCondition(E); // C++ 6.4p4
14350 
14351     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14352     if (ERes.isInvalid())
14353       return ExprError();
14354     E = ERes.get();
14355 
14356     QualType T = E->getType();
14357     if (!T->isScalarType()) { // C99 6.8.4.1p1
14358       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14359         << T << E->getSourceRange();
14360       return ExprError();
14361     }
14362     CheckBoolLikeConversion(E, Loc);
14363   }
14364 
14365   return E;
14366 }
14367 
14368 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
14369                                        Expr *SubExpr) {
14370   if (!SubExpr)
14371     return ExprError();
14372 
14373   return CheckBooleanCondition(SubExpr, Loc);
14374 }
14375 
14376 namespace {
14377   /// A visitor for rebuilding a call to an __unknown_any expression
14378   /// to have an appropriate type.
14379   struct RebuildUnknownAnyFunction
14380     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14381 
14382     Sema &S;
14383 
14384     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14385 
14386     ExprResult VisitStmt(Stmt *S) {
14387       llvm_unreachable("unexpected statement!");
14388     }
14389 
14390     ExprResult VisitExpr(Expr *E) {
14391       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14392         << E->getSourceRange();
14393       return ExprError();
14394     }
14395 
14396     /// Rebuild an expression which simply semantically wraps another
14397     /// expression which it shares the type and value kind of.
14398     template <class T> ExprResult rebuildSugarExpr(T *E) {
14399       ExprResult SubResult = Visit(E->getSubExpr());
14400       if (SubResult.isInvalid()) return ExprError();
14401 
14402       Expr *SubExpr = SubResult.get();
14403       E->setSubExpr(SubExpr);
14404       E->setType(SubExpr->getType());
14405       E->setValueKind(SubExpr->getValueKind());
14406       assert(E->getObjectKind() == OK_Ordinary);
14407       return E;
14408     }
14409 
14410     ExprResult VisitParenExpr(ParenExpr *E) {
14411       return rebuildSugarExpr(E);
14412     }
14413 
14414     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14415       return rebuildSugarExpr(E);
14416     }
14417 
14418     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14419       ExprResult SubResult = Visit(E->getSubExpr());
14420       if (SubResult.isInvalid()) return ExprError();
14421 
14422       Expr *SubExpr = SubResult.get();
14423       E->setSubExpr(SubExpr);
14424       E->setType(S.Context.getPointerType(SubExpr->getType()));
14425       assert(E->getValueKind() == VK_RValue);
14426       assert(E->getObjectKind() == OK_Ordinary);
14427       return E;
14428     }
14429 
14430     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14431       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14432 
14433       E->setType(VD->getType());
14434 
14435       assert(E->getValueKind() == VK_RValue);
14436       if (S.getLangOpts().CPlusPlus &&
14437           !(isa<CXXMethodDecl>(VD) &&
14438             cast<CXXMethodDecl>(VD)->isInstance()))
14439         E->setValueKind(VK_LValue);
14440 
14441       return E;
14442     }
14443 
14444     ExprResult VisitMemberExpr(MemberExpr *E) {
14445       return resolveDecl(E, E->getMemberDecl());
14446     }
14447 
14448     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14449       return resolveDecl(E, E->getDecl());
14450     }
14451   };
14452 }
14453 
14454 /// Given a function expression of unknown-any type, try to rebuild it
14455 /// to have a function type.
14456 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14457   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14458   if (Result.isInvalid()) return ExprError();
14459   return S.DefaultFunctionArrayConversion(Result.get());
14460 }
14461 
14462 namespace {
14463   /// A visitor for rebuilding an expression of type __unknown_anytype
14464   /// into one which resolves the type directly on the referring
14465   /// expression.  Strict preservation of the original source
14466   /// structure is not a goal.
14467   struct RebuildUnknownAnyExpr
14468     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14469 
14470     Sema &S;
14471 
14472     /// The current destination type.
14473     QualType DestType;
14474 
14475     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14476       : S(S), DestType(CastType) {}
14477 
14478     ExprResult VisitStmt(Stmt *S) {
14479       llvm_unreachable("unexpected statement!");
14480     }
14481 
14482     ExprResult VisitExpr(Expr *E) {
14483       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14484         << E->getSourceRange();
14485       return ExprError();
14486     }
14487 
14488     ExprResult VisitCallExpr(CallExpr *E);
14489     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14490 
14491     /// Rebuild an expression which simply semantically wraps another
14492     /// expression which it shares the type and value kind of.
14493     template <class T> ExprResult rebuildSugarExpr(T *E) {
14494       ExprResult SubResult = Visit(E->getSubExpr());
14495       if (SubResult.isInvalid()) return ExprError();
14496       Expr *SubExpr = SubResult.get();
14497       E->setSubExpr(SubExpr);
14498       E->setType(SubExpr->getType());
14499       E->setValueKind(SubExpr->getValueKind());
14500       assert(E->getObjectKind() == OK_Ordinary);
14501       return E;
14502     }
14503 
14504     ExprResult VisitParenExpr(ParenExpr *E) {
14505       return rebuildSugarExpr(E);
14506     }
14507 
14508     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14509       return rebuildSugarExpr(E);
14510     }
14511 
14512     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14513       const PointerType *Ptr = DestType->getAs<PointerType>();
14514       if (!Ptr) {
14515         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14516           << E->getSourceRange();
14517         return ExprError();
14518       }
14519       assert(E->getValueKind() == VK_RValue);
14520       assert(E->getObjectKind() == OK_Ordinary);
14521       E->setType(DestType);
14522 
14523       // Build the sub-expression as if it were an object of the pointee type.
14524       DestType = Ptr->getPointeeType();
14525       ExprResult SubResult = Visit(E->getSubExpr());
14526       if (SubResult.isInvalid()) return ExprError();
14527       E->setSubExpr(SubResult.get());
14528       return E;
14529     }
14530 
14531     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14532 
14533     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14534 
14535     ExprResult VisitMemberExpr(MemberExpr *E) {
14536       return resolveDecl(E, E->getMemberDecl());
14537     }
14538 
14539     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14540       return resolveDecl(E, E->getDecl());
14541     }
14542   };
14543 }
14544 
14545 /// Rebuilds a call expression which yielded __unknown_anytype.
14546 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14547   Expr *CalleeExpr = E->getCallee();
14548 
14549   enum FnKind {
14550     FK_MemberFunction,
14551     FK_FunctionPointer,
14552     FK_BlockPointer
14553   };
14554 
14555   FnKind Kind;
14556   QualType CalleeType = CalleeExpr->getType();
14557   if (CalleeType == S.Context.BoundMemberTy) {
14558     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14559     Kind = FK_MemberFunction;
14560     CalleeType = Expr::findBoundMemberType(CalleeExpr);
14561   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14562     CalleeType = Ptr->getPointeeType();
14563     Kind = FK_FunctionPointer;
14564   } else {
14565     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14566     Kind = FK_BlockPointer;
14567   }
14568   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14569 
14570   // Verify that this is a legal result type of a function.
14571   if (DestType->isArrayType() || DestType->isFunctionType()) {
14572     unsigned diagID = diag::err_func_returning_array_function;
14573     if (Kind == FK_BlockPointer)
14574       diagID = diag::err_block_returning_array_function;
14575 
14576     S.Diag(E->getExprLoc(), diagID)
14577       << DestType->isFunctionType() << DestType;
14578     return ExprError();
14579   }
14580 
14581   // Otherwise, go ahead and set DestType as the call's result.
14582   E->setType(DestType.getNonLValueExprType(S.Context));
14583   E->setValueKind(Expr::getValueKindForType(DestType));
14584   assert(E->getObjectKind() == OK_Ordinary);
14585 
14586   // Rebuild the function type, replacing the result type with DestType.
14587   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14588   if (Proto) {
14589     // __unknown_anytype(...) is a special case used by the debugger when
14590     // it has no idea what a function's signature is.
14591     //
14592     // We want to build this call essentially under the K&R
14593     // unprototyped rules, but making a FunctionNoProtoType in C++
14594     // would foul up all sorts of assumptions.  However, we cannot
14595     // simply pass all arguments as variadic arguments, nor can we
14596     // portably just call the function under a non-variadic type; see
14597     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14598     // However, it turns out that in practice it is generally safe to
14599     // call a function declared as "A foo(B,C,D);" under the prototype
14600     // "A foo(B,C,D,...);".  The only known exception is with the
14601     // Windows ABI, where any variadic function is implicitly cdecl
14602     // regardless of its normal CC.  Therefore we change the parameter
14603     // types to match the types of the arguments.
14604     //
14605     // This is a hack, but it is far superior to moving the
14606     // corresponding target-specific code from IR-gen to Sema/AST.
14607 
14608     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
14609     SmallVector<QualType, 8> ArgTypes;
14610     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14611       ArgTypes.reserve(E->getNumArgs());
14612       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14613         Expr *Arg = E->getArg(i);
14614         QualType ArgType = Arg->getType();
14615         if (E->isLValue()) {
14616           ArgType = S.Context.getLValueReferenceType(ArgType);
14617         } else if (E->isXValue()) {
14618           ArgType = S.Context.getRValueReferenceType(ArgType);
14619         }
14620         ArgTypes.push_back(ArgType);
14621       }
14622       ParamTypes = ArgTypes;
14623     }
14624     DestType = S.Context.getFunctionType(DestType, ParamTypes,
14625                                          Proto->getExtProtoInfo());
14626   } else {
14627     DestType = S.Context.getFunctionNoProtoType(DestType,
14628                                                 FnType->getExtInfo());
14629   }
14630 
14631   // Rebuild the appropriate pointer-to-function type.
14632   switch (Kind) {
14633   case FK_MemberFunction:
14634     // Nothing to do.
14635     break;
14636 
14637   case FK_FunctionPointer:
14638     DestType = S.Context.getPointerType(DestType);
14639     break;
14640 
14641   case FK_BlockPointer:
14642     DestType = S.Context.getBlockPointerType(DestType);
14643     break;
14644   }
14645 
14646   // Finally, we can recurse.
14647   ExprResult CalleeResult = Visit(CalleeExpr);
14648   if (!CalleeResult.isUsable()) return ExprError();
14649   E->setCallee(CalleeResult.get());
14650 
14651   // Bind a temporary if necessary.
14652   return S.MaybeBindToTemporary(E);
14653 }
14654 
14655 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
14656   // Verify that this is a legal result type of a call.
14657   if (DestType->isArrayType() || DestType->isFunctionType()) {
14658     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
14659       << DestType->isFunctionType() << DestType;
14660     return ExprError();
14661   }
14662 
14663   // Rewrite the method result type if available.
14664   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
14665     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
14666     Method->setReturnType(DestType);
14667   }
14668 
14669   // Change the type of the message.
14670   E->setType(DestType.getNonReferenceType());
14671   E->setValueKind(Expr::getValueKindForType(DestType));
14672 
14673   return S.MaybeBindToTemporary(E);
14674 }
14675 
14676 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
14677   // The only case we should ever see here is a function-to-pointer decay.
14678   if (E->getCastKind() == CK_FunctionToPointerDecay) {
14679     assert(E->getValueKind() == VK_RValue);
14680     assert(E->getObjectKind() == OK_Ordinary);
14681 
14682     E->setType(DestType);
14683 
14684     // Rebuild the sub-expression as the pointee (function) type.
14685     DestType = DestType->castAs<PointerType>()->getPointeeType();
14686 
14687     ExprResult Result = Visit(E->getSubExpr());
14688     if (!Result.isUsable()) return ExprError();
14689 
14690     E->setSubExpr(Result.get());
14691     return E;
14692   } else if (E->getCastKind() == CK_LValueToRValue) {
14693     assert(E->getValueKind() == VK_RValue);
14694     assert(E->getObjectKind() == OK_Ordinary);
14695 
14696     assert(isa<BlockPointerType>(E->getType()));
14697 
14698     E->setType(DestType);
14699 
14700     // The sub-expression has to be a lvalue reference, so rebuild it as such.
14701     DestType = S.Context.getLValueReferenceType(DestType);
14702 
14703     ExprResult Result = Visit(E->getSubExpr());
14704     if (!Result.isUsable()) return ExprError();
14705 
14706     E->setSubExpr(Result.get());
14707     return E;
14708   } else {
14709     llvm_unreachable("Unhandled cast type!");
14710   }
14711 }
14712 
14713 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
14714   ExprValueKind ValueKind = VK_LValue;
14715   QualType Type = DestType;
14716 
14717   // We know how to make this work for certain kinds of decls:
14718 
14719   //  - functions
14720   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
14721     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
14722       DestType = Ptr->getPointeeType();
14723       ExprResult Result = resolveDecl(E, VD);
14724       if (Result.isInvalid()) return ExprError();
14725       return S.ImpCastExprToType(Result.get(), Type,
14726                                  CK_FunctionToPointerDecay, VK_RValue);
14727     }
14728 
14729     if (!Type->isFunctionType()) {
14730       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
14731         << VD << E->getSourceRange();
14732       return ExprError();
14733     }
14734     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
14735       // We must match the FunctionDecl's type to the hack introduced in
14736       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
14737       // type. See the lengthy commentary in that routine.
14738       QualType FDT = FD->getType();
14739       const FunctionType *FnType = FDT->castAs<FunctionType>();
14740       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
14741       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14742       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
14743         SourceLocation Loc = FD->getLocation();
14744         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
14745                                       FD->getDeclContext(),
14746                                       Loc, Loc, FD->getNameInfo().getName(),
14747                                       DestType, FD->getTypeSourceInfo(),
14748                                       SC_None, false/*isInlineSpecified*/,
14749                                       FD->hasPrototype(),
14750                                       false/*isConstexprSpecified*/);
14751 
14752         if (FD->getQualifier())
14753           NewFD->setQualifierInfo(FD->getQualifierLoc());
14754 
14755         SmallVector<ParmVarDecl*, 16> Params;
14756         for (const auto &AI : FT->param_types()) {
14757           ParmVarDecl *Param =
14758             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
14759           Param->setScopeInfo(0, Params.size());
14760           Params.push_back(Param);
14761         }
14762         NewFD->setParams(Params);
14763         DRE->setDecl(NewFD);
14764         VD = DRE->getDecl();
14765       }
14766     }
14767 
14768     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
14769       if (MD->isInstance()) {
14770         ValueKind = VK_RValue;
14771         Type = S.Context.BoundMemberTy;
14772       }
14773 
14774     // Function references aren't l-values in C.
14775     if (!S.getLangOpts().CPlusPlus)
14776       ValueKind = VK_RValue;
14777 
14778   //  - variables
14779   } else if (isa<VarDecl>(VD)) {
14780     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
14781       Type = RefTy->getPointeeType();
14782     } else if (Type->isFunctionType()) {
14783       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
14784         << VD << E->getSourceRange();
14785       return ExprError();
14786     }
14787 
14788   //  - nothing else
14789   } else {
14790     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
14791       << VD << E->getSourceRange();
14792     return ExprError();
14793   }
14794 
14795   // Modifying the declaration like this is friendly to IR-gen but
14796   // also really dangerous.
14797   VD->setType(DestType);
14798   E->setType(Type);
14799   E->setValueKind(ValueKind);
14800   return E;
14801 }
14802 
14803 /// Check a cast of an unknown-any type.  We intentionally only
14804 /// trigger this for C-style casts.
14805 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
14806                                      Expr *CastExpr, CastKind &CastKind,
14807                                      ExprValueKind &VK, CXXCastPath &Path) {
14808   // The type we're casting to must be either void or complete.
14809   if (!CastType->isVoidType() &&
14810       RequireCompleteType(TypeRange.getBegin(), CastType,
14811                           diag::err_typecheck_cast_to_incomplete))
14812     return ExprError();
14813 
14814   // Rewrite the casted expression from scratch.
14815   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
14816   if (!result.isUsable()) return ExprError();
14817 
14818   CastExpr = result.get();
14819   VK = CastExpr->getValueKind();
14820   CastKind = CK_NoOp;
14821 
14822   return CastExpr;
14823 }
14824 
14825 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
14826   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
14827 }
14828 
14829 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
14830                                     Expr *arg, QualType &paramType) {
14831   // If the syntactic form of the argument is not an explicit cast of
14832   // any sort, just do default argument promotion.
14833   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
14834   if (!castArg) {
14835     ExprResult result = DefaultArgumentPromotion(arg);
14836     if (result.isInvalid()) return ExprError();
14837     paramType = result.get()->getType();
14838     return result;
14839   }
14840 
14841   // Otherwise, use the type that was written in the explicit cast.
14842   assert(!arg->hasPlaceholderType());
14843   paramType = castArg->getTypeAsWritten();
14844 
14845   // Copy-initialize a parameter of that type.
14846   InitializedEntity entity =
14847     InitializedEntity::InitializeParameter(Context, paramType,
14848                                            /*consumed*/ false);
14849   return PerformCopyInitialization(entity, callLoc, arg);
14850 }
14851 
14852 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
14853   Expr *orig = E;
14854   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
14855   while (true) {
14856     E = E->IgnoreParenImpCasts();
14857     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
14858       E = call->getCallee();
14859       diagID = diag::err_uncasted_call_of_unknown_any;
14860     } else {
14861       break;
14862     }
14863   }
14864 
14865   SourceLocation loc;
14866   NamedDecl *d;
14867   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
14868     loc = ref->getLocation();
14869     d = ref->getDecl();
14870   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
14871     loc = mem->getMemberLoc();
14872     d = mem->getMemberDecl();
14873   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
14874     diagID = diag::err_uncasted_call_of_unknown_any;
14875     loc = msg->getSelectorStartLoc();
14876     d = msg->getMethodDecl();
14877     if (!d) {
14878       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
14879         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
14880         << orig->getSourceRange();
14881       return ExprError();
14882     }
14883   } else {
14884     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14885       << E->getSourceRange();
14886     return ExprError();
14887   }
14888 
14889   S.Diag(loc, diagID) << d << orig->getSourceRange();
14890 
14891   // Never recoverable.
14892   return ExprError();
14893 }
14894 
14895 /// Check for operands with placeholder types and complain if found.
14896 /// Returns true if there was an error and no recovery was possible.
14897 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
14898   if (!getLangOpts().CPlusPlus) {
14899     // C cannot handle TypoExpr nodes on either side of a binop because it
14900     // doesn't handle dependent types properly, so make sure any TypoExprs have
14901     // been dealt with before checking the operands.
14902     ExprResult Result = CorrectDelayedTyposInExpr(E);
14903     if (!Result.isUsable()) return ExprError();
14904     E = Result.get();
14905   }
14906 
14907   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
14908   if (!placeholderType) return E;
14909 
14910   switch (placeholderType->getKind()) {
14911 
14912   // Overloaded expressions.
14913   case BuiltinType::Overload: {
14914     // Try to resolve a single function template specialization.
14915     // This is obligatory.
14916     ExprResult result = E;
14917     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
14918       return result;
14919 
14920     // If that failed, try to recover with a call.
14921     } else {
14922       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
14923                            /*complain*/ true);
14924       return result;
14925     }
14926   }
14927 
14928   // Bound member functions.
14929   case BuiltinType::BoundMember: {
14930     ExprResult result = E;
14931     const Expr *BME = E->IgnoreParens();
14932     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
14933     // Try to give a nicer diagnostic if it is a bound member that we recognize.
14934     if (isa<CXXPseudoDestructorExpr>(BME)) {
14935       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
14936     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
14937       if (ME->getMemberNameInfo().getName().getNameKind() ==
14938           DeclarationName::CXXDestructorName)
14939         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
14940     }
14941     tryToRecoverWithCall(result, PD,
14942                          /*complain*/ true);
14943     return result;
14944   }
14945 
14946   // ARC unbridged casts.
14947   case BuiltinType::ARCUnbridgedCast: {
14948     Expr *realCast = stripARCUnbridgedCast(E);
14949     diagnoseARCUnbridgedCast(realCast);
14950     return realCast;
14951   }
14952 
14953   // Expressions of unknown type.
14954   case BuiltinType::UnknownAny:
14955     return diagnoseUnknownAnyExpr(*this, E);
14956 
14957   // Pseudo-objects.
14958   case BuiltinType::PseudoObject:
14959     return checkPseudoObjectRValue(E);
14960 
14961   case BuiltinType::BuiltinFn: {
14962     // Accept __noop without parens by implicitly converting it to a call expr.
14963     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
14964     if (DRE) {
14965       auto *FD = cast<FunctionDecl>(DRE->getDecl());
14966       if (FD->getBuiltinID() == Builtin::BI__noop) {
14967         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
14968                               CK_BuiltinFnToFnPtr).get();
14969         return new (Context) CallExpr(Context, E, None, Context.IntTy,
14970                                       VK_RValue, SourceLocation());
14971       }
14972     }
14973 
14974     Diag(E->getLocStart(), diag::err_builtin_fn_use);
14975     return ExprError();
14976   }
14977 
14978   // Expressions of unknown type.
14979   case BuiltinType::OMPArraySection:
14980     Diag(E->getLocStart(), diag::err_omp_array_section_use);
14981     return ExprError();
14982 
14983   // Everything else should be impossible.
14984 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
14985   case BuiltinType::Id:
14986 #include "clang/Basic/OpenCLImageTypes.def"
14987 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
14988 #define PLACEHOLDER_TYPE(Id, SingletonId)
14989 #include "clang/AST/BuiltinTypes.def"
14990     break;
14991   }
14992 
14993   llvm_unreachable("invalid placeholder type!");
14994 }
14995 
14996 bool Sema::CheckCaseExpression(Expr *E) {
14997   if (E->isTypeDependent())
14998     return true;
14999   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15000     return E->getType()->isIntegralOrEnumerationType();
15001   return false;
15002 }
15003 
15004 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15005 ExprResult
15006 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15007   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15008          "Unknown Objective-C Boolean value!");
15009   QualType BoolT = Context.ObjCBuiltinBoolTy;
15010   if (!Context.getBOOLDecl()) {
15011     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15012                         Sema::LookupOrdinaryName);
15013     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15014       NamedDecl *ND = Result.getFoundDecl();
15015       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15016         Context.setBOOLDecl(TD);
15017     }
15018   }
15019   if (Context.getBOOLDecl())
15020     BoolT = Context.getBOOLType();
15021   return new (Context)
15022       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15023 }
15024