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/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/Support/ConvertUTF.h"
46 using namespace clang;
47 using namespace sema;
48 
49 /// \brief Determine whether the use of this declaration is valid, without
50 /// emitting diagnostics.
51 bool Sema::CanUseDecl(NamedDecl *D) {
52   // See if this is an auto-typed variable whose initializer we are parsing.
53   if (ParsingInitForAutoVars.count(D))
54     return false;
55 
56   // See if this is a deleted function.
57   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
58     if (FD->isDeleted())
59       return false;
60 
61     // If the function has a deduced return type, and we can't deduce it,
62     // then we can't use it either.
63     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
64         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
65       return false;
66   }
67 
68   // See if this function is unavailable.
69   if (D->getAvailability() == AR_Unavailable &&
70       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
71     return false;
72 
73   return true;
74 }
75 
76 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
77   // Warn if this is used but marked unused.
78   if (D->hasAttr<UnusedAttr>()) {
79     const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
80     if (DC && !DC->hasAttr<UnusedAttr>())
81       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
82   }
83 }
84 
85 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
86   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
87   if (!OMD)
88     return false;
89   const ObjCInterfaceDecl *OID = OMD->getClassInterface();
90   if (!OID)
91     return false;
92 
93   for (const ObjCCategoryDecl *Cat : OID->visible_categories())
94     if (ObjCMethodDecl *CatMeth =
95             Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
96       if (!CatMeth->hasAttr<AvailabilityAttr>())
97         return true;
98   return false;
99 }
100 
101 static AvailabilityResult
102 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
103                            const ObjCInterfaceDecl *UnknownObjCClass,
104                            bool ObjCPropertyAccess) {
105   // See if this declaration is unavailable or deprecated.
106   std::string Message;
107   AvailabilityResult Result = D->getAvailability(&Message);
108 
109   // For typedefs, if the typedef declaration appears available look
110   // to the underlying type to see if it is more restrictive.
111   while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
112     if (Result == AR_Available) {
113       if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
114         D = TT->getDecl();
115         Result = D->getAvailability(&Message);
116         continue;
117       }
118     }
119     break;
120   }
121 
122   // Forward class declarations get their attributes from their definition.
123   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
124     if (IDecl->getDefinition()) {
125       D = IDecl->getDefinition();
126       Result = D->getAvailability(&Message);
127     }
128   }
129 
130   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
131     if (Result == AR_Available) {
132       const DeclContext *DC = ECD->getDeclContext();
133       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
134         Result = TheEnumDecl->getAvailability(&Message);
135     }
136 
137   const ObjCPropertyDecl *ObjCPDecl = nullptr;
138   if (Result == AR_Deprecated || Result == AR_Unavailable ||
139       AR_NotYetIntroduced) {
140     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
141       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
142         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
143         if (PDeclResult == Result)
144           ObjCPDecl = PD;
145       }
146     }
147   }
148 
149   switch (Result) {
150     case AR_Available:
151       break;
152 
153     case AR_Deprecated:
154       if (S.getCurContextAvailability() != AR_Deprecated)
155         S.EmitAvailabilityWarning(Sema::AD_Deprecation,
156                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
157                                   ObjCPropertyAccess);
158       break;
159 
160     case AR_NotYetIntroduced: {
161       // Don't do this for enums, they can't be redeclared.
162       if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
163         break;
164 
165       bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
166       // Objective-C method declarations in categories are not modelled as
167       // redeclarations, so manually look for a redeclaration in a category
168       // if necessary.
169       if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
170         Warn = false;
171       // In general, D will point to the most recent redeclaration. However,
172       // for `@class A;` decls, this isn't true -- manually go through the
173       // redecl chain in that case.
174       if (Warn && isa<ObjCInterfaceDecl>(D))
175         for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
176              Redecl = Redecl->getPreviousDecl())
177           if (!Redecl->hasAttr<AvailabilityAttr>() ||
178               Redecl->getAttr<AvailabilityAttr>()->isInherited())
179             Warn = false;
180 
181       if (Warn)
182         S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc,
183                                   UnknownObjCClass, ObjCPDecl,
184                                   ObjCPropertyAccess);
185       break;
186     }
187 
188     case AR_Unavailable:
189       if (S.getCurContextAvailability() != AR_Unavailable)
190         S.EmitAvailabilityWarning(Sema::AD_Unavailable,
191                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
192                                   ObjCPropertyAccess);
193       break;
194 
195     }
196     return Result;
197 }
198 
199 /// \brief Emit a note explaining that this function is deleted.
200 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
201   assert(Decl->isDeleted());
202 
203   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
204 
205   if (Method && Method->isDeleted() && Method->isDefaulted()) {
206     // If the method was explicitly defaulted, point at that declaration.
207     if (!Method->isImplicit())
208       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
209 
210     // Try to diagnose why this special member function was implicitly
211     // deleted. This might fail, if that reason no longer applies.
212     CXXSpecialMember CSM = getSpecialMember(Method);
213     if (CSM != CXXInvalid)
214       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
215 
216     return;
217   }
218 
219   if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
220     if (CXXConstructorDecl *BaseCD =
221             const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
222       Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
223       if (BaseCD->isDeleted()) {
224         NoteDeletedFunction(BaseCD);
225       } else {
226         // FIXME: An explanation of why exactly it can't be inherited
227         // would be nice.
228         Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
229       }
230       return;
231     }
232   }
233 
234   Diag(Decl->getLocation(), diag::note_availability_specified_here)
235     << Decl << true;
236 }
237 
238 /// \brief Determine whether a FunctionDecl was ever declared with an
239 /// explicit storage class.
240 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
241   for (auto I : D->redecls()) {
242     if (I->getStorageClass() != SC_None)
243       return true;
244   }
245   return false;
246 }
247 
248 /// \brief Check whether we're in an extern inline function and referring to a
249 /// variable or function with internal linkage (C11 6.7.4p3).
250 ///
251 /// This is only a warning because we used to silently accept this code, but
252 /// in many cases it will not behave correctly. This is not enabled in C++ mode
253 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
254 /// and so while there may still be user mistakes, most of the time we can't
255 /// prove that there are errors.
256 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
257                                                       const NamedDecl *D,
258                                                       SourceLocation Loc) {
259   // This is disabled under C++; there are too many ways for this to fire in
260   // contexts where the warning is a false positive, or where it is technically
261   // correct but benign.
262   if (S.getLangOpts().CPlusPlus)
263     return;
264 
265   // Check if this is an inlined function or method.
266   FunctionDecl *Current = S.getCurFunctionDecl();
267   if (!Current)
268     return;
269   if (!Current->isInlined())
270     return;
271   if (!Current->isExternallyVisible())
272     return;
273 
274   // Check if the decl has internal linkage.
275   if (D->getFormalLinkage() != InternalLinkage)
276     return;
277 
278   // Downgrade from ExtWarn to Extension if
279   //  (1) the supposedly external inline function is in the main file,
280   //      and probably won't be included anywhere else.
281   //  (2) the thing we're referencing is a pure function.
282   //  (3) the thing we're referencing is another inline function.
283   // This last can give us false negatives, but it's better than warning on
284   // wrappers for simple C library functions.
285   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
286   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
287   if (!DowngradeWarning && UsedFn)
288     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
289 
290   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
291                                : diag::ext_internal_in_extern_inline)
292     << /*IsVar=*/!UsedFn << D;
293 
294   S.MaybeSuggestAddingStaticToDecl(Current);
295 
296   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
297       << D;
298 }
299 
300 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
301   const FunctionDecl *First = Cur->getFirstDecl();
302 
303   // Suggest "static" on the function, if possible.
304   if (!hasAnyExplicitStorageClass(First)) {
305     SourceLocation DeclBegin = First->getSourceRange().getBegin();
306     Diag(DeclBegin, diag::note_convert_inline_to_static)
307       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
308   }
309 }
310 
311 /// \brief Determine whether the use of this declaration is valid, and
312 /// emit any corresponding diagnostics.
313 ///
314 /// This routine diagnoses various problems with referencing
315 /// declarations that can occur when using a declaration. For example,
316 /// it might warn if a deprecated or unavailable declaration is being
317 /// used, or produce an error (and return true) if a C++0x deleted
318 /// function is being used.
319 ///
320 /// \returns true if there was an error (this declaration cannot be
321 /// referenced), false otherwise.
322 ///
323 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
324                              const ObjCInterfaceDecl *UnknownObjCClass,
325                              bool ObjCPropertyAccess) {
326   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
327     // If there were any diagnostics suppressed by template argument deduction,
328     // emit them now.
329     SuppressedDiagnosticsMap::iterator
330       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
331     if (Pos != SuppressedDiagnostics.end()) {
332       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
333       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
334         Diag(Suppressed[I].first, Suppressed[I].second);
335 
336       // Clear out the list of suppressed diagnostics, so that we don't emit
337       // them again for this specialization. However, we don't obsolete this
338       // entry from the table, because we want to avoid ever emitting these
339       // diagnostics again.
340       Suppressed.clear();
341     }
342 
343     // C++ [basic.start.main]p3:
344     //   The function 'main' shall not be used within a program.
345     if (cast<FunctionDecl>(D)->isMain())
346       Diag(Loc, diag::ext_main_used);
347   }
348 
349   // See if this is an auto-typed variable whose initializer we are parsing.
350   if (ParsingInitForAutoVars.count(D)) {
351     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
352       << D->getDeclName();
353     return true;
354   }
355 
356   // See if this is a deleted function.
357   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
358     if (FD->isDeleted()) {
359       Diag(Loc, diag::err_deleted_function_use);
360       NoteDeletedFunction(FD);
361       return true;
362     }
363 
364     // If the function has a deduced return type, and we can't deduce it,
365     // then we can't use it either.
366     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
367         DeduceReturnType(FD, Loc))
368       return true;
369   }
370   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
371                              ObjCPropertyAccess);
372 
373   DiagnoseUnusedOfDecl(*this, D, Loc);
374 
375   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
376 
377   return false;
378 }
379 
380 /// \brief Retrieve the message suffix that should be added to a
381 /// diagnostic complaining about the given function being deleted or
382 /// unavailable.
383 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
384   std::string Message;
385   if (FD->getAvailability(&Message))
386     return ": " + Message;
387 
388   return std::string();
389 }
390 
391 /// DiagnoseSentinelCalls - This routine checks whether a call or
392 /// message-send is to a declaration with the sentinel attribute, and
393 /// if so, it checks that the requirements of the sentinel are
394 /// satisfied.
395 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
396                                  ArrayRef<Expr *> Args) {
397   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
398   if (!attr)
399     return;
400 
401   // The number of formal parameters of the declaration.
402   unsigned numFormalParams;
403 
404   // The kind of declaration.  This is also an index into a %select in
405   // the diagnostic.
406   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
407 
408   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
409     numFormalParams = MD->param_size();
410     calleeType = CT_Method;
411   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
412     numFormalParams = FD->param_size();
413     calleeType = CT_Function;
414   } else if (isa<VarDecl>(D)) {
415     QualType type = cast<ValueDecl>(D)->getType();
416     const FunctionType *fn = nullptr;
417     if (const PointerType *ptr = type->getAs<PointerType>()) {
418       fn = ptr->getPointeeType()->getAs<FunctionType>();
419       if (!fn) return;
420       calleeType = CT_Function;
421     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
422       fn = ptr->getPointeeType()->castAs<FunctionType>();
423       calleeType = CT_Block;
424     } else {
425       return;
426     }
427 
428     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
429       numFormalParams = proto->getNumParams();
430     } else {
431       numFormalParams = 0;
432     }
433   } else {
434     return;
435   }
436 
437   // "nullPos" is the number of formal parameters at the end which
438   // effectively count as part of the variadic arguments.  This is
439   // useful if you would prefer to not have *any* formal parameters,
440   // but the language forces you to have at least one.
441   unsigned nullPos = attr->getNullPos();
442   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
443   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
444 
445   // The number of arguments which should follow the sentinel.
446   unsigned numArgsAfterSentinel = attr->getSentinel();
447 
448   // If there aren't enough arguments for all the formal parameters,
449   // the sentinel, and the args after the sentinel, complain.
450   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
451     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
452     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
453     return;
454   }
455 
456   // Otherwise, find the sentinel expression.
457   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
458   if (!sentinelExpr) return;
459   if (sentinelExpr->isValueDependent()) return;
460   if (Context.isSentinelNullExpr(sentinelExpr)) return;
461 
462   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
463   // or 'NULL' if those are actually defined in the context.  Only use
464   // 'nil' for ObjC methods, where it's much more likely that the
465   // variadic arguments form a list of object pointers.
466   SourceLocation MissingNilLoc
467     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
468   std::string NullValue;
469   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
470     NullValue = "nil";
471   else if (getLangOpts().CPlusPlus11)
472     NullValue = "nullptr";
473   else if (PP.isMacroDefined("NULL"))
474     NullValue = "NULL";
475   else
476     NullValue = "(void*) 0";
477 
478   if (MissingNilLoc.isInvalid())
479     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
480   else
481     Diag(MissingNilLoc, diag::warn_missing_sentinel)
482       << int(calleeType)
483       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
484   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
485 }
486 
487 SourceRange Sema::getExprRange(Expr *E) const {
488   return E ? E->getSourceRange() : SourceRange();
489 }
490 
491 //===----------------------------------------------------------------------===//
492 //  Standard Promotions and Conversions
493 //===----------------------------------------------------------------------===//
494 
495 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
496 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
497   // Handle any placeholder expressions which made it here.
498   if (E->getType()->isPlaceholderType()) {
499     ExprResult result = CheckPlaceholderExpr(E);
500     if (result.isInvalid()) return ExprError();
501     E = result.get();
502   }
503 
504   QualType Ty = E->getType();
505   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
506 
507   if (Ty->isFunctionType()) {
508     // If we are here, we are not calling a function but taking
509     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
510     if (getLangOpts().OpenCL) {
511       Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
512       return ExprError();
513     }
514     E = ImpCastExprToType(E, Context.getPointerType(Ty),
515                           CK_FunctionToPointerDecay).get();
516   } else if (Ty->isArrayType()) {
517     // In C90 mode, arrays only promote to pointers if the array expression is
518     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
519     // type 'array of type' is converted to an expression that has type 'pointer
520     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
521     // that has type 'array of type' ...".  The relevant change is "an lvalue"
522     // (C90) to "an expression" (C99).
523     //
524     // C++ 4.2p1:
525     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
526     // T" can be converted to an rvalue of type "pointer to T".
527     //
528     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
529       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
530                             CK_ArrayToPointerDecay).get();
531   }
532   return E;
533 }
534 
535 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
536   // Check to see if we are dereferencing a null pointer.  If so,
537   // and if not volatile-qualified, this is undefined behavior that the
538   // optimizer will delete, so warn about it.  People sometimes try to use this
539   // to get a deterministic trap and are surprised by clang's behavior.  This
540   // only handles the pattern "*null", which is a very syntactic check.
541   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
542     if (UO->getOpcode() == UO_Deref &&
543         UO->getSubExpr()->IgnoreParenCasts()->
544           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
545         !UO->getType().isVolatileQualified()) {
546     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
547                           S.PDiag(diag::warn_indirection_through_null)
548                             << UO->getSubExpr()->getSourceRange());
549     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
550                         S.PDiag(diag::note_indirection_through_null));
551   }
552 }
553 
554 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
555                                     SourceLocation AssignLoc,
556                                     const Expr* RHS) {
557   const ObjCIvarDecl *IV = OIRE->getDecl();
558   if (!IV)
559     return;
560 
561   DeclarationName MemberName = IV->getDeclName();
562   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
563   if (!Member || !Member->isStr("isa"))
564     return;
565 
566   const Expr *Base = OIRE->getBase();
567   QualType BaseType = Base->getType();
568   if (OIRE->isArrow())
569     BaseType = BaseType->getPointeeType();
570   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
571     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
572       ObjCInterfaceDecl *ClassDeclared = nullptr;
573       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
574       if (!ClassDeclared->getSuperClass()
575           && (*ClassDeclared->ivar_begin()) == IV) {
576         if (RHS) {
577           NamedDecl *ObjectSetClass =
578             S.LookupSingleName(S.TUScope,
579                                &S.Context.Idents.get("object_setClass"),
580                                SourceLocation(), S.LookupOrdinaryName);
581           if (ObjectSetClass) {
582             SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
583             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
584             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
585             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
586                                                      AssignLoc), ",") <<
587             FixItHint::CreateInsertion(RHSLocEnd, ")");
588           }
589           else
590             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
591         } else {
592           NamedDecl *ObjectGetClass =
593             S.LookupSingleName(S.TUScope,
594                                &S.Context.Idents.get("object_getClass"),
595                                SourceLocation(), S.LookupOrdinaryName);
596           if (ObjectGetClass)
597             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
598             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
599             FixItHint::CreateReplacement(
600                                          SourceRange(OIRE->getOpLoc(),
601                                                      OIRE->getLocEnd()), ")");
602           else
603             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
604         }
605         S.Diag(IV->getLocation(), diag::note_ivar_decl);
606       }
607     }
608 }
609 
610 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
611   // Handle any placeholder expressions which made it here.
612   if (E->getType()->isPlaceholderType()) {
613     ExprResult result = CheckPlaceholderExpr(E);
614     if (result.isInvalid()) return ExprError();
615     E = result.get();
616   }
617 
618   // C++ [conv.lval]p1:
619   //   A glvalue of a non-function, non-array type T can be
620   //   converted to a prvalue.
621   if (!E->isGLValue()) return E;
622 
623   QualType T = E->getType();
624   assert(!T.isNull() && "r-value conversion on typeless expression?");
625 
626   // We don't want to throw lvalue-to-rvalue casts on top of
627   // expressions of certain types in C++.
628   if (getLangOpts().CPlusPlus &&
629       (E->getType() == Context.OverloadTy ||
630        T->isDependentType() ||
631        T->isRecordType()))
632     return E;
633 
634   // The C standard is actually really unclear on this point, and
635   // DR106 tells us what the result should be but not why.  It's
636   // generally best to say that void types just doesn't undergo
637   // lvalue-to-rvalue at all.  Note that expressions of unqualified
638   // 'void' type are never l-values, but qualified void can be.
639   if (T->isVoidType())
640     return E;
641 
642   // OpenCL usually rejects direct accesses to values of 'half' type.
643   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
644       T->isHalfType()) {
645     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
646       << 0 << T;
647     return ExprError();
648   }
649 
650   CheckForNullPointerDereference(*this, E);
651   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
652     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
653                                      &Context.Idents.get("object_getClass"),
654                                      SourceLocation(), LookupOrdinaryName);
655     if (ObjectGetClass)
656       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
657         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
658         FixItHint::CreateReplacement(
659                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
660     else
661       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
662   }
663   else if (const ObjCIvarRefExpr *OIRE =
664             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
665     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
666 
667   // C++ [conv.lval]p1:
668   //   [...] If T is a non-class type, the type of the prvalue is the
669   //   cv-unqualified version of T. Otherwise, the type of the
670   //   rvalue is T.
671   //
672   // C99 6.3.2.1p2:
673   //   If the lvalue has qualified type, the value has the unqualified
674   //   version of the type of the lvalue; otherwise, the value has the
675   //   type of the lvalue.
676   if (T.hasQualifiers())
677     T = T.getUnqualifiedType();
678 
679   UpdateMarkingForLValueToRValue(E);
680 
681   // Loading a __weak object implicitly retains the value, so we need a cleanup to
682   // balance that.
683   if (getLangOpts().ObjCAutoRefCount &&
684       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
685     ExprNeedsCleanups = true;
686 
687   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
688                                             nullptr, VK_RValue);
689 
690   // C11 6.3.2.1p2:
691   //   ... if the lvalue has atomic type, the value has the non-atomic version
692   //   of the type of the lvalue ...
693   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
694     T = Atomic->getValueType().getUnqualifiedType();
695     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
696                                    nullptr, VK_RValue);
697   }
698 
699   return Res;
700 }
701 
702 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
703   ExprResult Res = DefaultFunctionArrayConversion(E);
704   if (Res.isInvalid())
705     return ExprError();
706   Res = DefaultLvalueConversion(Res.get());
707   if (Res.isInvalid())
708     return ExprError();
709   return Res;
710 }
711 
712 /// CallExprUnaryConversions - a special case of an unary conversion
713 /// performed on a function designator of a call expression.
714 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
715   QualType Ty = E->getType();
716   ExprResult Res = E;
717   // Only do implicit cast for a function type, but not for a pointer
718   // to function type.
719   if (Ty->isFunctionType()) {
720     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
721                             CK_FunctionToPointerDecay).get();
722     if (Res.isInvalid())
723       return ExprError();
724   }
725   Res = DefaultLvalueConversion(Res.get());
726   if (Res.isInvalid())
727     return ExprError();
728   return Res.get();
729 }
730 
731 /// UsualUnaryConversions - Performs various conversions that are common to most
732 /// operators (C99 6.3). The conversions of array and function types are
733 /// sometimes suppressed. For example, the array->pointer conversion doesn't
734 /// apply if the array is an argument to the sizeof or address (&) operators.
735 /// In these instances, this routine should *not* be called.
736 ExprResult Sema::UsualUnaryConversions(Expr *E) {
737   // First, convert to an r-value.
738   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
739   if (Res.isInvalid())
740     return ExprError();
741   E = Res.get();
742 
743   QualType Ty = E->getType();
744   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
745 
746   // Half FP have to be promoted to float unless it is natively supported
747   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
748     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
749 
750   // Try to perform integral promotions if the object has a theoretically
751   // promotable type.
752   if (Ty->isIntegralOrUnscopedEnumerationType()) {
753     // C99 6.3.1.1p2:
754     //
755     //   The following may be used in an expression wherever an int or
756     //   unsigned int may be used:
757     //     - an object or expression with an integer type whose integer
758     //       conversion rank is less than or equal to the rank of int
759     //       and unsigned int.
760     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
761     //
762     //   If an int can represent all values of the original type, the
763     //   value is converted to an int; otherwise, it is converted to an
764     //   unsigned int. These are called the integer promotions. All
765     //   other types are unchanged by the integer promotions.
766 
767     QualType PTy = Context.isPromotableBitField(E);
768     if (!PTy.isNull()) {
769       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
770       return E;
771     }
772     if (Ty->isPromotableIntegerType()) {
773       QualType PT = Context.getPromotedIntegerType(Ty);
774       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
775       return E;
776     }
777   }
778   return E;
779 }
780 
781 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
782 /// do not have a prototype. Arguments that have type float or __fp16
783 /// are promoted to double. All other argument types are converted by
784 /// UsualUnaryConversions().
785 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
786   QualType Ty = E->getType();
787   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
788 
789   ExprResult Res = UsualUnaryConversions(E);
790   if (Res.isInvalid())
791     return ExprError();
792   E = Res.get();
793 
794   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
795   // double.
796   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
797   if (BTy && (BTy->getKind() == BuiltinType::Half ||
798               BTy->getKind() == BuiltinType::Float))
799     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
800 
801   // C++ performs lvalue-to-rvalue conversion as a default argument
802   // promotion, even on class types, but note:
803   //   C++11 [conv.lval]p2:
804   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
805   //     operand or a subexpression thereof the value contained in the
806   //     referenced object is not accessed. Otherwise, if the glvalue
807   //     has a class type, the conversion copy-initializes a temporary
808   //     of type T from the glvalue and the result of the conversion
809   //     is a prvalue for the temporary.
810   // FIXME: add some way to gate this entire thing for correctness in
811   // potentially potentially evaluated contexts.
812   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
813     ExprResult Temp = PerformCopyInitialization(
814                        InitializedEntity::InitializeTemporary(E->getType()),
815                                                 E->getExprLoc(), E);
816     if (Temp.isInvalid())
817       return ExprError();
818     E = Temp.get();
819   }
820 
821   return E;
822 }
823 
824 /// Determine the degree of POD-ness for an expression.
825 /// Incomplete types are considered POD, since this check can be performed
826 /// when we're in an unevaluated context.
827 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
828   if (Ty->isIncompleteType()) {
829     // C++11 [expr.call]p7:
830     //   After these conversions, if the argument does not have arithmetic,
831     //   enumeration, pointer, pointer to member, or class type, the program
832     //   is ill-formed.
833     //
834     // Since we've already performed array-to-pointer and function-to-pointer
835     // decay, the only such type in C++ is cv void. This also handles
836     // initializer lists as variadic arguments.
837     if (Ty->isVoidType())
838       return VAK_Invalid;
839 
840     if (Ty->isObjCObjectType())
841       return VAK_Invalid;
842     return VAK_Valid;
843   }
844 
845   if (Ty.isCXX98PODType(Context))
846     return VAK_Valid;
847 
848   // C++11 [expr.call]p7:
849   //   Passing a potentially-evaluated argument of class type (Clause 9)
850   //   having a non-trivial copy constructor, a non-trivial move constructor,
851   //   or a non-trivial destructor, with no corresponding parameter,
852   //   is conditionally-supported with implementation-defined semantics.
853   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
854     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
855       if (!Record->hasNonTrivialCopyConstructor() &&
856           !Record->hasNonTrivialMoveConstructor() &&
857           !Record->hasNonTrivialDestructor())
858         return VAK_ValidInCXX11;
859 
860   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
861     return VAK_Valid;
862 
863   if (Ty->isObjCObjectType())
864     return VAK_Invalid;
865 
866   if (getLangOpts().MSVCCompat)
867     return VAK_MSVCUndefined;
868 
869   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
870   // permitted to reject them. We should consider doing so.
871   return VAK_Undefined;
872 }
873 
874 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
875   // Don't allow one to pass an Objective-C interface to a vararg.
876   const QualType &Ty = E->getType();
877   VarArgKind VAK = isValidVarArgType(Ty);
878 
879   // Complain about passing non-POD types through varargs.
880   switch (VAK) {
881   case VAK_ValidInCXX11:
882     DiagRuntimeBehavior(
883         E->getLocStart(), nullptr,
884         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
885           << Ty << CT);
886     // Fall through.
887   case VAK_Valid:
888     if (Ty->isRecordType()) {
889       // This is unlikely to be what the user intended. If the class has a
890       // 'c_str' member function, the user probably meant to call that.
891       DiagRuntimeBehavior(E->getLocStart(), nullptr,
892                           PDiag(diag::warn_pass_class_arg_to_vararg)
893                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
894     }
895     break;
896 
897   case VAK_Undefined:
898   case VAK_MSVCUndefined:
899     DiagRuntimeBehavior(
900         E->getLocStart(), nullptr,
901         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
902           << getLangOpts().CPlusPlus11 << Ty << CT);
903     break;
904 
905   case VAK_Invalid:
906     if (Ty->isObjCObjectType())
907       DiagRuntimeBehavior(
908           E->getLocStart(), nullptr,
909           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
910             << Ty << CT);
911     else
912       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
913         << isa<InitListExpr>(E) << Ty << CT;
914     break;
915   }
916 }
917 
918 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
919 /// will create a trap if the resulting type is not a POD type.
920 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
921                                                   FunctionDecl *FDecl) {
922   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
923     // Strip the unbridged-cast placeholder expression off, if applicable.
924     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
925         (CT == VariadicMethod ||
926          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
927       E = stripARCUnbridgedCast(E);
928 
929     // Otherwise, do normal placeholder checking.
930     } else {
931       ExprResult ExprRes = CheckPlaceholderExpr(E);
932       if (ExprRes.isInvalid())
933         return ExprError();
934       E = ExprRes.get();
935     }
936   }
937 
938   ExprResult ExprRes = DefaultArgumentPromotion(E);
939   if (ExprRes.isInvalid())
940     return ExprError();
941   E = ExprRes.get();
942 
943   // Diagnostics regarding non-POD argument types are
944   // emitted along with format string checking in Sema::CheckFunctionCall().
945   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
946     // Turn this into a trap.
947     CXXScopeSpec SS;
948     SourceLocation TemplateKWLoc;
949     UnqualifiedId Name;
950     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
951                        E->getLocStart());
952     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
953                                           Name, true, false);
954     if (TrapFn.isInvalid())
955       return ExprError();
956 
957     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
958                                     E->getLocStart(), None,
959                                     E->getLocEnd());
960     if (Call.isInvalid())
961       return ExprError();
962 
963     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
964                                   Call.get(), E);
965     if (Comma.isInvalid())
966       return ExprError();
967     return Comma.get();
968   }
969 
970   if (!getLangOpts().CPlusPlus &&
971       RequireCompleteType(E->getExprLoc(), E->getType(),
972                           diag::err_call_incomplete_argument))
973     return ExprError();
974 
975   return E;
976 }
977 
978 /// \brief Converts an integer to complex float type.  Helper function of
979 /// UsualArithmeticConversions()
980 ///
981 /// \return false if the integer expression is an integer type and is
982 /// successfully converted to the complex type.
983 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
984                                                   ExprResult &ComplexExpr,
985                                                   QualType IntTy,
986                                                   QualType ComplexTy,
987                                                   bool SkipCast) {
988   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
989   if (SkipCast) return false;
990   if (IntTy->isIntegerType()) {
991     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
992     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
993     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
994                                   CK_FloatingRealToComplex);
995   } else {
996     assert(IntTy->isComplexIntegerType());
997     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
998                                   CK_IntegralComplexToFloatingComplex);
999   }
1000   return false;
1001 }
1002 
1003 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1004 /// UsualArithmeticConversions()
1005 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1006                                              ExprResult &RHS, QualType LHSType,
1007                                              QualType RHSType,
1008                                              bool IsCompAssign) {
1009   // if we have an integer operand, the result is the complex type.
1010   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1011                                              /*skipCast*/false))
1012     return LHSType;
1013   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1014                                              /*skipCast*/IsCompAssign))
1015     return RHSType;
1016 
1017   // This handles complex/complex, complex/float, or float/complex.
1018   // When both operands are complex, the shorter operand is converted to the
1019   // type of the longer, and that is the type of the result. This corresponds
1020   // to what is done when combining two real floating-point operands.
1021   // The fun begins when size promotion occur across type domains.
1022   // From H&S 6.3.4: When one operand is complex and the other is a real
1023   // floating-point type, the less precise type is converted, within it's
1024   // real or complex domain, to the precision of the other type. For example,
1025   // when combining a "long double" with a "double _Complex", the
1026   // "double _Complex" is promoted to "long double _Complex".
1027 
1028   // Compute the rank of the two types, regardless of whether they are complex.
1029   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1030 
1031   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1032   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1033   QualType LHSElementType =
1034       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1035   QualType RHSElementType =
1036       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1037 
1038   QualType ResultType = S.Context.getComplexType(LHSElementType);
1039   if (Order < 0) {
1040     // Promote the precision of the LHS if not an assignment.
1041     ResultType = S.Context.getComplexType(RHSElementType);
1042     if (!IsCompAssign) {
1043       if (LHSComplexType)
1044         LHS =
1045             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1046       else
1047         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1048     }
1049   } else if (Order > 0) {
1050     // Promote the precision of the RHS.
1051     if (RHSComplexType)
1052       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1053     else
1054       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1055   }
1056   return ResultType;
1057 }
1058 
1059 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1060 /// of UsualArithmeticConversions()
1061 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1062                                            ExprResult &IntExpr,
1063                                            QualType FloatTy, QualType IntTy,
1064                                            bool ConvertFloat, bool ConvertInt) {
1065   if (IntTy->isIntegerType()) {
1066     if (ConvertInt)
1067       // Convert intExpr to the lhs floating point type.
1068       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1069                                     CK_IntegralToFloating);
1070     return FloatTy;
1071   }
1072 
1073   // Convert both sides to the appropriate complex float.
1074   assert(IntTy->isComplexIntegerType());
1075   QualType result = S.Context.getComplexType(FloatTy);
1076 
1077   // _Complex int -> _Complex float
1078   if (ConvertInt)
1079     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1080                                   CK_IntegralComplexToFloatingComplex);
1081 
1082   // float -> _Complex float
1083   if (ConvertFloat)
1084     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1085                                     CK_FloatingRealToComplex);
1086 
1087   return result;
1088 }
1089 
1090 /// \brief Handle arithmethic conversion with floating point types.  Helper
1091 /// function of UsualArithmeticConversions()
1092 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1093                                       ExprResult &RHS, QualType LHSType,
1094                                       QualType RHSType, bool IsCompAssign) {
1095   bool LHSFloat = LHSType->isRealFloatingType();
1096   bool RHSFloat = RHSType->isRealFloatingType();
1097 
1098   // If we have two real floating types, convert the smaller operand
1099   // to the bigger result.
1100   if (LHSFloat && RHSFloat) {
1101     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1102     if (order > 0) {
1103       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1104       return LHSType;
1105     }
1106 
1107     assert(order < 0 && "illegal float comparison");
1108     if (!IsCompAssign)
1109       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1110     return RHSType;
1111   }
1112 
1113   if (LHSFloat) {
1114     // Half FP has to be promoted to float unless it is natively supported
1115     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1116       LHSType = S.Context.FloatTy;
1117 
1118     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1119                                       /*convertFloat=*/!IsCompAssign,
1120                                       /*convertInt=*/ true);
1121   }
1122   assert(RHSFloat);
1123   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1124                                     /*convertInt=*/ true,
1125                                     /*convertFloat=*/!IsCompAssign);
1126 }
1127 
1128 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1129 
1130 namespace {
1131 /// These helper callbacks are placed in an anonymous namespace to
1132 /// permit their use as function template parameters.
1133 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1134   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1135 }
1136 
1137 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1138   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1139                              CK_IntegralComplexCast);
1140 }
1141 }
1142 
1143 /// \brief Handle integer arithmetic conversions.  Helper function of
1144 /// UsualArithmeticConversions()
1145 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1146 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1147                                         ExprResult &RHS, QualType LHSType,
1148                                         QualType RHSType, bool IsCompAssign) {
1149   // The rules for this case are in C99 6.3.1.8
1150   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1151   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1152   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1153   if (LHSSigned == RHSSigned) {
1154     // Same signedness; use the higher-ranked type
1155     if (order >= 0) {
1156       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1157       return LHSType;
1158     } else if (!IsCompAssign)
1159       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1160     return RHSType;
1161   } else if (order != (LHSSigned ? 1 : -1)) {
1162     // The unsigned type has greater than or equal rank to the
1163     // signed type, so use the unsigned type
1164     if (RHSSigned) {
1165       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1166       return LHSType;
1167     } else if (!IsCompAssign)
1168       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1169     return RHSType;
1170   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1171     // The two types are different widths; if we are here, that
1172     // means the signed type is larger than the unsigned type, so
1173     // use the signed type.
1174     if (LHSSigned) {
1175       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1176       return LHSType;
1177     } else if (!IsCompAssign)
1178       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1179     return RHSType;
1180   } else {
1181     // The signed type is higher-ranked than the unsigned type,
1182     // but isn't actually any bigger (like unsigned int and long
1183     // on most 32-bit systems).  Use the unsigned type corresponding
1184     // to the signed type.
1185     QualType result =
1186       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1187     RHS = (*doRHSCast)(S, RHS.get(), result);
1188     if (!IsCompAssign)
1189       LHS = (*doLHSCast)(S, LHS.get(), result);
1190     return result;
1191   }
1192 }
1193 
1194 /// \brief Handle conversions with GCC complex int extension.  Helper function
1195 /// of UsualArithmeticConversions()
1196 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1197                                            ExprResult &RHS, QualType LHSType,
1198                                            QualType RHSType,
1199                                            bool IsCompAssign) {
1200   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1201   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1202 
1203   if (LHSComplexInt && RHSComplexInt) {
1204     QualType LHSEltType = LHSComplexInt->getElementType();
1205     QualType RHSEltType = RHSComplexInt->getElementType();
1206     QualType ScalarType =
1207       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1208         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1209 
1210     return S.Context.getComplexType(ScalarType);
1211   }
1212 
1213   if (LHSComplexInt) {
1214     QualType LHSEltType = LHSComplexInt->getElementType();
1215     QualType ScalarType =
1216       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1217         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1218     QualType ComplexType = S.Context.getComplexType(ScalarType);
1219     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1220                               CK_IntegralRealToComplex);
1221 
1222     return ComplexType;
1223   }
1224 
1225   assert(RHSComplexInt);
1226 
1227   QualType RHSEltType = RHSComplexInt->getElementType();
1228   QualType ScalarType =
1229     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1230       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1231   QualType ComplexType = S.Context.getComplexType(ScalarType);
1232 
1233   if (!IsCompAssign)
1234     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1235                               CK_IntegralRealToComplex);
1236   return ComplexType;
1237 }
1238 
1239 /// UsualArithmeticConversions - Performs various conversions that are common to
1240 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1241 /// routine returns the first non-arithmetic type found. The client is
1242 /// responsible for emitting appropriate error diagnostics.
1243 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1244                                           bool IsCompAssign) {
1245   if (!IsCompAssign) {
1246     LHS = UsualUnaryConversions(LHS.get());
1247     if (LHS.isInvalid())
1248       return QualType();
1249   }
1250 
1251   RHS = UsualUnaryConversions(RHS.get());
1252   if (RHS.isInvalid())
1253     return QualType();
1254 
1255   // For conversion purposes, we ignore any qualifiers.
1256   // For example, "const float" and "float" are equivalent.
1257   QualType LHSType =
1258     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1259   QualType RHSType =
1260     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1261 
1262   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1263   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1264     LHSType = AtomicLHS->getValueType();
1265 
1266   // If both types are identical, no conversion is needed.
1267   if (LHSType == RHSType)
1268     return LHSType;
1269 
1270   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1271   // The caller can deal with this (e.g. pointer + int).
1272   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1273     return QualType();
1274 
1275   // Apply unary and bitfield promotions to the LHS's type.
1276   QualType LHSUnpromotedType = LHSType;
1277   if (LHSType->isPromotableIntegerType())
1278     LHSType = Context.getPromotedIntegerType(LHSType);
1279   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1280   if (!LHSBitfieldPromoteTy.isNull())
1281     LHSType = LHSBitfieldPromoteTy;
1282   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1283     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1284 
1285   // If both types are identical, no conversion is needed.
1286   if (LHSType == RHSType)
1287     return LHSType;
1288 
1289   // At this point, we have two different arithmetic types.
1290 
1291   // Handle complex types first (C99 6.3.1.8p1).
1292   if (LHSType->isComplexType() || RHSType->isComplexType())
1293     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1294                                         IsCompAssign);
1295 
1296   // Now handle "real" floating types (i.e. float, double, long double).
1297   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1298     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1299                                  IsCompAssign);
1300 
1301   // Handle GCC complex int extension.
1302   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1303     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1304                                       IsCompAssign);
1305 
1306   // Finally, we have two differing integer types.
1307   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1308            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1309 }
1310 
1311 
1312 //===----------------------------------------------------------------------===//
1313 //  Semantic Analysis for various Expression Types
1314 //===----------------------------------------------------------------------===//
1315 
1316 
1317 ExprResult
1318 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1319                                 SourceLocation DefaultLoc,
1320                                 SourceLocation RParenLoc,
1321                                 Expr *ControllingExpr,
1322                                 ArrayRef<ParsedType> ArgTypes,
1323                                 ArrayRef<Expr *> ArgExprs) {
1324   unsigned NumAssocs = ArgTypes.size();
1325   assert(NumAssocs == ArgExprs.size());
1326 
1327   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1328   for (unsigned i = 0; i < NumAssocs; ++i) {
1329     if (ArgTypes[i])
1330       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1331     else
1332       Types[i] = nullptr;
1333   }
1334 
1335   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1336                                              ControllingExpr,
1337                                              llvm::makeArrayRef(Types, NumAssocs),
1338                                              ArgExprs);
1339   delete [] Types;
1340   return ER;
1341 }
1342 
1343 ExprResult
1344 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1345                                  SourceLocation DefaultLoc,
1346                                  SourceLocation RParenLoc,
1347                                  Expr *ControllingExpr,
1348                                  ArrayRef<TypeSourceInfo *> Types,
1349                                  ArrayRef<Expr *> Exprs) {
1350   unsigned NumAssocs = Types.size();
1351   assert(NumAssocs == Exprs.size());
1352   if (ControllingExpr->getType()->isPlaceholderType()) {
1353     ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1354     if (result.isInvalid()) return ExprError();
1355     ControllingExpr = result.get();
1356   }
1357 
1358   // The controlling expression is an unevaluated operand, so side effects are
1359   // likely unintended.
1360   if (ActiveTemplateInstantiations.empty() &&
1361       ControllingExpr->HasSideEffects(Context, false))
1362     Diag(ControllingExpr->getExprLoc(),
1363          diag::warn_side_effects_unevaluated_context);
1364 
1365   bool TypeErrorFound = false,
1366        IsResultDependent = ControllingExpr->isTypeDependent(),
1367        ContainsUnexpandedParameterPack
1368          = ControllingExpr->containsUnexpandedParameterPack();
1369 
1370   for (unsigned i = 0; i < NumAssocs; ++i) {
1371     if (Exprs[i]->containsUnexpandedParameterPack())
1372       ContainsUnexpandedParameterPack = true;
1373 
1374     if (Types[i]) {
1375       if (Types[i]->getType()->containsUnexpandedParameterPack())
1376         ContainsUnexpandedParameterPack = true;
1377 
1378       if (Types[i]->getType()->isDependentType()) {
1379         IsResultDependent = true;
1380       } else {
1381         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1382         // complete object type other than a variably modified type."
1383         unsigned D = 0;
1384         if (Types[i]->getType()->isIncompleteType())
1385           D = diag::err_assoc_type_incomplete;
1386         else if (!Types[i]->getType()->isObjectType())
1387           D = diag::err_assoc_type_nonobject;
1388         else if (Types[i]->getType()->isVariablyModifiedType())
1389           D = diag::err_assoc_type_variably_modified;
1390 
1391         if (D != 0) {
1392           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1393             << Types[i]->getTypeLoc().getSourceRange()
1394             << Types[i]->getType();
1395           TypeErrorFound = true;
1396         }
1397 
1398         // C11 6.5.1.1p2 "No two generic associations in the same generic
1399         // selection shall specify compatible types."
1400         for (unsigned j = i+1; j < NumAssocs; ++j)
1401           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1402               Context.typesAreCompatible(Types[i]->getType(),
1403                                          Types[j]->getType())) {
1404             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1405                  diag::err_assoc_compatible_types)
1406               << Types[j]->getTypeLoc().getSourceRange()
1407               << Types[j]->getType()
1408               << Types[i]->getType();
1409             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1410                  diag::note_compat_assoc)
1411               << Types[i]->getTypeLoc().getSourceRange()
1412               << Types[i]->getType();
1413             TypeErrorFound = true;
1414           }
1415       }
1416     }
1417   }
1418   if (TypeErrorFound)
1419     return ExprError();
1420 
1421   // If we determined that the generic selection is result-dependent, don't
1422   // try to compute the result expression.
1423   if (IsResultDependent)
1424     return new (Context) GenericSelectionExpr(
1425         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1426         ContainsUnexpandedParameterPack);
1427 
1428   SmallVector<unsigned, 1> CompatIndices;
1429   unsigned DefaultIndex = -1U;
1430   for (unsigned i = 0; i < NumAssocs; ++i) {
1431     if (!Types[i])
1432       DefaultIndex = i;
1433     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1434                                         Types[i]->getType()))
1435       CompatIndices.push_back(i);
1436   }
1437 
1438   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1439   // type compatible with at most one of the types named in its generic
1440   // association list."
1441   if (CompatIndices.size() > 1) {
1442     // We strip parens here because the controlling expression is typically
1443     // parenthesized in macro definitions.
1444     ControllingExpr = ControllingExpr->IgnoreParens();
1445     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1446       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1447       << (unsigned) CompatIndices.size();
1448     for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
1449          E = CompatIndices.end(); I != E; ++I) {
1450       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1451            diag::note_compat_assoc)
1452         << Types[*I]->getTypeLoc().getSourceRange()
1453         << Types[*I]->getType();
1454     }
1455     return ExprError();
1456   }
1457 
1458   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1459   // its controlling expression shall have type compatible with exactly one of
1460   // the types named in its generic association list."
1461   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1462     // We strip parens here because the controlling expression is typically
1463     // parenthesized in macro definitions.
1464     ControllingExpr = ControllingExpr->IgnoreParens();
1465     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1466       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1467     return ExprError();
1468   }
1469 
1470   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1471   // type name that is compatible with the type of the controlling expression,
1472   // then the result expression of the generic selection is the expression
1473   // in that generic association. Otherwise, the result expression of the
1474   // generic selection is the expression in the default generic association."
1475   unsigned ResultIndex =
1476     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1477 
1478   return new (Context) GenericSelectionExpr(
1479       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1480       ContainsUnexpandedParameterPack, ResultIndex);
1481 }
1482 
1483 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1484 /// location of the token and the offset of the ud-suffix within it.
1485 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1486                                      unsigned Offset) {
1487   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1488                                         S.getLangOpts());
1489 }
1490 
1491 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1492 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1493 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1494                                                  IdentifierInfo *UDSuffix,
1495                                                  SourceLocation UDSuffixLoc,
1496                                                  ArrayRef<Expr*> Args,
1497                                                  SourceLocation LitEndLoc) {
1498   assert(Args.size() <= 2 && "too many arguments for literal operator");
1499 
1500   QualType ArgTy[2];
1501   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1502     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1503     if (ArgTy[ArgIdx]->isArrayType())
1504       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1505   }
1506 
1507   DeclarationName OpName =
1508     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1509   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1510   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1511 
1512   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1513   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1514                               /*AllowRaw*/false, /*AllowTemplate*/false,
1515                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1516     return ExprError();
1517 
1518   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1519 }
1520 
1521 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1522 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1523 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1524 /// multiple tokens.  However, the common case is that StringToks points to one
1525 /// string.
1526 ///
1527 ExprResult
1528 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1529   assert(!StringToks.empty() && "Must have at least one string!");
1530 
1531   StringLiteralParser Literal(StringToks, PP);
1532   if (Literal.hadError)
1533     return ExprError();
1534 
1535   SmallVector<SourceLocation, 4> StringTokLocs;
1536   for (unsigned i = 0; i != StringToks.size(); ++i)
1537     StringTokLocs.push_back(StringToks[i].getLocation());
1538 
1539   QualType CharTy = Context.CharTy;
1540   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1541   if (Literal.isWide()) {
1542     CharTy = Context.getWideCharType();
1543     Kind = StringLiteral::Wide;
1544   } else if (Literal.isUTF8()) {
1545     Kind = StringLiteral::UTF8;
1546   } else if (Literal.isUTF16()) {
1547     CharTy = Context.Char16Ty;
1548     Kind = StringLiteral::UTF16;
1549   } else if (Literal.isUTF32()) {
1550     CharTy = Context.Char32Ty;
1551     Kind = StringLiteral::UTF32;
1552   } else if (Literal.isPascal()) {
1553     CharTy = Context.UnsignedCharTy;
1554   }
1555 
1556   QualType CharTyConst = CharTy;
1557   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1558   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1559     CharTyConst.addConst();
1560 
1561   // Get an array type for the string, according to C99 6.4.5.  This includes
1562   // the nul terminator character as well as the string length for pascal
1563   // strings.
1564   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1565                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1566                                  ArrayType::Normal, 0);
1567 
1568   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1569   if (getLangOpts().OpenCL) {
1570     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1571   }
1572 
1573   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1574   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1575                                              Kind, Literal.Pascal, StrTy,
1576                                              &StringTokLocs[0],
1577                                              StringTokLocs.size());
1578   if (Literal.getUDSuffix().empty())
1579     return Lit;
1580 
1581   // We're building a user-defined literal.
1582   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1583   SourceLocation UDSuffixLoc =
1584     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1585                    Literal.getUDSuffixOffset());
1586 
1587   // Make sure we're allowed user-defined literals here.
1588   if (!UDLScope)
1589     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1590 
1591   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1592   //   operator "" X (str, len)
1593   QualType SizeType = Context.getSizeType();
1594 
1595   DeclarationName OpName =
1596     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1597   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1598   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1599 
1600   QualType ArgTy[] = {
1601     Context.getArrayDecayedType(StrTy), SizeType
1602   };
1603 
1604   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1605   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1606                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1607                                 /*AllowStringTemplate*/true)) {
1608 
1609   case LOLR_Cooked: {
1610     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1611     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1612                                                     StringTokLocs[0]);
1613     Expr *Args[] = { Lit, LenArg };
1614 
1615     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1616   }
1617 
1618   case LOLR_StringTemplate: {
1619     TemplateArgumentListInfo ExplicitArgs;
1620 
1621     unsigned CharBits = Context.getIntWidth(CharTy);
1622     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1623     llvm::APSInt Value(CharBits, CharIsUnsigned);
1624 
1625     TemplateArgument TypeArg(CharTy);
1626     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1627     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1628 
1629     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1630       Value = Lit->getCodeUnit(I);
1631       TemplateArgument Arg(Context, Value, CharTy);
1632       TemplateArgumentLocInfo ArgInfo;
1633       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1634     }
1635     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1636                                     &ExplicitArgs);
1637   }
1638   case LOLR_Raw:
1639   case LOLR_Template:
1640     llvm_unreachable("unexpected literal operator lookup result");
1641   case LOLR_Error:
1642     return ExprError();
1643   }
1644   llvm_unreachable("unexpected literal operator lookup result");
1645 }
1646 
1647 ExprResult
1648 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1649                        SourceLocation Loc,
1650                        const CXXScopeSpec *SS) {
1651   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1652   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1653 }
1654 
1655 /// BuildDeclRefExpr - Build an expression that references a
1656 /// declaration that does not require a closure capture.
1657 ExprResult
1658 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1659                        const DeclarationNameInfo &NameInfo,
1660                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1661                        const TemplateArgumentListInfo *TemplateArgs) {
1662   if (getLangOpts().CUDA)
1663     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1664       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1665         if (CheckCUDATarget(Caller, Callee)) {
1666           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1667             << IdentifyCUDATarget(Callee) << D->getIdentifier()
1668             << IdentifyCUDATarget(Caller);
1669           Diag(D->getLocation(), diag::note_previous_decl)
1670             << D->getIdentifier();
1671           return ExprError();
1672         }
1673       }
1674 
1675   bool RefersToCapturedVariable =
1676       isa<VarDecl>(D) &&
1677       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1678 
1679   DeclRefExpr *E;
1680   if (isa<VarTemplateSpecializationDecl>(D)) {
1681     VarTemplateSpecializationDecl *VarSpec =
1682         cast<VarTemplateSpecializationDecl>(D);
1683 
1684     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1685                                         : NestedNameSpecifierLoc(),
1686                             VarSpec->getTemplateKeywordLoc(), D,
1687                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1688                             FoundD, TemplateArgs);
1689   } else {
1690     assert(!TemplateArgs && "No template arguments for non-variable"
1691                             " template specialization references");
1692     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1693                                         : NestedNameSpecifierLoc(),
1694                             SourceLocation(), D, RefersToCapturedVariable,
1695                             NameInfo, Ty, VK, FoundD);
1696   }
1697 
1698   MarkDeclRefReferenced(E);
1699 
1700   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1701       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1702       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1703       recordUseOfEvaluatedWeak(E);
1704 
1705   // Just in case we're building an illegal pointer-to-member.
1706   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1707   if (FD && FD->isBitField())
1708     E->setObjectKind(OK_BitField);
1709 
1710   return E;
1711 }
1712 
1713 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1714 /// possibly a list of template arguments.
1715 ///
1716 /// If this produces template arguments, it is permitted to call
1717 /// DecomposeTemplateName.
1718 ///
1719 /// This actually loses a lot of source location information for
1720 /// non-standard name kinds; we should consider preserving that in
1721 /// some way.
1722 void
1723 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1724                              TemplateArgumentListInfo &Buffer,
1725                              DeclarationNameInfo &NameInfo,
1726                              const TemplateArgumentListInfo *&TemplateArgs) {
1727   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1728     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1729     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1730 
1731     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1732                                        Id.TemplateId->NumArgs);
1733     translateTemplateArguments(TemplateArgsPtr, Buffer);
1734 
1735     TemplateName TName = Id.TemplateId->Template.get();
1736     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1737     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1738     TemplateArgs = &Buffer;
1739   } else {
1740     NameInfo = GetNameFromUnqualifiedId(Id);
1741     TemplateArgs = nullptr;
1742   }
1743 }
1744 
1745 static void emitEmptyLookupTypoDiagnostic(
1746     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1747     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1748     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1749   DeclContext *Ctx =
1750       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1751   if (!TC) {
1752     // Emit a special diagnostic for failed member lookups.
1753     // FIXME: computing the declaration context might fail here (?)
1754     if (Ctx)
1755       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1756                                                  << SS.getRange();
1757     else
1758       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1759     return;
1760   }
1761 
1762   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1763   bool DroppedSpecifier =
1764       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1765   unsigned NoteID =
1766       (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl()))
1767           ? diag::note_implicit_param_decl
1768           : diag::note_previous_decl;
1769   if (!Ctx)
1770     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1771                          SemaRef.PDiag(NoteID));
1772   else
1773     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1774                                  << Typo << Ctx << DroppedSpecifier
1775                                  << SS.getRange(),
1776                          SemaRef.PDiag(NoteID));
1777 }
1778 
1779 /// Diagnose an empty lookup.
1780 ///
1781 /// \return false if new lookup candidates were found
1782 bool
1783 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1784                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1785                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1786                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1787   DeclarationName Name = R.getLookupName();
1788 
1789   unsigned diagnostic = diag::err_undeclared_var_use;
1790   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1791   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1792       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1793       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1794     diagnostic = diag::err_undeclared_use;
1795     diagnostic_suggest = diag::err_undeclared_use_suggest;
1796   }
1797 
1798   // If the original lookup was an unqualified lookup, fake an
1799   // unqualified lookup.  This is useful when (for example) the
1800   // original lookup would not have found something because it was a
1801   // dependent name.
1802   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1803     ? CurContext : nullptr;
1804   while (DC) {
1805     if (isa<CXXRecordDecl>(DC)) {
1806       LookupQualifiedName(R, DC);
1807 
1808       if (!R.empty()) {
1809         // Don't give errors about ambiguities in this lookup.
1810         R.suppressDiagnostics();
1811 
1812         // During a default argument instantiation the CurContext points
1813         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1814         // function parameter list, hence add an explicit check.
1815         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1816                               ActiveTemplateInstantiations.back().Kind ==
1817             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1818         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1819         bool isInstance = CurMethod &&
1820                           CurMethod->isInstance() &&
1821                           DC == CurMethod->getParent() && !isDefaultArgument;
1822 
1823 
1824         // Give a code modification hint to insert 'this->'.
1825         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1826         // Actually quite difficult!
1827         if (getLangOpts().MSVCCompat)
1828           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1829         if (isInstance) {
1830           Diag(R.getNameLoc(), diagnostic) << Name
1831             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1832           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1833               CallsUndergoingInstantiation.back()->getCallee());
1834 
1835           CXXMethodDecl *DepMethod;
1836           if (CurMethod->isDependentContext())
1837             DepMethod = CurMethod;
1838           else if (CurMethod->getTemplatedKind() ==
1839               FunctionDecl::TK_FunctionTemplateSpecialization)
1840             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1841                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1842           else
1843             DepMethod = cast<CXXMethodDecl>(
1844                 CurMethod->getInstantiatedFromMemberFunction());
1845           assert(DepMethod && "No template pattern found");
1846 
1847           QualType DepThisType = DepMethod->getThisType(Context);
1848           CheckCXXThisCapture(R.getNameLoc());
1849           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1850                                      R.getNameLoc(), DepThisType, false);
1851           TemplateArgumentListInfo TList;
1852           if (ULE->hasExplicitTemplateArgs())
1853             ULE->copyTemplateArgumentsInto(TList);
1854 
1855           CXXScopeSpec SS;
1856           SS.Adopt(ULE->getQualifierLoc());
1857           CXXDependentScopeMemberExpr *DepExpr =
1858               CXXDependentScopeMemberExpr::Create(
1859                   Context, DepThis, DepThisType, true, SourceLocation(),
1860                   SS.getWithLocInContext(Context),
1861                   ULE->getTemplateKeywordLoc(), nullptr,
1862                   R.getLookupNameInfo(),
1863                   ULE->hasExplicitTemplateArgs() ? &TList : nullptr);
1864           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1865         } else {
1866           Diag(R.getNameLoc(), diagnostic) << Name;
1867         }
1868 
1869         // Do we really want to note all of these?
1870         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1871           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1872 
1873         // Return true if we are inside a default argument instantiation
1874         // and the found name refers to an instance member function, otherwise
1875         // the function calling DiagnoseEmptyLookup will try to create an
1876         // implicit member call and this is wrong for default argument.
1877         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1878           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1879           return true;
1880         }
1881 
1882         // Tell the callee to try to recover.
1883         return false;
1884       }
1885 
1886       R.clear();
1887     }
1888 
1889     // In Microsoft mode, if we are performing lookup from within a friend
1890     // function definition declared at class scope then we must set
1891     // DC to the lexical parent to be able to search into the parent
1892     // class.
1893     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1894         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1895         DC->getLexicalParent()->isRecord())
1896       DC = DC->getLexicalParent();
1897     else
1898       DC = DC->getParent();
1899   }
1900 
1901   // We didn't find anything, so try to correct for a typo.
1902   TypoCorrection Corrected;
1903   if (S && Out) {
1904     SourceLocation TypoLoc = R.getNameLoc();
1905     assert(!ExplicitTemplateArgs &&
1906            "Diagnosing an empty lookup with explicit template args!");
1907     *Out = CorrectTypoDelayed(
1908         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1909         [=](const TypoCorrection &TC) {
1910           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1911                                         diagnostic, diagnostic_suggest);
1912         },
1913         nullptr, CTK_ErrorRecovery);
1914     if (*Out)
1915       return true;
1916   } else if (S && (Corrected =
1917                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1918                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1919     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1920     bool DroppedSpecifier =
1921         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1922     R.setLookupName(Corrected.getCorrection());
1923 
1924     bool AcceptableWithRecovery = false;
1925     bool AcceptableWithoutRecovery = false;
1926     NamedDecl *ND = Corrected.getCorrectionDecl();
1927     if (ND) {
1928       if (Corrected.isOverloaded()) {
1929         OverloadCandidateSet OCS(R.getNameLoc(),
1930                                  OverloadCandidateSet::CSK_Normal);
1931         OverloadCandidateSet::iterator Best;
1932         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1933                                         CDEnd = Corrected.end();
1934              CD != CDEnd; ++CD) {
1935           if (FunctionTemplateDecl *FTD =
1936                    dyn_cast<FunctionTemplateDecl>(*CD))
1937             AddTemplateOverloadCandidate(
1938                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1939                 Args, OCS);
1940           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1941             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1942               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1943                                    Args, OCS);
1944         }
1945         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1946         case OR_Success:
1947           ND = Best->Function;
1948           Corrected.setCorrectionDecl(ND);
1949           break;
1950         default:
1951           // FIXME: Arbitrarily pick the first declaration for the note.
1952           Corrected.setCorrectionDecl(ND);
1953           break;
1954         }
1955       }
1956       R.addDecl(ND);
1957       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1958         CXXRecordDecl *Record = nullptr;
1959         if (Corrected.getCorrectionSpecifier()) {
1960           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1961           Record = Ty->getAsCXXRecordDecl();
1962         }
1963         if (!Record)
1964           Record = cast<CXXRecordDecl>(
1965               ND->getDeclContext()->getRedeclContext());
1966         R.setNamingClass(Record);
1967       }
1968 
1969       AcceptableWithRecovery =
1970           isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1971       // FIXME: If we ended up with a typo for a type name or
1972       // Objective-C class name, we're in trouble because the parser
1973       // is in the wrong place to recover. Suggest the typo
1974       // correction, but don't make it a fix-it since we're not going
1975       // to recover well anyway.
1976       AcceptableWithoutRecovery =
1977           isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1978     } else {
1979       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1980       // because we aren't able to recover.
1981       AcceptableWithoutRecovery = true;
1982     }
1983 
1984     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1985       unsigned NoteID = (Corrected.getCorrectionDecl() &&
1986                          isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1987                             ? diag::note_implicit_param_decl
1988                             : diag::note_previous_decl;
1989       if (SS.isEmpty())
1990         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1991                      PDiag(NoteID), AcceptableWithRecovery);
1992       else
1993         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1994                                   << Name << computeDeclContext(SS, false)
1995                                   << DroppedSpecifier << SS.getRange(),
1996                      PDiag(NoteID), AcceptableWithRecovery);
1997 
1998       // Tell the callee whether to try to recover.
1999       return !AcceptableWithRecovery;
2000     }
2001   }
2002   R.clear();
2003 
2004   // Emit a special diagnostic for failed member lookups.
2005   // FIXME: computing the declaration context might fail here (?)
2006   if (!SS.isEmpty()) {
2007     Diag(R.getNameLoc(), diag::err_no_member)
2008       << Name << computeDeclContext(SS, false)
2009       << SS.getRange();
2010     return true;
2011   }
2012 
2013   // Give up, we can't recover.
2014   Diag(R.getNameLoc(), diagnostic) << Name;
2015   return true;
2016 }
2017 
2018 /// In Microsoft mode, if we are inside a template class whose parent class has
2019 /// dependent base classes, and we can't resolve an unqualified identifier, then
2020 /// assume the identifier is a member of a dependent base class.  We can only
2021 /// recover successfully in static methods, instance methods, and other contexts
2022 /// where 'this' is available.  This doesn't precisely match MSVC's
2023 /// instantiation model, but it's close enough.
2024 static Expr *
2025 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2026                                DeclarationNameInfo &NameInfo,
2027                                SourceLocation TemplateKWLoc,
2028                                const TemplateArgumentListInfo *TemplateArgs) {
2029   // Only try to recover from lookup into dependent bases in static methods or
2030   // contexts where 'this' is available.
2031   QualType ThisType = S.getCurrentThisType();
2032   const CXXRecordDecl *RD = nullptr;
2033   if (!ThisType.isNull())
2034     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2035   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2036     RD = MD->getParent();
2037   if (!RD || !RD->hasAnyDependentBases())
2038     return nullptr;
2039 
2040   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2041   // is available, suggest inserting 'this->' as a fixit.
2042   SourceLocation Loc = NameInfo.getLoc();
2043   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2044   DB << NameInfo.getName() << RD;
2045 
2046   if (!ThisType.isNull()) {
2047     DB << FixItHint::CreateInsertion(Loc, "this->");
2048     return CXXDependentScopeMemberExpr::Create(
2049         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2050         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2051         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2052   }
2053 
2054   // Synthesize a fake NNS that points to the derived class.  This will
2055   // perform name lookup during template instantiation.
2056   CXXScopeSpec SS;
2057   auto *NNS =
2058       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2059   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2060   return DependentScopeDeclRefExpr::Create(
2061       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2062       TemplateArgs);
2063 }
2064 
2065 ExprResult
2066 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2067                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2068                         bool HasTrailingLParen, bool IsAddressOfOperand,
2069                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2070                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2071   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2072          "cannot be direct & operand and have a trailing lparen");
2073   if (SS.isInvalid())
2074     return ExprError();
2075 
2076   TemplateArgumentListInfo TemplateArgsBuffer;
2077 
2078   // Decompose the UnqualifiedId into the following data.
2079   DeclarationNameInfo NameInfo;
2080   const TemplateArgumentListInfo *TemplateArgs;
2081   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2082 
2083   DeclarationName Name = NameInfo.getName();
2084   IdentifierInfo *II = Name.getAsIdentifierInfo();
2085   SourceLocation NameLoc = NameInfo.getLoc();
2086 
2087   // C++ [temp.dep.expr]p3:
2088   //   An id-expression is type-dependent if it contains:
2089   //     -- an identifier that was declared with a dependent type,
2090   //        (note: handled after lookup)
2091   //     -- a template-id that is dependent,
2092   //        (note: handled in BuildTemplateIdExpr)
2093   //     -- a conversion-function-id that specifies a dependent type,
2094   //     -- a nested-name-specifier that contains a class-name that
2095   //        names a dependent type.
2096   // Determine whether this is a member of an unknown specialization;
2097   // we need to handle these differently.
2098   bool DependentID = false;
2099   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2100       Name.getCXXNameType()->isDependentType()) {
2101     DependentID = true;
2102   } else if (SS.isSet()) {
2103     if (DeclContext *DC = computeDeclContext(SS, false)) {
2104       if (RequireCompleteDeclContext(SS, DC))
2105         return ExprError();
2106     } else {
2107       DependentID = true;
2108     }
2109   }
2110 
2111   if (DependentID)
2112     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2113                                       IsAddressOfOperand, TemplateArgs);
2114 
2115   // Perform the required lookup.
2116   LookupResult R(*this, NameInfo,
2117                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2118                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2119   if (TemplateArgs) {
2120     // Lookup the template name again to correctly establish the context in
2121     // which it was found. This is really unfortunate as we already did the
2122     // lookup to determine that it was a template name in the first place. If
2123     // this becomes a performance hit, we can work harder to preserve those
2124     // results until we get here but it's likely not worth it.
2125     bool MemberOfUnknownSpecialization;
2126     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2127                        MemberOfUnknownSpecialization);
2128 
2129     if (MemberOfUnknownSpecialization ||
2130         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2131       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2132                                         IsAddressOfOperand, TemplateArgs);
2133   } else {
2134     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2135     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2136 
2137     // If the result might be in a dependent base class, this is a dependent
2138     // id-expression.
2139     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2140       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2141                                         IsAddressOfOperand, TemplateArgs);
2142 
2143     // If this reference is in an Objective-C method, then we need to do
2144     // some special Objective-C lookup, too.
2145     if (IvarLookupFollowUp) {
2146       ExprResult E(LookupInObjCMethod(R, S, II, true));
2147       if (E.isInvalid())
2148         return ExprError();
2149 
2150       if (Expr *Ex = E.getAs<Expr>())
2151         return Ex;
2152     }
2153   }
2154 
2155   if (R.isAmbiguous())
2156     return ExprError();
2157 
2158   // This could be an implicitly declared function reference (legal in C90,
2159   // extension in C99, forbidden in C++).
2160   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2161     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2162     if (D) R.addDecl(D);
2163   }
2164 
2165   // Determine whether this name might be a candidate for
2166   // argument-dependent lookup.
2167   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2168 
2169   if (R.empty() && !ADL) {
2170     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2171       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2172                                                    TemplateKWLoc, TemplateArgs))
2173         return E;
2174     }
2175 
2176     // Don't diagnose an empty lookup for inline assembly.
2177     if (IsInlineAsmIdentifier)
2178       return ExprError();
2179 
2180     // If this name wasn't predeclared and if this is not a function
2181     // call, diagnose the problem.
2182     TypoExpr *TE = nullptr;
2183     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2184         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2185     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2186     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2187            "Typo correction callback misconfigured");
2188     if (CCC) {
2189       // Make sure the callback knows what the typo being diagnosed is.
2190       CCC->setTypoName(II);
2191       if (SS.isValid())
2192         CCC->setTypoNNS(SS.getScopeRep());
2193     }
2194     if (DiagnoseEmptyLookup(S, SS, R,
2195                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2196                             nullptr, None, &TE)) {
2197       if (TE && KeywordReplacement) {
2198         auto &State = getTypoExprState(TE);
2199         auto BestTC = State.Consumer->getNextCorrection();
2200         if (BestTC.isKeyword()) {
2201           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2202           if (State.DiagHandler)
2203             State.DiagHandler(BestTC);
2204           KeywordReplacement->startToken();
2205           KeywordReplacement->setKind(II->getTokenID());
2206           KeywordReplacement->setIdentifierInfo(II);
2207           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2208           // Clean up the state associated with the TypoExpr, since it has
2209           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2210           clearDelayedTypo(TE);
2211           // Signal that a correction to a keyword was performed by returning a
2212           // valid-but-null ExprResult.
2213           return (Expr*)nullptr;
2214         }
2215         State.Consumer->resetCorrectionStream();
2216       }
2217       return TE ? TE : ExprError();
2218     }
2219 
2220     assert(!R.empty() &&
2221            "DiagnoseEmptyLookup returned false but added no results");
2222 
2223     // If we found an Objective-C instance variable, let
2224     // LookupInObjCMethod build the appropriate expression to
2225     // reference the ivar.
2226     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2227       R.clear();
2228       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2229       // In a hopelessly buggy code, Objective-C instance variable
2230       // lookup fails and no expression will be built to reference it.
2231       if (!E.isInvalid() && !E.get())
2232         return ExprError();
2233       return E;
2234     }
2235   }
2236 
2237   // This is guaranteed from this point on.
2238   assert(!R.empty() || ADL);
2239 
2240   // Check whether this might be a C++ implicit instance member access.
2241   // C++ [class.mfct.non-static]p3:
2242   //   When an id-expression that is not part of a class member access
2243   //   syntax and not used to form a pointer to member is used in the
2244   //   body of a non-static member function of class X, if name lookup
2245   //   resolves the name in the id-expression to a non-static non-type
2246   //   member of some class C, the id-expression is transformed into a
2247   //   class member access expression using (*this) as the
2248   //   postfix-expression to the left of the . operator.
2249   //
2250   // But we don't actually need to do this for '&' operands if R
2251   // resolved to a function or overloaded function set, because the
2252   // expression is ill-formed if it actually works out to be a
2253   // non-static member function:
2254   //
2255   // C++ [expr.ref]p4:
2256   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2257   //   [t]he expression can be used only as the left-hand operand of a
2258   //   member function call.
2259   //
2260   // There are other safeguards against such uses, but it's important
2261   // to get this right here so that we don't end up making a
2262   // spuriously dependent expression if we're inside a dependent
2263   // instance method.
2264   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2265     bool MightBeImplicitMember;
2266     if (!IsAddressOfOperand)
2267       MightBeImplicitMember = true;
2268     else if (!SS.isEmpty())
2269       MightBeImplicitMember = false;
2270     else if (R.isOverloadedResult())
2271       MightBeImplicitMember = false;
2272     else if (R.isUnresolvableResult())
2273       MightBeImplicitMember = true;
2274     else
2275       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2276                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2277                               isa<MSPropertyDecl>(R.getFoundDecl());
2278 
2279     if (MightBeImplicitMember)
2280       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2281                                              R, TemplateArgs);
2282   }
2283 
2284   if (TemplateArgs || TemplateKWLoc.isValid()) {
2285 
2286     // In C++1y, if this is a variable template id, then check it
2287     // in BuildTemplateIdExpr().
2288     // The single lookup result must be a variable template declaration.
2289     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2290         Id.TemplateId->Kind == TNK_Var_template) {
2291       assert(R.getAsSingle<VarTemplateDecl>() &&
2292              "There should only be one declaration found.");
2293     }
2294 
2295     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2296   }
2297 
2298   return BuildDeclarationNameExpr(SS, R, ADL);
2299 }
2300 
2301 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2302 /// declaration name, generally during template instantiation.
2303 /// There's a large number of things which don't need to be done along
2304 /// this path.
2305 ExprResult
2306 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2307                                         const DeclarationNameInfo &NameInfo,
2308                                         bool IsAddressOfOperand,
2309                                         TypeSourceInfo **RecoveryTSI) {
2310   DeclContext *DC = computeDeclContext(SS, false);
2311   if (!DC)
2312     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2313                                      NameInfo, /*TemplateArgs=*/nullptr);
2314 
2315   if (RequireCompleteDeclContext(SS, DC))
2316     return ExprError();
2317 
2318   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2319   LookupQualifiedName(R, DC);
2320 
2321   if (R.isAmbiguous())
2322     return ExprError();
2323 
2324   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2325     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2326                                      NameInfo, /*TemplateArgs=*/nullptr);
2327 
2328   if (R.empty()) {
2329     Diag(NameInfo.getLoc(), diag::err_no_member)
2330       << NameInfo.getName() << DC << SS.getRange();
2331     return ExprError();
2332   }
2333 
2334   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2335     // Diagnose a missing typename if this resolved unambiguously to a type in
2336     // a dependent context.  If we can recover with a type, downgrade this to
2337     // a warning in Microsoft compatibility mode.
2338     unsigned DiagID = diag::err_typename_missing;
2339     if (RecoveryTSI && getLangOpts().MSVCCompat)
2340       DiagID = diag::ext_typename_missing;
2341     SourceLocation Loc = SS.getBeginLoc();
2342     auto D = Diag(Loc, DiagID);
2343     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2344       << SourceRange(Loc, NameInfo.getEndLoc());
2345 
2346     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2347     // context.
2348     if (!RecoveryTSI)
2349       return ExprError();
2350 
2351     // Only issue the fixit if we're prepared to recover.
2352     D << FixItHint::CreateInsertion(Loc, "typename ");
2353 
2354     // Recover by pretending this was an elaborated type.
2355     QualType Ty = Context.getTypeDeclType(TD);
2356     TypeLocBuilder TLB;
2357     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2358 
2359     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2360     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2361     QTL.setElaboratedKeywordLoc(SourceLocation());
2362     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2363 
2364     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2365 
2366     return ExprEmpty();
2367   }
2368 
2369   // Defend against this resolving to an implicit member access. We usually
2370   // won't get here if this might be a legitimate a class member (we end up in
2371   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2372   // a pointer-to-member or in an unevaluated context in C++11.
2373   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2374     return BuildPossibleImplicitMemberExpr(SS,
2375                                            /*TemplateKWLoc=*/SourceLocation(),
2376                                            R, /*TemplateArgs=*/nullptr);
2377 
2378   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2379 }
2380 
2381 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2382 /// detected that we're currently inside an ObjC method.  Perform some
2383 /// additional lookup.
2384 ///
2385 /// Ideally, most of this would be done by lookup, but there's
2386 /// actually quite a lot of extra work involved.
2387 ///
2388 /// Returns a null sentinel to indicate trivial success.
2389 ExprResult
2390 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2391                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2392   SourceLocation Loc = Lookup.getNameLoc();
2393   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2394 
2395   // Check for error condition which is already reported.
2396   if (!CurMethod)
2397     return ExprError();
2398 
2399   // There are two cases to handle here.  1) scoped lookup could have failed,
2400   // in which case we should look for an ivar.  2) scoped lookup could have
2401   // found a decl, but that decl is outside the current instance method (i.e.
2402   // a global variable).  In these two cases, we do a lookup for an ivar with
2403   // this name, if the lookup sucedes, we replace it our current decl.
2404 
2405   // If we're in a class method, we don't normally want to look for
2406   // ivars.  But if we don't find anything else, and there's an
2407   // ivar, that's an error.
2408   bool IsClassMethod = CurMethod->isClassMethod();
2409 
2410   bool LookForIvars;
2411   if (Lookup.empty())
2412     LookForIvars = true;
2413   else if (IsClassMethod)
2414     LookForIvars = false;
2415   else
2416     LookForIvars = (Lookup.isSingleResult() &&
2417                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2418   ObjCInterfaceDecl *IFace = nullptr;
2419   if (LookForIvars) {
2420     IFace = CurMethod->getClassInterface();
2421     ObjCInterfaceDecl *ClassDeclared;
2422     ObjCIvarDecl *IV = nullptr;
2423     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2424       // Diagnose using an ivar in a class method.
2425       if (IsClassMethod)
2426         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2427                          << IV->getDeclName());
2428 
2429       // If we're referencing an invalid decl, just return this as a silent
2430       // error node.  The error diagnostic was already emitted on the decl.
2431       if (IV->isInvalidDecl())
2432         return ExprError();
2433 
2434       // Check if referencing a field with __attribute__((deprecated)).
2435       if (DiagnoseUseOfDecl(IV, Loc))
2436         return ExprError();
2437 
2438       // Diagnose the use of an ivar outside of the declaring class.
2439       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2440           !declaresSameEntity(ClassDeclared, IFace) &&
2441           !getLangOpts().DebuggerSupport)
2442         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2443 
2444       // FIXME: This should use a new expr for a direct reference, don't
2445       // turn this into Self->ivar, just return a BareIVarExpr or something.
2446       IdentifierInfo &II = Context.Idents.get("self");
2447       UnqualifiedId SelfName;
2448       SelfName.setIdentifier(&II, SourceLocation());
2449       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2450       CXXScopeSpec SelfScopeSpec;
2451       SourceLocation TemplateKWLoc;
2452       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2453                                               SelfName, false, false);
2454       if (SelfExpr.isInvalid())
2455         return ExprError();
2456 
2457       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2458       if (SelfExpr.isInvalid())
2459         return ExprError();
2460 
2461       MarkAnyDeclReferenced(Loc, IV, true);
2462 
2463       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2464       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2465           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2466         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2467 
2468       ObjCIvarRefExpr *Result = new (Context)
2469           ObjCIvarRefExpr(IV, IV->getType(), Loc, IV->getLocation(),
2470                           SelfExpr.get(), true, true);
2471 
2472       if (getLangOpts().ObjCAutoRefCount) {
2473         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2474           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2475             recordUseOfEvaluatedWeak(Result);
2476         }
2477         if (CurContext->isClosure())
2478           Diag(Loc, diag::warn_implicitly_retains_self)
2479             << FixItHint::CreateInsertion(Loc, "self->");
2480       }
2481 
2482       return Result;
2483     }
2484   } else if (CurMethod->isInstanceMethod()) {
2485     // We should warn if a local variable hides an ivar.
2486     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2487       ObjCInterfaceDecl *ClassDeclared;
2488       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2489         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2490             declaresSameEntity(IFace, ClassDeclared))
2491           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2492       }
2493     }
2494   } else if (Lookup.isSingleResult() &&
2495              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2496     // If accessing a stand-alone ivar in a class method, this is an error.
2497     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2498       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2499                        << IV->getDeclName());
2500   }
2501 
2502   if (Lookup.empty() && II && AllowBuiltinCreation) {
2503     // FIXME. Consolidate this with similar code in LookupName.
2504     if (unsigned BuiltinID = II->getBuiltinID()) {
2505       if (!(getLangOpts().CPlusPlus &&
2506             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2507         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2508                                            S, Lookup.isForRedeclaration(),
2509                                            Lookup.getNameLoc());
2510         if (D) Lookup.addDecl(D);
2511       }
2512     }
2513   }
2514   // Sentinel value saying that we didn't do anything special.
2515   return ExprResult((Expr *)nullptr);
2516 }
2517 
2518 /// \brief Cast a base object to a member's actual type.
2519 ///
2520 /// Logically this happens in three phases:
2521 ///
2522 /// * First we cast from the base type to the naming class.
2523 ///   The naming class is the class into which we were looking
2524 ///   when we found the member;  it's the qualifier type if a
2525 ///   qualifier was provided, and otherwise it's the base type.
2526 ///
2527 /// * Next we cast from the naming class to the declaring class.
2528 ///   If the member we found was brought into a class's scope by
2529 ///   a using declaration, this is that class;  otherwise it's
2530 ///   the class declaring the member.
2531 ///
2532 /// * Finally we cast from the declaring class to the "true"
2533 ///   declaring class of the member.  This conversion does not
2534 ///   obey access control.
2535 ExprResult
2536 Sema::PerformObjectMemberConversion(Expr *From,
2537                                     NestedNameSpecifier *Qualifier,
2538                                     NamedDecl *FoundDecl,
2539                                     NamedDecl *Member) {
2540   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2541   if (!RD)
2542     return From;
2543 
2544   QualType DestRecordType;
2545   QualType DestType;
2546   QualType FromRecordType;
2547   QualType FromType = From->getType();
2548   bool PointerConversions = false;
2549   if (isa<FieldDecl>(Member)) {
2550     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2551 
2552     if (FromType->getAs<PointerType>()) {
2553       DestType = Context.getPointerType(DestRecordType);
2554       FromRecordType = FromType->getPointeeType();
2555       PointerConversions = true;
2556     } else {
2557       DestType = DestRecordType;
2558       FromRecordType = FromType;
2559     }
2560   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2561     if (Method->isStatic())
2562       return From;
2563 
2564     DestType = Method->getThisType(Context);
2565     DestRecordType = DestType->getPointeeType();
2566 
2567     if (FromType->getAs<PointerType>()) {
2568       FromRecordType = FromType->getPointeeType();
2569       PointerConversions = true;
2570     } else {
2571       FromRecordType = FromType;
2572       DestType = DestRecordType;
2573     }
2574   } else {
2575     // No conversion necessary.
2576     return From;
2577   }
2578 
2579   if (DestType->isDependentType() || FromType->isDependentType())
2580     return From;
2581 
2582   // If the unqualified types are the same, no conversion is necessary.
2583   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2584     return From;
2585 
2586   SourceRange FromRange = From->getSourceRange();
2587   SourceLocation FromLoc = FromRange.getBegin();
2588 
2589   ExprValueKind VK = From->getValueKind();
2590 
2591   // C++ [class.member.lookup]p8:
2592   //   [...] Ambiguities can often be resolved by qualifying a name with its
2593   //   class name.
2594   //
2595   // If the member was a qualified name and the qualified referred to a
2596   // specific base subobject type, we'll cast to that intermediate type
2597   // first and then to the object in which the member is declared. That allows
2598   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2599   //
2600   //   class Base { public: int x; };
2601   //   class Derived1 : public Base { };
2602   //   class Derived2 : public Base { };
2603   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2604   //
2605   //   void VeryDerived::f() {
2606   //     x = 17; // error: ambiguous base subobjects
2607   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2608   //   }
2609   if (Qualifier && Qualifier->getAsType()) {
2610     QualType QType = QualType(Qualifier->getAsType(), 0);
2611     assert(QType->isRecordType() && "lookup done with non-record type");
2612 
2613     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2614 
2615     // In C++98, the qualifier type doesn't actually have to be a base
2616     // type of the object type, in which case we just ignore it.
2617     // Otherwise build the appropriate casts.
2618     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2619       CXXCastPath BasePath;
2620       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2621                                        FromLoc, FromRange, &BasePath))
2622         return ExprError();
2623 
2624       if (PointerConversions)
2625         QType = Context.getPointerType(QType);
2626       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2627                                VK, &BasePath).get();
2628 
2629       FromType = QType;
2630       FromRecordType = QRecordType;
2631 
2632       // If the qualifier type was the same as the destination type,
2633       // we're done.
2634       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2635         return From;
2636     }
2637   }
2638 
2639   bool IgnoreAccess = false;
2640 
2641   // If we actually found the member through a using declaration, cast
2642   // down to the using declaration's type.
2643   //
2644   // Pointer equality is fine here because only one declaration of a
2645   // class ever has member declarations.
2646   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2647     assert(isa<UsingShadowDecl>(FoundDecl));
2648     QualType URecordType = Context.getTypeDeclType(
2649                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2650 
2651     // We only need to do this if the naming-class to declaring-class
2652     // conversion is non-trivial.
2653     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2654       assert(IsDerivedFrom(FromRecordType, URecordType));
2655       CXXCastPath BasePath;
2656       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2657                                        FromLoc, FromRange, &BasePath))
2658         return ExprError();
2659 
2660       QualType UType = URecordType;
2661       if (PointerConversions)
2662         UType = Context.getPointerType(UType);
2663       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2664                                VK, &BasePath).get();
2665       FromType = UType;
2666       FromRecordType = URecordType;
2667     }
2668 
2669     // We don't do access control for the conversion from the
2670     // declaring class to the true declaring class.
2671     IgnoreAccess = true;
2672   }
2673 
2674   CXXCastPath BasePath;
2675   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2676                                    FromLoc, FromRange, &BasePath,
2677                                    IgnoreAccess))
2678     return ExprError();
2679 
2680   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2681                            VK, &BasePath);
2682 }
2683 
2684 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2685                                       const LookupResult &R,
2686                                       bool HasTrailingLParen) {
2687   // Only when used directly as the postfix-expression of a call.
2688   if (!HasTrailingLParen)
2689     return false;
2690 
2691   // Never if a scope specifier was provided.
2692   if (SS.isSet())
2693     return false;
2694 
2695   // Only in C++ or ObjC++.
2696   if (!getLangOpts().CPlusPlus)
2697     return false;
2698 
2699   // Turn off ADL when we find certain kinds of declarations during
2700   // normal lookup:
2701   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2702     NamedDecl *D = *I;
2703 
2704     // C++0x [basic.lookup.argdep]p3:
2705     //     -- a declaration of a class member
2706     // Since using decls preserve this property, we check this on the
2707     // original decl.
2708     if (D->isCXXClassMember())
2709       return false;
2710 
2711     // C++0x [basic.lookup.argdep]p3:
2712     //     -- a block-scope function declaration that is not a
2713     //        using-declaration
2714     // NOTE: we also trigger this for function templates (in fact, we
2715     // don't check the decl type at all, since all other decl types
2716     // turn off ADL anyway).
2717     if (isa<UsingShadowDecl>(D))
2718       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2719     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2720       return false;
2721 
2722     // C++0x [basic.lookup.argdep]p3:
2723     //     -- a declaration that is neither a function or a function
2724     //        template
2725     // And also for builtin functions.
2726     if (isa<FunctionDecl>(D)) {
2727       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2728 
2729       // But also builtin functions.
2730       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2731         return false;
2732     } else if (!isa<FunctionTemplateDecl>(D))
2733       return false;
2734   }
2735 
2736   return true;
2737 }
2738 
2739 
2740 /// Diagnoses obvious problems with the use of the given declaration
2741 /// as an expression.  This is only actually called for lookups that
2742 /// were not overloaded, and it doesn't promise that the declaration
2743 /// will in fact be used.
2744 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2745   if (isa<TypedefNameDecl>(D)) {
2746     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2747     return true;
2748   }
2749 
2750   if (isa<ObjCInterfaceDecl>(D)) {
2751     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2752     return true;
2753   }
2754 
2755   if (isa<NamespaceDecl>(D)) {
2756     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2757     return true;
2758   }
2759 
2760   return false;
2761 }
2762 
2763 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2764                                           LookupResult &R, bool NeedsADL,
2765                                           bool AcceptInvalidDecl) {
2766   // If this is a single, fully-resolved result and we don't need ADL,
2767   // just build an ordinary singleton decl ref.
2768   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2769     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2770                                     R.getRepresentativeDecl(), nullptr,
2771                                     AcceptInvalidDecl);
2772 
2773   // We only need to check the declaration if there's exactly one
2774   // result, because in the overloaded case the results can only be
2775   // functions and function templates.
2776   if (R.isSingleResult() &&
2777       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2778     return ExprError();
2779 
2780   // Otherwise, just build an unresolved lookup expression.  Suppress
2781   // any lookup-related diagnostics; we'll hash these out later, when
2782   // we've picked a target.
2783   R.suppressDiagnostics();
2784 
2785   UnresolvedLookupExpr *ULE
2786     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2787                                    SS.getWithLocInContext(Context),
2788                                    R.getLookupNameInfo(),
2789                                    NeedsADL, R.isOverloadedResult(),
2790                                    R.begin(), R.end());
2791 
2792   return ULE;
2793 }
2794 
2795 /// \brief Complete semantic analysis for a reference to the given declaration.
2796 ExprResult Sema::BuildDeclarationNameExpr(
2797     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2798     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2799     bool AcceptInvalidDecl) {
2800   assert(D && "Cannot refer to a NULL declaration");
2801   assert(!isa<FunctionTemplateDecl>(D) &&
2802          "Cannot refer unambiguously to a function template");
2803 
2804   SourceLocation Loc = NameInfo.getLoc();
2805   if (CheckDeclInExpr(*this, Loc, D))
2806     return ExprError();
2807 
2808   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2809     // Specifically diagnose references to class templates that are missing
2810     // a template argument list.
2811     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2812                                            << Template << SS.getRange();
2813     Diag(Template->getLocation(), diag::note_template_decl_here);
2814     return ExprError();
2815   }
2816 
2817   // Make sure that we're referring to a value.
2818   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2819   if (!VD) {
2820     Diag(Loc, diag::err_ref_non_value)
2821       << D << SS.getRange();
2822     Diag(D->getLocation(), diag::note_declared_at);
2823     return ExprError();
2824   }
2825 
2826   // Check whether this declaration can be used. Note that we suppress
2827   // this check when we're going to perform argument-dependent lookup
2828   // on this function name, because this might not be the function
2829   // that overload resolution actually selects.
2830   if (DiagnoseUseOfDecl(VD, Loc))
2831     return ExprError();
2832 
2833   // Only create DeclRefExpr's for valid Decl's.
2834   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2835     return ExprError();
2836 
2837   // Handle members of anonymous structs and unions.  If we got here,
2838   // and the reference is to a class member indirect field, then this
2839   // must be the subject of a pointer-to-member expression.
2840   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2841     if (!indirectField->isCXXClassMember())
2842       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2843                                                       indirectField);
2844 
2845   {
2846     QualType type = VD->getType();
2847     ExprValueKind valueKind = VK_RValue;
2848 
2849     switch (D->getKind()) {
2850     // Ignore all the non-ValueDecl kinds.
2851 #define ABSTRACT_DECL(kind)
2852 #define VALUE(type, base)
2853 #define DECL(type, base) \
2854     case Decl::type:
2855 #include "clang/AST/DeclNodes.inc"
2856       llvm_unreachable("invalid value decl kind");
2857 
2858     // These shouldn't make it here.
2859     case Decl::ObjCAtDefsField:
2860     case Decl::ObjCIvar:
2861       llvm_unreachable("forming non-member reference to ivar?");
2862 
2863     // Enum constants are always r-values and never references.
2864     // Unresolved using declarations are dependent.
2865     case Decl::EnumConstant:
2866     case Decl::UnresolvedUsingValue:
2867       valueKind = VK_RValue;
2868       break;
2869 
2870     // Fields and indirect fields that got here must be for
2871     // pointer-to-member expressions; we just call them l-values for
2872     // internal consistency, because this subexpression doesn't really
2873     // exist in the high-level semantics.
2874     case Decl::Field:
2875     case Decl::IndirectField:
2876       assert(getLangOpts().CPlusPlus &&
2877              "building reference to field in C?");
2878 
2879       // These can't have reference type in well-formed programs, but
2880       // for internal consistency we do this anyway.
2881       type = type.getNonReferenceType();
2882       valueKind = VK_LValue;
2883       break;
2884 
2885     // Non-type template parameters are either l-values or r-values
2886     // depending on the type.
2887     case Decl::NonTypeTemplateParm: {
2888       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2889         type = reftype->getPointeeType();
2890         valueKind = VK_LValue; // even if the parameter is an r-value reference
2891         break;
2892       }
2893 
2894       // For non-references, we need to strip qualifiers just in case
2895       // the template parameter was declared as 'const int' or whatever.
2896       valueKind = VK_RValue;
2897       type = type.getUnqualifiedType();
2898       break;
2899     }
2900 
2901     case Decl::Var:
2902     case Decl::VarTemplateSpecialization:
2903     case Decl::VarTemplatePartialSpecialization:
2904       // In C, "extern void blah;" is valid and is an r-value.
2905       if (!getLangOpts().CPlusPlus &&
2906           !type.hasQualifiers() &&
2907           type->isVoidType()) {
2908         valueKind = VK_RValue;
2909         break;
2910       }
2911       // fallthrough
2912 
2913     case Decl::ImplicitParam:
2914     case Decl::ParmVar: {
2915       // These are always l-values.
2916       valueKind = VK_LValue;
2917       type = type.getNonReferenceType();
2918 
2919       // FIXME: Does the addition of const really only apply in
2920       // potentially-evaluated contexts? Since the variable isn't actually
2921       // captured in an unevaluated context, it seems that the answer is no.
2922       if (!isUnevaluatedContext()) {
2923         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2924         if (!CapturedType.isNull())
2925           type = CapturedType;
2926       }
2927 
2928       break;
2929     }
2930 
2931     case Decl::Function: {
2932       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2933         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2934           type = Context.BuiltinFnTy;
2935           valueKind = VK_RValue;
2936           break;
2937         }
2938       }
2939 
2940       const FunctionType *fty = type->castAs<FunctionType>();
2941 
2942       // If we're referring to a function with an __unknown_anytype
2943       // result type, make the entire expression __unknown_anytype.
2944       if (fty->getReturnType() == Context.UnknownAnyTy) {
2945         type = Context.UnknownAnyTy;
2946         valueKind = VK_RValue;
2947         break;
2948       }
2949 
2950       // Functions are l-values in C++.
2951       if (getLangOpts().CPlusPlus) {
2952         valueKind = VK_LValue;
2953         break;
2954       }
2955 
2956       // C99 DR 316 says that, if a function type comes from a
2957       // function definition (without a prototype), that type is only
2958       // used for checking compatibility. Therefore, when referencing
2959       // the function, we pretend that we don't have the full function
2960       // type.
2961       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2962           isa<FunctionProtoType>(fty))
2963         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2964                                               fty->getExtInfo());
2965 
2966       // Functions are r-values in C.
2967       valueKind = VK_RValue;
2968       break;
2969     }
2970 
2971     case Decl::MSProperty:
2972       valueKind = VK_LValue;
2973       break;
2974 
2975     case Decl::CXXMethod:
2976       // If we're referring to a method with an __unknown_anytype
2977       // result type, make the entire expression __unknown_anytype.
2978       // This should only be possible with a type written directly.
2979       if (const FunctionProtoType *proto
2980             = dyn_cast<FunctionProtoType>(VD->getType()))
2981         if (proto->getReturnType() == Context.UnknownAnyTy) {
2982           type = Context.UnknownAnyTy;
2983           valueKind = VK_RValue;
2984           break;
2985         }
2986 
2987       // C++ methods are l-values if static, r-values if non-static.
2988       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2989         valueKind = VK_LValue;
2990         break;
2991       }
2992       // fallthrough
2993 
2994     case Decl::CXXConversion:
2995     case Decl::CXXDestructor:
2996     case Decl::CXXConstructor:
2997       valueKind = VK_RValue;
2998       break;
2999     }
3000 
3001     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3002                             TemplateArgs);
3003   }
3004 }
3005 
3006 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3007                                     SmallString<32> &Target) {
3008   Target.resize(CharByteWidth * (Source.size() + 1));
3009   char *ResultPtr = &Target[0];
3010   const UTF8 *ErrorPtr;
3011   bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3012   (void)success;
3013   assert(success);
3014   Target.resize(ResultPtr - &Target[0]);
3015 }
3016 
3017 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3018                                      PredefinedExpr::IdentType IT) {
3019   // Pick the current block, lambda, captured statement or function.
3020   Decl *currentDecl = nullptr;
3021   if (const BlockScopeInfo *BSI = getCurBlock())
3022     currentDecl = BSI->TheDecl;
3023   else if (const LambdaScopeInfo *LSI = getCurLambda())
3024     currentDecl = LSI->CallOperator;
3025   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3026     currentDecl = CSI->TheCapturedDecl;
3027   else
3028     currentDecl = getCurFunctionOrMethodDecl();
3029 
3030   if (!currentDecl) {
3031     Diag(Loc, diag::ext_predef_outside_function);
3032     currentDecl = Context.getTranslationUnitDecl();
3033   }
3034 
3035   QualType ResTy;
3036   StringLiteral *SL = nullptr;
3037   if (cast<DeclContext>(currentDecl)->isDependentContext())
3038     ResTy = Context.DependentTy;
3039   else {
3040     // Pre-defined identifiers are of type char[x], where x is the length of
3041     // the string.
3042     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3043     unsigned Length = Str.length();
3044 
3045     llvm::APInt LengthI(32, Length + 1);
3046     if (IT == PredefinedExpr::LFunction) {
3047       ResTy = Context.WideCharTy.withConst();
3048       SmallString<32> RawChars;
3049       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3050                               Str, RawChars);
3051       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3052                                            /*IndexTypeQuals*/ 0);
3053       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3054                                  /*Pascal*/ false, ResTy, Loc);
3055     } else {
3056       ResTy = Context.CharTy.withConst();
3057       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3058                                            /*IndexTypeQuals*/ 0);
3059       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3060                                  /*Pascal*/ false, ResTy, Loc);
3061     }
3062   }
3063 
3064   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3065 }
3066 
3067 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3068   PredefinedExpr::IdentType IT;
3069 
3070   switch (Kind) {
3071   default: llvm_unreachable("Unknown simple primary expr!");
3072   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3073   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3074   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3075   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3076   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3077   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3078   }
3079 
3080   return BuildPredefinedExpr(Loc, IT);
3081 }
3082 
3083 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3084   SmallString<16> CharBuffer;
3085   bool Invalid = false;
3086   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3087   if (Invalid)
3088     return ExprError();
3089 
3090   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3091                             PP, Tok.getKind());
3092   if (Literal.hadError())
3093     return ExprError();
3094 
3095   QualType Ty;
3096   if (Literal.isWide())
3097     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3098   else if (Literal.isUTF16())
3099     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3100   else if (Literal.isUTF32())
3101     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3102   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3103     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3104   else
3105     Ty = Context.CharTy;  // 'x' -> char in C++
3106 
3107   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3108   if (Literal.isWide())
3109     Kind = CharacterLiteral::Wide;
3110   else if (Literal.isUTF16())
3111     Kind = CharacterLiteral::UTF16;
3112   else if (Literal.isUTF32())
3113     Kind = CharacterLiteral::UTF32;
3114 
3115   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3116                                              Tok.getLocation());
3117 
3118   if (Literal.getUDSuffix().empty())
3119     return Lit;
3120 
3121   // We're building a user-defined literal.
3122   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3123   SourceLocation UDSuffixLoc =
3124     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3125 
3126   // Make sure we're allowed user-defined literals here.
3127   if (!UDLScope)
3128     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3129 
3130   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3131   //   operator "" X (ch)
3132   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3133                                         Lit, Tok.getLocation());
3134 }
3135 
3136 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3137   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3138   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3139                                 Context.IntTy, Loc);
3140 }
3141 
3142 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3143                                   QualType Ty, SourceLocation Loc) {
3144   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3145 
3146   using llvm::APFloat;
3147   APFloat Val(Format);
3148 
3149   APFloat::opStatus result = Literal.GetFloatValue(Val);
3150 
3151   // Overflow is always an error, but underflow is only an error if
3152   // we underflowed to zero (APFloat reports denormals as underflow).
3153   if ((result & APFloat::opOverflow) ||
3154       ((result & APFloat::opUnderflow) && Val.isZero())) {
3155     unsigned diagnostic;
3156     SmallString<20> buffer;
3157     if (result & APFloat::opOverflow) {
3158       diagnostic = diag::warn_float_overflow;
3159       APFloat::getLargest(Format).toString(buffer);
3160     } else {
3161       diagnostic = diag::warn_float_underflow;
3162       APFloat::getSmallest(Format).toString(buffer);
3163     }
3164 
3165     S.Diag(Loc, diagnostic)
3166       << Ty
3167       << StringRef(buffer.data(), buffer.size());
3168   }
3169 
3170   bool isExact = (result == APFloat::opOK);
3171   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3172 }
3173 
3174 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3175   assert(E && "Invalid expression");
3176 
3177   if (E->isValueDependent())
3178     return false;
3179 
3180   QualType QT = E->getType();
3181   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3182     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3183     return true;
3184   }
3185 
3186   llvm::APSInt ValueAPS;
3187   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3188 
3189   if (R.isInvalid())
3190     return true;
3191 
3192   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3193   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3194     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3195         << ValueAPS.toString(10) << ValueIsPositive;
3196     return true;
3197   }
3198 
3199   return false;
3200 }
3201 
3202 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3203   // Fast path for a single digit (which is quite common).  A single digit
3204   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3205   if (Tok.getLength() == 1) {
3206     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3207     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3208   }
3209 
3210   SmallString<128> SpellingBuffer;
3211   // NumericLiteralParser wants to overread by one character.  Add padding to
3212   // the buffer in case the token is copied to the buffer.  If getSpelling()
3213   // returns a StringRef to the memory buffer, it should have a null char at
3214   // the EOF, so it is also safe.
3215   SpellingBuffer.resize(Tok.getLength() + 1);
3216 
3217   // Get the spelling of the token, which eliminates trigraphs, etc.
3218   bool Invalid = false;
3219   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3220   if (Invalid)
3221     return ExprError();
3222 
3223   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3224   if (Literal.hadError)
3225     return ExprError();
3226 
3227   if (Literal.hasUDSuffix()) {
3228     // We're building a user-defined literal.
3229     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3230     SourceLocation UDSuffixLoc =
3231       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3232 
3233     // Make sure we're allowed user-defined literals here.
3234     if (!UDLScope)
3235       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3236 
3237     QualType CookedTy;
3238     if (Literal.isFloatingLiteral()) {
3239       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3240       // long double, the literal is treated as a call of the form
3241       //   operator "" X (f L)
3242       CookedTy = Context.LongDoubleTy;
3243     } else {
3244       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3245       // unsigned long long, the literal is treated as a call of the form
3246       //   operator "" X (n ULL)
3247       CookedTy = Context.UnsignedLongLongTy;
3248     }
3249 
3250     DeclarationName OpName =
3251       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3252     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3253     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3254 
3255     SourceLocation TokLoc = Tok.getLocation();
3256 
3257     // Perform literal operator lookup to determine if we're building a raw
3258     // literal or a cooked one.
3259     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3260     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3261                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3262                                   /*AllowStringTemplate*/false)) {
3263     case LOLR_Error:
3264       return ExprError();
3265 
3266     case LOLR_Cooked: {
3267       Expr *Lit;
3268       if (Literal.isFloatingLiteral()) {
3269         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3270       } else {
3271         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3272         if (Literal.GetIntegerValue(ResultVal))
3273           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3274               << /* Unsigned */ 1;
3275         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3276                                      Tok.getLocation());
3277       }
3278       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3279     }
3280 
3281     case LOLR_Raw: {
3282       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3283       // literal is treated as a call of the form
3284       //   operator "" X ("n")
3285       unsigned Length = Literal.getUDSuffixOffset();
3286       QualType StrTy = Context.getConstantArrayType(
3287           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3288           ArrayType::Normal, 0);
3289       Expr *Lit = StringLiteral::Create(
3290           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3291           /*Pascal*/false, StrTy, &TokLoc, 1);
3292       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3293     }
3294 
3295     case LOLR_Template: {
3296       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3297       // template), L is treated as a call fo the form
3298       //   operator "" X <'c1', 'c2', ... 'ck'>()
3299       // where n is the source character sequence c1 c2 ... ck.
3300       TemplateArgumentListInfo ExplicitArgs;
3301       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3302       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3303       llvm::APSInt Value(CharBits, CharIsUnsigned);
3304       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3305         Value = TokSpelling[I];
3306         TemplateArgument Arg(Context, Value, Context.CharTy);
3307         TemplateArgumentLocInfo ArgInfo;
3308         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3309       }
3310       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3311                                       &ExplicitArgs);
3312     }
3313     case LOLR_StringTemplate:
3314       llvm_unreachable("unexpected literal operator lookup result");
3315     }
3316   }
3317 
3318   Expr *Res;
3319 
3320   if (Literal.isFloatingLiteral()) {
3321     QualType Ty;
3322     if (Literal.isFloat)
3323       Ty = Context.FloatTy;
3324     else if (!Literal.isLong)
3325       Ty = Context.DoubleTy;
3326     else
3327       Ty = Context.LongDoubleTy;
3328 
3329     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3330 
3331     if (Ty == Context.DoubleTy) {
3332       if (getLangOpts().SinglePrecisionConstants) {
3333         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3334       } else if (getLangOpts().OpenCL &&
3335                  !((getLangOpts().OpenCLVersion >= 120) ||
3336                    getOpenCLOptions().cl_khr_fp64)) {
3337         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3338         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3339       }
3340     }
3341   } else if (!Literal.isIntegerLiteral()) {
3342     return ExprError();
3343   } else {
3344     QualType Ty;
3345 
3346     // 'long long' is a C99 or C++11 feature.
3347     if (!getLangOpts().C99 && Literal.isLongLong) {
3348       if (getLangOpts().CPlusPlus)
3349         Diag(Tok.getLocation(),
3350              getLangOpts().CPlusPlus11 ?
3351              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3352       else
3353         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3354     }
3355 
3356     // Get the value in the widest-possible width.
3357     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3358     // The microsoft literal suffix extensions support 128-bit literals, which
3359     // may be wider than [u]intmax_t.
3360     // FIXME: Actually, they don't. We seem to have accidentally invented the
3361     //        i128 suffix.
3362     if (Literal.MicrosoftInteger == 128 && MaxWidth < 128 &&
3363         Context.getTargetInfo().hasInt128Type())
3364       MaxWidth = 128;
3365     llvm::APInt ResultVal(MaxWidth, 0);
3366 
3367     if (Literal.GetIntegerValue(ResultVal)) {
3368       // If this value didn't fit into uintmax_t, error and force to ull.
3369       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3370           << /* Unsigned */ 1;
3371       Ty = Context.UnsignedLongLongTy;
3372       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3373              "long long is not intmax_t?");
3374     } else {
3375       // If this value fits into a ULL, try to figure out what else it fits into
3376       // according to the rules of C99 6.4.4.1p5.
3377 
3378       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3379       // be an unsigned int.
3380       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3381 
3382       // Check from smallest to largest, picking the smallest type we can.
3383       unsigned Width = 0;
3384 
3385       // Microsoft specific integer suffixes are explicitly sized.
3386       if (Literal.MicrosoftInteger) {
3387         if (Literal.MicrosoftInteger > MaxWidth) {
3388           // If this target doesn't support __int128, error and force to ull.
3389           Diag(Tok.getLocation(), diag::err_int128_unsupported);
3390           Width = MaxWidth;
3391           Ty = Context.getIntMaxType();
3392         } else if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3393           Width = 8;
3394           Ty = Context.CharTy;
3395         } else {
3396           Width = Literal.MicrosoftInteger;
3397           Ty = Context.getIntTypeForBitwidth(Width,
3398                                              /*Signed=*/!Literal.isUnsigned);
3399         }
3400       }
3401 
3402       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3403         // Are int/unsigned possibilities?
3404         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3405 
3406         // Does it fit in a unsigned int?
3407         if (ResultVal.isIntN(IntSize)) {
3408           // Does it fit in a signed int?
3409           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3410             Ty = Context.IntTy;
3411           else if (AllowUnsigned)
3412             Ty = Context.UnsignedIntTy;
3413           Width = IntSize;
3414         }
3415       }
3416 
3417       // Are long/unsigned long possibilities?
3418       if (Ty.isNull() && !Literal.isLongLong) {
3419         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3420 
3421         // Does it fit in a unsigned long?
3422         if (ResultVal.isIntN(LongSize)) {
3423           // Does it fit in a signed long?
3424           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3425             Ty = Context.LongTy;
3426           else if (AllowUnsigned)
3427             Ty = Context.UnsignedLongTy;
3428           Width = LongSize;
3429         }
3430       }
3431 
3432       // Check long long if needed.
3433       if (Ty.isNull()) {
3434         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3435 
3436         // Does it fit in a unsigned long long?
3437         if (ResultVal.isIntN(LongLongSize)) {
3438           // Does it fit in a signed long long?
3439           // To be compatible with MSVC, hex integer literals ending with the
3440           // LL or i64 suffix are always signed in Microsoft mode.
3441           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3442               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3443             Ty = Context.LongLongTy;
3444           else if (AllowUnsigned)
3445             Ty = Context.UnsignedLongLongTy;
3446           Width = LongLongSize;
3447         }
3448       }
3449 
3450       // If we still couldn't decide a type, we probably have something that
3451       // does not fit in a signed long long, but has no U suffix.
3452       if (Ty.isNull()) {
3453         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3454         Ty = Context.UnsignedLongLongTy;
3455         Width = Context.getTargetInfo().getLongLongWidth();
3456       }
3457 
3458       if (ResultVal.getBitWidth() != Width)
3459         ResultVal = ResultVal.trunc(Width);
3460     }
3461     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3462   }
3463 
3464   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3465   if (Literal.isImaginary)
3466     Res = new (Context) ImaginaryLiteral(Res,
3467                                         Context.getComplexType(Res->getType()));
3468 
3469   return Res;
3470 }
3471 
3472 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3473   assert(E && "ActOnParenExpr() missing expr");
3474   return new (Context) ParenExpr(L, R, E);
3475 }
3476 
3477 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3478                                          SourceLocation Loc,
3479                                          SourceRange ArgRange) {
3480   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3481   // scalar or vector data type argument..."
3482   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3483   // type (C99 6.2.5p18) or void.
3484   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3485     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3486       << T << ArgRange;
3487     return true;
3488   }
3489 
3490   assert((T->isVoidType() || !T->isIncompleteType()) &&
3491          "Scalar types should always be complete");
3492   return false;
3493 }
3494 
3495 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3496                                            SourceLocation Loc,
3497                                            SourceRange ArgRange,
3498                                            UnaryExprOrTypeTrait TraitKind) {
3499   // Invalid types must be hard errors for SFINAE in C++.
3500   if (S.LangOpts.CPlusPlus)
3501     return true;
3502 
3503   // C99 6.5.3.4p1:
3504   if (T->isFunctionType() &&
3505       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3506     // sizeof(function)/alignof(function) is allowed as an extension.
3507     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3508       << TraitKind << ArgRange;
3509     return false;
3510   }
3511 
3512   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3513   // this is an error (OpenCL v1.1 s6.3.k)
3514   if (T->isVoidType()) {
3515     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3516                                         : diag::ext_sizeof_alignof_void_type;
3517     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3518     return false;
3519   }
3520 
3521   return true;
3522 }
3523 
3524 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3525                                              SourceLocation Loc,
3526                                              SourceRange ArgRange,
3527                                              UnaryExprOrTypeTrait TraitKind) {
3528   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3529   // runtime doesn't allow it.
3530   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3531     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3532       << T << (TraitKind == UETT_SizeOf)
3533       << ArgRange;
3534     return true;
3535   }
3536 
3537   return false;
3538 }
3539 
3540 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3541 /// pointer type is equal to T) and emit a warning if it is.
3542 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3543                                      Expr *E) {
3544   // Don't warn if the operation changed the type.
3545   if (T != E->getType())
3546     return;
3547 
3548   // Now look for array decays.
3549   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3550   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3551     return;
3552 
3553   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3554                                              << ICE->getType()
3555                                              << ICE->getSubExpr()->getType();
3556 }
3557 
3558 /// \brief Check the constraints on expression operands to unary type expression
3559 /// and type traits.
3560 ///
3561 /// Completes any types necessary and validates the constraints on the operand
3562 /// expression. The logic mostly mirrors the type-based overload, but may modify
3563 /// the expression as it completes the type for that expression through template
3564 /// instantiation, etc.
3565 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3566                                             UnaryExprOrTypeTrait ExprKind) {
3567   QualType ExprTy = E->getType();
3568   assert(!ExprTy->isReferenceType());
3569 
3570   if (ExprKind == UETT_VecStep)
3571     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3572                                         E->getSourceRange());
3573 
3574   // Whitelist some types as extensions
3575   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3576                                       E->getSourceRange(), ExprKind))
3577     return false;
3578 
3579   // 'alignof' applied to an expression only requires the base element type of
3580   // the expression to be complete. 'sizeof' requires the expression's type to
3581   // be complete (and will attempt to complete it if it's an array of unknown
3582   // bound).
3583   if (ExprKind == UETT_AlignOf) {
3584     if (RequireCompleteType(E->getExprLoc(),
3585                             Context.getBaseElementType(E->getType()),
3586                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3587                             E->getSourceRange()))
3588       return true;
3589   } else {
3590     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3591                                 ExprKind, E->getSourceRange()))
3592       return true;
3593   }
3594 
3595   // Completing the expression's type may have changed it.
3596   ExprTy = E->getType();
3597   assert(!ExprTy->isReferenceType());
3598 
3599   if (ExprTy->isFunctionType()) {
3600     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3601       << ExprKind << E->getSourceRange();
3602     return true;
3603   }
3604 
3605   // The operand for sizeof and alignof is in an unevaluated expression context,
3606   // so side effects could result in unintended consequences.
3607   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3608       ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3609     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3610 
3611   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3612                                        E->getSourceRange(), ExprKind))
3613     return true;
3614 
3615   if (ExprKind == UETT_SizeOf) {
3616     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3617       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3618         QualType OType = PVD->getOriginalType();
3619         QualType Type = PVD->getType();
3620         if (Type->isPointerType() && OType->isArrayType()) {
3621           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3622             << Type << OType;
3623           Diag(PVD->getLocation(), diag::note_declared_at);
3624         }
3625       }
3626     }
3627 
3628     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3629     // decays into a pointer and returns an unintended result. This is most
3630     // likely a typo for "sizeof(array) op x".
3631     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3632       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3633                                BO->getLHS());
3634       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3635                                BO->getRHS());
3636     }
3637   }
3638 
3639   return false;
3640 }
3641 
3642 /// \brief Check the constraints on operands to unary expression and type
3643 /// traits.
3644 ///
3645 /// This will complete any types necessary, and validate the various constraints
3646 /// on those operands.
3647 ///
3648 /// The UsualUnaryConversions() function is *not* called by this routine.
3649 /// C99 6.3.2.1p[2-4] all state:
3650 ///   Except when it is the operand of the sizeof operator ...
3651 ///
3652 /// C++ [expr.sizeof]p4
3653 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3654 ///   standard conversions are not applied to the operand of sizeof.
3655 ///
3656 /// This policy is followed for all of the unary trait expressions.
3657 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3658                                             SourceLocation OpLoc,
3659                                             SourceRange ExprRange,
3660                                             UnaryExprOrTypeTrait ExprKind) {
3661   if (ExprType->isDependentType())
3662     return false;
3663 
3664   // C++ [expr.sizeof]p2:
3665   //     When applied to a reference or a reference type, the result
3666   //     is the size of the referenced type.
3667   // C++11 [expr.alignof]p3:
3668   //     When alignof is applied to a reference type, the result
3669   //     shall be the alignment of the referenced type.
3670   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3671     ExprType = Ref->getPointeeType();
3672 
3673   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3674   //   When alignof or _Alignof is applied to an array type, the result
3675   //   is the alignment of the element type.
3676   if (ExprKind == UETT_AlignOf)
3677     ExprType = Context.getBaseElementType(ExprType);
3678 
3679   if (ExprKind == UETT_VecStep)
3680     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3681 
3682   // Whitelist some types as extensions
3683   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3684                                       ExprKind))
3685     return false;
3686 
3687   if (RequireCompleteType(OpLoc, ExprType,
3688                           diag::err_sizeof_alignof_incomplete_type,
3689                           ExprKind, ExprRange))
3690     return true;
3691 
3692   if (ExprType->isFunctionType()) {
3693     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3694       << ExprKind << ExprRange;
3695     return true;
3696   }
3697 
3698   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3699                                        ExprKind))
3700     return true;
3701 
3702   return false;
3703 }
3704 
3705 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3706   E = E->IgnoreParens();
3707 
3708   // Cannot know anything else if the expression is dependent.
3709   if (E->isTypeDependent())
3710     return false;
3711 
3712   if (E->getObjectKind() == OK_BitField) {
3713     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3714        << 1 << E->getSourceRange();
3715     return true;
3716   }
3717 
3718   ValueDecl *D = nullptr;
3719   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3720     D = DRE->getDecl();
3721   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3722     D = ME->getMemberDecl();
3723   }
3724 
3725   // If it's a field, require the containing struct to have a
3726   // complete definition so that we can compute the layout.
3727   //
3728   // This can happen in C++11 onwards, either by naming the member
3729   // in a way that is not transformed into a member access expression
3730   // (in an unevaluated operand, for instance), or by naming the member
3731   // in a trailing-return-type.
3732   //
3733   // For the record, since __alignof__ on expressions is a GCC
3734   // extension, GCC seems to permit this but always gives the
3735   // nonsensical answer 0.
3736   //
3737   // We don't really need the layout here --- we could instead just
3738   // directly check for all the appropriate alignment-lowing
3739   // attributes --- but that would require duplicating a lot of
3740   // logic that just isn't worth duplicating for such a marginal
3741   // use-case.
3742   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3743     // Fast path this check, since we at least know the record has a
3744     // definition if we can find a member of it.
3745     if (!FD->getParent()->isCompleteDefinition()) {
3746       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3747         << E->getSourceRange();
3748       return true;
3749     }
3750 
3751     // Otherwise, if it's a field, and the field doesn't have
3752     // reference type, then it must have a complete type (or be a
3753     // flexible array member, which we explicitly want to
3754     // white-list anyway), which makes the following checks trivial.
3755     if (!FD->getType()->isReferenceType())
3756       return false;
3757   }
3758 
3759   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3760 }
3761 
3762 bool Sema::CheckVecStepExpr(Expr *E) {
3763   E = E->IgnoreParens();
3764 
3765   // Cannot know anything else if the expression is dependent.
3766   if (E->isTypeDependent())
3767     return false;
3768 
3769   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3770 }
3771 
3772 /// \brief Build a sizeof or alignof expression given a type operand.
3773 ExprResult
3774 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3775                                      SourceLocation OpLoc,
3776                                      UnaryExprOrTypeTrait ExprKind,
3777                                      SourceRange R) {
3778   if (!TInfo)
3779     return ExprError();
3780 
3781   QualType T = TInfo->getType();
3782 
3783   if (!T->isDependentType() &&
3784       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3785     return ExprError();
3786 
3787   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3788   return new (Context) UnaryExprOrTypeTraitExpr(
3789       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3790 }
3791 
3792 /// \brief Build a sizeof or alignof expression given an expression
3793 /// operand.
3794 ExprResult
3795 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3796                                      UnaryExprOrTypeTrait ExprKind) {
3797   ExprResult PE = CheckPlaceholderExpr(E);
3798   if (PE.isInvalid())
3799     return ExprError();
3800 
3801   E = PE.get();
3802 
3803   // Verify that the operand is valid.
3804   bool isInvalid = false;
3805   if (E->isTypeDependent()) {
3806     // Delay type-checking for type-dependent expressions.
3807   } else if (ExprKind == UETT_AlignOf) {
3808     isInvalid = CheckAlignOfExpr(*this, E);
3809   } else if (ExprKind == UETT_VecStep) {
3810     isInvalid = CheckVecStepExpr(E);
3811   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3812     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3813     isInvalid = true;
3814   } else {
3815     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3816   }
3817 
3818   if (isInvalid)
3819     return ExprError();
3820 
3821   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3822     PE = TransformToPotentiallyEvaluated(E);
3823     if (PE.isInvalid()) return ExprError();
3824     E = PE.get();
3825   }
3826 
3827   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3828   return new (Context) UnaryExprOrTypeTraitExpr(
3829       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
3830 }
3831 
3832 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3833 /// expr and the same for @c alignof and @c __alignof
3834 /// Note that the ArgRange is invalid if isType is false.
3835 ExprResult
3836 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3837                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3838                                     void *TyOrEx, const SourceRange &ArgRange) {
3839   // If error parsing type, ignore.
3840   if (!TyOrEx) return ExprError();
3841 
3842   if (IsType) {
3843     TypeSourceInfo *TInfo;
3844     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3845     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3846   }
3847 
3848   Expr *ArgEx = (Expr *)TyOrEx;
3849   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3850   return Result;
3851 }
3852 
3853 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3854                                      bool IsReal) {
3855   if (V.get()->isTypeDependent())
3856     return S.Context.DependentTy;
3857 
3858   // _Real and _Imag are only l-values for normal l-values.
3859   if (V.get()->getObjectKind() != OK_Ordinary) {
3860     V = S.DefaultLvalueConversion(V.get());
3861     if (V.isInvalid())
3862       return QualType();
3863   }
3864 
3865   // These operators return the element type of a complex type.
3866   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3867     return CT->getElementType();
3868 
3869   // Otherwise they pass through real integer and floating point types here.
3870   if (V.get()->getType()->isArithmeticType())
3871     return V.get()->getType();
3872 
3873   // Test for placeholders.
3874   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3875   if (PR.isInvalid()) return QualType();
3876   if (PR.get() != V.get()) {
3877     V = PR;
3878     return CheckRealImagOperand(S, V, Loc, IsReal);
3879   }
3880 
3881   // Reject anything else.
3882   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3883     << (IsReal ? "__real" : "__imag");
3884   return QualType();
3885 }
3886 
3887 
3888 
3889 ExprResult
3890 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3891                           tok::TokenKind Kind, Expr *Input) {
3892   UnaryOperatorKind Opc;
3893   switch (Kind) {
3894   default: llvm_unreachable("Unknown unary op!");
3895   case tok::plusplus:   Opc = UO_PostInc; break;
3896   case tok::minusminus: Opc = UO_PostDec; break;
3897   }
3898 
3899   // Since this might is a postfix expression, get rid of ParenListExprs.
3900   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3901   if (Result.isInvalid()) return ExprError();
3902   Input = Result.get();
3903 
3904   return BuildUnaryOp(S, OpLoc, Opc, Input);
3905 }
3906 
3907 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3908 ///
3909 /// \return true on error
3910 static bool checkArithmeticOnObjCPointer(Sema &S,
3911                                          SourceLocation opLoc,
3912                                          Expr *op) {
3913   assert(op->getType()->isObjCObjectPointerType());
3914   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
3915       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
3916     return false;
3917 
3918   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3919     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3920     << op->getSourceRange();
3921   return true;
3922 }
3923 
3924 ExprResult
3925 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3926                               Expr *idx, SourceLocation rbLoc) {
3927   // Since this might be a postfix expression, get rid of ParenListExprs.
3928   if (isa<ParenListExpr>(base)) {
3929     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3930     if (result.isInvalid()) return ExprError();
3931     base = result.get();
3932   }
3933 
3934   // Handle any non-overload placeholder types in the base and index
3935   // expressions.  We can't handle overloads here because the other
3936   // operand might be an overloadable type, in which case the overload
3937   // resolution for the operator overload should get the first crack
3938   // at the overload.
3939   if (base->getType()->isNonOverloadPlaceholderType()) {
3940     ExprResult result = CheckPlaceholderExpr(base);
3941     if (result.isInvalid()) return ExprError();
3942     base = result.get();
3943   }
3944   if (idx->getType()->isNonOverloadPlaceholderType()) {
3945     ExprResult result = CheckPlaceholderExpr(idx);
3946     if (result.isInvalid()) return ExprError();
3947     idx = result.get();
3948   }
3949 
3950   // Build an unanalyzed expression if either operand is type-dependent.
3951   if (getLangOpts().CPlusPlus &&
3952       (base->isTypeDependent() || idx->isTypeDependent())) {
3953     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
3954                                             VK_LValue, OK_Ordinary, rbLoc);
3955   }
3956 
3957   // Use C++ overloaded-operator rules if either operand has record
3958   // type.  The spec says to do this if either type is *overloadable*,
3959   // but enum types can't declare subscript operators or conversion
3960   // operators, so there's nothing interesting for overload resolution
3961   // to do if there aren't any record types involved.
3962   //
3963   // ObjC pointers have their own subscripting logic that is not tied
3964   // to overload resolution and so should not take this path.
3965   if (getLangOpts().CPlusPlus &&
3966       (base->getType()->isRecordType() ||
3967        (!base->getType()->isObjCObjectPointerType() &&
3968         idx->getType()->isRecordType()))) {
3969     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3970   }
3971 
3972   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3973 }
3974 
3975 ExprResult
3976 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3977                                       Expr *Idx, SourceLocation RLoc) {
3978   Expr *LHSExp = Base;
3979   Expr *RHSExp = Idx;
3980 
3981   // Perform default conversions.
3982   if (!LHSExp->getType()->getAs<VectorType>()) {
3983     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3984     if (Result.isInvalid())
3985       return ExprError();
3986     LHSExp = Result.get();
3987   }
3988   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3989   if (Result.isInvalid())
3990     return ExprError();
3991   RHSExp = Result.get();
3992 
3993   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3994   ExprValueKind VK = VK_LValue;
3995   ExprObjectKind OK = OK_Ordinary;
3996 
3997   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3998   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3999   // in the subscript position. As a result, we need to derive the array base
4000   // and index from the expression types.
4001   Expr *BaseExpr, *IndexExpr;
4002   QualType ResultType;
4003   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4004     BaseExpr = LHSExp;
4005     IndexExpr = RHSExp;
4006     ResultType = Context.DependentTy;
4007   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4008     BaseExpr = LHSExp;
4009     IndexExpr = RHSExp;
4010     ResultType = PTy->getPointeeType();
4011   } else if (const ObjCObjectPointerType *PTy =
4012                LHSTy->getAs<ObjCObjectPointerType>()) {
4013     BaseExpr = LHSExp;
4014     IndexExpr = RHSExp;
4015 
4016     // Use custom logic if this should be the pseudo-object subscript
4017     // expression.
4018     if (!LangOpts.isSubscriptPointerArithmetic())
4019       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4020                                           nullptr);
4021 
4022     ResultType = PTy->getPointeeType();
4023   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4024      // Handle the uncommon case of "123[Ptr]".
4025     BaseExpr = RHSExp;
4026     IndexExpr = LHSExp;
4027     ResultType = PTy->getPointeeType();
4028   } else if (const ObjCObjectPointerType *PTy =
4029                RHSTy->getAs<ObjCObjectPointerType>()) {
4030      // Handle the uncommon case of "123[Ptr]".
4031     BaseExpr = RHSExp;
4032     IndexExpr = LHSExp;
4033     ResultType = PTy->getPointeeType();
4034     if (!LangOpts.isSubscriptPointerArithmetic()) {
4035       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4036         << ResultType << BaseExpr->getSourceRange();
4037       return ExprError();
4038     }
4039   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4040     BaseExpr = LHSExp;    // vectors: V[123]
4041     IndexExpr = RHSExp;
4042     VK = LHSExp->getValueKind();
4043     if (VK != VK_RValue)
4044       OK = OK_VectorComponent;
4045 
4046     // FIXME: need to deal with const...
4047     ResultType = VTy->getElementType();
4048   } else if (LHSTy->isArrayType()) {
4049     // If we see an array that wasn't promoted by
4050     // DefaultFunctionArrayLvalueConversion, it must be an array that
4051     // wasn't promoted because of the C90 rule that doesn't
4052     // allow promoting non-lvalue arrays.  Warn, then
4053     // force the promotion here.
4054     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4055         LHSExp->getSourceRange();
4056     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4057                                CK_ArrayToPointerDecay).get();
4058     LHSTy = LHSExp->getType();
4059 
4060     BaseExpr = LHSExp;
4061     IndexExpr = RHSExp;
4062     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4063   } else if (RHSTy->isArrayType()) {
4064     // Same as previous, except for 123[f().a] case
4065     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4066         RHSExp->getSourceRange();
4067     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4068                                CK_ArrayToPointerDecay).get();
4069     RHSTy = RHSExp->getType();
4070 
4071     BaseExpr = RHSExp;
4072     IndexExpr = LHSExp;
4073     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4074   } else {
4075     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4076        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4077   }
4078   // C99 6.5.2.1p1
4079   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4080     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4081                      << IndexExpr->getSourceRange());
4082 
4083   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4084        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4085          && !IndexExpr->isTypeDependent())
4086     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4087 
4088   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4089   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4090   // type. Note that Functions are not objects, and that (in C99 parlance)
4091   // incomplete types are not object types.
4092   if (ResultType->isFunctionType()) {
4093     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4094       << ResultType << BaseExpr->getSourceRange();
4095     return ExprError();
4096   }
4097 
4098   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4099     // GNU extension: subscripting on pointer to void
4100     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4101       << BaseExpr->getSourceRange();
4102 
4103     // C forbids expressions of unqualified void type from being l-values.
4104     // See IsCForbiddenLValueType.
4105     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4106   } else if (!ResultType->isDependentType() &&
4107       RequireCompleteType(LLoc, ResultType,
4108                           diag::err_subscript_incomplete_type, BaseExpr))
4109     return ExprError();
4110 
4111   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4112          !ResultType.isCForbiddenLValueType());
4113 
4114   return new (Context)
4115       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4116 }
4117 
4118 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4119                                         FunctionDecl *FD,
4120                                         ParmVarDecl *Param) {
4121   if (Param->hasUnparsedDefaultArg()) {
4122     Diag(CallLoc,
4123          diag::err_use_of_default_argument_to_function_declared_later) <<
4124       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4125     Diag(UnparsedDefaultArgLocs[Param],
4126          diag::note_default_argument_declared_here);
4127     return ExprError();
4128   }
4129 
4130   if (Param->hasUninstantiatedDefaultArg()) {
4131     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4132 
4133     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4134                                                  Param);
4135 
4136     // Instantiate the expression.
4137     MultiLevelTemplateArgumentList MutiLevelArgList
4138       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4139 
4140     InstantiatingTemplate Inst(*this, CallLoc, Param,
4141                                MutiLevelArgList.getInnermost());
4142     if (Inst.isInvalid())
4143       return ExprError();
4144 
4145     ExprResult Result;
4146     {
4147       // C++ [dcl.fct.default]p5:
4148       //   The names in the [default argument] expression are bound, and
4149       //   the semantic constraints are checked, at the point where the
4150       //   default argument expression appears.
4151       ContextRAII SavedContext(*this, FD);
4152       LocalInstantiationScope Local(*this);
4153       Result = SubstExpr(UninstExpr, MutiLevelArgList);
4154     }
4155     if (Result.isInvalid())
4156       return ExprError();
4157 
4158     // Check the expression as an initializer for the parameter.
4159     InitializedEntity Entity
4160       = InitializedEntity::InitializeParameter(Context, Param);
4161     InitializationKind Kind
4162       = InitializationKind::CreateCopy(Param->getLocation(),
4163              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4164     Expr *ResultE = Result.getAs<Expr>();
4165 
4166     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4167     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4168     if (Result.isInvalid())
4169       return ExprError();
4170 
4171     Expr *Arg = Result.getAs<Expr>();
4172     CheckCompletedExpr(Arg, Param->getOuterLocStart());
4173     // Build the default argument expression.
4174     return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
4175   }
4176 
4177   // If the default expression creates temporaries, we need to
4178   // push them to the current stack of expression temporaries so they'll
4179   // be properly destroyed.
4180   // FIXME: We should really be rebuilding the default argument with new
4181   // bound temporaries; see the comment in PR5810.
4182   // We don't need to do that with block decls, though, because
4183   // blocks in default argument expression can never capture anything.
4184   if (isa<ExprWithCleanups>(Param->getInit())) {
4185     // Set the "needs cleanups" bit regardless of whether there are
4186     // any explicit objects.
4187     ExprNeedsCleanups = true;
4188 
4189     // Append all the objects to the cleanup list.  Right now, this
4190     // should always be a no-op, because blocks in default argument
4191     // expressions should never be able to capture anything.
4192     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
4193            "default argument expression has capturing blocks?");
4194   }
4195 
4196   // We already type-checked the argument, so we know it works.
4197   // Just mark all of the declarations in this potentially-evaluated expression
4198   // as being "referenced".
4199   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4200                                    /*SkipLocalVariables=*/true);
4201   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4202 }
4203 
4204 
4205 Sema::VariadicCallType
4206 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4207                           Expr *Fn) {
4208   if (Proto && Proto->isVariadic()) {
4209     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4210       return VariadicConstructor;
4211     else if (Fn && Fn->getType()->isBlockPointerType())
4212       return VariadicBlock;
4213     else if (FDecl) {
4214       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4215         if (Method->isInstance())
4216           return VariadicMethod;
4217     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4218       return VariadicMethod;
4219     return VariadicFunction;
4220   }
4221   return VariadicDoesNotApply;
4222 }
4223 
4224 namespace {
4225 class FunctionCallCCC : public FunctionCallFilterCCC {
4226 public:
4227   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4228                   unsigned NumArgs, MemberExpr *ME)
4229       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4230         FunctionName(FuncName) {}
4231 
4232   bool ValidateCandidate(const TypoCorrection &candidate) override {
4233     if (!candidate.getCorrectionSpecifier() ||
4234         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4235       return false;
4236     }
4237 
4238     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4239   }
4240 
4241 private:
4242   const IdentifierInfo *const FunctionName;
4243 };
4244 }
4245 
4246 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4247                                                FunctionDecl *FDecl,
4248                                                ArrayRef<Expr *> Args) {
4249   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4250   DeclarationName FuncName = FDecl->getDeclName();
4251   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4252 
4253   if (TypoCorrection Corrected = S.CorrectTypo(
4254           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4255           S.getScopeForContext(S.CurContext), nullptr,
4256           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4257                                              Args.size(), ME),
4258           Sema::CTK_ErrorRecovery)) {
4259     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
4260       if (Corrected.isOverloaded()) {
4261         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4262         OverloadCandidateSet::iterator Best;
4263         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
4264                                            CDEnd = Corrected.end();
4265              CD != CDEnd; ++CD) {
4266           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
4267             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4268                                    OCS);
4269         }
4270         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4271         case OR_Success:
4272           ND = Best->Function;
4273           Corrected.setCorrectionDecl(ND);
4274           break;
4275         default:
4276           break;
4277         }
4278       }
4279       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
4280         return Corrected;
4281       }
4282     }
4283   }
4284   return TypoCorrection();
4285 }
4286 
4287 /// ConvertArgumentsForCall - Converts the arguments specified in
4288 /// Args/NumArgs to the parameter types of the function FDecl with
4289 /// function prototype Proto. Call is the call expression itself, and
4290 /// Fn is the function expression. For a C++ member function, this
4291 /// routine does not attempt to convert the object argument. Returns
4292 /// true if the call is ill-formed.
4293 bool
4294 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4295                               FunctionDecl *FDecl,
4296                               const FunctionProtoType *Proto,
4297                               ArrayRef<Expr *> Args,
4298                               SourceLocation RParenLoc,
4299                               bool IsExecConfig) {
4300   // Bail out early if calling a builtin with custom typechecking.
4301   // We don't need to do this in the
4302   if (FDecl)
4303     if (unsigned ID = FDecl->getBuiltinID())
4304       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4305         return false;
4306 
4307   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4308   // assignment, to the types of the corresponding parameter, ...
4309   unsigned NumParams = Proto->getNumParams();
4310   bool Invalid = false;
4311   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4312   unsigned FnKind = Fn->getType()->isBlockPointerType()
4313                        ? 1 /* block */
4314                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4315                                        : 0 /* function */);
4316 
4317   // If too few arguments are available (and we don't have default
4318   // arguments for the remaining parameters), don't make the call.
4319   if (Args.size() < NumParams) {
4320     if (Args.size() < MinArgs) {
4321       TypoCorrection TC;
4322       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4323         unsigned diag_id =
4324             MinArgs == NumParams && !Proto->isVariadic()
4325                 ? diag::err_typecheck_call_too_few_args_suggest
4326                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4327         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4328                                         << static_cast<unsigned>(Args.size())
4329                                         << TC.getCorrectionRange());
4330       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4331         Diag(RParenLoc,
4332              MinArgs == NumParams && !Proto->isVariadic()
4333                  ? diag::err_typecheck_call_too_few_args_one
4334                  : diag::err_typecheck_call_too_few_args_at_least_one)
4335             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4336       else
4337         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4338                             ? diag::err_typecheck_call_too_few_args
4339                             : diag::err_typecheck_call_too_few_args_at_least)
4340             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4341             << Fn->getSourceRange();
4342 
4343       // Emit the location of the prototype.
4344       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4345         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4346           << FDecl;
4347 
4348       return true;
4349     }
4350     Call->setNumArgs(Context, NumParams);
4351   }
4352 
4353   // If too many are passed and not variadic, error on the extras and drop
4354   // them.
4355   if (Args.size() > NumParams) {
4356     if (!Proto->isVariadic()) {
4357       TypoCorrection TC;
4358       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4359         unsigned diag_id =
4360             MinArgs == NumParams && !Proto->isVariadic()
4361                 ? diag::err_typecheck_call_too_many_args_suggest
4362                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4363         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4364                                         << static_cast<unsigned>(Args.size())
4365                                         << TC.getCorrectionRange());
4366       } else if (NumParams == 1 && FDecl &&
4367                  FDecl->getParamDecl(0)->getDeclName())
4368         Diag(Args[NumParams]->getLocStart(),
4369              MinArgs == NumParams
4370                  ? diag::err_typecheck_call_too_many_args_one
4371                  : diag::err_typecheck_call_too_many_args_at_most_one)
4372             << FnKind << FDecl->getParamDecl(0)
4373             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4374             << SourceRange(Args[NumParams]->getLocStart(),
4375                            Args.back()->getLocEnd());
4376       else
4377         Diag(Args[NumParams]->getLocStart(),
4378              MinArgs == NumParams
4379                  ? diag::err_typecheck_call_too_many_args
4380                  : diag::err_typecheck_call_too_many_args_at_most)
4381             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4382             << Fn->getSourceRange()
4383             << SourceRange(Args[NumParams]->getLocStart(),
4384                            Args.back()->getLocEnd());
4385 
4386       // Emit the location of the prototype.
4387       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4388         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4389           << FDecl;
4390 
4391       // This deletes the extra arguments.
4392       Call->setNumArgs(Context, NumParams);
4393       return true;
4394     }
4395   }
4396   SmallVector<Expr *, 8> AllArgs;
4397   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4398 
4399   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4400                                    Proto, 0, Args, AllArgs, CallType);
4401   if (Invalid)
4402     return true;
4403   unsigned TotalNumArgs = AllArgs.size();
4404   for (unsigned i = 0; i < TotalNumArgs; ++i)
4405     Call->setArg(i, AllArgs[i]);
4406 
4407   return false;
4408 }
4409 
4410 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4411                                   const FunctionProtoType *Proto,
4412                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4413                                   SmallVectorImpl<Expr *> &AllArgs,
4414                                   VariadicCallType CallType, bool AllowExplicit,
4415                                   bool IsListInitialization) {
4416   unsigned NumParams = Proto->getNumParams();
4417   bool Invalid = false;
4418   unsigned ArgIx = 0;
4419   // Continue to check argument types (even if we have too few/many args).
4420   for (unsigned i = FirstParam; i < NumParams; i++) {
4421     QualType ProtoArgType = Proto->getParamType(i);
4422 
4423     Expr *Arg;
4424     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4425     if (ArgIx < Args.size()) {
4426       Arg = Args[ArgIx++];
4427 
4428       if (RequireCompleteType(Arg->getLocStart(),
4429                               ProtoArgType,
4430                               diag::err_call_incomplete_argument, Arg))
4431         return true;
4432 
4433       // Strip the unbridged-cast placeholder expression off, if applicable.
4434       bool CFAudited = false;
4435       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4436           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4437           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4438         Arg = stripARCUnbridgedCast(Arg);
4439       else if (getLangOpts().ObjCAutoRefCount &&
4440                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4441                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4442         CFAudited = true;
4443 
4444       InitializedEntity Entity =
4445           Param ? InitializedEntity::InitializeParameter(Context, Param,
4446                                                          ProtoArgType)
4447                 : InitializedEntity::InitializeParameter(
4448                       Context, ProtoArgType, Proto->isParamConsumed(i));
4449 
4450       // Remember that parameter belongs to a CF audited API.
4451       if (CFAudited)
4452         Entity.setParameterCFAudited();
4453 
4454       ExprResult ArgE = PerformCopyInitialization(
4455           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4456       if (ArgE.isInvalid())
4457         return true;
4458 
4459       Arg = ArgE.getAs<Expr>();
4460     } else {
4461       assert(Param && "can't use default arguments without a known callee");
4462 
4463       ExprResult ArgExpr =
4464         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4465       if (ArgExpr.isInvalid())
4466         return true;
4467 
4468       Arg = ArgExpr.getAs<Expr>();
4469     }
4470 
4471     // Check for array bounds violations for each argument to the call. This
4472     // check only triggers warnings when the argument isn't a more complex Expr
4473     // with its own checking, such as a BinaryOperator.
4474     CheckArrayAccess(Arg);
4475 
4476     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4477     CheckStaticArrayArgument(CallLoc, Param, Arg);
4478 
4479     AllArgs.push_back(Arg);
4480   }
4481 
4482   // If this is a variadic call, handle args passed through "...".
4483   if (CallType != VariadicDoesNotApply) {
4484     // Assume that extern "C" functions with variadic arguments that
4485     // return __unknown_anytype aren't *really* variadic.
4486     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4487         FDecl->isExternC()) {
4488       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4489         QualType paramType; // ignored
4490         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
4491         Invalid |= arg.isInvalid();
4492         AllArgs.push_back(arg.get());
4493       }
4494 
4495     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4496     } else {
4497       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4498         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4499                                                           FDecl);
4500         Invalid |= Arg.isInvalid();
4501         AllArgs.push_back(Arg.get());
4502       }
4503     }
4504 
4505     // Check for array bounds violations.
4506     for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4507       CheckArrayAccess(Args[i]);
4508   }
4509   return Invalid;
4510 }
4511 
4512 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4513   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4514   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4515     TL = DTL.getOriginalLoc();
4516   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4517     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4518       << ATL.getLocalSourceRange();
4519 }
4520 
4521 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4522 /// array parameter, check that it is non-null, and that if it is formed by
4523 /// array-to-pointer decay, the underlying array is sufficiently large.
4524 ///
4525 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4526 /// array type derivation, then for each call to the function, the value of the
4527 /// corresponding actual argument shall provide access to the first element of
4528 /// an array with at least as many elements as specified by the size expression.
4529 void
4530 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4531                                ParmVarDecl *Param,
4532                                const Expr *ArgExpr) {
4533   // Static array parameters are not supported in C++.
4534   if (!Param || getLangOpts().CPlusPlus)
4535     return;
4536 
4537   QualType OrigTy = Param->getOriginalType();
4538 
4539   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4540   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4541     return;
4542 
4543   if (ArgExpr->isNullPointerConstant(Context,
4544                                      Expr::NPC_NeverValueDependent)) {
4545     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4546     DiagnoseCalleeStaticArrayParam(*this, Param);
4547     return;
4548   }
4549 
4550   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4551   if (!CAT)
4552     return;
4553 
4554   const ConstantArrayType *ArgCAT =
4555     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4556   if (!ArgCAT)
4557     return;
4558 
4559   if (ArgCAT->getSize().ult(CAT->getSize())) {
4560     Diag(CallLoc, diag::warn_static_array_too_small)
4561       << ArgExpr->getSourceRange()
4562       << (unsigned) ArgCAT->getSize().getZExtValue()
4563       << (unsigned) CAT->getSize().getZExtValue();
4564     DiagnoseCalleeStaticArrayParam(*this, Param);
4565   }
4566 }
4567 
4568 /// Given a function expression of unknown-any type, try to rebuild it
4569 /// to have a function type.
4570 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4571 
4572 /// Is the given type a placeholder that we need to lower out
4573 /// immediately during argument processing?
4574 static bool isPlaceholderToRemoveAsArg(QualType type) {
4575   // Placeholders are never sugared.
4576   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4577   if (!placeholder) return false;
4578 
4579   switch (placeholder->getKind()) {
4580   // Ignore all the non-placeholder types.
4581 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4582 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4583 #include "clang/AST/BuiltinTypes.def"
4584     return false;
4585 
4586   // We cannot lower out overload sets; they might validly be resolved
4587   // by the call machinery.
4588   case BuiltinType::Overload:
4589     return false;
4590 
4591   // Unbridged casts in ARC can be handled in some call positions and
4592   // should be left in place.
4593   case BuiltinType::ARCUnbridgedCast:
4594     return false;
4595 
4596   // Pseudo-objects should be converted as soon as possible.
4597   case BuiltinType::PseudoObject:
4598     return true;
4599 
4600   // The debugger mode could theoretically but currently does not try
4601   // to resolve unknown-typed arguments based on known parameter types.
4602   case BuiltinType::UnknownAny:
4603     return true;
4604 
4605   // These are always invalid as call arguments and should be reported.
4606   case BuiltinType::BoundMember:
4607   case BuiltinType::BuiltinFn:
4608     return true;
4609   }
4610   llvm_unreachable("bad builtin type kind");
4611 }
4612 
4613 /// Check an argument list for placeholders that we won't try to
4614 /// handle later.
4615 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4616   // Apply this processing to all the arguments at once instead of
4617   // dying at the first failure.
4618   bool hasInvalid = false;
4619   for (size_t i = 0, e = args.size(); i != e; i++) {
4620     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4621       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4622       if (result.isInvalid()) hasInvalid = true;
4623       else args[i] = result.get();
4624     } else if (hasInvalid) {
4625       (void)S.CorrectDelayedTyposInExpr(args[i]);
4626     }
4627   }
4628   return hasInvalid;
4629 }
4630 
4631 /// If a builtin function has a pointer argument with no explicit address
4632 /// space, than it should be able to accept a pointer to any address
4633 /// space as input.  In order to do this, we need to replace the
4634 /// standard builtin declaration with one that uses the same address space
4635 /// as the call.
4636 ///
4637 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
4638 ///                  it does not contain any pointer arguments without
4639 ///                  an address space qualifer.  Otherwise the rewritten
4640 ///                  FunctionDecl is returned.
4641 /// TODO: Handle pointer return types.
4642 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
4643                                                 const FunctionDecl *FDecl,
4644                                                 MultiExprArg ArgExprs) {
4645 
4646   QualType DeclType = FDecl->getType();
4647   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
4648 
4649   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
4650       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
4651     return nullptr;
4652 
4653   bool NeedsNewDecl = false;
4654   unsigned i = 0;
4655   SmallVector<QualType, 8> OverloadParams;
4656 
4657   for (QualType ParamType : FT->param_types()) {
4658 
4659     // Convert array arguments to pointer to simplify type lookup.
4660     Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get();
4661     QualType ArgType = Arg->getType();
4662     if (!ParamType->isPointerType() ||
4663         ParamType.getQualifiers().hasAddressSpace() ||
4664         !ArgType->isPointerType() ||
4665         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
4666       OverloadParams.push_back(ParamType);
4667       continue;
4668     }
4669 
4670     NeedsNewDecl = true;
4671     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
4672 
4673     QualType PointeeType = ParamType->getPointeeType();
4674     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
4675     OverloadParams.push_back(Context.getPointerType(PointeeType));
4676   }
4677 
4678   if (!NeedsNewDecl)
4679     return nullptr;
4680 
4681   FunctionProtoType::ExtProtoInfo EPI;
4682   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
4683                                                 OverloadParams, EPI);
4684   DeclContext *Parent = Context.getTranslationUnitDecl();
4685   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
4686                                                     FDecl->getLocation(),
4687                                                     FDecl->getLocation(),
4688                                                     FDecl->getIdentifier(),
4689                                                     OverloadTy,
4690                                                     /*TInfo=*/nullptr,
4691                                                     SC_Extern, false,
4692                                                     /*hasPrototype=*/true);
4693   SmallVector<ParmVarDecl*, 16> Params;
4694   FT = cast<FunctionProtoType>(OverloadTy);
4695   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
4696     QualType ParamType = FT->getParamType(i);
4697     ParmVarDecl *Parm =
4698         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
4699                                 SourceLocation(), nullptr, ParamType,
4700                                 /*TInfo=*/nullptr, SC_None, nullptr);
4701     Parm->setScopeInfo(0, i);
4702     Params.push_back(Parm);
4703   }
4704   OverloadDecl->setParams(Params);
4705   return OverloadDecl;
4706 }
4707 
4708 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4709 /// This provides the location of the left/right parens and a list of comma
4710 /// locations.
4711 ExprResult
4712 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4713                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
4714                     Expr *ExecConfig, bool IsExecConfig) {
4715   // Since this might be a postfix expression, get rid of ParenListExprs.
4716   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4717   if (Result.isInvalid()) return ExprError();
4718   Fn = Result.get();
4719 
4720   if (checkArgsForPlaceholders(*this, ArgExprs))
4721     return ExprError();
4722 
4723   if (getLangOpts().CPlusPlus) {
4724     // If this is a pseudo-destructor expression, build the call immediately.
4725     if (isa<CXXPseudoDestructorExpr>(Fn)) {
4726       if (!ArgExprs.empty()) {
4727         // Pseudo-destructor calls should not have any arguments.
4728         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4729           << FixItHint::CreateRemoval(
4730                                     SourceRange(ArgExprs[0]->getLocStart(),
4731                                                 ArgExprs.back()->getLocEnd()));
4732       }
4733 
4734       return new (Context)
4735           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
4736     }
4737     if (Fn->getType() == Context.PseudoObjectTy) {
4738       ExprResult result = CheckPlaceholderExpr(Fn);
4739       if (result.isInvalid()) return ExprError();
4740       Fn = result.get();
4741     }
4742 
4743     // Determine whether this is a dependent call inside a C++ template,
4744     // in which case we won't do any semantic analysis now.
4745     // FIXME: Will need to cache the results of name lookup (including ADL) in
4746     // Fn.
4747     bool Dependent = false;
4748     if (Fn->isTypeDependent())
4749       Dependent = true;
4750     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4751       Dependent = true;
4752 
4753     if (Dependent) {
4754       if (ExecConfig) {
4755         return new (Context) CUDAKernelCallExpr(
4756             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4757             Context.DependentTy, VK_RValue, RParenLoc);
4758       } else {
4759         return new (Context) CallExpr(
4760             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
4761       }
4762     }
4763 
4764     // Determine whether this is a call to an object (C++ [over.call.object]).
4765     if (Fn->getType()->isRecordType())
4766       return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
4767                                           RParenLoc);
4768 
4769     if (Fn->getType() == Context.UnknownAnyTy) {
4770       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4771       if (result.isInvalid()) return ExprError();
4772       Fn = result.get();
4773     }
4774 
4775     if (Fn->getType() == Context.BoundMemberTy) {
4776       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4777     }
4778   }
4779 
4780   // Check for overloaded calls.  This can happen even in C due to extensions.
4781   if (Fn->getType() == Context.OverloadTy) {
4782     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4783 
4784     // We aren't supposed to apply this logic for if there's an '&' involved.
4785     if (!find.HasFormOfMemberPointer) {
4786       OverloadExpr *ovl = find.Expression;
4787       if (isa<UnresolvedLookupExpr>(ovl)) {
4788         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4789         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4790                                        RParenLoc, ExecConfig);
4791       } else {
4792         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4793                                          RParenLoc);
4794       }
4795     }
4796   }
4797 
4798   // If we're directly calling a function, get the appropriate declaration.
4799   if (Fn->getType() == Context.UnknownAnyTy) {
4800     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4801     if (result.isInvalid()) return ExprError();
4802     Fn = result.get();
4803   }
4804 
4805   Expr *NakedFn = Fn->IgnoreParens();
4806 
4807   NamedDecl *NDecl = nullptr;
4808   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4809     if (UnOp->getOpcode() == UO_AddrOf)
4810       NakedFn = UnOp->getSubExpr()->IgnoreParens();
4811 
4812   if (isa<DeclRefExpr>(NakedFn)) {
4813     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4814 
4815     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
4816     if (FDecl && FDecl->getBuiltinID()) {
4817       // Rewrite the function decl for this builtin by replacing paramaters
4818       // with no explicit address space with the address space of the arguments
4819       // in ArgExprs.
4820       if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
4821         NDecl = FDecl;
4822         Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(),
4823                            SourceLocation(), FDecl, false,
4824                            SourceLocation(), FDecl->getType(),
4825                            Fn->getValueKind(), FDecl);
4826       }
4827     }
4828   } else if (isa<MemberExpr>(NakedFn))
4829     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4830 
4831   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
4832     if (FD->hasAttr<EnableIfAttr>()) {
4833       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
4834         Diag(Fn->getLocStart(),
4835              isa<CXXMethodDecl>(FD) ?
4836                  diag::err_ovl_no_viable_member_function_in_call :
4837                  diag::err_ovl_no_viable_function_in_call)
4838           << FD << FD->getSourceRange();
4839         Diag(FD->getLocation(),
4840              diag::note_ovl_candidate_disabled_by_enable_if_attr)
4841             << Attr->getCond()->getSourceRange() << Attr->getMessage();
4842       }
4843     }
4844   }
4845 
4846   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4847                                ExecConfig, IsExecConfig);
4848 }
4849 
4850 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4851 ///
4852 /// __builtin_astype( value, dst type )
4853 ///
4854 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4855                                  SourceLocation BuiltinLoc,
4856                                  SourceLocation RParenLoc) {
4857   ExprValueKind VK = VK_RValue;
4858   ExprObjectKind OK = OK_Ordinary;
4859   QualType DstTy = GetTypeFromParser(ParsedDestTy);
4860   QualType SrcTy = E->getType();
4861   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4862     return ExprError(Diag(BuiltinLoc,
4863                           diag::err_invalid_astype_of_different_size)
4864                      << DstTy
4865                      << SrcTy
4866                      << E->getSourceRange());
4867   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4868 }
4869 
4870 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
4871 /// provided arguments.
4872 ///
4873 /// __builtin_convertvector( value, dst type )
4874 ///
4875 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4876                                         SourceLocation BuiltinLoc,
4877                                         SourceLocation RParenLoc) {
4878   TypeSourceInfo *TInfo;
4879   GetTypeFromParser(ParsedDestTy, &TInfo);
4880   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
4881 }
4882 
4883 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4884 /// i.e. an expression not of \p OverloadTy.  The expression should
4885 /// unary-convert to an expression of function-pointer or
4886 /// block-pointer type.
4887 ///
4888 /// \param NDecl the declaration being called, if available
4889 ExprResult
4890 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4891                             SourceLocation LParenLoc,
4892                             ArrayRef<Expr *> Args,
4893                             SourceLocation RParenLoc,
4894                             Expr *Config, bool IsExecConfig) {
4895   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4896   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4897 
4898   // Promote the function operand.
4899   // We special-case function promotion here because we only allow promoting
4900   // builtin functions to function pointers in the callee of a call.
4901   ExprResult Result;
4902   if (BuiltinID &&
4903       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4904     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4905                                CK_BuiltinFnToFnPtr).get();
4906   } else {
4907     Result = CallExprUnaryConversions(Fn);
4908   }
4909   if (Result.isInvalid())
4910     return ExprError();
4911   Fn = Result.get();
4912 
4913   // Make the call expr early, before semantic checks.  This guarantees cleanup
4914   // of arguments and function on error.
4915   CallExpr *TheCall;
4916   if (Config)
4917     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4918                                                cast<CallExpr>(Config), Args,
4919                                                Context.BoolTy, VK_RValue,
4920                                                RParenLoc);
4921   else
4922     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4923                                      VK_RValue, RParenLoc);
4924 
4925   // Bail out early if calling a builtin with custom typechecking.
4926   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4927     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
4928 
4929  retry:
4930   const FunctionType *FuncT;
4931   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4932     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4933     // have type pointer to function".
4934     FuncT = PT->getPointeeType()->getAs<FunctionType>();
4935     if (!FuncT)
4936       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4937                          << Fn->getType() << Fn->getSourceRange());
4938   } else if (const BlockPointerType *BPT =
4939                Fn->getType()->getAs<BlockPointerType>()) {
4940     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4941   } else {
4942     // Handle calls to expressions of unknown-any type.
4943     if (Fn->getType() == Context.UnknownAnyTy) {
4944       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4945       if (rewrite.isInvalid()) return ExprError();
4946       Fn = rewrite.get();
4947       TheCall->setCallee(Fn);
4948       goto retry;
4949     }
4950 
4951     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4952       << Fn->getType() << Fn->getSourceRange());
4953   }
4954 
4955   if (getLangOpts().CUDA) {
4956     if (Config) {
4957       // CUDA: Kernel calls must be to global functions
4958       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4959         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4960             << FDecl->getName() << Fn->getSourceRange());
4961 
4962       // CUDA: Kernel function must have 'void' return type
4963       if (!FuncT->getReturnType()->isVoidType())
4964         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4965             << Fn->getType() << Fn->getSourceRange());
4966     } else {
4967       // CUDA: Calls to global functions must be configured
4968       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4969         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4970             << FDecl->getName() << Fn->getSourceRange());
4971     }
4972   }
4973 
4974   // Check for a valid return type
4975   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
4976                           FDecl))
4977     return ExprError();
4978 
4979   // We know the result type of the call, set it.
4980   TheCall->setType(FuncT->getCallResultType(Context));
4981   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
4982 
4983   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4984   if (Proto) {
4985     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4986                                 IsExecConfig))
4987       return ExprError();
4988   } else {
4989     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4990 
4991     if (FDecl) {
4992       // Check if we have too few/too many template arguments, based
4993       // on our knowledge of the function definition.
4994       const FunctionDecl *Def = nullptr;
4995       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
4996         Proto = Def->getType()->getAs<FunctionProtoType>();
4997        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
4998           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4999           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5000       }
5001 
5002       // If the function we're calling isn't a function prototype, but we have
5003       // a function prototype from a prior declaratiom, use that prototype.
5004       if (!FDecl->hasPrototype())
5005         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5006     }
5007 
5008     // Promote the arguments (C99 6.5.2.2p6).
5009     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5010       Expr *Arg = Args[i];
5011 
5012       if (Proto && i < Proto->getNumParams()) {
5013         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5014             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5015         ExprResult ArgE =
5016             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5017         if (ArgE.isInvalid())
5018           return true;
5019 
5020         Arg = ArgE.getAs<Expr>();
5021 
5022       } else {
5023         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5024 
5025         if (ArgE.isInvalid())
5026           return true;
5027 
5028         Arg = ArgE.getAs<Expr>();
5029       }
5030 
5031       if (RequireCompleteType(Arg->getLocStart(),
5032                               Arg->getType(),
5033                               diag::err_call_incomplete_argument, Arg))
5034         return ExprError();
5035 
5036       TheCall->setArg(i, Arg);
5037     }
5038   }
5039 
5040   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5041     if (!Method->isStatic())
5042       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5043         << Fn->getSourceRange());
5044 
5045   // Check for sentinels
5046   if (NDecl)
5047     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5048 
5049   // Do special checking on direct calls to functions.
5050   if (FDecl) {
5051     if (CheckFunctionCall(FDecl, TheCall, Proto))
5052       return ExprError();
5053 
5054     if (BuiltinID)
5055       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5056   } else if (NDecl) {
5057     if (CheckPointerCall(NDecl, TheCall, Proto))
5058       return ExprError();
5059   } else {
5060     if (CheckOtherCall(TheCall, Proto))
5061       return ExprError();
5062   }
5063 
5064   return MaybeBindToTemporary(TheCall);
5065 }
5066 
5067 ExprResult
5068 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5069                            SourceLocation RParenLoc, Expr *InitExpr) {
5070   assert(Ty && "ActOnCompoundLiteral(): missing type");
5071   // FIXME: put back this assert when initializers are worked out.
5072   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
5073 
5074   TypeSourceInfo *TInfo;
5075   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5076   if (!TInfo)
5077     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5078 
5079   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5080 }
5081 
5082 ExprResult
5083 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5084                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5085   QualType literalType = TInfo->getType();
5086 
5087   if (literalType->isArrayType()) {
5088     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5089           diag::err_illegal_decl_array_incomplete_type,
5090           SourceRange(LParenLoc,
5091                       LiteralExpr->getSourceRange().getEnd())))
5092       return ExprError();
5093     if (literalType->isVariableArrayType())
5094       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5095         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5096   } else if (!literalType->isDependentType() &&
5097              RequireCompleteType(LParenLoc, literalType,
5098                diag::err_typecheck_decl_incomplete_type,
5099                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5100     return ExprError();
5101 
5102   InitializedEntity Entity
5103     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5104   InitializationKind Kind
5105     = InitializationKind::CreateCStyleCast(LParenLoc,
5106                                            SourceRange(LParenLoc, RParenLoc),
5107                                            /*InitList=*/true);
5108   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5109   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5110                                       &literalType);
5111   if (Result.isInvalid())
5112     return ExprError();
5113   LiteralExpr = Result.get();
5114 
5115   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
5116   if (isFileScope &&
5117       !LiteralExpr->isTypeDependent() &&
5118       !LiteralExpr->isValueDependent() &&
5119       !literalType->isDependentType()) { // 6.5.2.5p3
5120     if (CheckForConstantInitializer(LiteralExpr, literalType))
5121       return ExprError();
5122   }
5123 
5124   // In C, compound literals are l-values for some reason.
5125   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
5126 
5127   return MaybeBindToTemporary(
5128            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5129                                              VK, LiteralExpr, isFileScope));
5130 }
5131 
5132 ExprResult
5133 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5134                     SourceLocation RBraceLoc) {
5135   // Immediately handle non-overload placeholders.  Overloads can be
5136   // resolved contextually, but everything else here can't.
5137   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5138     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5139       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5140 
5141       // Ignore failures; dropping the entire initializer list because
5142       // of one failure would be terrible for indexing/etc.
5143       if (result.isInvalid()) continue;
5144 
5145       InitArgList[I] = result.get();
5146     }
5147   }
5148 
5149   // Semantic analysis for initializers is done by ActOnDeclarator() and
5150   // CheckInitializer() - it requires knowledge of the object being intialized.
5151 
5152   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5153                                                RBraceLoc);
5154   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5155   return E;
5156 }
5157 
5158 /// Do an explicit extend of the given block pointer if we're in ARC.
5159 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
5160   assert(E.get()->getType()->isBlockPointerType());
5161   assert(E.get()->isRValue());
5162 
5163   // Only do this in an r-value context.
5164   if (!S.getLangOpts().ObjCAutoRefCount) return;
5165 
5166   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
5167                                CK_ARCExtendBlockObject, E.get(),
5168                                /*base path*/ nullptr, VK_RValue);
5169   S.ExprNeedsCleanups = true;
5170 }
5171 
5172 /// Prepare a conversion of the given expression to an ObjC object
5173 /// pointer type.
5174 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5175   QualType type = E.get()->getType();
5176   if (type->isObjCObjectPointerType()) {
5177     return CK_BitCast;
5178   } else if (type->isBlockPointerType()) {
5179     maybeExtendBlockObject(*this, E);
5180     return CK_BlockPointerToObjCPointerCast;
5181   } else {
5182     assert(type->isPointerType());
5183     return CK_CPointerToObjCPointerCast;
5184   }
5185 }
5186 
5187 /// Prepares for a scalar cast, performing all the necessary stages
5188 /// except the final cast and returning the kind required.
5189 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5190   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5191   // Also, callers should have filtered out the invalid cases with
5192   // pointers.  Everything else should be possible.
5193 
5194   QualType SrcTy = Src.get()->getType();
5195   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5196     return CK_NoOp;
5197 
5198   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5199   case Type::STK_MemberPointer:
5200     llvm_unreachable("member pointer type in C");
5201 
5202   case Type::STK_CPointer:
5203   case Type::STK_BlockPointer:
5204   case Type::STK_ObjCObjectPointer:
5205     switch (DestTy->getScalarTypeKind()) {
5206     case Type::STK_CPointer: {
5207       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5208       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5209       if (SrcAS != DestAS)
5210         return CK_AddressSpaceConversion;
5211       return CK_BitCast;
5212     }
5213     case Type::STK_BlockPointer:
5214       return (SrcKind == Type::STK_BlockPointer
5215                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5216     case Type::STK_ObjCObjectPointer:
5217       if (SrcKind == Type::STK_ObjCObjectPointer)
5218         return CK_BitCast;
5219       if (SrcKind == Type::STK_CPointer)
5220         return CK_CPointerToObjCPointerCast;
5221       maybeExtendBlockObject(*this, Src);
5222       return CK_BlockPointerToObjCPointerCast;
5223     case Type::STK_Bool:
5224       return CK_PointerToBoolean;
5225     case Type::STK_Integral:
5226       return CK_PointerToIntegral;
5227     case Type::STK_Floating:
5228     case Type::STK_FloatingComplex:
5229     case Type::STK_IntegralComplex:
5230     case Type::STK_MemberPointer:
5231       llvm_unreachable("illegal cast from pointer");
5232     }
5233     llvm_unreachable("Should have returned before this");
5234 
5235   case Type::STK_Bool: // casting from bool is like casting from an integer
5236   case Type::STK_Integral:
5237     switch (DestTy->getScalarTypeKind()) {
5238     case Type::STK_CPointer:
5239     case Type::STK_ObjCObjectPointer:
5240     case Type::STK_BlockPointer:
5241       if (Src.get()->isNullPointerConstant(Context,
5242                                            Expr::NPC_ValueDependentIsNull))
5243         return CK_NullToPointer;
5244       return CK_IntegralToPointer;
5245     case Type::STK_Bool:
5246       return CK_IntegralToBoolean;
5247     case Type::STK_Integral:
5248       return CK_IntegralCast;
5249     case Type::STK_Floating:
5250       return CK_IntegralToFloating;
5251     case Type::STK_IntegralComplex:
5252       Src = ImpCastExprToType(Src.get(),
5253                               DestTy->castAs<ComplexType>()->getElementType(),
5254                               CK_IntegralCast);
5255       return CK_IntegralRealToComplex;
5256     case Type::STK_FloatingComplex:
5257       Src = ImpCastExprToType(Src.get(),
5258                               DestTy->castAs<ComplexType>()->getElementType(),
5259                               CK_IntegralToFloating);
5260       return CK_FloatingRealToComplex;
5261     case Type::STK_MemberPointer:
5262       llvm_unreachable("member pointer type in C");
5263     }
5264     llvm_unreachable("Should have returned before this");
5265 
5266   case Type::STK_Floating:
5267     switch (DestTy->getScalarTypeKind()) {
5268     case Type::STK_Floating:
5269       return CK_FloatingCast;
5270     case Type::STK_Bool:
5271       return CK_FloatingToBoolean;
5272     case Type::STK_Integral:
5273       return CK_FloatingToIntegral;
5274     case Type::STK_FloatingComplex:
5275       Src = ImpCastExprToType(Src.get(),
5276                               DestTy->castAs<ComplexType>()->getElementType(),
5277                               CK_FloatingCast);
5278       return CK_FloatingRealToComplex;
5279     case Type::STK_IntegralComplex:
5280       Src = ImpCastExprToType(Src.get(),
5281                               DestTy->castAs<ComplexType>()->getElementType(),
5282                               CK_FloatingToIntegral);
5283       return CK_IntegralRealToComplex;
5284     case Type::STK_CPointer:
5285     case Type::STK_ObjCObjectPointer:
5286     case Type::STK_BlockPointer:
5287       llvm_unreachable("valid float->pointer cast?");
5288     case Type::STK_MemberPointer:
5289       llvm_unreachable("member pointer type in C");
5290     }
5291     llvm_unreachable("Should have returned before this");
5292 
5293   case Type::STK_FloatingComplex:
5294     switch (DestTy->getScalarTypeKind()) {
5295     case Type::STK_FloatingComplex:
5296       return CK_FloatingComplexCast;
5297     case Type::STK_IntegralComplex:
5298       return CK_FloatingComplexToIntegralComplex;
5299     case Type::STK_Floating: {
5300       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5301       if (Context.hasSameType(ET, DestTy))
5302         return CK_FloatingComplexToReal;
5303       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5304       return CK_FloatingCast;
5305     }
5306     case Type::STK_Bool:
5307       return CK_FloatingComplexToBoolean;
5308     case Type::STK_Integral:
5309       Src = ImpCastExprToType(Src.get(),
5310                               SrcTy->castAs<ComplexType>()->getElementType(),
5311                               CK_FloatingComplexToReal);
5312       return CK_FloatingToIntegral;
5313     case Type::STK_CPointer:
5314     case Type::STK_ObjCObjectPointer:
5315     case Type::STK_BlockPointer:
5316       llvm_unreachable("valid complex float->pointer cast?");
5317     case Type::STK_MemberPointer:
5318       llvm_unreachable("member pointer type in C");
5319     }
5320     llvm_unreachable("Should have returned before this");
5321 
5322   case Type::STK_IntegralComplex:
5323     switch (DestTy->getScalarTypeKind()) {
5324     case Type::STK_FloatingComplex:
5325       return CK_IntegralComplexToFloatingComplex;
5326     case Type::STK_IntegralComplex:
5327       return CK_IntegralComplexCast;
5328     case Type::STK_Integral: {
5329       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5330       if (Context.hasSameType(ET, DestTy))
5331         return CK_IntegralComplexToReal;
5332       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5333       return CK_IntegralCast;
5334     }
5335     case Type::STK_Bool:
5336       return CK_IntegralComplexToBoolean;
5337     case Type::STK_Floating:
5338       Src = ImpCastExprToType(Src.get(),
5339                               SrcTy->castAs<ComplexType>()->getElementType(),
5340                               CK_IntegralComplexToReal);
5341       return CK_IntegralToFloating;
5342     case Type::STK_CPointer:
5343     case Type::STK_ObjCObjectPointer:
5344     case Type::STK_BlockPointer:
5345       llvm_unreachable("valid complex int->pointer cast?");
5346     case Type::STK_MemberPointer:
5347       llvm_unreachable("member pointer type in C");
5348     }
5349     llvm_unreachable("Should have returned before this");
5350   }
5351 
5352   llvm_unreachable("Unhandled scalar cast");
5353 }
5354 
5355 static bool breakDownVectorType(QualType type, uint64_t &len,
5356                                 QualType &eltType) {
5357   // Vectors are simple.
5358   if (const VectorType *vecType = type->getAs<VectorType>()) {
5359     len = vecType->getNumElements();
5360     eltType = vecType->getElementType();
5361     assert(eltType->isScalarType());
5362     return true;
5363   }
5364 
5365   // We allow lax conversion to and from non-vector types, but only if
5366   // they're real types (i.e. non-complex, non-pointer scalar types).
5367   if (!type->isRealType()) return false;
5368 
5369   len = 1;
5370   eltType = type;
5371   return true;
5372 }
5373 
5374 static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) {
5375   uint64_t srcLen, destLen;
5376   QualType srcElt, destElt;
5377   if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false;
5378   if (!breakDownVectorType(destTy, destLen, destElt)) return false;
5379 
5380   // ASTContext::getTypeSize will return the size rounded up to a
5381   // power of 2, so instead of using that, we need to use the raw
5382   // element size multiplied by the element count.
5383   uint64_t srcEltSize = S.Context.getTypeSize(srcElt);
5384   uint64_t destEltSize = S.Context.getTypeSize(destElt);
5385 
5386   return (srcLen * srcEltSize == destLen * destEltSize);
5387 }
5388 
5389 /// Is this a legal conversion between two known vector types?
5390 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5391   assert(destTy->isVectorType() || srcTy->isVectorType());
5392 
5393   if (!Context.getLangOpts().LaxVectorConversions)
5394     return false;
5395   return VectorTypesMatch(*this, srcTy, destTy);
5396 }
5397 
5398 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5399                            CastKind &Kind) {
5400   assert(VectorTy->isVectorType() && "Not a vector type!");
5401 
5402   if (Ty->isVectorType() || Ty->isIntegerType()) {
5403     if (!VectorTypesMatch(*this, Ty, VectorTy))
5404       return Diag(R.getBegin(),
5405                   Ty->isVectorType() ?
5406                   diag::err_invalid_conversion_between_vectors :
5407                   diag::err_invalid_conversion_between_vector_and_integer)
5408         << VectorTy << Ty << R;
5409   } else
5410     return Diag(R.getBegin(),
5411                 diag::err_invalid_conversion_between_vector_and_scalar)
5412       << VectorTy << Ty << R;
5413 
5414   Kind = CK_BitCast;
5415   return false;
5416 }
5417 
5418 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5419                                     Expr *CastExpr, CastKind &Kind) {
5420   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5421 
5422   QualType SrcTy = CastExpr->getType();
5423 
5424   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5425   // an ExtVectorType.
5426   // In OpenCL, casts between vectors of different types are not allowed.
5427   // (See OpenCL 6.2).
5428   if (SrcTy->isVectorType()) {
5429     if (!VectorTypesMatch(*this, SrcTy, DestTy)
5430         || (getLangOpts().OpenCL &&
5431             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5432       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5433         << DestTy << SrcTy << R;
5434       return ExprError();
5435     }
5436     Kind = CK_BitCast;
5437     return CastExpr;
5438   }
5439 
5440   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5441   // conversion will take place first from scalar to elt type, and then
5442   // splat from elt type to vector.
5443   if (SrcTy->isPointerType())
5444     return Diag(R.getBegin(),
5445                 diag::err_invalid_conversion_between_vector_and_scalar)
5446       << DestTy << SrcTy << R;
5447 
5448   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5449   ExprResult CastExprRes = CastExpr;
5450   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
5451   if (CastExprRes.isInvalid())
5452     return ExprError();
5453   CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
5454 
5455   Kind = CK_VectorSplat;
5456   return CastExpr;
5457 }
5458 
5459 ExprResult
5460 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5461                     Declarator &D, ParsedType &Ty,
5462                     SourceLocation RParenLoc, Expr *CastExpr) {
5463   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5464          "ActOnCastExpr(): missing type or expr");
5465 
5466   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5467   if (D.isInvalidType())
5468     return ExprError();
5469 
5470   if (getLangOpts().CPlusPlus) {
5471     // Check that there are no default arguments (C++ only).
5472     CheckExtraCXXDefaultArguments(D);
5473   } else {
5474     // Make sure any TypoExprs have been dealt with.
5475     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
5476     if (!Res.isUsable())
5477       return ExprError();
5478     CastExpr = Res.get();
5479   }
5480 
5481   checkUnusedDeclAttributes(D);
5482 
5483   QualType castType = castTInfo->getType();
5484   Ty = CreateParsedType(castType, castTInfo);
5485 
5486   bool isVectorLiteral = false;
5487 
5488   // Check for an altivec or OpenCL literal,
5489   // i.e. all the elements are integer constants.
5490   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5491   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5492   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
5493        && castType->isVectorType() && (PE || PLE)) {
5494     if (PLE && PLE->getNumExprs() == 0) {
5495       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5496       return ExprError();
5497     }
5498     if (PE || PLE->getNumExprs() == 1) {
5499       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5500       if (!E->getType()->isVectorType())
5501         isVectorLiteral = true;
5502     }
5503     else
5504       isVectorLiteral = true;
5505   }
5506 
5507   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5508   // then handle it as such.
5509   if (isVectorLiteral)
5510     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5511 
5512   // If the Expr being casted is a ParenListExpr, handle it specially.
5513   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5514   // sequence of BinOp comma operators.
5515   if (isa<ParenListExpr>(CastExpr)) {
5516     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5517     if (Result.isInvalid()) return ExprError();
5518     CastExpr = Result.get();
5519   }
5520 
5521   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5522       !getSourceManager().isInSystemMacro(LParenLoc))
5523     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
5524 
5525   CheckTollFreeBridgeCast(castType, CastExpr);
5526 
5527   CheckObjCBridgeRelatedCast(castType, CastExpr);
5528 
5529   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5530 }
5531 
5532 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5533                                     SourceLocation RParenLoc, Expr *E,
5534                                     TypeSourceInfo *TInfo) {
5535   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5536          "Expected paren or paren list expression");
5537 
5538   Expr **exprs;
5539   unsigned numExprs;
5540   Expr *subExpr;
5541   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5542   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5543     LiteralLParenLoc = PE->getLParenLoc();
5544     LiteralRParenLoc = PE->getRParenLoc();
5545     exprs = PE->getExprs();
5546     numExprs = PE->getNumExprs();
5547   } else { // isa<ParenExpr> by assertion at function entrance
5548     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5549     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5550     subExpr = cast<ParenExpr>(E)->getSubExpr();
5551     exprs = &subExpr;
5552     numExprs = 1;
5553   }
5554 
5555   QualType Ty = TInfo->getType();
5556   assert(Ty->isVectorType() && "Expected vector type");
5557 
5558   SmallVector<Expr *, 8> initExprs;
5559   const VectorType *VTy = Ty->getAs<VectorType>();
5560   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5561 
5562   // '(...)' form of vector initialization in AltiVec: the number of
5563   // initializers must be one or must match the size of the vector.
5564   // If a single value is specified in the initializer then it will be
5565   // replicated to all the components of the vector
5566   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5567     // The number of initializers must be one or must match the size of the
5568     // vector. If a single value is specified in the initializer then it will
5569     // be replicated to all the components of the vector
5570     if (numExprs == 1) {
5571       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5572       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5573       if (Literal.isInvalid())
5574         return ExprError();
5575       Literal = ImpCastExprToType(Literal.get(), ElemTy,
5576                                   PrepareScalarCast(Literal, ElemTy));
5577       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5578     }
5579     else if (numExprs < numElems) {
5580       Diag(E->getExprLoc(),
5581            diag::err_incorrect_number_of_vector_initializers);
5582       return ExprError();
5583     }
5584     else
5585       initExprs.append(exprs, exprs + numExprs);
5586   }
5587   else {
5588     // For OpenCL, when the number of initializers is a single value,
5589     // it will be replicated to all components of the vector.
5590     if (getLangOpts().OpenCL &&
5591         VTy->getVectorKind() == VectorType::GenericVector &&
5592         numExprs == 1) {
5593         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5594         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5595         if (Literal.isInvalid())
5596           return ExprError();
5597         Literal = ImpCastExprToType(Literal.get(), ElemTy,
5598                                     PrepareScalarCast(Literal, ElemTy));
5599         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5600     }
5601 
5602     initExprs.append(exprs, exprs + numExprs);
5603   }
5604   // FIXME: This means that pretty-printing the final AST will produce curly
5605   // braces instead of the original commas.
5606   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5607                                                    initExprs, LiteralRParenLoc);
5608   initE->setType(Ty);
5609   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5610 }
5611 
5612 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5613 /// the ParenListExpr into a sequence of comma binary operators.
5614 ExprResult
5615 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5616   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5617   if (!E)
5618     return OrigExpr;
5619 
5620   ExprResult Result(E->getExpr(0));
5621 
5622   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5623     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5624                         E->getExpr(i));
5625 
5626   if (Result.isInvalid()) return ExprError();
5627 
5628   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5629 }
5630 
5631 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5632                                     SourceLocation R,
5633                                     MultiExprArg Val) {
5634   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5635   return expr;
5636 }
5637 
5638 /// \brief Emit a specialized diagnostic when one expression is a null pointer
5639 /// constant and the other is not a pointer.  Returns true if a diagnostic is
5640 /// emitted.
5641 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5642                                       SourceLocation QuestionLoc) {
5643   Expr *NullExpr = LHSExpr;
5644   Expr *NonPointerExpr = RHSExpr;
5645   Expr::NullPointerConstantKind NullKind =
5646       NullExpr->isNullPointerConstant(Context,
5647                                       Expr::NPC_ValueDependentIsNotNull);
5648 
5649   if (NullKind == Expr::NPCK_NotNull) {
5650     NullExpr = RHSExpr;
5651     NonPointerExpr = LHSExpr;
5652     NullKind =
5653         NullExpr->isNullPointerConstant(Context,
5654                                         Expr::NPC_ValueDependentIsNotNull);
5655   }
5656 
5657   if (NullKind == Expr::NPCK_NotNull)
5658     return false;
5659 
5660   if (NullKind == Expr::NPCK_ZeroExpression)
5661     return false;
5662 
5663   if (NullKind == Expr::NPCK_ZeroLiteral) {
5664     // In this case, check to make sure that we got here from a "NULL"
5665     // string in the source code.
5666     NullExpr = NullExpr->IgnoreParenImpCasts();
5667     SourceLocation loc = NullExpr->getExprLoc();
5668     if (!findMacroSpelling(loc, "NULL"))
5669       return false;
5670   }
5671 
5672   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5673   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5674       << NonPointerExpr->getType() << DiagType
5675       << NonPointerExpr->getSourceRange();
5676   return true;
5677 }
5678 
5679 /// \brief Return false if the condition expression is valid, true otherwise.
5680 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
5681   QualType CondTy = Cond->getType();
5682 
5683   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
5684   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
5685     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
5686       << CondTy << Cond->getSourceRange();
5687     return true;
5688   }
5689 
5690   // C99 6.5.15p2
5691   if (CondTy->isScalarType()) return false;
5692 
5693   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
5694     << CondTy << Cond->getSourceRange();
5695   return true;
5696 }
5697 
5698 /// \brief Handle when one or both operands are void type.
5699 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5700                                          ExprResult &RHS) {
5701     Expr *LHSExpr = LHS.get();
5702     Expr *RHSExpr = RHS.get();
5703 
5704     if (!LHSExpr->getType()->isVoidType())
5705       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5706         << RHSExpr->getSourceRange();
5707     if (!RHSExpr->getType()->isVoidType())
5708       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5709         << LHSExpr->getSourceRange();
5710     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
5711     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
5712     return S.Context.VoidTy;
5713 }
5714 
5715 /// \brief Return false if the NullExpr can be promoted to PointerTy,
5716 /// true otherwise.
5717 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5718                                         QualType PointerTy) {
5719   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5720       !NullExpr.get()->isNullPointerConstant(S.Context,
5721                                             Expr::NPC_ValueDependentIsNull))
5722     return true;
5723 
5724   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
5725   return false;
5726 }
5727 
5728 /// \brief Checks compatibility between two pointers and return the resulting
5729 /// type.
5730 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5731                                                      ExprResult &RHS,
5732                                                      SourceLocation Loc) {
5733   QualType LHSTy = LHS.get()->getType();
5734   QualType RHSTy = RHS.get()->getType();
5735 
5736   if (S.Context.hasSameType(LHSTy, RHSTy)) {
5737     // Two identical pointers types are always compatible.
5738     return LHSTy;
5739   }
5740 
5741   QualType lhptee, rhptee;
5742 
5743   // Get the pointee types.
5744   bool IsBlockPointer = false;
5745   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5746     lhptee = LHSBTy->getPointeeType();
5747     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5748     IsBlockPointer = true;
5749   } else {
5750     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5751     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5752   }
5753 
5754   // C99 6.5.15p6: If both operands are pointers to compatible types or to
5755   // differently qualified versions of compatible types, the result type is
5756   // a pointer to an appropriately qualified version of the composite
5757   // type.
5758 
5759   // Only CVR-qualifiers exist in the standard, and the differently-qualified
5760   // clause doesn't make sense for our extensions. E.g. address space 2 should
5761   // be incompatible with address space 3: they may live on different devices or
5762   // anything.
5763   Qualifiers lhQual = lhptee.getQualifiers();
5764   Qualifiers rhQual = rhptee.getQualifiers();
5765 
5766   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5767   lhQual.removeCVRQualifiers();
5768   rhQual.removeCVRQualifiers();
5769 
5770   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5771   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5772 
5773   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5774 
5775   if (CompositeTy.isNull()) {
5776     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
5777       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5778       << RHS.get()->getSourceRange();
5779     // In this situation, we assume void* type. No especially good
5780     // reason, but this is what gcc does, and we do have to pick
5781     // to get a consistent AST.
5782     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5783     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5784     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5785     return incompatTy;
5786   }
5787 
5788   // The pointer types are compatible.
5789   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5790   if (IsBlockPointer)
5791     ResultTy = S.Context.getBlockPointerType(ResultTy);
5792   else
5793     ResultTy = S.Context.getPointerType(ResultTy);
5794 
5795   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
5796   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
5797   return ResultTy;
5798 }
5799 
5800 /// \brief Returns true if QT is quelified-id and implements 'NSObject' and/or
5801 /// 'NSCopying' protocols (and nothing else); or QT is an NSObject and optionally
5802 /// implements 'NSObject' and/or NSCopying' protocols (and nothing else).
5803 static bool isObjCPtrBlockCompatible(Sema &S, ASTContext &C, QualType QT) {
5804   if (QT->isObjCIdType())
5805     return true;
5806 
5807   const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
5808   if (!OPT)
5809     return false;
5810 
5811   if (ObjCInterfaceDecl *ID = OPT->getInterfaceDecl())
5812     if (ID->getIdentifier() != &C.Idents.get("NSObject"))
5813       return false;
5814 
5815   ObjCProtocolDecl* PNSCopying =
5816     S.LookupProtocol(&C.Idents.get("NSCopying"), SourceLocation());
5817   ObjCProtocolDecl* PNSObject =
5818     S.LookupProtocol(&C.Idents.get("NSObject"), SourceLocation());
5819 
5820   for (auto *Proto : OPT->quals()) {
5821     if ((PNSCopying && declaresSameEntity(Proto, PNSCopying)) ||
5822         (PNSObject && declaresSameEntity(Proto, PNSObject)))
5823       ;
5824     else
5825       return false;
5826   }
5827   return true;
5828 }
5829 
5830 /// \brief Return the resulting type when the operands are both block pointers.
5831 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5832                                                           ExprResult &LHS,
5833                                                           ExprResult &RHS,
5834                                                           SourceLocation Loc) {
5835   QualType LHSTy = LHS.get()->getType();
5836   QualType RHSTy = RHS.get()->getType();
5837 
5838   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5839     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5840       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5841       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5842       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5843       return destType;
5844     }
5845     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5846       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5847       << RHS.get()->getSourceRange();
5848     return QualType();
5849   }
5850 
5851   // We have 2 block pointer types.
5852   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5853 }
5854 
5855 /// \brief Return the resulting type when the operands are both pointers.
5856 static QualType
5857 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5858                                             ExprResult &RHS,
5859                                             SourceLocation Loc) {
5860   // get the pointer types
5861   QualType LHSTy = LHS.get()->getType();
5862   QualType RHSTy = RHS.get()->getType();
5863 
5864   // get the "pointed to" types
5865   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5866   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5867 
5868   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5869   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5870     // Figure out necessary qualifiers (C99 6.5.15p6)
5871     QualType destPointee
5872       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5873     QualType destType = S.Context.getPointerType(destPointee);
5874     // Add qualifiers if necessary.
5875     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
5876     // Promote to void*.
5877     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5878     return destType;
5879   }
5880   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5881     QualType destPointee
5882       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5883     QualType destType = S.Context.getPointerType(destPointee);
5884     // Add qualifiers if necessary.
5885     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
5886     // Promote to void*.
5887     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5888     return destType;
5889   }
5890 
5891   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5892 }
5893 
5894 /// \brief Return false if the first expression is not an integer and the second
5895 /// expression is not a pointer, true otherwise.
5896 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5897                                         Expr* PointerExpr, SourceLocation Loc,
5898                                         bool IsIntFirstExpr) {
5899   if (!PointerExpr->getType()->isPointerType() ||
5900       !Int.get()->getType()->isIntegerType())
5901     return false;
5902 
5903   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5904   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5905 
5906   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
5907     << Expr1->getType() << Expr2->getType()
5908     << Expr1->getSourceRange() << Expr2->getSourceRange();
5909   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
5910                             CK_IntegralToPointer);
5911   return true;
5912 }
5913 
5914 /// \brief Simple conversion between integer and floating point types.
5915 ///
5916 /// Used when handling the OpenCL conditional operator where the
5917 /// condition is a vector while the other operands are scalar.
5918 ///
5919 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
5920 /// types are either integer or floating type. Between the two
5921 /// operands, the type with the higher rank is defined as the "result
5922 /// type". The other operand needs to be promoted to the same type. No
5923 /// other type promotion is allowed. We cannot use
5924 /// UsualArithmeticConversions() for this purpose, since it always
5925 /// promotes promotable types.
5926 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
5927                                             ExprResult &RHS,
5928                                             SourceLocation QuestionLoc) {
5929   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
5930   if (LHS.isInvalid())
5931     return QualType();
5932   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
5933   if (RHS.isInvalid())
5934     return QualType();
5935 
5936   // For conversion purposes, we ignore any qualifiers.
5937   // For example, "const float" and "float" are equivalent.
5938   QualType LHSType =
5939     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5940   QualType RHSType =
5941     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
5942 
5943   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
5944     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
5945       << LHSType << LHS.get()->getSourceRange();
5946     return QualType();
5947   }
5948 
5949   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
5950     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
5951       << RHSType << RHS.get()->getSourceRange();
5952     return QualType();
5953   }
5954 
5955   // If both types are identical, no conversion is needed.
5956   if (LHSType == RHSType)
5957     return LHSType;
5958 
5959   // Now handle "real" floating types (i.e. float, double, long double).
5960   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
5961     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
5962                                  /*IsCompAssign = */ false);
5963 
5964   // Finally, we have two differing integer types.
5965   return handleIntegerConversion<doIntegralCast, doIntegralCast>
5966   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
5967 }
5968 
5969 /// \brief Convert scalar operands to a vector that matches the
5970 ///        condition in length.
5971 ///
5972 /// Used when handling the OpenCL conditional operator where the
5973 /// condition is a vector while the other operands are scalar.
5974 ///
5975 /// We first compute the "result type" for the scalar operands
5976 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
5977 /// into a vector of that type where the length matches the condition
5978 /// vector type. s6.11.6 requires that the element types of the result
5979 /// and the condition must have the same number of bits.
5980 static QualType
5981 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
5982                               QualType CondTy, SourceLocation QuestionLoc) {
5983   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
5984   if (ResTy.isNull()) return QualType();
5985 
5986   const VectorType *CV = CondTy->getAs<VectorType>();
5987   assert(CV);
5988 
5989   // Determine the vector result type
5990   unsigned NumElements = CV->getNumElements();
5991   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
5992 
5993   // Ensure that all types have the same number of bits
5994   if (S.Context.getTypeSize(CV->getElementType())
5995       != S.Context.getTypeSize(ResTy)) {
5996     // Since VectorTy is created internally, it does not pretty print
5997     // with an OpenCL name. Instead, we just print a description.
5998     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
5999     SmallString<64> Str;
6000     llvm::raw_svector_ostream OS(Str);
6001     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6002     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6003       << CondTy << OS.str();
6004     return QualType();
6005   }
6006 
6007   // Convert operands to the vector result type
6008   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6009   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6010 
6011   return VectorTy;
6012 }
6013 
6014 /// \brief Return false if this is a valid OpenCL condition vector
6015 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6016                                        SourceLocation QuestionLoc) {
6017   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6018   // integral type.
6019   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6020   assert(CondTy);
6021   QualType EleTy = CondTy->getElementType();
6022   if (EleTy->isIntegerType()) return false;
6023 
6024   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6025     << Cond->getType() << Cond->getSourceRange();
6026   return true;
6027 }
6028 
6029 /// \brief Return false if the vector condition type and the vector
6030 ///        result type are compatible.
6031 ///
6032 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6033 /// number of elements, and their element types have the same number
6034 /// of bits.
6035 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6036                               SourceLocation QuestionLoc) {
6037   const VectorType *CV = CondTy->getAs<VectorType>();
6038   const VectorType *RV = VecResTy->getAs<VectorType>();
6039   assert(CV && RV);
6040 
6041   if (CV->getNumElements() != RV->getNumElements()) {
6042     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6043       << CondTy << VecResTy;
6044     return true;
6045   }
6046 
6047   QualType CVE = CV->getElementType();
6048   QualType RVE = RV->getElementType();
6049 
6050   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6051     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6052       << CondTy << VecResTy;
6053     return true;
6054   }
6055 
6056   return false;
6057 }
6058 
6059 /// \brief Return the resulting type for the conditional operator in
6060 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6061 ///        s6.3.i) when the condition is a vector type.
6062 static QualType
6063 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6064                              ExprResult &LHS, ExprResult &RHS,
6065                              SourceLocation QuestionLoc) {
6066   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6067   if (Cond.isInvalid())
6068     return QualType();
6069   QualType CondTy = Cond.get()->getType();
6070 
6071   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6072     return QualType();
6073 
6074   // If either operand is a vector then find the vector type of the
6075   // result as specified in OpenCL v1.1 s6.3.i.
6076   if (LHS.get()->getType()->isVectorType() ||
6077       RHS.get()->getType()->isVectorType()) {
6078     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6079                                               /*isCompAssign*/false);
6080     if (VecResTy.isNull()) return QualType();
6081     // The result type must match the condition type as specified in
6082     // OpenCL v1.1 s6.11.6.
6083     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6084       return QualType();
6085     return VecResTy;
6086   }
6087 
6088   // Both operands are scalar.
6089   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6090 }
6091 
6092 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6093 /// In that case, LHS = cond.
6094 /// C99 6.5.15
6095 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6096                                         ExprResult &RHS, ExprValueKind &VK,
6097                                         ExprObjectKind &OK,
6098                                         SourceLocation QuestionLoc) {
6099 
6100   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6101   if (!LHSResult.isUsable()) return QualType();
6102   LHS = LHSResult;
6103 
6104   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6105   if (!RHSResult.isUsable()) return QualType();
6106   RHS = RHSResult;
6107 
6108   // C++ is sufficiently different to merit its own checker.
6109   if (getLangOpts().CPlusPlus)
6110     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6111 
6112   VK = VK_RValue;
6113   OK = OK_Ordinary;
6114 
6115   // The OpenCL operator with a vector condition is sufficiently
6116   // different to merit its own checker.
6117   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6118     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6119 
6120   // First, check the condition.
6121   Cond = UsualUnaryConversions(Cond.get());
6122   if (Cond.isInvalid())
6123     return QualType();
6124   if (checkCondition(*this, Cond.get(), QuestionLoc))
6125     return QualType();
6126 
6127   // Now check the two expressions.
6128   if (LHS.get()->getType()->isVectorType() ||
6129       RHS.get()->getType()->isVectorType())
6130     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
6131 
6132   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6133   if (LHS.isInvalid() || RHS.isInvalid())
6134     return QualType();
6135 
6136   QualType LHSTy = LHS.get()->getType();
6137   QualType RHSTy = RHS.get()->getType();
6138 
6139   // If both operands have arithmetic type, do the usual arithmetic conversions
6140   // to find a common type: C99 6.5.15p3,5.
6141   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6142     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6143     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6144 
6145     return ResTy;
6146   }
6147 
6148   // If both operands are the same structure or union type, the result is that
6149   // type.
6150   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6151     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6152       if (LHSRT->getDecl() == RHSRT->getDecl())
6153         // "If both the operands have structure or union type, the result has
6154         // that type."  This implies that CV qualifiers are dropped.
6155         return LHSTy.getUnqualifiedType();
6156     // FIXME: Type of conditional expression must be complete in C mode.
6157   }
6158 
6159   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6160   // The following || allows only one side to be void (a GCC-ism).
6161   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6162     return checkConditionalVoidType(*this, LHS, RHS);
6163   }
6164 
6165   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6166   // the type of the other operand."
6167   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6168   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6169 
6170   // All objective-c pointer type analysis is done here.
6171   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6172                                                         QuestionLoc);
6173   if (LHS.isInvalid() || RHS.isInvalid())
6174     return QualType();
6175   if (!compositeType.isNull())
6176     return compositeType;
6177 
6178 
6179   // Handle block pointer types.
6180   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6181     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6182                                                      QuestionLoc);
6183 
6184   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6185   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6186     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6187                                                        QuestionLoc);
6188 
6189   // GCC compatibility: soften pointer/integer mismatch.  Note that
6190   // null pointers have been filtered out by this point.
6191   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6192       /*isIntFirstExpr=*/true))
6193     return RHSTy;
6194   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6195       /*isIntFirstExpr=*/false))
6196     return LHSTy;
6197 
6198   // Emit a better diagnostic if one of the expressions is a null pointer
6199   // constant and the other is not a pointer type. In this case, the user most
6200   // likely forgot to take the address of the other expression.
6201   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6202     return QualType();
6203 
6204   // Otherwise, the operands are not compatible.
6205   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6206     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6207     << RHS.get()->getSourceRange();
6208   return QualType();
6209 }
6210 
6211 /// FindCompositeObjCPointerType - Helper method to find composite type of
6212 /// two objective-c pointer types of the two input expressions.
6213 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6214                                             SourceLocation QuestionLoc) {
6215   QualType LHSTy = LHS.get()->getType();
6216   QualType RHSTy = RHS.get()->getType();
6217 
6218   // Handle things like Class and struct objc_class*.  Here we case the result
6219   // to the pseudo-builtin, because that will be implicitly cast back to the
6220   // redefinition type if an attempt is made to access its fields.
6221   if (LHSTy->isObjCClassType() &&
6222       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6223     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6224     return LHSTy;
6225   }
6226   if (RHSTy->isObjCClassType() &&
6227       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6228     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6229     return RHSTy;
6230   }
6231   // And the same for struct objc_object* / id
6232   if (LHSTy->isObjCIdType() &&
6233       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6234     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6235     return LHSTy;
6236   }
6237   if (RHSTy->isObjCIdType() &&
6238       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6239     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6240     return RHSTy;
6241   }
6242   // And the same for struct objc_selector* / SEL
6243   if (Context.isObjCSelType(LHSTy) &&
6244       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6245     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6246     return LHSTy;
6247   }
6248   if (Context.isObjCSelType(RHSTy) &&
6249       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6250     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6251     return RHSTy;
6252   }
6253   // Check constraints for Objective-C object pointers types.
6254   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6255 
6256     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6257       // Two identical object pointer types are always compatible.
6258       return LHSTy;
6259     }
6260     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6261     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6262     QualType compositeType = LHSTy;
6263 
6264     // If both operands are interfaces and either operand can be
6265     // assigned to the other, use that type as the composite
6266     // type. This allows
6267     //   xxx ? (A*) a : (B*) b
6268     // where B is a subclass of A.
6269     //
6270     // Additionally, as for assignment, if either type is 'id'
6271     // allow silent coercion. Finally, if the types are
6272     // incompatible then make sure to use 'id' as the composite
6273     // type so the result is acceptable for sending messages to.
6274 
6275     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6276     // It could return the composite type.
6277     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6278       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6279     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6280       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6281     } else if ((LHSTy->isObjCQualifiedIdType() ||
6282                 RHSTy->isObjCQualifiedIdType()) &&
6283                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6284       // Need to handle "id<xx>" explicitly.
6285       // GCC allows qualified id and any Objective-C type to devolve to
6286       // id. Currently localizing to here until clear this should be
6287       // part of ObjCQualifiedIdTypesAreCompatible.
6288       compositeType = Context.getObjCIdType();
6289     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6290       compositeType = Context.getObjCIdType();
6291     } else if (!(compositeType =
6292                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
6293       ;
6294     else {
6295       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6296       << LHSTy << RHSTy
6297       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6298       QualType incompatTy = Context.getObjCIdType();
6299       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6300       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6301       return incompatTy;
6302     }
6303     // The object pointer types are compatible.
6304     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6305     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6306     return compositeType;
6307   }
6308   // Check Objective-C object pointer types and 'void *'
6309   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6310     if (getLangOpts().ObjCAutoRefCount) {
6311       // ARC forbids the implicit conversion of object pointers to 'void *',
6312       // so these types are not compatible.
6313       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6314           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6315       LHS = RHS = true;
6316       return QualType();
6317     }
6318     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6319     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6320     QualType destPointee
6321     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6322     QualType destType = Context.getPointerType(destPointee);
6323     // Add qualifiers if necessary.
6324     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6325     // Promote to void*.
6326     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6327     return destType;
6328   }
6329   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6330     if (getLangOpts().ObjCAutoRefCount) {
6331       // ARC forbids the implicit conversion of object pointers to 'void *',
6332       // so these types are not compatible.
6333       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6334           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6335       LHS = RHS = true;
6336       return QualType();
6337     }
6338     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6339     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6340     QualType destPointee
6341     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6342     QualType destType = Context.getPointerType(destPointee);
6343     // Add qualifiers if necessary.
6344     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6345     // Promote to void*.
6346     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6347     return destType;
6348   }
6349   return QualType();
6350 }
6351 
6352 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6353 /// ParenRange in parentheses.
6354 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6355                                const PartialDiagnostic &Note,
6356                                SourceRange ParenRange) {
6357   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6358   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6359       EndLoc.isValid()) {
6360     Self.Diag(Loc, Note)
6361       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6362       << FixItHint::CreateInsertion(EndLoc, ")");
6363   } else {
6364     // We can't display the parentheses, so just show the bare note.
6365     Self.Diag(Loc, Note) << ParenRange;
6366   }
6367 }
6368 
6369 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6370   return Opc >= BO_Mul && Opc <= BO_Shr;
6371 }
6372 
6373 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6374 /// expression, either using a built-in or overloaded operator,
6375 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6376 /// expression.
6377 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6378                                    Expr **RHSExprs) {
6379   // Don't strip parenthesis: we should not warn if E is in parenthesis.
6380   E = E->IgnoreImpCasts();
6381   E = E->IgnoreConversionOperator();
6382   E = E->IgnoreImpCasts();
6383 
6384   // Built-in binary operator.
6385   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6386     if (IsArithmeticOp(OP->getOpcode())) {
6387       *Opcode = OP->getOpcode();
6388       *RHSExprs = OP->getRHS();
6389       return true;
6390     }
6391   }
6392 
6393   // Overloaded operator.
6394   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6395     if (Call->getNumArgs() != 2)
6396       return false;
6397 
6398     // Make sure this is really a binary operator that is safe to pass into
6399     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6400     OverloadedOperatorKind OO = Call->getOperator();
6401     if (OO < OO_Plus || OO > OO_Arrow ||
6402         OO == OO_PlusPlus || OO == OO_MinusMinus)
6403       return false;
6404 
6405     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6406     if (IsArithmeticOp(OpKind)) {
6407       *Opcode = OpKind;
6408       *RHSExprs = Call->getArg(1);
6409       return true;
6410     }
6411   }
6412 
6413   return false;
6414 }
6415 
6416 static bool IsLogicOp(BinaryOperatorKind Opc) {
6417   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
6418 }
6419 
6420 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6421 /// or is a logical expression such as (x==y) which has int type, but is
6422 /// commonly interpreted as boolean.
6423 static bool ExprLooksBoolean(Expr *E) {
6424   E = E->IgnoreParenImpCasts();
6425 
6426   if (E->getType()->isBooleanType())
6427     return true;
6428   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6429     return IsLogicOp(OP->getOpcode());
6430   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6431     return OP->getOpcode() == UO_LNot;
6432   if (E->getType()->isPointerType())
6433     return true;
6434 
6435   return false;
6436 }
6437 
6438 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6439 /// and binary operator are mixed in a way that suggests the programmer assumed
6440 /// the conditional operator has higher precedence, for example:
6441 /// "int x = a + someBinaryCondition ? 1 : 2".
6442 static void DiagnoseConditionalPrecedence(Sema &Self,
6443                                           SourceLocation OpLoc,
6444                                           Expr *Condition,
6445                                           Expr *LHSExpr,
6446                                           Expr *RHSExpr) {
6447   BinaryOperatorKind CondOpcode;
6448   Expr *CondRHS;
6449 
6450   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
6451     return;
6452   if (!ExprLooksBoolean(CondRHS))
6453     return;
6454 
6455   // The condition is an arithmetic binary expression, with a right-
6456   // hand side that looks boolean, so warn.
6457 
6458   Self.Diag(OpLoc, diag::warn_precedence_conditional)
6459       << Condition->getSourceRange()
6460       << BinaryOperator::getOpcodeStr(CondOpcode);
6461 
6462   SuggestParentheses(Self, OpLoc,
6463     Self.PDiag(diag::note_precedence_silence)
6464       << BinaryOperator::getOpcodeStr(CondOpcode),
6465     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
6466 
6467   SuggestParentheses(Self, OpLoc,
6468     Self.PDiag(diag::note_precedence_conditional_first),
6469     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
6470 }
6471 
6472 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
6473 /// in the case of a the GNU conditional expr extension.
6474 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
6475                                     SourceLocation ColonLoc,
6476                                     Expr *CondExpr, Expr *LHSExpr,
6477                                     Expr *RHSExpr) {
6478   if (!getLangOpts().CPlusPlus) {
6479     // C cannot handle TypoExpr nodes in the condition because it
6480     // doesn't handle dependent types properly, so make sure any TypoExprs have
6481     // been dealt with before checking the operands.
6482     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
6483     if (!CondResult.isUsable()) return ExprError();
6484     CondExpr = CondResult.get();
6485   }
6486 
6487   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6488   // was the condition.
6489   OpaqueValueExpr *opaqueValue = nullptr;
6490   Expr *commonExpr = nullptr;
6491   if (!LHSExpr) {
6492     commonExpr = CondExpr;
6493     // Lower out placeholder types first.  This is important so that we don't
6494     // try to capture a placeholder. This happens in few cases in C++; such
6495     // as Objective-C++'s dictionary subscripting syntax.
6496     if (commonExpr->hasPlaceholderType()) {
6497       ExprResult result = CheckPlaceholderExpr(commonExpr);
6498       if (!result.isUsable()) return ExprError();
6499       commonExpr = result.get();
6500     }
6501     // We usually want to apply unary conversions *before* saving, except
6502     // in the special case of a C++ l-value conditional.
6503     if (!(getLangOpts().CPlusPlus
6504           && !commonExpr->isTypeDependent()
6505           && commonExpr->getValueKind() == RHSExpr->getValueKind()
6506           && commonExpr->isGLValue()
6507           && commonExpr->isOrdinaryOrBitFieldObject()
6508           && RHSExpr->isOrdinaryOrBitFieldObject()
6509           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
6510       ExprResult commonRes = UsualUnaryConversions(commonExpr);
6511       if (commonRes.isInvalid())
6512         return ExprError();
6513       commonExpr = commonRes.get();
6514     }
6515 
6516     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6517                                                 commonExpr->getType(),
6518                                                 commonExpr->getValueKind(),
6519                                                 commonExpr->getObjectKind(),
6520                                                 commonExpr);
6521     LHSExpr = CondExpr = opaqueValue;
6522   }
6523 
6524   ExprValueKind VK = VK_RValue;
6525   ExprObjectKind OK = OK_Ordinary;
6526   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
6527   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
6528                                              VK, OK, QuestionLoc);
6529   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6530       RHS.isInvalid())
6531     return ExprError();
6532 
6533   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6534                                 RHS.get());
6535 
6536   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
6537 
6538   if (!commonExpr)
6539     return new (Context)
6540         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
6541                             RHS.get(), result, VK, OK);
6542 
6543   return new (Context) BinaryConditionalOperator(
6544       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
6545       ColonLoc, result, VK, OK);
6546 }
6547 
6548 // checkPointerTypesForAssignment - This is a very tricky routine (despite
6549 // being closely modeled after the C99 spec:-). The odd characteristic of this
6550 // routine is it effectively iqnores the qualifiers on the top level pointee.
6551 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6552 // FIXME: add a couple examples in this comment.
6553 static Sema::AssignConvertType
6554 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
6555   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6556   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6557 
6558   // get the "pointed to" type (ignoring qualifiers at the top level)
6559   const Type *lhptee, *rhptee;
6560   Qualifiers lhq, rhq;
6561   std::tie(lhptee, lhq) =
6562       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
6563   std::tie(rhptee, rhq) =
6564       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
6565 
6566   Sema::AssignConvertType ConvTy = Sema::Compatible;
6567 
6568   // C99 6.5.16.1p1: This following citation is common to constraints
6569   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6570   // qualifiers of the type *pointed to* by the right;
6571 
6572   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6573   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6574       lhq.compatiblyIncludesObjCLifetime(rhq)) {
6575     // Ignore lifetime for further calculation.
6576     lhq.removeObjCLifetime();
6577     rhq.removeObjCLifetime();
6578   }
6579 
6580   if (!lhq.compatiblyIncludes(rhq)) {
6581     // Treat address-space mismatches as fatal.  TODO: address subspaces
6582     if (!lhq.isAddressSpaceSupersetOf(rhq))
6583       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6584 
6585     // It's okay to add or remove GC or lifetime qualifiers when converting to
6586     // and from void*.
6587     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
6588                         .compatiblyIncludes(
6589                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
6590              && (lhptee->isVoidType() || rhptee->isVoidType()))
6591       ; // keep old
6592 
6593     // Treat lifetime mismatches as fatal.
6594     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6595       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6596 
6597     // For GCC compatibility, other qualifier mismatches are treated
6598     // as still compatible in C.
6599     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6600   }
6601 
6602   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6603   // incomplete type and the other is a pointer to a qualified or unqualified
6604   // version of void...
6605   if (lhptee->isVoidType()) {
6606     if (rhptee->isIncompleteOrObjectType())
6607       return ConvTy;
6608 
6609     // As an extension, we allow cast to/from void* to function pointer.
6610     assert(rhptee->isFunctionType());
6611     return Sema::FunctionVoidPointer;
6612   }
6613 
6614   if (rhptee->isVoidType()) {
6615     if (lhptee->isIncompleteOrObjectType())
6616       return ConvTy;
6617 
6618     // As an extension, we allow cast to/from void* to function pointer.
6619     assert(lhptee->isFunctionType());
6620     return Sema::FunctionVoidPointer;
6621   }
6622 
6623   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6624   // unqualified versions of compatible types, ...
6625   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6626   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6627     // Check if the pointee types are compatible ignoring the sign.
6628     // We explicitly check for char so that we catch "char" vs
6629     // "unsigned char" on systems where "char" is unsigned.
6630     if (lhptee->isCharType())
6631       ltrans = S.Context.UnsignedCharTy;
6632     else if (lhptee->hasSignedIntegerRepresentation())
6633       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6634 
6635     if (rhptee->isCharType())
6636       rtrans = S.Context.UnsignedCharTy;
6637     else if (rhptee->hasSignedIntegerRepresentation())
6638       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6639 
6640     if (ltrans == rtrans) {
6641       // Types are compatible ignoring the sign. Qualifier incompatibility
6642       // takes priority over sign incompatibility because the sign
6643       // warning can be disabled.
6644       if (ConvTy != Sema::Compatible)
6645         return ConvTy;
6646 
6647       return Sema::IncompatiblePointerSign;
6648     }
6649 
6650     // If we are a multi-level pointer, it's possible that our issue is simply
6651     // one of qualification - e.g. char ** -> const char ** is not allowed. If
6652     // the eventual target type is the same and the pointers have the same
6653     // level of indirection, this must be the issue.
6654     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6655       do {
6656         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6657         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6658       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6659 
6660       if (lhptee == rhptee)
6661         return Sema::IncompatibleNestedPointerQualifiers;
6662     }
6663 
6664     // General pointer incompatibility takes priority over qualifiers.
6665     return Sema::IncompatiblePointer;
6666   }
6667   if (!S.getLangOpts().CPlusPlus &&
6668       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6669     return Sema::IncompatiblePointer;
6670   return ConvTy;
6671 }
6672 
6673 /// checkBlockPointerTypesForAssignment - This routine determines whether two
6674 /// block pointer types are compatible or whether a block and normal pointer
6675 /// are compatible. It is more restrict than comparing two function pointer
6676 // types.
6677 static Sema::AssignConvertType
6678 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6679                                     QualType RHSType) {
6680   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6681   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6682 
6683   QualType lhptee, rhptee;
6684 
6685   // get the "pointed to" type (ignoring qualifiers at the top level)
6686   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6687   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6688 
6689   // In C++, the types have to match exactly.
6690   if (S.getLangOpts().CPlusPlus)
6691     return Sema::IncompatibleBlockPointer;
6692 
6693   Sema::AssignConvertType ConvTy = Sema::Compatible;
6694 
6695   // For blocks we enforce that qualifiers are identical.
6696   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6697     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6698 
6699   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6700     return Sema::IncompatibleBlockPointer;
6701 
6702   return ConvTy;
6703 }
6704 
6705 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6706 /// for assignment compatibility.
6707 static Sema::AssignConvertType
6708 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6709                                    QualType RHSType) {
6710   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6711   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6712 
6713   if (LHSType->isObjCBuiltinType()) {
6714     // Class is not compatible with ObjC object pointers.
6715     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6716         !RHSType->isObjCQualifiedClassType())
6717       return Sema::IncompatiblePointer;
6718     return Sema::Compatible;
6719   }
6720   if (RHSType->isObjCBuiltinType()) {
6721     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6722         !LHSType->isObjCQualifiedClassType())
6723       return Sema::IncompatiblePointer;
6724     return Sema::Compatible;
6725   }
6726   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6727   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6728 
6729   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6730       // make an exception for id<P>
6731       !LHSType->isObjCQualifiedIdType())
6732     return Sema::CompatiblePointerDiscardsQualifiers;
6733 
6734   if (S.Context.typesAreCompatible(LHSType, RHSType))
6735     return Sema::Compatible;
6736   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6737     return Sema::IncompatibleObjCQualifiedId;
6738   return Sema::IncompatiblePointer;
6739 }
6740 
6741 Sema::AssignConvertType
6742 Sema::CheckAssignmentConstraints(SourceLocation Loc,
6743                                  QualType LHSType, QualType RHSType) {
6744   // Fake up an opaque expression.  We don't actually care about what
6745   // cast operations are required, so if CheckAssignmentConstraints
6746   // adds casts to this they'll be wasted, but fortunately that doesn't
6747   // usually happen on valid code.
6748   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6749   ExprResult RHSPtr = &RHSExpr;
6750   CastKind K = CK_Invalid;
6751 
6752   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
6753 }
6754 
6755 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6756 /// has code to accommodate several GCC extensions when type checking
6757 /// pointers. Here are some objectionable examples that GCC considers warnings:
6758 ///
6759 ///  int a, *pint;
6760 ///  short *pshort;
6761 ///  struct foo *pfoo;
6762 ///
6763 ///  pint = pshort; // warning: assignment from incompatible pointer type
6764 ///  a = pint; // warning: assignment makes integer from pointer without a cast
6765 ///  pint = a; // warning: assignment makes pointer from integer without a cast
6766 ///  pint = pfoo; // warning: assignment from incompatible pointer type
6767 ///
6768 /// As a result, the code for dealing with pointers is more complex than the
6769 /// C99 spec dictates.
6770 ///
6771 /// Sets 'Kind' for any result kind except Incompatible.
6772 Sema::AssignConvertType
6773 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6774                                  CastKind &Kind) {
6775   QualType RHSType = RHS.get()->getType();
6776   QualType OrigLHSType = LHSType;
6777 
6778   // Get canonical types.  We're not formatting these types, just comparing
6779   // them.
6780   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6781   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6782 
6783   // Common case: no conversion required.
6784   if (LHSType == RHSType) {
6785     Kind = CK_NoOp;
6786     return Compatible;
6787   }
6788 
6789   // If we have an atomic type, try a non-atomic assignment, then just add an
6790   // atomic qualification step.
6791   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6792     Sema::AssignConvertType result =
6793       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6794     if (result != Compatible)
6795       return result;
6796     if (Kind != CK_NoOp)
6797       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
6798     Kind = CK_NonAtomicToAtomic;
6799     return Compatible;
6800   }
6801 
6802   // If the left-hand side is a reference type, then we are in a
6803   // (rare!) case where we've allowed the use of references in C,
6804   // e.g., as a parameter type in a built-in function. In this case,
6805   // just make sure that the type referenced is compatible with the
6806   // right-hand side type. The caller is responsible for adjusting
6807   // LHSType so that the resulting expression does not have reference
6808   // type.
6809   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6810     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6811       Kind = CK_LValueBitCast;
6812       return Compatible;
6813     }
6814     return Incompatible;
6815   }
6816 
6817   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6818   // to the same ExtVector type.
6819   if (LHSType->isExtVectorType()) {
6820     if (RHSType->isExtVectorType())
6821       return Incompatible;
6822     if (RHSType->isArithmeticType()) {
6823       // CK_VectorSplat does T -> vector T, so first cast to the
6824       // element type.
6825       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6826       if (elType != RHSType) {
6827         Kind = PrepareScalarCast(RHS, elType);
6828         RHS = ImpCastExprToType(RHS.get(), elType, Kind);
6829       }
6830       Kind = CK_VectorSplat;
6831       return Compatible;
6832     }
6833   }
6834 
6835   // Conversions to or from vector type.
6836   if (LHSType->isVectorType() || RHSType->isVectorType()) {
6837     if (LHSType->isVectorType() && RHSType->isVectorType()) {
6838       // Allow assignments of an AltiVec vector type to an equivalent GCC
6839       // vector type and vice versa
6840       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6841         Kind = CK_BitCast;
6842         return Compatible;
6843       }
6844 
6845       // If we are allowing lax vector conversions, and LHS and RHS are both
6846       // vectors, the total size only needs to be the same. This is a bitcast;
6847       // no bits are changed but the result type is different.
6848       if (isLaxVectorConversion(RHSType, LHSType)) {
6849         Kind = CK_BitCast;
6850         return IncompatibleVectors;
6851       }
6852     }
6853     return Incompatible;
6854   }
6855 
6856   // Arithmetic conversions.
6857   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
6858       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
6859     Kind = PrepareScalarCast(RHS, LHSType);
6860     return Compatible;
6861   }
6862 
6863   // Conversions to normal pointers.
6864   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
6865     // U* -> T*
6866     if (isa<PointerType>(RHSType)) {
6867       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
6868       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
6869       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
6870       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
6871     }
6872 
6873     // int -> T*
6874     if (RHSType->isIntegerType()) {
6875       Kind = CK_IntegralToPointer; // FIXME: null?
6876       return IntToPointer;
6877     }
6878 
6879     // C pointers are not compatible with ObjC object pointers,
6880     // with two exceptions:
6881     if (isa<ObjCObjectPointerType>(RHSType)) {
6882       //  - conversions to void*
6883       if (LHSPointer->getPointeeType()->isVoidType()) {
6884         Kind = CK_BitCast;
6885         return Compatible;
6886       }
6887 
6888       //  - conversions from 'Class' to the redefinition type
6889       if (RHSType->isObjCClassType() &&
6890           Context.hasSameType(LHSType,
6891                               Context.getObjCClassRedefinitionType())) {
6892         Kind = CK_BitCast;
6893         return Compatible;
6894       }
6895 
6896       Kind = CK_BitCast;
6897       return IncompatiblePointer;
6898     }
6899 
6900     // U^ -> void*
6901     if (RHSType->getAs<BlockPointerType>()) {
6902       if (LHSPointer->getPointeeType()->isVoidType()) {
6903         Kind = CK_BitCast;
6904         return Compatible;
6905       }
6906     }
6907 
6908     return Incompatible;
6909   }
6910 
6911   // Conversions to block pointers.
6912   if (isa<BlockPointerType>(LHSType)) {
6913     // U^ -> T^
6914     if (RHSType->isBlockPointerType()) {
6915       Kind = CK_BitCast;
6916       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
6917     }
6918 
6919     // int or null -> T^
6920     if (RHSType->isIntegerType()) {
6921       Kind = CK_IntegralToPointer; // FIXME: null
6922       return IntToBlockPointer;
6923     }
6924 
6925     // id -> T^
6926     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
6927       Kind = CK_AnyPointerToBlockPointerCast;
6928       return Compatible;
6929     }
6930 
6931     // void* -> T^
6932     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
6933       if (RHSPT->getPointeeType()->isVoidType()) {
6934         Kind = CK_AnyPointerToBlockPointerCast;
6935         return Compatible;
6936       }
6937 
6938     return Incompatible;
6939   }
6940 
6941   // Conversions to Objective-C pointers.
6942   if (isa<ObjCObjectPointerType>(LHSType)) {
6943     // A* -> B*
6944     if (RHSType->isObjCObjectPointerType()) {
6945       Kind = CK_BitCast;
6946       Sema::AssignConvertType result =
6947         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
6948       if (getLangOpts().ObjCAutoRefCount &&
6949           result == Compatible &&
6950           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
6951         result = IncompatibleObjCWeakRef;
6952       return result;
6953     }
6954 
6955     // int or null -> A*
6956     if (RHSType->isIntegerType()) {
6957       Kind = CK_IntegralToPointer; // FIXME: null
6958       return IntToPointer;
6959     }
6960 
6961     // In general, C pointers are not compatible with ObjC object pointers,
6962     // with two exceptions:
6963     if (isa<PointerType>(RHSType)) {
6964       Kind = CK_CPointerToObjCPointerCast;
6965 
6966       //  - conversions from 'void*'
6967       if (RHSType->isVoidPointerType()) {
6968         return Compatible;
6969       }
6970 
6971       //  - conversions to 'Class' from its redefinition type
6972       if (LHSType->isObjCClassType() &&
6973           Context.hasSameType(RHSType,
6974                               Context.getObjCClassRedefinitionType())) {
6975         return Compatible;
6976       }
6977 
6978       return IncompatiblePointer;
6979     }
6980 
6981     // Only under strict condition T^ is compatible with an Objective-C pointer.
6982     if (RHSType->isBlockPointerType() &&
6983         isObjCPtrBlockCompatible(*this, Context, LHSType)) {
6984       maybeExtendBlockObject(*this, RHS);
6985       Kind = CK_BlockPointerToObjCPointerCast;
6986       return Compatible;
6987     }
6988 
6989     return Incompatible;
6990   }
6991 
6992   // Conversions from pointers that are not covered by the above.
6993   if (isa<PointerType>(RHSType)) {
6994     // T* -> _Bool
6995     if (LHSType == Context.BoolTy) {
6996       Kind = CK_PointerToBoolean;
6997       return Compatible;
6998     }
6999 
7000     // T* -> int
7001     if (LHSType->isIntegerType()) {
7002       Kind = CK_PointerToIntegral;
7003       return PointerToInt;
7004     }
7005 
7006     return Incompatible;
7007   }
7008 
7009   // Conversions from Objective-C pointers that are not covered by the above.
7010   if (isa<ObjCObjectPointerType>(RHSType)) {
7011     // T* -> _Bool
7012     if (LHSType == Context.BoolTy) {
7013       Kind = CK_PointerToBoolean;
7014       return Compatible;
7015     }
7016 
7017     // T* -> int
7018     if (LHSType->isIntegerType()) {
7019       Kind = CK_PointerToIntegral;
7020       return PointerToInt;
7021     }
7022 
7023     return Incompatible;
7024   }
7025 
7026   // struct A -> struct B
7027   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7028     if (Context.typesAreCompatible(LHSType, RHSType)) {
7029       Kind = CK_NoOp;
7030       return Compatible;
7031     }
7032   }
7033 
7034   return Incompatible;
7035 }
7036 
7037 /// \brief Constructs a transparent union from an expression that is
7038 /// used to initialize the transparent union.
7039 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7040                                       ExprResult &EResult, QualType UnionType,
7041                                       FieldDecl *Field) {
7042   // Build an initializer list that designates the appropriate member
7043   // of the transparent union.
7044   Expr *E = EResult.get();
7045   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7046                                                    E, SourceLocation());
7047   Initializer->setType(UnionType);
7048   Initializer->setInitializedFieldInUnion(Field);
7049 
7050   // Build a compound literal constructing a value of the transparent
7051   // union type from this initializer list.
7052   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7053   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7054                                         VK_RValue, Initializer, false);
7055 }
7056 
7057 Sema::AssignConvertType
7058 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7059                                                ExprResult &RHS) {
7060   QualType RHSType = RHS.get()->getType();
7061 
7062   // If the ArgType is a Union type, we want to handle a potential
7063   // transparent_union GCC extension.
7064   const RecordType *UT = ArgType->getAsUnionType();
7065   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7066     return Incompatible;
7067 
7068   // The field to initialize within the transparent union.
7069   RecordDecl *UD = UT->getDecl();
7070   FieldDecl *InitField = nullptr;
7071   // It's compatible if the expression matches any of the fields.
7072   for (auto *it : UD->fields()) {
7073     if (it->getType()->isPointerType()) {
7074       // If the transparent union contains a pointer type, we allow:
7075       // 1) void pointer
7076       // 2) null pointer constant
7077       if (RHSType->isPointerType())
7078         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7079           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7080           InitField = it;
7081           break;
7082         }
7083 
7084       if (RHS.get()->isNullPointerConstant(Context,
7085                                            Expr::NPC_ValueDependentIsNull)) {
7086         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7087                                 CK_NullToPointer);
7088         InitField = it;
7089         break;
7090       }
7091     }
7092 
7093     CastKind Kind = CK_Invalid;
7094     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7095           == Compatible) {
7096       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7097       InitField = it;
7098       break;
7099     }
7100   }
7101 
7102   if (!InitField)
7103     return Incompatible;
7104 
7105   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7106   return Compatible;
7107 }
7108 
7109 Sema::AssignConvertType
7110 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7111                                        bool Diagnose,
7112                                        bool DiagnoseCFAudited) {
7113   if (getLangOpts().CPlusPlus) {
7114     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7115       // C++ 5.17p3: If the left operand is not of class type, the
7116       // expression is implicitly converted (C++ 4) to the
7117       // cv-unqualified type of the left operand.
7118       ExprResult Res;
7119       if (Diagnose) {
7120         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7121                                         AA_Assigning);
7122       } else {
7123         ImplicitConversionSequence ICS =
7124             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7125                                   /*SuppressUserConversions=*/false,
7126                                   /*AllowExplicit=*/false,
7127                                   /*InOverloadResolution=*/false,
7128                                   /*CStyle=*/false,
7129                                   /*AllowObjCWritebackConversion=*/false);
7130         if (ICS.isFailure())
7131           return Incompatible;
7132         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7133                                         ICS, AA_Assigning);
7134       }
7135       if (Res.isInvalid())
7136         return Incompatible;
7137       Sema::AssignConvertType result = Compatible;
7138       if (getLangOpts().ObjCAutoRefCount &&
7139           !CheckObjCARCUnavailableWeakConversion(LHSType,
7140                                                  RHS.get()->getType()))
7141         result = IncompatibleObjCWeakRef;
7142       RHS = Res;
7143       return result;
7144     }
7145 
7146     // FIXME: Currently, we fall through and treat C++ classes like C
7147     // structures.
7148     // FIXME: We also fall through for atomics; not sure what should
7149     // happen there, though.
7150   }
7151 
7152   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7153   // a null pointer constant.
7154   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7155        LHSType->isBlockPointerType()) &&
7156       RHS.get()->isNullPointerConstant(Context,
7157                                        Expr::NPC_ValueDependentIsNull)) {
7158     CastKind Kind;
7159     CXXCastPath Path;
7160     CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
7161     RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7162     return Compatible;
7163   }
7164 
7165   // This check seems unnatural, however it is necessary to ensure the proper
7166   // conversion of functions/arrays. If the conversion were done for all
7167   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7168   // expressions that suppress this implicit conversion (&, sizeof).
7169   //
7170   // Suppress this for references: C++ 8.5.3p5.
7171   if (!LHSType->isReferenceType()) {
7172     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
7173     if (RHS.isInvalid())
7174       return Incompatible;
7175   }
7176 
7177   Expr *PRE = RHS.get()->IgnoreParenCasts();
7178   if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) {
7179     ObjCProtocolDecl *PDecl = OPE->getProtocol();
7180     if (PDecl && !PDecl->hasDefinition()) {
7181       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7182       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7183     }
7184   }
7185 
7186   CastKind Kind = CK_Invalid;
7187   Sema::AssignConvertType result =
7188     CheckAssignmentConstraints(LHSType, RHS, Kind);
7189 
7190   // C99 6.5.16.1p2: The value of the right operand is converted to the
7191   // type of the assignment expression.
7192   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7193   // so that we can use references in built-in functions even in C.
7194   // The getNonReferenceType() call makes sure that the resulting expression
7195   // does not have reference type.
7196   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7197     QualType Ty = LHSType.getNonLValueExprType(Context);
7198     Expr *E = RHS.get();
7199     if (getLangOpts().ObjCAutoRefCount)
7200       CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7201                              DiagnoseCFAudited);
7202     if (getLangOpts().ObjC1 &&
7203         (CheckObjCBridgeRelatedConversions(E->getLocStart(),
7204                                           LHSType, E->getType(), E) ||
7205          ConversionToObjCStringLiteralCheck(LHSType, E))) {
7206       RHS = E;
7207       return Compatible;
7208     }
7209 
7210     RHS = ImpCastExprToType(E, Ty, Kind);
7211   }
7212   return result;
7213 }
7214 
7215 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7216                                ExprResult &RHS) {
7217   Diag(Loc, diag::err_typecheck_invalid_operands)
7218     << LHS.get()->getType() << RHS.get()->getType()
7219     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7220   return QualType();
7221 }
7222 
7223 /// Try to convert a value of non-vector type to a vector type by converting
7224 /// the type to the element type of the vector and then performing a splat.
7225 /// If the language is OpenCL, we only use conversions that promote scalar
7226 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7227 /// for float->int.
7228 ///
7229 /// \param scalar - if non-null, actually perform the conversions
7230 /// \return true if the operation fails (but without diagnosing the failure)
7231 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7232                                      QualType scalarTy,
7233                                      QualType vectorEltTy,
7234                                      QualType vectorTy) {
7235   // The conversion to apply to the scalar before splatting it,
7236   // if necessary.
7237   CastKind scalarCast = CK_Invalid;
7238 
7239   if (vectorEltTy->isIntegralType(S.Context)) {
7240     if (!scalarTy->isIntegralType(S.Context))
7241       return true;
7242     if (S.getLangOpts().OpenCL &&
7243         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7244       return true;
7245     scalarCast = CK_IntegralCast;
7246   } else if (vectorEltTy->isRealFloatingType()) {
7247     if (scalarTy->isRealFloatingType()) {
7248       if (S.getLangOpts().OpenCL &&
7249           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7250         return true;
7251       scalarCast = CK_FloatingCast;
7252     }
7253     else if (scalarTy->isIntegralType(S.Context))
7254       scalarCast = CK_IntegralToFloating;
7255     else
7256       return true;
7257   } else {
7258     return true;
7259   }
7260 
7261   // Adjust scalar if desired.
7262   if (scalar) {
7263     if (scalarCast != CK_Invalid)
7264       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
7265     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
7266   }
7267   return false;
7268 }
7269 
7270 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7271                                    SourceLocation Loc, bool IsCompAssign) {
7272   if (!IsCompAssign) {
7273     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
7274     if (LHS.isInvalid())
7275       return QualType();
7276   }
7277   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
7278   if (RHS.isInvalid())
7279     return QualType();
7280 
7281   // For conversion purposes, we ignore any qualifiers.
7282   // For example, "const float" and "float" are equivalent.
7283   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
7284   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
7285 
7286   // If the vector types are identical, return.
7287   if (Context.hasSameType(LHSType, RHSType))
7288     return LHSType;
7289 
7290   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
7291   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
7292   assert(LHSVecType || RHSVecType);
7293 
7294   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
7295   if (LHSVecType && RHSVecType &&
7296       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7297     if (isa<ExtVectorType>(LHSVecType)) {
7298       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7299       return LHSType;
7300     }
7301 
7302     if (!IsCompAssign)
7303       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7304     return RHSType;
7305   }
7306 
7307   // If there's an ext-vector type and a scalar, try to convert the scalar to
7308   // the vector element type and splat.
7309   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
7310     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
7311                                   LHSVecType->getElementType(), LHSType))
7312       return LHSType;
7313   }
7314   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
7315     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
7316                                   LHSType, RHSVecType->getElementType(),
7317                                   RHSType))
7318       return RHSType;
7319   }
7320 
7321   // If we're allowing lax vector conversions, only the total (data) size
7322   // needs to be the same.
7323   // FIXME: Should we really be allowing this?
7324   // FIXME: We really just pick the LHS type arbitrarily?
7325   if (isLaxVectorConversion(RHSType, LHSType)) {
7326     QualType resultType = LHSType;
7327     RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
7328     return resultType;
7329   }
7330 
7331   // Okay, the expression is invalid.
7332 
7333   // If there's a non-vector, non-real operand, diagnose that.
7334   if ((!RHSVecType && !RHSType->isRealType()) ||
7335       (!LHSVecType && !LHSType->isRealType())) {
7336     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
7337       << LHSType << RHSType
7338       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7339     return QualType();
7340   }
7341 
7342   // Otherwise, use the generic diagnostic.
7343   Diag(Loc, diag::err_typecheck_vector_not_convertable)
7344     << LHSType << RHSType
7345     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7346   return QualType();
7347 }
7348 
7349 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
7350 // expression.  These are mainly cases where the null pointer is used as an
7351 // integer instead of a pointer.
7352 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
7353                                 SourceLocation Loc, bool IsCompare) {
7354   // The canonical way to check for a GNU null is with isNullPointerConstant,
7355   // but we use a bit of a hack here for speed; this is a relatively
7356   // hot path, and isNullPointerConstant is slow.
7357   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
7358   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
7359 
7360   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
7361 
7362   // Avoid analyzing cases where the result will either be invalid (and
7363   // diagnosed as such) or entirely valid and not something to warn about.
7364   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
7365       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
7366     return;
7367 
7368   // Comparison operations would not make sense with a null pointer no matter
7369   // what the other expression is.
7370   if (!IsCompare) {
7371     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
7372         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
7373         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
7374     return;
7375   }
7376 
7377   // The rest of the operations only make sense with a null pointer
7378   // if the other expression is a pointer.
7379   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
7380       NonNullType->canDecayToPointerType())
7381     return;
7382 
7383   S.Diag(Loc, diag::warn_null_in_comparison_operation)
7384       << LHSNull /* LHS is NULL */ << NonNullType
7385       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7386 }
7387 
7388 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
7389                                            SourceLocation Loc,
7390                                            bool IsCompAssign, bool IsDiv) {
7391   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7392 
7393   if (LHS.get()->getType()->isVectorType() ||
7394       RHS.get()->getType()->isVectorType())
7395     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7396 
7397   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
7398   if (LHS.isInvalid() || RHS.isInvalid())
7399     return QualType();
7400 
7401 
7402   if (compType.isNull() || !compType->isArithmeticType())
7403     return InvalidOperands(Loc, LHS, RHS);
7404 
7405   // Check for division by zero.
7406   llvm::APSInt RHSValue;
7407   if (IsDiv && !RHS.get()->isValueDependent() &&
7408       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
7409     DiagRuntimeBehavior(Loc, RHS.get(),
7410                         PDiag(diag::warn_division_by_zero)
7411                           << RHS.get()->getSourceRange());
7412 
7413   return compType;
7414 }
7415 
7416 QualType Sema::CheckRemainderOperands(
7417   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7418   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7419 
7420   if (LHS.get()->getType()->isVectorType() ||
7421       RHS.get()->getType()->isVectorType()) {
7422     if (LHS.get()->getType()->hasIntegerRepresentation() &&
7423         RHS.get()->getType()->hasIntegerRepresentation())
7424       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7425     return InvalidOperands(Loc, LHS, RHS);
7426   }
7427 
7428   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
7429   if (LHS.isInvalid() || RHS.isInvalid())
7430     return QualType();
7431 
7432   if (compType.isNull() || !compType->isIntegerType())
7433     return InvalidOperands(Loc, LHS, RHS);
7434 
7435   // Check for remainder by zero.
7436   llvm::APSInt RHSValue;
7437   if (!RHS.get()->isValueDependent() &&
7438       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
7439     DiagRuntimeBehavior(Loc, RHS.get(),
7440                         PDiag(diag::warn_remainder_by_zero)
7441                           << RHS.get()->getSourceRange());
7442 
7443   return compType;
7444 }
7445 
7446 /// \brief Diagnose invalid arithmetic on two void pointers.
7447 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
7448                                                 Expr *LHSExpr, Expr *RHSExpr) {
7449   S.Diag(Loc, S.getLangOpts().CPlusPlus
7450                 ? diag::err_typecheck_pointer_arith_void_type
7451                 : diag::ext_gnu_void_ptr)
7452     << 1 /* two pointers */ << LHSExpr->getSourceRange()
7453                             << RHSExpr->getSourceRange();
7454 }
7455 
7456 /// \brief Diagnose invalid arithmetic on a void pointer.
7457 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
7458                                             Expr *Pointer) {
7459   S.Diag(Loc, S.getLangOpts().CPlusPlus
7460                 ? diag::err_typecheck_pointer_arith_void_type
7461                 : diag::ext_gnu_void_ptr)
7462     << 0 /* one pointer */ << Pointer->getSourceRange();
7463 }
7464 
7465 /// \brief Diagnose invalid arithmetic on two function pointers.
7466 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
7467                                                     Expr *LHS, Expr *RHS) {
7468   assert(LHS->getType()->isAnyPointerType());
7469   assert(RHS->getType()->isAnyPointerType());
7470   S.Diag(Loc, S.getLangOpts().CPlusPlus
7471                 ? diag::err_typecheck_pointer_arith_function_type
7472                 : diag::ext_gnu_ptr_func_arith)
7473     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
7474     // We only show the second type if it differs from the first.
7475     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
7476                                                    RHS->getType())
7477     << RHS->getType()->getPointeeType()
7478     << LHS->getSourceRange() << RHS->getSourceRange();
7479 }
7480 
7481 /// \brief Diagnose invalid arithmetic on a function pointer.
7482 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
7483                                                 Expr *Pointer) {
7484   assert(Pointer->getType()->isAnyPointerType());
7485   S.Diag(Loc, S.getLangOpts().CPlusPlus
7486                 ? diag::err_typecheck_pointer_arith_function_type
7487                 : diag::ext_gnu_ptr_func_arith)
7488     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
7489     << 0 /* one pointer, so only one type */
7490     << Pointer->getSourceRange();
7491 }
7492 
7493 /// \brief Emit error if Operand is incomplete pointer type
7494 ///
7495 /// \returns True if pointer has incomplete type
7496 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
7497                                                  Expr *Operand) {
7498   QualType ResType = Operand->getType();
7499   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7500     ResType = ResAtomicType->getValueType();
7501 
7502   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
7503   QualType PointeeTy = ResType->getPointeeType();
7504   return S.RequireCompleteType(Loc, PointeeTy,
7505                                diag::err_typecheck_arithmetic_incomplete_type,
7506                                PointeeTy, Operand->getSourceRange());
7507 }
7508 
7509 /// \brief Check the validity of an arithmetic pointer operand.
7510 ///
7511 /// If the operand has pointer type, this code will check for pointer types
7512 /// which are invalid in arithmetic operations. These will be diagnosed
7513 /// appropriately, including whether or not the use is supported as an
7514 /// extension.
7515 ///
7516 /// \returns True when the operand is valid to use (even if as an extension).
7517 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
7518                                             Expr *Operand) {
7519   QualType ResType = Operand->getType();
7520   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7521     ResType = ResAtomicType->getValueType();
7522 
7523   if (!ResType->isAnyPointerType()) return true;
7524 
7525   QualType PointeeTy = ResType->getPointeeType();
7526   if (PointeeTy->isVoidType()) {
7527     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
7528     return !S.getLangOpts().CPlusPlus;
7529   }
7530   if (PointeeTy->isFunctionType()) {
7531     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
7532     return !S.getLangOpts().CPlusPlus;
7533   }
7534 
7535   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
7536 
7537   return true;
7538 }
7539 
7540 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
7541 /// operands.
7542 ///
7543 /// This routine will diagnose any invalid arithmetic on pointer operands much
7544 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
7545 /// for emitting a single diagnostic even for operations where both LHS and RHS
7546 /// are (potentially problematic) pointers.
7547 ///
7548 /// \returns True when the operand is valid to use (even if as an extension).
7549 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
7550                                                 Expr *LHSExpr, Expr *RHSExpr) {
7551   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
7552   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
7553   if (!isLHSPointer && !isRHSPointer) return true;
7554 
7555   QualType LHSPointeeTy, RHSPointeeTy;
7556   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
7557   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
7558 
7559   // if both are pointers check if operation is valid wrt address spaces
7560   if (isLHSPointer && isRHSPointer) {
7561     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
7562     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
7563     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
7564       S.Diag(Loc,
7565              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7566           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
7567           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
7568       return false;
7569     }
7570   }
7571 
7572   // Check for arithmetic on pointers to incomplete types.
7573   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
7574   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
7575   if (isLHSVoidPtr || isRHSVoidPtr) {
7576     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
7577     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
7578     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
7579 
7580     return !S.getLangOpts().CPlusPlus;
7581   }
7582 
7583   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
7584   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
7585   if (isLHSFuncPtr || isRHSFuncPtr) {
7586     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
7587     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
7588                                                                 RHSExpr);
7589     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
7590 
7591     return !S.getLangOpts().CPlusPlus;
7592   }
7593 
7594   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
7595     return false;
7596   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
7597     return false;
7598 
7599   return true;
7600 }
7601 
7602 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
7603 /// literal.
7604 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
7605                                   Expr *LHSExpr, Expr *RHSExpr) {
7606   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
7607   Expr* IndexExpr = RHSExpr;
7608   if (!StrExpr) {
7609     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
7610     IndexExpr = LHSExpr;
7611   }
7612 
7613   bool IsStringPlusInt = StrExpr &&
7614       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
7615   if (!IsStringPlusInt || IndexExpr->isValueDependent())
7616     return;
7617 
7618   llvm::APSInt index;
7619   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
7620     unsigned StrLenWithNull = StrExpr->getLength() + 1;
7621     if (index.isNonNegative() &&
7622         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
7623                               index.isUnsigned()))
7624       return;
7625   }
7626 
7627   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7628   Self.Diag(OpLoc, diag::warn_string_plus_int)
7629       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
7630 
7631   // Only print a fixit for "str" + int, not for int + "str".
7632   if (IndexExpr == RHSExpr) {
7633     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7634     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7635         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7636         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7637         << FixItHint::CreateInsertion(EndLoc, "]");
7638   } else
7639     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7640 }
7641 
7642 /// \brief Emit a warning when adding a char literal to a string.
7643 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
7644                                    Expr *LHSExpr, Expr *RHSExpr) {
7645   const Expr *StringRefExpr = LHSExpr;
7646   const CharacterLiteral *CharExpr =
7647       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
7648 
7649   if (!CharExpr) {
7650     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
7651     StringRefExpr = RHSExpr;
7652   }
7653 
7654   if (!CharExpr || !StringRefExpr)
7655     return;
7656 
7657   const QualType StringType = StringRefExpr->getType();
7658 
7659   // Return if not a PointerType.
7660   if (!StringType->isAnyPointerType())
7661     return;
7662 
7663   // Return if not a CharacterType.
7664   if (!StringType->getPointeeType()->isAnyCharacterType())
7665     return;
7666 
7667   ASTContext &Ctx = Self.getASTContext();
7668   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7669 
7670   const QualType CharType = CharExpr->getType();
7671   if (!CharType->isAnyCharacterType() &&
7672       CharType->isIntegerType() &&
7673       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
7674     Self.Diag(OpLoc, diag::warn_string_plus_char)
7675         << DiagRange << Ctx.CharTy;
7676   } else {
7677     Self.Diag(OpLoc, diag::warn_string_plus_char)
7678         << DiagRange << CharExpr->getType();
7679   }
7680 
7681   // Only print a fixit for str + char, not for char + str.
7682   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
7683     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7684     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7685         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7686         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7687         << FixItHint::CreateInsertion(EndLoc, "]");
7688   } else {
7689     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7690   }
7691 }
7692 
7693 /// \brief Emit error when two pointers are incompatible.
7694 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
7695                                            Expr *LHSExpr, Expr *RHSExpr) {
7696   assert(LHSExpr->getType()->isAnyPointerType());
7697   assert(RHSExpr->getType()->isAnyPointerType());
7698   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7699     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
7700     << RHSExpr->getSourceRange();
7701 }
7702 
7703 QualType Sema::CheckAdditionOperands( // C99 6.5.6
7704     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7705     QualType* CompLHSTy) {
7706   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7707 
7708   if (LHS.get()->getType()->isVectorType() ||
7709       RHS.get()->getType()->isVectorType()) {
7710     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7711     if (CompLHSTy) *CompLHSTy = compType;
7712     return compType;
7713   }
7714 
7715   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7716   if (LHS.isInvalid() || RHS.isInvalid())
7717     return QualType();
7718 
7719   // Diagnose "string literal" '+' int and string '+' "char literal".
7720   if (Opc == BO_Add) {
7721     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
7722     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
7723   }
7724 
7725   // handle the common case first (both operands are arithmetic).
7726   if (!compType.isNull() && compType->isArithmeticType()) {
7727     if (CompLHSTy) *CompLHSTy = compType;
7728     return compType;
7729   }
7730 
7731   // Type-checking.  Ultimately the pointer's going to be in PExp;
7732   // note that we bias towards the LHS being the pointer.
7733   Expr *PExp = LHS.get(), *IExp = RHS.get();
7734 
7735   bool isObjCPointer;
7736   if (PExp->getType()->isPointerType()) {
7737     isObjCPointer = false;
7738   } else if (PExp->getType()->isObjCObjectPointerType()) {
7739     isObjCPointer = true;
7740   } else {
7741     std::swap(PExp, IExp);
7742     if (PExp->getType()->isPointerType()) {
7743       isObjCPointer = false;
7744     } else if (PExp->getType()->isObjCObjectPointerType()) {
7745       isObjCPointer = true;
7746     } else {
7747       return InvalidOperands(Loc, LHS, RHS);
7748     }
7749   }
7750   assert(PExp->getType()->isAnyPointerType());
7751 
7752   if (!IExp->getType()->isIntegerType())
7753     return InvalidOperands(Loc, LHS, RHS);
7754 
7755   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
7756     return QualType();
7757 
7758   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
7759     return QualType();
7760 
7761   // Check array bounds for pointer arithemtic
7762   CheckArrayAccess(PExp, IExp);
7763 
7764   if (CompLHSTy) {
7765     QualType LHSTy = Context.isPromotableBitField(LHS.get());
7766     if (LHSTy.isNull()) {
7767       LHSTy = LHS.get()->getType();
7768       if (LHSTy->isPromotableIntegerType())
7769         LHSTy = Context.getPromotedIntegerType(LHSTy);
7770     }
7771     *CompLHSTy = LHSTy;
7772   }
7773 
7774   return PExp->getType();
7775 }
7776 
7777 // C99 6.5.6
7778 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
7779                                         SourceLocation Loc,
7780                                         QualType* CompLHSTy) {
7781   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7782 
7783   if (LHS.get()->getType()->isVectorType() ||
7784       RHS.get()->getType()->isVectorType()) {
7785     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7786     if (CompLHSTy) *CompLHSTy = compType;
7787     return compType;
7788   }
7789 
7790   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7791   if (LHS.isInvalid() || RHS.isInvalid())
7792     return QualType();
7793 
7794   // Enforce type constraints: C99 6.5.6p3.
7795 
7796   // Handle the common case first (both operands are arithmetic).
7797   if (!compType.isNull() && compType->isArithmeticType()) {
7798     if (CompLHSTy) *CompLHSTy = compType;
7799     return compType;
7800   }
7801 
7802   // Either ptr - int   or   ptr - ptr.
7803   if (LHS.get()->getType()->isAnyPointerType()) {
7804     QualType lpointee = LHS.get()->getType()->getPointeeType();
7805 
7806     // Diagnose bad cases where we step over interface counts.
7807     if (LHS.get()->getType()->isObjCObjectPointerType() &&
7808         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
7809       return QualType();
7810 
7811     // The result type of a pointer-int computation is the pointer type.
7812     if (RHS.get()->getType()->isIntegerType()) {
7813       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
7814         return QualType();
7815 
7816       // Check array bounds for pointer arithemtic
7817       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
7818                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
7819 
7820       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7821       return LHS.get()->getType();
7822     }
7823 
7824     // Handle pointer-pointer subtractions.
7825     if (const PointerType *RHSPTy
7826           = RHS.get()->getType()->getAs<PointerType>()) {
7827       QualType rpointee = RHSPTy->getPointeeType();
7828 
7829       if (getLangOpts().CPlusPlus) {
7830         // Pointee types must be the same: C++ [expr.add]
7831         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7832           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7833         }
7834       } else {
7835         // Pointee types must be compatible C99 6.5.6p3
7836         if (!Context.typesAreCompatible(
7837                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7838                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7839           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7840           return QualType();
7841         }
7842       }
7843 
7844       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
7845                                                LHS.get(), RHS.get()))
7846         return QualType();
7847 
7848       // The pointee type may have zero size.  As an extension, a structure or
7849       // union may have zero size or an array may have zero length.  In this
7850       // case subtraction does not make sense.
7851       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
7852         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
7853         if (ElementSize.isZero()) {
7854           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
7855             << rpointee.getUnqualifiedType()
7856             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7857         }
7858       }
7859 
7860       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7861       return Context.getPointerDiffType();
7862     }
7863   }
7864 
7865   return InvalidOperands(Loc, LHS, RHS);
7866 }
7867 
7868 static bool isScopedEnumerationType(QualType T) {
7869   if (const EnumType *ET = T->getAs<EnumType>())
7870     return ET->getDecl()->isScoped();
7871   return false;
7872 }
7873 
7874 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
7875                                    SourceLocation Loc, unsigned Opc,
7876                                    QualType LHSType) {
7877   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
7878   // so skip remaining warnings as we don't want to modify values within Sema.
7879   if (S.getLangOpts().OpenCL)
7880     return;
7881 
7882   llvm::APSInt Right;
7883   // Check right/shifter operand
7884   if (RHS.get()->isValueDependent() ||
7885       !RHS.get()->EvaluateAsInt(Right, S.Context))
7886     return;
7887 
7888   if (Right.isNegative()) {
7889     S.DiagRuntimeBehavior(Loc, RHS.get(),
7890                           S.PDiag(diag::warn_shift_negative)
7891                             << RHS.get()->getSourceRange());
7892     return;
7893   }
7894   llvm::APInt LeftBits(Right.getBitWidth(),
7895                        S.Context.getTypeSize(LHS.get()->getType()));
7896   if (Right.uge(LeftBits)) {
7897     S.DiagRuntimeBehavior(Loc, RHS.get(),
7898                           S.PDiag(diag::warn_shift_gt_typewidth)
7899                             << RHS.get()->getSourceRange());
7900     return;
7901   }
7902   if (Opc != BO_Shl)
7903     return;
7904 
7905   // When left shifting an ICE which is signed, we can check for overflow which
7906   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7907   // integers have defined behavior modulo one more than the maximum value
7908   // representable in the result type, so never warn for those.
7909   llvm::APSInt Left;
7910   if (LHS.get()->isValueDependent() ||
7911       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
7912       LHSType->hasUnsignedIntegerRepresentation())
7913     return;
7914   llvm::APInt ResultBits =
7915       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7916   if (LeftBits.uge(ResultBits))
7917     return;
7918   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7919   Result = Result.shl(Right);
7920 
7921   // Print the bit representation of the signed integer as an unsigned
7922   // hexadecimal number.
7923   SmallString<40> HexResult;
7924   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7925 
7926   // If we are only missing a sign bit, this is less likely to result in actual
7927   // bugs -- if the result is cast back to an unsigned type, it will have the
7928   // expected value. Thus we place this behind a different warning that can be
7929   // turned off separately if needed.
7930   if (LeftBits == ResultBits - 1) {
7931     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7932         << HexResult << LHSType
7933         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7934     return;
7935   }
7936 
7937   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7938     << HexResult.str() << Result.getMinSignedBits() << LHSType
7939     << Left.getBitWidth() << LHS.get()->getSourceRange()
7940     << RHS.get()->getSourceRange();
7941 }
7942 
7943 /// \brief Return the resulting type when an OpenCL vector is shifted
7944 ///        by a scalar or vector shift amount.
7945 static QualType checkOpenCLVectorShift(Sema &S,
7946                                        ExprResult &LHS, ExprResult &RHS,
7947                                        SourceLocation Loc, bool IsCompAssign) {
7948   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
7949   if (!LHS.get()->getType()->isVectorType()) {
7950     S.Diag(Loc, diag::err_shift_rhs_only_vector)
7951       << RHS.get()->getType() << LHS.get()->getType()
7952       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7953     return QualType();
7954   }
7955 
7956   if (!IsCompAssign) {
7957     LHS = S.UsualUnaryConversions(LHS.get());
7958     if (LHS.isInvalid()) return QualType();
7959   }
7960 
7961   RHS = S.UsualUnaryConversions(RHS.get());
7962   if (RHS.isInvalid()) return QualType();
7963 
7964   QualType LHSType = LHS.get()->getType();
7965   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
7966   QualType LHSEleType = LHSVecTy->getElementType();
7967 
7968   // Note that RHS might not be a vector.
7969   QualType RHSType = RHS.get()->getType();
7970   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
7971   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
7972 
7973   // OpenCL v1.1 s6.3.j says that the operands need to be integers.
7974   if (!LHSEleType->isIntegerType()) {
7975     S.Diag(Loc, diag::err_typecheck_expect_int)
7976       << LHS.get()->getType() << LHS.get()->getSourceRange();
7977     return QualType();
7978   }
7979 
7980   if (!RHSEleType->isIntegerType()) {
7981     S.Diag(Loc, diag::err_typecheck_expect_int)
7982       << RHS.get()->getType() << RHS.get()->getSourceRange();
7983     return QualType();
7984   }
7985 
7986   if (RHSVecTy) {
7987     // OpenCL v1.1 s6.3.j says that for vector types, the operators
7988     // are applied component-wise. So if RHS is a vector, then ensure
7989     // that the number of elements is the same as LHS...
7990     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
7991       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
7992         << LHS.get()->getType() << RHS.get()->getType()
7993         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7994       return QualType();
7995     }
7996   } else {
7997     // ...else expand RHS to match the number of elements in LHS.
7998     QualType VecTy =
7999       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8000     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8001   }
8002 
8003   return LHSType;
8004 }
8005 
8006 // C99 6.5.7
8007 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8008                                   SourceLocation Loc, unsigned Opc,
8009                                   bool IsCompAssign) {
8010   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8011 
8012   // Vector shifts promote their scalar inputs to vector type.
8013   if (LHS.get()->getType()->isVectorType() ||
8014       RHS.get()->getType()->isVectorType()) {
8015     if (LangOpts.OpenCL)
8016       return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8017     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
8018   }
8019 
8020   // Shifts don't perform usual arithmetic conversions, they just do integer
8021   // promotions on each operand. C99 6.5.7p3
8022 
8023   // For the LHS, do usual unary conversions, but then reset them away
8024   // if this is a compound assignment.
8025   ExprResult OldLHS = LHS;
8026   LHS = UsualUnaryConversions(LHS.get());
8027   if (LHS.isInvalid())
8028     return QualType();
8029   QualType LHSType = LHS.get()->getType();
8030   if (IsCompAssign) LHS = OldLHS;
8031 
8032   // The RHS is simpler.
8033   RHS = UsualUnaryConversions(RHS.get());
8034   if (RHS.isInvalid())
8035     return QualType();
8036   QualType RHSType = RHS.get()->getType();
8037 
8038   // C99 6.5.7p2: Each of the operands shall have integer type.
8039   if (!LHSType->hasIntegerRepresentation() ||
8040       !RHSType->hasIntegerRepresentation())
8041     return InvalidOperands(Loc, LHS, RHS);
8042 
8043   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8044   // hasIntegerRepresentation() above instead of this.
8045   if (isScopedEnumerationType(LHSType) ||
8046       isScopedEnumerationType(RHSType)) {
8047     return InvalidOperands(Loc, LHS, RHS);
8048   }
8049   // Sanity-check shift operands
8050   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8051 
8052   // "The type of the result is that of the promoted left operand."
8053   return LHSType;
8054 }
8055 
8056 static bool IsWithinTemplateSpecialization(Decl *D) {
8057   if (DeclContext *DC = D->getDeclContext()) {
8058     if (isa<ClassTemplateSpecializationDecl>(DC))
8059       return true;
8060     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8061       return FD->isFunctionTemplateSpecialization();
8062   }
8063   return false;
8064 }
8065 
8066 /// If two different enums are compared, raise a warning.
8067 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8068                                 Expr *RHS) {
8069   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8070   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8071 
8072   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8073   if (!LHSEnumType)
8074     return;
8075   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8076   if (!RHSEnumType)
8077     return;
8078 
8079   // Ignore anonymous enums.
8080   if (!LHSEnumType->getDecl()->getIdentifier())
8081     return;
8082   if (!RHSEnumType->getDecl()->getIdentifier())
8083     return;
8084 
8085   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8086     return;
8087 
8088   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8089       << LHSStrippedType << RHSStrippedType
8090       << LHS->getSourceRange() << RHS->getSourceRange();
8091 }
8092 
8093 /// \brief Diagnose bad pointer comparisons.
8094 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8095                                               ExprResult &LHS, ExprResult &RHS,
8096                                               bool IsError) {
8097   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8098                       : diag::ext_typecheck_comparison_of_distinct_pointers)
8099     << LHS.get()->getType() << RHS.get()->getType()
8100     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8101 }
8102 
8103 /// \brief Returns false if the pointers are converted to a composite type,
8104 /// true otherwise.
8105 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8106                                            ExprResult &LHS, ExprResult &RHS) {
8107   // C++ [expr.rel]p2:
8108   //   [...] Pointer conversions (4.10) and qualification
8109   //   conversions (4.4) are performed on pointer operands (or on
8110   //   a pointer operand and a null pointer constant) to bring
8111   //   them to their composite pointer type. [...]
8112   //
8113   // C++ [expr.eq]p1 uses the same notion for (in)equality
8114   // comparisons of pointers.
8115 
8116   // C++ [expr.eq]p2:
8117   //   In addition, pointers to members can be compared, or a pointer to
8118   //   member and a null pointer constant. Pointer to member conversions
8119   //   (4.11) and qualification conversions (4.4) are performed to bring
8120   //   them to a common type. If one operand is a null pointer constant,
8121   //   the common type is the type of the other operand. Otherwise, the
8122   //   common type is a pointer to member type similar (4.4) to the type
8123   //   of one of the operands, with a cv-qualification signature (4.4)
8124   //   that is the union of the cv-qualification signatures of the operand
8125   //   types.
8126 
8127   QualType LHSType = LHS.get()->getType();
8128   QualType RHSType = RHS.get()->getType();
8129   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
8130          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
8131 
8132   bool NonStandardCompositeType = false;
8133   bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
8134   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
8135   if (T.isNull()) {
8136     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8137     return true;
8138   }
8139 
8140   if (NonStandardCompositeType)
8141     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
8142       << LHSType << RHSType << T << LHS.get()->getSourceRange()
8143       << RHS.get()->getSourceRange();
8144 
8145   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8146   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
8147   return false;
8148 }
8149 
8150 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
8151                                                     ExprResult &LHS,
8152                                                     ExprResult &RHS,
8153                                                     bool IsError) {
8154   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8155                       : diag::ext_typecheck_comparison_of_fptr_to_void)
8156     << LHS.get()->getType() << RHS.get()->getType()
8157     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8158 }
8159 
8160 static bool isObjCObjectLiteral(ExprResult &E) {
8161   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
8162   case Stmt::ObjCArrayLiteralClass:
8163   case Stmt::ObjCDictionaryLiteralClass:
8164   case Stmt::ObjCStringLiteralClass:
8165   case Stmt::ObjCBoxedExprClass:
8166     return true;
8167   default:
8168     // Note that ObjCBoolLiteral is NOT an object literal!
8169     return false;
8170   }
8171 }
8172 
8173 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
8174   const ObjCObjectPointerType *Type =
8175     LHS->getType()->getAs<ObjCObjectPointerType>();
8176 
8177   // If this is not actually an Objective-C object, bail out.
8178   if (!Type)
8179     return false;
8180 
8181   // Get the LHS object's interface type.
8182   QualType InterfaceType = Type->getPointeeType();
8183   if (const ObjCObjectType *iQFaceTy =
8184       InterfaceType->getAsObjCQualifiedInterfaceType())
8185     InterfaceType = iQFaceTy->getBaseType();
8186 
8187   // If the RHS isn't an Objective-C object, bail out.
8188   if (!RHS->getType()->isObjCObjectPointerType())
8189     return false;
8190 
8191   // Try to find the -isEqual: method.
8192   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
8193   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
8194                                                       InterfaceType,
8195                                                       /*instance=*/true);
8196   if (!Method) {
8197     if (Type->isObjCIdType()) {
8198       // For 'id', just check the global pool.
8199       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
8200                                                   /*receiverId=*/true);
8201     } else {
8202       // Check protocols.
8203       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
8204                                              /*instance=*/true);
8205     }
8206   }
8207 
8208   if (!Method)
8209     return false;
8210 
8211   QualType T = Method->parameters()[0]->getType();
8212   if (!T->isObjCObjectPointerType())
8213     return false;
8214 
8215   QualType R = Method->getReturnType();
8216   if (!R->isScalarType())
8217     return false;
8218 
8219   return true;
8220 }
8221 
8222 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
8223   FromE = FromE->IgnoreParenImpCasts();
8224   switch (FromE->getStmtClass()) {
8225     default:
8226       break;
8227     case Stmt::ObjCStringLiteralClass:
8228       // "string literal"
8229       return LK_String;
8230     case Stmt::ObjCArrayLiteralClass:
8231       // "array literal"
8232       return LK_Array;
8233     case Stmt::ObjCDictionaryLiteralClass:
8234       // "dictionary literal"
8235       return LK_Dictionary;
8236     case Stmt::BlockExprClass:
8237       return LK_Block;
8238     case Stmt::ObjCBoxedExprClass: {
8239       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
8240       switch (Inner->getStmtClass()) {
8241         case Stmt::IntegerLiteralClass:
8242         case Stmt::FloatingLiteralClass:
8243         case Stmt::CharacterLiteralClass:
8244         case Stmt::ObjCBoolLiteralExprClass:
8245         case Stmt::CXXBoolLiteralExprClass:
8246           // "numeric literal"
8247           return LK_Numeric;
8248         case Stmt::ImplicitCastExprClass: {
8249           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
8250           // Boolean literals can be represented by implicit casts.
8251           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
8252             return LK_Numeric;
8253           break;
8254         }
8255         default:
8256           break;
8257       }
8258       return LK_Boxed;
8259     }
8260   }
8261   return LK_None;
8262 }
8263 
8264 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
8265                                           ExprResult &LHS, ExprResult &RHS,
8266                                           BinaryOperator::Opcode Opc){
8267   Expr *Literal;
8268   Expr *Other;
8269   if (isObjCObjectLiteral(LHS)) {
8270     Literal = LHS.get();
8271     Other = RHS.get();
8272   } else {
8273     Literal = RHS.get();
8274     Other = LHS.get();
8275   }
8276 
8277   // Don't warn on comparisons against nil.
8278   Other = Other->IgnoreParenCasts();
8279   if (Other->isNullPointerConstant(S.getASTContext(),
8280                                    Expr::NPC_ValueDependentIsNotNull))
8281     return;
8282 
8283   // This should be kept in sync with warn_objc_literal_comparison.
8284   // LK_String should always be after the other literals, since it has its own
8285   // warning flag.
8286   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
8287   assert(LiteralKind != Sema::LK_Block);
8288   if (LiteralKind == Sema::LK_None) {
8289     llvm_unreachable("Unknown Objective-C object literal kind");
8290   }
8291 
8292   if (LiteralKind == Sema::LK_String)
8293     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
8294       << Literal->getSourceRange();
8295   else
8296     S.Diag(Loc, diag::warn_objc_literal_comparison)
8297       << LiteralKind << Literal->getSourceRange();
8298 
8299   if (BinaryOperator::isEqualityOp(Opc) &&
8300       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
8301     SourceLocation Start = LHS.get()->getLocStart();
8302     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
8303     CharSourceRange OpRange =
8304       CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
8305 
8306     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
8307       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
8308       << FixItHint::CreateReplacement(OpRange, " isEqual:")
8309       << FixItHint::CreateInsertion(End, "]");
8310   }
8311 }
8312 
8313 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
8314                                                 ExprResult &RHS,
8315                                                 SourceLocation Loc,
8316                                                 unsigned OpaqueOpc) {
8317   // This checking requires bools.
8318   if (!S.getLangOpts().Bool) return;
8319 
8320   // Check that left hand side is !something.
8321   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
8322   if (!UO || UO->getOpcode() != UO_LNot) return;
8323 
8324   // Only check if the right hand side is non-bool arithmetic type.
8325   if (RHS.get()->getType()->isBooleanType()) return;
8326 
8327   // Make sure that the something in !something is not bool.
8328   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
8329   if (SubExpr->getType()->isBooleanType()) return;
8330 
8331   // Emit warning.
8332   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
8333       << Loc;
8334 
8335   // First note suggest !(x < y)
8336   SourceLocation FirstOpen = SubExpr->getLocStart();
8337   SourceLocation FirstClose = RHS.get()->getLocEnd();
8338   FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
8339   if (FirstClose.isInvalid())
8340     FirstOpen = SourceLocation();
8341   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
8342       << FixItHint::CreateInsertion(FirstOpen, "(")
8343       << FixItHint::CreateInsertion(FirstClose, ")");
8344 
8345   // Second note suggests (!x) < y
8346   SourceLocation SecondOpen = LHS.get()->getLocStart();
8347   SourceLocation SecondClose = LHS.get()->getLocEnd();
8348   SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
8349   if (SecondClose.isInvalid())
8350     SecondOpen = SourceLocation();
8351   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
8352       << FixItHint::CreateInsertion(SecondOpen, "(")
8353       << FixItHint::CreateInsertion(SecondClose, ")");
8354 }
8355 
8356 // Get the decl for a simple expression: a reference to a variable,
8357 // an implicit C++ field reference, or an implicit ObjC ivar reference.
8358 static ValueDecl *getCompareDecl(Expr *E) {
8359   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
8360     return DR->getDecl();
8361   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
8362     if (Ivar->isFreeIvar())
8363       return Ivar->getDecl();
8364   }
8365   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
8366     if (Mem->isImplicitAccess())
8367       return Mem->getMemberDecl();
8368   }
8369   return nullptr;
8370 }
8371 
8372 // C99 6.5.8, C++ [expr.rel]
8373 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
8374                                     SourceLocation Loc, unsigned OpaqueOpc,
8375                                     bool IsRelational) {
8376   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
8377 
8378   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
8379 
8380   // Handle vector comparisons separately.
8381   if (LHS.get()->getType()->isVectorType() ||
8382       RHS.get()->getType()->isVectorType())
8383     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
8384 
8385   QualType LHSType = LHS.get()->getType();
8386   QualType RHSType = RHS.get()->getType();
8387 
8388   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
8389   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
8390 
8391   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
8392   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
8393 
8394   if (!LHSType->hasFloatingRepresentation() &&
8395       !(LHSType->isBlockPointerType() && IsRelational) &&
8396       !LHS.get()->getLocStart().isMacroID() &&
8397       !RHS.get()->getLocStart().isMacroID() &&
8398       ActiveTemplateInstantiations.empty()) {
8399     // For non-floating point types, check for self-comparisons of the form
8400     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
8401     // often indicate logic errors in the program.
8402     //
8403     // NOTE: Don't warn about comparison expressions resulting from macro
8404     // expansion. Also don't warn about comparisons which are only self
8405     // comparisons within a template specialization. The warnings should catch
8406     // obvious cases in the definition of the template anyways. The idea is to
8407     // warn when the typed comparison operator will always evaluate to the same
8408     // result.
8409     ValueDecl *DL = getCompareDecl(LHSStripped);
8410     ValueDecl *DR = getCompareDecl(RHSStripped);
8411     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
8412       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
8413                           << 0 // self-
8414                           << (Opc == BO_EQ
8415                               || Opc == BO_LE
8416                               || Opc == BO_GE));
8417     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
8418                !DL->getType()->isReferenceType() &&
8419                !DR->getType()->isReferenceType()) {
8420         // what is it always going to eval to?
8421         char always_evals_to;
8422         switch(Opc) {
8423         case BO_EQ: // e.g. array1 == array2
8424           always_evals_to = 0; // false
8425           break;
8426         case BO_NE: // e.g. array1 != array2
8427           always_evals_to = 1; // true
8428           break;
8429         default:
8430           // best we can say is 'a constant'
8431           always_evals_to = 2; // e.g. array1 <= array2
8432           break;
8433         }
8434         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
8435                             << 1 // array
8436                             << always_evals_to);
8437     }
8438 
8439     if (isa<CastExpr>(LHSStripped))
8440       LHSStripped = LHSStripped->IgnoreParenCasts();
8441     if (isa<CastExpr>(RHSStripped))
8442       RHSStripped = RHSStripped->IgnoreParenCasts();
8443 
8444     // Warn about comparisons against a string constant (unless the other
8445     // operand is null), the user probably wants strcmp.
8446     Expr *literalString = nullptr;
8447     Expr *literalStringStripped = nullptr;
8448     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
8449         !RHSStripped->isNullPointerConstant(Context,
8450                                             Expr::NPC_ValueDependentIsNull)) {
8451       literalString = LHS.get();
8452       literalStringStripped = LHSStripped;
8453     } else if ((isa<StringLiteral>(RHSStripped) ||
8454                 isa<ObjCEncodeExpr>(RHSStripped)) &&
8455                !LHSStripped->isNullPointerConstant(Context,
8456                                             Expr::NPC_ValueDependentIsNull)) {
8457       literalString = RHS.get();
8458       literalStringStripped = RHSStripped;
8459     }
8460 
8461     if (literalString) {
8462       DiagRuntimeBehavior(Loc, nullptr,
8463         PDiag(diag::warn_stringcompare)
8464           << isa<ObjCEncodeExpr>(literalStringStripped)
8465           << literalString->getSourceRange());
8466     }
8467   }
8468 
8469   // C99 6.5.8p3 / C99 6.5.9p4
8470   UsualArithmeticConversions(LHS, RHS);
8471   if (LHS.isInvalid() || RHS.isInvalid())
8472     return QualType();
8473 
8474   LHSType = LHS.get()->getType();
8475   RHSType = RHS.get()->getType();
8476 
8477   // The result of comparisons is 'bool' in C++, 'int' in C.
8478   QualType ResultTy = Context.getLogicalOperationType();
8479 
8480   if (IsRelational) {
8481     if (LHSType->isRealType() && RHSType->isRealType())
8482       return ResultTy;
8483   } else {
8484     // Check for comparisons of floating point operands using != and ==.
8485     if (LHSType->hasFloatingRepresentation())
8486       CheckFloatComparison(Loc, LHS.get(), RHS.get());
8487 
8488     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
8489       return ResultTy;
8490   }
8491 
8492   const Expr::NullPointerConstantKind LHSNullKind =
8493       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
8494   const Expr::NullPointerConstantKind RHSNullKind =
8495       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
8496   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
8497   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
8498 
8499   if (!IsRelational && LHSIsNull != RHSIsNull) {
8500     bool IsEquality = Opc == BO_EQ;
8501     if (RHSIsNull)
8502       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
8503                                    RHS.get()->getSourceRange());
8504     else
8505       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
8506                                    LHS.get()->getSourceRange());
8507   }
8508 
8509   // All of the following pointer-related warnings are GCC extensions, except
8510   // when handling null pointer constants.
8511   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
8512     QualType LCanPointeeTy =
8513       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
8514     QualType RCanPointeeTy =
8515       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
8516 
8517     if (getLangOpts().CPlusPlus) {
8518       if (LCanPointeeTy == RCanPointeeTy)
8519         return ResultTy;
8520       if (!IsRelational &&
8521           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8522         // Valid unless comparison between non-null pointer and function pointer
8523         // This is a gcc extension compatibility comparison.
8524         // In a SFINAE context, we treat this as a hard error to maintain
8525         // conformance with the C++ standard.
8526         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8527             && !LHSIsNull && !RHSIsNull) {
8528           diagnoseFunctionPointerToVoidComparison(
8529               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
8530 
8531           if (isSFINAEContext())
8532             return QualType();
8533 
8534           RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8535           return ResultTy;
8536         }
8537       }
8538 
8539       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8540         return QualType();
8541       else
8542         return ResultTy;
8543     }
8544     // C99 6.5.9p2 and C99 6.5.8p2
8545     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
8546                                    RCanPointeeTy.getUnqualifiedType())) {
8547       // Valid unless a relational comparison of function pointers
8548       if (IsRelational && LCanPointeeTy->isFunctionType()) {
8549         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
8550           << LHSType << RHSType << LHS.get()->getSourceRange()
8551           << RHS.get()->getSourceRange();
8552       }
8553     } else if (!IsRelational &&
8554                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8555       // Valid unless comparison between non-null pointer and function pointer
8556       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8557           && !LHSIsNull && !RHSIsNull)
8558         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
8559                                                 /*isError*/false);
8560     } else {
8561       // Invalid
8562       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
8563     }
8564     if (LCanPointeeTy != RCanPointeeTy) {
8565       const PointerType *lhsPtr = LHSType->getAs<PointerType>();
8566       if (!lhsPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
8567         Diag(Loc,
8568              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8569             << LHSType << RHSType << 0 /* comparison */
8570             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8571       }
8572       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
8573       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
8574       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
8575                                                : CK_BitCast;
8576       if (LHSIsNull && !RHSIsNull)
8577         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
8578       else
8579         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
8580     }
8581     return ResultTy;
8582   }
8583 
8584   if (getLangOpts().CPlusPlus) {
8585     // Comparison of nullptr_t with itself.
8586     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
8587       return ResultTy;
8588 
8589     // Comparison of pointers with null pointer constants and equality
8590     // comparisons of member pointers to null pointer constants.
8591     if (RHSIsNull &&
8592         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
8593          (!IsRelational &&
8594           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
8595       RHS = ImpCastExprToType(RHS.get(), LHSType,
8596                         LHSType->isMemberPointerType()
8597                           ? CK_NullToMemberPointer
8598                           : CK_NullToPointer);
8599       return ResultTy;
8600     }
8601     if (LHSIsNull &&
8602         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
8603          (!IsRelational &&
8604           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
8605       LHS = ImpCastExprToType(LHS.get(), RHSType,
8606                         RHSType->isMemberPointerType()
8607                           ? CK_NullToMemberPointer
8608                           : CK_NullToPointer);
8609       return ResultTy;
8610     }
8611 
8612     // Comparison of member pointers.
8613     if (!IsRelational &&
8614         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
8615       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8616         return QualType();
8617       else
8618         return ResultTy;
8619     }
8620 
8621     // Handle scoped enumeration types specifically, since they don't promote
8622     // to integers.
8623     if (LHS.get()->getType()->isEnumeralType() &&
8624         Context.hasSameUnqualifiedType(LHS.get()->getType(),
8625                                        RHS.get()->getType()))
8626       return ResultTy;
8627   }
8628 
8629   // Handle block pointer types.
8630   if (!IsRelational && LHSType->isBlockPointerType() &&
8631       RHSType->isBlockPointerType()) {
8632     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
8633     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
8634 
8635     if (!LHSIsNull && !RHSIsNull &&
8636         !Context.typesAreCompatible(lpointee, rpointee)) {
8637       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8638         << LHSType << RHSType << LHS.get()->getSourceRange()
8639         << RHS.get()->getSourceRange();
8640     }
8641     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8642     return ResultTy;
8643   }
8644 
8645   // Allow block pointers to be compared with null pointer constants.
8646   if (!IsRelational
8647       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
8648           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
8649     if (!LHSIsNull && !RHSIsNull) {
8650       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
8651              ->getPointeeType()->isVoidType())
8652             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
8653                 ->getPointeeType()->isVoidType())))
8654         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8655           << LHSType << RHSType << LHS.get()->getSourceRange()
8656           << RHS.get()->getSourceRange();
8657     }
8658     if (LHSIsNull && !RHSIsNull)
8659       LHS = ImpCastExprToType(LHS.get(), RHSType,
8660                               RHSType->isPointerType() ? CK_BitCast
8661                                 : CK_AnyPointerToBlockPointerCast);
8662     else
8663       RHS = ImpCastExprToType(RHS.get(), LHSType,
8664                               LHSType->isPointerType() ? CK_BitCast
8665                                 : CK_AnyPointerToBlockPointerCast);
8666     return ResultTy;
8667   }
8668 
8669   if (LHSType->isObjCObjectPointerType() ||
8670       RHSType->isObjCObjectPointerType()) {
8671     const PointerType *LPT = LHSType->getAs<PointerType>();
8672     const PointerType *RPT = RHSType->getAs<PointerType>();
8673     if (LPT || RPT) {
8674       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
8675       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
8676 
8677       if (!LPtrToVoid && !RPtrToVoid &&
8678           !Context.typesAreCompatible(LHSType, RHSType)) {
8679         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8680                                           /*isError*/false);
8681       }
8682       if (LHSIsNull && !RHSIsNull) {
8683         Expr *E = LHS.get();
8684         if (getLangOpts().ObjCAutoRefCount)
8685           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
8686         LHS = ImpCastExprToType(E, RHSType,
8687                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8688       }
8689       else {
8690         Expr *E = RHS.get();
8691         if (getLangOpts().ObjCAutoRefCount)
8692           CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
8693                                  Opc);
8694         RHS = ImpCastExprToType(E, LHSType,
8695                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8696       }
8697       return ResultTy;
8698     }
8699     if (LHSType->isObjCObjectPointerType() &&
8700         RHSType->isObjCObjectPointerType()) {
8701       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
8702         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8703                                           /*isError*/false);
8704       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
8705         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
8706 
8707       if (LHSIsNull && !RHSIsNull)
8708         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8709       else
8710         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8711       return ResultTy;
8712     }
8713   }
8714   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
8715       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
8716     unsigned DiagID = 0;
8717     bool isError = false;
8718     if (LangOpts.DebuggerSupport) {
8719       // Under a debugger, allow the comparison of pointers to integers,
8720       // since users tend to want to compare addresses.
8721     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
8722         (RHSIsNull && RHSType->isIntegerType())) {
8723       if (IsRelational && !getLangOpts().CPlusPlus)
8724         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
8725     } else if (IsRelational && !getLangOpts().CPlusPlus)
8726       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
8727     else if (getLangOpts().CPlusPlus) {
8728       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
8729       isError = true;
8730     } else
8731       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
8732 
8733     if (DiagID) {
8734       Diag(Loc, DiagID)
8735         << LHSType << RHSType << LHS.get()->getSourceRange()
8736         << RHS.get()->getSourceRange();
8737       if (isError)
8738         return QualType();
8739     }
8740 
8741     if (LHSType->isIntegerType())
8742       LHS = ImpCastExprToType(LHS.get(), RHSType,
8743                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8744     else
8745       RHS = ImpCastExprToType(RHS.get(), LHSType,
8746                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8747     return ResultTy;
8748   }
8749 
8750   // Handle block pointers.
8751   if (!IsRelational && RHSIsNull
8752       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
8753     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8754     return ResultTy;
8755   }
8756   if (!IsRelational && LHSIsNull
8757       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
8758     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
8759     return ResultTy;
8760   }
8761 
8762   return InvalidOperands(Loc, LHS, RHS);
8763 }
8764 
8765 
8766 // Return a signed type that is of identical size and number of elements.
8767 // For floating point vectors, return an integer type of identical size
8768 // and number of elements.
8769 QualType Sema::GetSignedVectorType(QualType V) {
8770   const VectorType *VTy = V->getAs<VectorType>();
8771   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
8772   if (TypeSize == Context.getTypeSize(Context.CharTy))
8773     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
8774   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
8775     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
8776   else if (TypeSize == Context.getTypeSize(Context.IntTy))
8777     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
8778   else if (TypeSize == Context.getTypeSize(Context.LongTy))
8779     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
8780   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
8781          "Unhandled vector element size in vector compare");
8782   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8783 }
8784 
8785 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
8786 /// operates on extended vector types.  Instead of producing an IntTy result,
8787 /// like a scalar comparison, a vector comparison produces a vector of integer
8788 /// types.
8789 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8790                                           SourceLocation Loc,
8791                                           bool IsRelational) {
8792   // Check to make sure we're operating on vectors of the same type and width,
8793   // Allowing one side to be a scalar of element type.
8794   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
8795   if (vType.isNull())
8796     return vType;
8797 
8798   QualType LHSType = LHS.get()->getType();
8799 
8800   // If AltiVec, the comparison results in a numeric type, i.e.
8801   // bool for C++, int for C
8802   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
8803     return Context.getLogicalOperationType();
8804 
8805   // For non-floating point types, check for self-comparisons of the form
8806   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
8807   // often indicate logic errors in the program.
8808   if (!LHSType->hasFloatingRepresentation() &&
8809       ActiveTemplateInstantiations.empty()) {
8810     if (DeclRefExpr* DRL
8811           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
8812       if (DeclRefExpr* DRR
8813             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
8814         if (DRL->getDecl() == DRR->getDecl())
8815           DiagRuntimeBehavior(Loc, nullptr,
8816                               PDiag(diag::warn_comparison_always)
8817                                 << 0 // self-
8818                                 << 2 // "a constant"
8819                               );
8820   }
8821 
8822   // Check for comparisons of floating point operands using != and ==.
8823   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
8824     assert (RHS.get()->getType()->hasFloatingRepresentation());
8825     CheckFloatComparison(Loc, LHS.get(), RHS.get());
8826   }
8827 
8828   // Return a signed type for the vector.
8829   return GetSignedVectorType(LHSType);
8830 }
8831 
8832 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8833                                           SourceLocation Loc) {
8834   // Ensure that either both operands are of the same vector type, or
8835   // one operand is of a vector type and the other is of its element type.
8836   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
8837   if (vType.isNull())
8838     return InvalidOperands(Loc, LHS, RHS);
8839   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
8840       vType->hasFloatingRepresentation())
8841     return InvalidOperands(Loc, LHS, RHS);
8842 
8843   return GetSignedVectorType(LHS.get()->getType());
8844 }
8845 
8846 inline QualType Sema::CheckBitwiseOperands(
8847   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8848   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8849 
8850   if (LHS.get()->getType()->isVectorType() ||
8851       RHS.get()->getType()->isVectorType()) {
8852     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8853         RHS.get()->getType()->hasIntegerRepresentation())
8854       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
8855 
8856     return InvalidOperands(Loc, LHS, RHS);
8857   }
8858 
8859   ExprResult LHSResult = LHS, RHSResult = RHS;
8860   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
8861                                                  IsCompAssign);
8862   if (LHSResult.isInvalid() || RHSResult.isInvalid())
8863     return QualType();
8864   LHS = LHSResult.get();
8865   RHS = RHSResult.get();
8866 
8867   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
8868     return compType;
8869   return InvalidOperands(Loc, LHS, RHS);
8870 }
8871 
8872 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
8873   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
8874 
8875   // Check vector operands differently.
8876   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
8877     return CheckVectorLogicalOperands(LHS, RHS, Loc);
8878 
8879   // Diagnose cases where the user write a logical and/or but probably meant a
8880   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
8881   // is a constant.
8882   if (LHS.get()->getType()->isIntegerType() &&
8883       !LHS.get()->getType()->isBooleanType() &&
8884       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
8885       // Don't warn in macros or template instantiations.
8886       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
8887     // If the RHS can be constant folded, and if it constant folds to something
8888     // that isn't 0 or 1 (which indicate a potential logical operation that
8889     // happened to fold to true/false) then warn.
8890     // Parens on the RHS are ignored.
8891     llvm::APSInt Result;
8892     if (RHS.get()->EvaluateAsInt(Result, Context))
8893       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
8894            !RHS.get()->getExprLoc().isMacroID()) ||
8895           (Result != 0 && Result != 1)) {
8896         Diag(Loc, diag::warn_logical_instead_of_bitwise)
8897           << RHS.get()->getSourceRange()
8898           << (Opc == BO_LAnd ? "&&" : "||");
8899         // Suggest replacing the logical operator with the bitwise version
8900         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
8901             << (Opc == BO_LAnd ? "&" : "|")
8902             << FixItHint::CreateReplacement(SourceRange(
8903                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
8904                                                 getLangOpts())),
8905                                             Opc == BO_LAnd ? "&" : "|");
8906         if (Opc == BO_LAnd)
8907           // Suggest replacing "Foo() && kNonZero" with "Foo()"
8908           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
8909               << FixItHint::CreateRemoval(
8910                   SourceRange(
8911                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
8912                                                  0, getSourceManager(),
8913                                                  getLangOpts()),
8914                       RHS.get()->getLocEnd()));
8915       }
8916   }
8917 
8918   if (!Context.getLangOpts().CPlusPlus) {
8919     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
8920     // not operate on the built-in scalar and vector float types.
8921     if (Context.getLangOpts().OpenCL &&
8922         Context.getLangOpts().OpenCLVersion < 120) {
8923       if (LHS.get()->getType()->isFloatingType() ||
8924           RHS.get()->getType()->isFloatingType())
8925         return InvalidOperands(Loc, LHS, RHS);
8926     }
8927 
8928     LHS = UsualUnaryConversions(LHS.get());
8929     if (LHS.isInvalid())
8930       return QualType();
8931 
8932     RHS = UsualUnaryConversions(RHS.get());
8933     if (RHS.isInvalid())
8934       return QualType();
8935 
8936     if (!LHS.get()->getType()->isScalarType() ||
8937         !RHS.get()->getType()->isScalarType())
8938       return InvalidOperands(Loc, LHS, RHS);
8939 
8940     return Context.IntTy;
8941   }
8942 
8943   // The following is safe because we only use this method for
8944   // non-overloadable operands.
8945 
8946   // C++ [expr.log.and]p1
8947   // C++ [expr.log.or]p1
8948   // The operands are both contextually converted to type bool.
8949   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
8950   if (LHSRes.isInvalid())
8951     return InvalidOperands(Loc, LHS, RHS);
8952   LHS = LHSRes;
8953 
8954   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
8955   if (RHSRes.isInvalid())
8956     return InvalidOperands(Loc, LHS, RHS);
8957   RHS = RHSRes;
8958 
8959   // C++ [expr.log.and]p2
8960   // C++ [expr.log.or]p2
8961   // The result is a bool.
8962   return Context.BoolTy;
8963 }
8964 
8965 static bool IsReadonlyMessage(Expr *E, Sema &S) {
8966   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
8967   if (!ME) return false;
8968   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
8969   ObjCMessageExpr *Base =
8970     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
8971   if (!Base) return false;
8972   return Base->getMethodDecl() != nullptr;
8973 }
8974 
8975 /// Is the given expression (which must be 'const') a reference to a
8976 /// variable which was originally non-const, but which has become
8977 /// 'const' due to being captured within a block?
8978 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
8979 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
8980   assert(E->isLValue() && E->getType().isConstQualified());
8981   E = E->IgnoreParens();
8982 
8983   // Must be a reference to a declaration from an enclosing scope.
8984   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
8985   if (!DRE) return NCCK_None;
8986   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
8987 
8988   // The declaration must be a variable which is not declared 'const'.
8989   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8990   if (!var) return NCCK_None;
8991   if (var->getType().isConstQualified()) return NCCK_None;
8992   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
8993 
8994   // Decide whether the first capture was for a block or a lambda.
8995   DeclContext *DC = S.CurContext, *Prev = nullptr;
8996   while (DC != var->getDeclContext()) {
8997     Prev = DC;
8998     DC = DC->getParent();
8999   }
9000   // Unless we have an init-capture, we've gone one step too far.
9001   if (!var->isInitCapture())
9002     DC = Prev;
9003   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9004 }
9005 
9006 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9007   Ty = Ty.getNonReferenceType();
9008   if (IsDereference && Ty->isPointerType())
9009     Ty = Ty->getPointeeType();
9010   return !Ty.isConstQualified();
9011 }
9012 
9013 /// Emit the "read-only variable not assignable" error and print notes to give
9014 /// more information about why the variable is not assignable, such as pointing
9015 /// to the declaration of a const variable, showing that a method is const, or
9016 /// that the function is returning a const reference.
9017 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9018                                     SourceLocation Loc) {
9019   // Update err_typecheck_assign_const and note_typecheck_assign_const
9020   // when this enum is changed.
9021   enum {
9022     ConstFunction,
9023     ConstVariable,
9024     ConstMember,
9025     ConstMethod,
9026     ConstUnknown,  // Keep as last element
9027   };
9028 
9029   SourceRange ExprRange = E->getSourceRange();
9030 
9031   // Only emit one error on the first const found.  All other consts will emit
9032   // a note to the error.
9033   bool DiagnosticEmitted = false;
9034 
9035   // Track if the current expression is the result of a derefence, and if the
9036   // next checked expression is the result of a derefence.
9037   bool IsDereference = false;
9038   bool NextIsDereference = false;
9039 
9040   // Loop to process MemberExpr chains.
9041   while (true) {
9042     IsDereference = NextIsDereference;
9043     NextIsDereference = false;
9044 
9045     E = E->IgnoreParenImpCasts();
9046     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9047       NextIsDereference = ME->isArrow();
9048       const ValueDecl *VD = ME->getMemberDecl();
9049       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9050         // Mutable fields can be modified even if the class is const.
9051         if (Field->isMutable()) {
9052           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9053           break;
9054         }
9055 
9056         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9057           if (!DiagnosticEmitted) {
9058             S.Diag(Loc, diag::err_typecheck_assign_const)
9059                 << ExprRange << ConstMember << false /*static*/ << Field
9060                 << Field->getType();
9061             DiagnosticEmitted = true;
9062           }
9063           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9064               << ConstMember << false /*static*/ << Field << Field->getType()
9065               << Field->getSourceRange();
9066         }
9067         E = ME->getBase();
9068         continue;
9069       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9070         if (VDecl->getType().isConstQualified()) {
9071           if (!DiagnosticEmitted) {
9072             S.Diag(Loc, diag::err_typecheck_assign_const)
9073                 << ExprRange << ConstMember << true /*static*/ << VDecl
9074                 << VDecl->getType();
9075             DiagnosticEmitted = true;
9076           }
9077           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9078               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9079               << VDecl->getSourceRange();
9080         }
9081         // Static fields do not inherit constness from parents.
9082         break;
9083       }
9084       break;
9085     } // End MemberExpr
9086     break;
9087   }
9088 
9089   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9090     // Function calls
9091     const FunctionDecl *FD = CE->getDirectCallee();
9092     if (!IsTypeModifiable(FD->getReturnType(), IsDereference)) {
9093       if (!DiagnosticEmitted) {
9094         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9095                                                       << ConstFunction << FD;
9096         DiagnosticEmitted = true;
9097       }
9098       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
9099              diag::note_typecheck_assign_const)
9100           << ConstFunction << FD << FD->getReturnType()
9101           << FD->getReturnTypeSourceRange();
9102     }
9103   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9104     // Point to variable declaration.
9105     if (const ValueDecl *VD = DRE->getDecl()) {
9106       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
9107         if (!DiagnosticEmitted) {
9108           S.Diag(Loc, diag::err_typecheck_assign_const)
9109               << ExprRange << ConstVariable << VD << VD->getType();
9110           DiagnosticEmitted = true;
9111         }
9112         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9113             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
9114       }
9115     }
9116   } else if (isa<CXXThisExpr>(E)) {
9117     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
9118       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
9119         if (MD->isConst()) {
9120           if (!DiagnosticEmitted) {
9121             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9122                                                           << ConstMethod << MD;
9123             DiagnosticEmitted = true;
9124           }
9125           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
9126               << ConstMethod << MD << MD->getSourceRange();
9127         }
9128       }
9129     }
9130   }
9131 
9132   if (DiagnosticEmitted)
9133     return;
9134 
9135   // Can't determine a more specific message, so display the generic error.
9136   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
9137 }
9138 
9139 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
9140 /// emit an error and return true.  If so, return false.
9141 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
9142   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
9143   SourceLocation OrigLoc = Loc;
9144   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
9145                                                               &Loc);
9146   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
9147     IsLV = Expr::MLV_InvalidMessageExpression;
9148   if (IsLV == Expr::MLV_Valid)
9149     return false;
9150 
9151   unsigned DiagID = 0;
9152   bool NeedType = false;
9153   switch (IsLV) { // C99 6.5.16p2
9154   case Expr::MLV_ConstQualified:
9155     // Use a specialized diagnostic when we're assigning to an object
9156     // from an enclosing function or block.
9157     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
9158       if (NCCK == NCCK_Block)
9159         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
9160       else
9161         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
9162       break;
9163     }
9164 
9165     // In ARC, use some specialized diagnostics for occasions where we
9166     // infer 'const'.  These are always pseudo-strong variables.
9167     if (S.getLangOpts().ObjCAutoRefCount) {
9168       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
9169       if (declRef && isa<VarDecl>(declRef->getDecl())) {
9170         VarDecl *var = cast<VarDecl>(declRef->getDecl());
9171 
9172         // Use the normal diagnostic if it's pseudo-__strong but the
9173         // user actually wrote 'const'.
9174         if (var->isARCPseudoStrong() &&
9175             (!var->getTypeSourceInfo() ||
9176              !var->getTypeSourceInfo()->getType().isConstQualified())) {
9177           // There are two pseudo-strong cases:
9178           //  - self
9179           ObjCMethodDecl *method = S.getCurMethodDecl();
9180           if (method && var == method->getSelfDecl())
9181             DiagID = method->isClassMethod()
9182               ? diag::err_typecheck_arc_assign_self_class_method
9183               : diag::err_typecheck_arc_assign_self;
9184 
9185           //  - fast enumeration variables
9186           else
9187             DiagID = diag::err_typecheck_arr_assign_enumeration;
9188 
9189           SourceRange Assign;
9190           if (Loc != OrigLoc)
9191             Assign = SourceRange(OrigLoc, OrigLoc);
9192           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9193           // We need to preserve the AST regardless, so migration tool
9194           // can do its job.
9195           return false;
9196         }
9197       }
9198     }
9199 
9200     // If none of the special cases above are triggered, then this is a
9201     // simple const assignment.
9202     if (DiagID == 0) {
9203       DiagnoseConstAssignment(S, E, Loc);
9204       return true;
9205     }
9206 
9207     break;
9208   case Expr::MLV_ConstAddrSpace:
9209     DiagnoseConstAssignment(S, E, Loc);
9210     return true;
9211   case Expr::MLV_ArrayType:
9212   case Expr::MLV_ArrayTemporary:
9213     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
9214     NeedType = true;
9215     break;
9216   case Expr::MLV_NotObjectType:
9217     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
9218     NeedType = true;
9219     break;
9220   case Expr::MLV_LValueCast:
9221     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
9222     break;
9223   case Expr::MLV_Valid:
9224     llvm_unreachable("did not take early return for MLV_Valid");
9225   case Expr::MLV_InvalidExpression:
9226   case Expr::MLV_MemberFunction:
9227   case Expr::MLV_ClassTemporary:
9228     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
9229     break;
9230   case Expr::MLV_IncompleteType:
9231   case Expr::MLV_IncompleteVoidType:
9232     return S.RequireCompleteType(Loc, E->getType(),
9233              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
9234   case Expr::MLV_DuplicateVectorComponents:
9235     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
9236     break;
9237   case Expr::MLV_NoSetterProperty:
9238     llvm_unreachable("readonly properties should be processed differently");
9239   case Expr::MLV_InvalidMessageExpression:
9240     DiagID = diag::error_readonly_message_assignment;
9241     break;
9242   case Expr::MLV_SubObjCPropertySetting:
9243     DiagID = diag::error_no_subobject_property_setting;
9244     break;
9245   }
9246 
9247   SourceRange Assign;
9248   if (Loc != OrigLoc)
9249     Assign = SourceRange(OrigLoc, OrigLoc);
9250   if (NeedType)
9251     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
9252   else
9253     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9254   return true;
9255 }
9256 
9257 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
9258                                          SourceLocation Loc,
9259                                          Sema &Sema) {
9260   // C / C++ fields
9261   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
9262   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
9263   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
9264     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
9265       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
9266   }
9267 
9268   // Objective-C instance variables
9269   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
9270   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
9271   if (OL && OR && OL->getDecl() == OR->getDecl()) {
9272     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
9273     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
9274     if (RL && RR && RL->getDecl() == RR->getDecl())
9275       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
9276   }
9277 }
9278 
9279 // C99 6.5.16.1
9280 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
9281                                        SourceLocation Loc,
9282                                        QualType CompoundType) {
9283   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
9284 
9285   // Verify that LHS is a modifiable lvalue, and emit error if not.
9286   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
9287     return QualType();
9288 
9289   QualType LHSType = LHSExpr->getType();
9290   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
9291                                              CompoundType;
9292   AssignConvertType ConvTy;
9293   if (CompoundType.isNull()) {
9294     Expr *RHSCheck = RHS.get();
9295 
9296     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
9297 
9298     QualType LHSTy(LHSType);
9299     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
9300     if (RHS.isInvalid())
9301       return QualType();
9302     // Special case of NSObject attributes on c-style pointer types.
9303     if (ConvTy == IncompatiblePointer &&
9304         ((Context.isObjCNSObjectType(LHSType) &&
9305           RHSType->isObjCObjectPointerType()) ||
9306          (Context.isObjCNSObjectType(RHSType) &&
9307           LHSType->isObjCObjectPointerType())))
9308       ConvTy = Compatible;
9309 
9310     if (ConvTy == Compatible &&
9311         LHSType->isObjCObjectType())
9312         Diag(Loc, diag::err_objc_object_assignment)
9313           << LHSType;
9314 
9315     // If the RHS is a unary plus or minus, check to see if they = and + are
9316     // right next to each other.  If so, the user may have typo'd "x =+ 4"
9317     // instead of "x += 4".
9318     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
9319       RHSCheck = ICE->getSubExpr();
9320     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
9321       if ((UO->getOpcode() == UO_Plus ||
9322            UO->getOpcode() == UO_Minus) &&
9323           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
9324           // Only if the two operators are exactly adjacent.
9325           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
9326           // And there is a space or other character before the subexpr of the
9327           // unary +/-.  We don't want to warn on "x=-1".
9328           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
9329           UO->getSubExpr()->getLocStart().isFileID()) {
9330         Diag(Loc, diag::warn_not_compound_assign)
9331           << (UO->getOpcode() == UO_Plus ? "+" : "-")
9332           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
9333       }
9334     }
9335 
9336     if (ConvTy == Compatible) {
9337       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
9338         // Warn about retain cycles where a block captures the LHS, but
9339         // not if the LHS is a simple variable into which the block is
9340         // being stored...unless that variable can be captured by reference!
9341         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
9342         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
9343         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
9344           checkRetainCycles(LHSExpr, RHS.get());
9345 
9346         // It is safe to assign a weak reference into a strong variable.
9347         // Although this code can still have problems:
9348         //   id x = self.weakProp;
9349         //   id y = self.weakProp;
9350         // we do not warn to warn spuriously when 'x' and 'y' are on separate
9351         // paths through the function. This should be revisited if
9352         // -Wrepeated-use-of-weak is made flow-sensitive.
9353         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9354                              RHS.get()->getLocStart()))
9355           getCurFunction()->markSafeWeakUse(RHS.get());
9356 
9357       } else if (getLangOpts().ObjCAutoRefCount) {
9358         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
9359       }
9360     }
9361   } else {
9362     // Compound assignment "x += y"
9363     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
9364   }
9365 
9366   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
9367                                RHS.get(), AA_Assigning))
9368     return QualType();
9369 
9370   CheckForNullPointerDereference(*this, LHSExpr);
9371 
9372   // C99 6.5.16p3: The type of an assignment expression is the type of the
9373   // left operand unless the left operand has qualified type, in which case
9374   // it is the unqualified version of the type of the left operand.
9375   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
9376   // is converted to the type of the assignment expression (above).
9377   // C++ 5.17p1: the type of the assignment expression is that of its left
9378   // operand.
9379   return (getLangOpts().CPlusPlus
9380           ? LHSType : LHSType.getUnqualifiedType());
9381 }
9382 
9383 // C99 6.5.17
9384 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
9385                                    SourceLocation Loc) {
9386   LHS = S.CheckPlaceholderExpr(LHS.get());
9387   RHS = S.CheckPlaceholderExpr(RHS.get());
9388   if (LHS.isInvalid() || RHS.isInvalid())
9389     return QualType();
9390 
9391   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
9392   // operands, but not unary promotions.
9393   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
9394 
9395   // So we treat the LHS as a ignored value, and in C++ we allow the
9396   // containing site to determine what should be done with the RHS.
9397   LHS = S.IgnoredValueConversions(LHS.get());
9398   if (LHS.isInvalid())
9399     return QualType();
9400 
9401   S.DiagnoseUnusedExprResult(LHS.get());
9402 
9403   if (!S.getLangOpts().CPlusPlus) {
9404     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
9405     if (RHS.isInvalid())
9406       return QualType();
9407     if (!RHS.get()->getType()->isVoidType())
9408       S.RequireCompleteType(Loc, RHS.get()->getType(),
9409                             diag::err_incomplete_type);
9410   }
9411 
9412   return RHS.get()->getType();
9413 }
9414 
9415 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
9416 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
9417 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
9418                                                ExprValueKind &VK,
9419                                                ExprObjectKind &OK,
9420                                                SourceLocation OpLoc,
9421                                                bool IsInc, bool IsPrefix) {
9422   if (Op->isTypeDependent())
9423     return S.Context.DependentTy;
9424 
9425   QualType ResType = Op->getType();
9426   // Atomic types can be used for increment / decrement where the non-atomic
9427   // versions can, so ignore the _Atomic() specifier for the purpose of
9428   // checking.
9429   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9430     ResType = ResAtomicType->getValueType();
9431 
9432   assert(!ResType.isNull() && "no type for increment/decrement expression");
9433 
9434   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
9435     // Decrement of bool is not allowed.
9436     if (!IsInc) {
9437       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
9438       return QualType();
9439     }
9440     // Increment of bool sets it to true, but is deprecated.
9441     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
9442   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
9443     // Error on enum increments and decrements in C++ mode
9444     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
9445     return QualType();
9446   } else if (ResType->isRealType()) {
9447     // OK!
9448   } else if (ResType->isPointerType()) {
9449     // C99 6.5.2.4p2, 6.5.6p2
9450     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
9451       return QualType();
9452   } else if (ResType->isObjCObjectPointerType()) {
9453     // On modern runtimes, ObjC pointer arithmetic is forbidden.
9454     // Otherwise, we just need a complete type.
9455     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
9456         checkArithmeticOnObjCPointer(S, OpLoc, Op))
9457       return QualType();
9458   } else if (ResType->isAnyComplexType()) {
9459     // C99 does not support ++/-- on complex types, we allow as an extension.
9460     S.Diag(OpLoc, diag::ext_integer_increment_complex)
9461       << ResType << Op->getSourceRange();
9462   } else if (ResType->isPlaceholderType()) {
9463     ExprResult PR = S.CheckPlaceholderExpr(Op);
9464     if (PR.isInvalid()) return QualType();
9465     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
9466                                           IsInc, IsPrefix);
9467   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
9468     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
9469   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
9470             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
9471     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
9472   } else {
9473     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
9474       << ResType << int(IsInc) << Op->getSourceRange();
9475     return QualType();
9476   }
9477   // At this point, we know we have a real, complex or pointer type.
9478   // Now make sure the operand is a modifiable lvalue.
9479   if (CheckForModifiableLvalue(Op, OpLoc, S))
9480     return QualType();
9481   // In C++, a prefix increment is the same type as the operand. Otherwise
9482   // (in C or with postfix), the increment is the unqualified type of the
9483   // operand.
9484   if (IsPrefix && S.getLangOpts().CPlusPlus) {
9485     VK = VK_LValue;
9486     OK = Op->getObjectKind();
9487     return ResType;
9488   } else {
9489     VK = VK_RValue;
9490     return ResType.getUnqualifiedType();
9491   }
9492 }
9493 
9494 
9495 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
9496 /// This routine allows us to typecheck complex/recursive expressions
9497 /// where the declaration is needed for type checking. We only need to
9498 /// handle cases when the expression references a function designator
9499 /// or is an lvalue. Here are some examples:
9500 ///  - &(x) => x
9501 ///  - &*****f => f for f a function designator.
9502 ///  - &s.xx => s
9503 ///  - &s.zz[1].yy -> s, if zz is an array
9504 ///  - *(x + 1) -> x, if x is an array
9505 ///  - &"123"[2] -> 0
9506 ///  - & __real__ x -> x
9507 static ValueDecl *getPrimaryDecl(Expr *E) {
9508   switch (E->getStmtClass()) {
9509   case Stmt::DeclRefExprClass:
9510     return cast<DeclRefExpr>(E)->getDecl();
9511   case Stmt::MemberExprClass:
9512     // If this is an arrow operator, the address is an offset from
9513     // the base's value, so the object the base refers to is
9514     // irrelevant.
9515     if (cast<MemberExpr>(E)->isArrow())
9516       return nullptr;
9517     // Otherwise, the expression refers to a part of the base
9518     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
9519   case Stmt::ArraySubscriptExprClass: {
9520     // FIXME: This code shouldn't be necessary!  We should catch the implicit
9521     // promotion of register arrays earlier.
9522     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
9523     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
9524       if (ICE->getSubExpr()->getType()->isArrayType())
9525         return getPrimaryDecl(ICE->getSubExpr());
9526     }
9527     return nullptr;
9528   }
9529   case Stmt::UnaryOperatorClass: {
9530     UnaryOperator *UO = cast<UnaryOperator>(E);
9531 
9532     switch(UO->getOpcode()) {
9533     case UO_Real:
9534     case UO_Imag:
9535     case UO_Extension:
9536       return getPrimaryDecl(UO->getSubExpr());
9537     default:
9538       return nullptr;
9539     }
9540   }
9541   case Stmt::ParenExprClass:
9542     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
9543   case Stmt::ImplicitCastExprClass:
9544     // If the result of an implicit cast is an l-value, we care about
9545     // the sub-expression; otherwise, the result here doesn't matter.
9546     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
9547   default:
9548     return nullptr;
9549   }
9550 }
9551 
9552 namespace {
9553   enum {
9554     AO_Bit_Field = 0,
9555     AO_Vector_Element = 1,
9556     AO_Property_Expansion = 2,
9557     AO_Register_Variable = 3,
9558     AO_No_Error = 4
9559   };
9560 }
9561 /// \brief Diagnose invalid operand for address of operations.
9562 ///
9563 /// \param Type The type of operand which cannot have its address taken.
9564 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
9565                                          Expr *E, unsigned Type) {
9566   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
9567 }
9568 
9569 /// CheckAddressOfOperand - The operand of & must be either a function
9570 /// designator or an lvalue designating an object. If it is an lvalue, the
9571 /// object cannot be declared with storage class register or be a bit field.
9572 /// Note: The usual conversions are *not* applied to the operand of the &
9573 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
9574 /// In C++, the operand might be an overloaded function name, in which case
9575 /// we allow the '&' but retain the overloaded-function type.
9576 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
9577   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
9578     if (PTy->getKind() == BuiltinType::Overload) {
9579       Expr *E = OrigOp.get()->IgnoreParens();
9580       if (!isa<OverloadExpr>(E)) {
9581         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
9582         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
9583           << OrigOp.get()->getSourceRange();
9584         return QualType();
9585       }
9586 
9587       OverloadExpr *Ovl = cast<OverloadExpr>(E);
9588       if (isa<UnresolvedMemberExpr>(Ovl))
9589         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
9590           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
9591             << OrigOp.get()->getSourceRange();
9592           return QualType();
9593         }
9594 
9595       return Context.OverloadTy;
9596     }
9597 
9598     if (PTy->getKind() == BuiltinType::UnknownAny)
9599       return Context.UnknownAnyTy;
9600 
9601     if (PTy->getKind() == BuiltinType::BoundMember) {
9602       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
9603         << OrigOp.get()->getSourceRange();
9604       return QualType();
9605     }
9606 
9607     OrigOp = CheckPlaceholderExpr(OrigOp.get());
9608     if (OrigOp.isInvalid()) return QualType();
9609   }
9610 
9611   if (OrigOp.get()->isTypeDependent())
9612     return Context.DependentTy;
9613 
9614   assert(!OrigOp.get()->getType()->isPlaceholderType());
9615 
9616   // Make sure to ignore parentheses in subsequent checks
9617   Expr *op = OrigOp.get()->IgnoreParens();
9618 
9619   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
9620   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
9621     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
9622     return QualType();
9623   }
9624 
9625   if (getLangOpts().C99) {
9626     // Implement C99-only parts of addressof rules.
9627     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
9628       if (uOp->getOpcode() == UO_Deref)
9629         // Per C99 6.5.3.2, the address of a deref always returns a valid result
9630         // (assuming the deref expression is valid).
9631         return uOp->getSubExpr()->getType();
9632     }
9633     // Technically, there should be a check for array subscript
9634     // expressions here, but the result of one is always an lvalue anyway.
9635   }
9636   ValueDecl *dcl = getPrimaryDecl(op);
9637   Expr::LValueClassification lval = op->ClassifyLValue(Context);
9638   unsigned AddressOfError = AO_No_Error;
9639 
9640   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
9641     bool sfinae = (bool)isSFINAEContext();
9642     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
9643                                   : diag::ext_typecheck_addrof_temporary)
9644       << op->getType() << op->getSourceRange();
9645     if (sfinae)
9646       return QualType();
9647     // Materialize the temporary as an lvalue so that we can take its address.
9648     OrigOp = op = new (Context)
9649         MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
9650   } else if (isa<ObjCSelectorExpr>(op)) {
9651     return Context.getPointerType(op->getType());
9652   } else if (lval == Expr::LV_MemberFunction) {
9653     // If it's an instance method, make a member pointer.
9654     // The expression must have exactly the form &A::foo.
9655 
9656     // If the underlying expression isn't a decl ref, give up.
9657     if (!isa<DeclRefExpr>(op)) {
9658       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
9659         << OrigOp.get()->getSourceRange();
9660       return QualType();
9661     }
9662     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
9663     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
9664 
9665     // The id-expression was parenthesized.
9666     if (OrigOp.get() != DRE) {
9667       Diag(OpLoc, diag::err_parens_pointer_member_function)
9668         << OrigOp.get()->getSourceRange();
9669 
9670     // The method was named without a qualifier.
9671     } else if (!DRE->getQualifier()) {
9672       if (MD->getParent()->getName().empty())
9673         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9674           << op->getSourceRange();
9675       else {
9676         SmallString<32> Str;
9677         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
9678         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9679           << op->getSourceRange()
9680           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
9681       }
9682     }
9683 
9684     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
9685     if (isa<CXXDestructorDecl>(MD))
9686       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
9687 
9688     QualType MPTy = Context.getMemberPointerType(
9689         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
9690     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9691       RequireCompleteType(OpLoc, MPTy, 0);
9692     return MPTy;
9693   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
9694     // C99 6.5.3.2p1
9695     // The operand must be either an l-value or a function designator
9696     if (!op->getType()->isFunctionType()) {
9697       // Use a special diagnostic for loads from property references.
9698       if (isa<PseudoObjectExpr>(op)) {
9699         AddressOfError = AO_Property_Expansion;
9700       } else {
9701         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
9702           << op->getType() << op->getSourceRange();
9703         return QualType();
9704       }
9705     }
9706   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
9707     // The operand cannot be a bit-field
9708     AddressOfError = AO_Bit_Field;
9709   } else if (op->getObjectKind() == OK_VectorComponent) {
9710     // The operand cannot be an element of a vector
9711     AddressOfError = AO_Vector_Element;
9712   } else if (dcl) { // C99 6.5.3.2p1
9713     // We have an lvalue with a decl. Make sure the decl is not declared
9714     // with the register storage-class specifier.
9715     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
9716       // in C++ it is not error to take address of a register
9717       // variable (c++03 7.1.1P3)
9718       if (vd->getStorageClass() == SC_Register &&
9719           !getLangOpts().CPlusPlus) {
9720         AddressOfError = AO_Register_Variable;
9721       }
9722     } else if (isa<MSPropertyDecl>(dcl)) {
9723       AddressOfError = AO_Property_Expansion;
9724     } else if (isa<FunctionTemplateDecl>(dcl)) {
9725       return Context.OverloadTy;
9726     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
9727       // Okay: we can take the address of a field.
9728       // Could be a pointer to member, though, if there is an explicit
9729       // scope qualifier for the class.
9730       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
9731         DeclContext *Ctx = dcl->getDeclContext();
9732         if (Ctx && Ctx->isRecord()) {
9733           if (dcl->getType()->isReferenceType()) {
9734             Diag(OpLoc,
9735                  diag::err_cannot_form_pointer_to_member_of_reference_type)
9736               << dcl->getDeclName() << dcl->getType();
9737             return QualType();
9738           }
9739 
9740           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
9741             Ctx = Ctx->getParent();
9742 
9743           QualType MPTy = Context.getMemberPointerType(
9744               op->getType(),
9745               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
9746           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9747             RequireCompleteType(OpLoc, MPTy, 0);
9748           return MPTy;
9749         }
9750       }
9751     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
9752       llvm_unreachable("Unknown/unexpected decl type");
9753   }
9754 
9755   if (AddressOfError != AO_No_Error) {
9756     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
9757     return QualType();
9758   }
9759 
9760   if (lval == Expr::LV_IncompleteVoidType) {
9761     // Taking the address of a void variable is technically illegal, but we
9762     // allow it in cases which are otherwise valid.
9763     // Example: "extern void x; void* y = &x;".
9764     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
9765   }
9766 
9767   // If the operand has type "type", the result has type "pointer to type".
9768   if (op->getType()->isObjCObjectType())
9769     return Context.getObjCObjectPointerType(op->getType());
9770   return Context.getPointerType(op->getType());
9771 }
9772 
9773 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
9774   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
9775   if (!DRE)
9776     return;
9777   const Decl *D = DRE->getDecl();
9778   if (!D)
9779     return;
9780   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
9781   if (!Param)
9782     return;
9783   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
9784     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
9785       return;
9786   if (FunctionScopeInfo *FD = S.getCurFunction())
9787     if (!FD->ModifiedNonNullParams.count(Param))
9788       FD->ModifiedNonNullParams.insert(Param);
9789 }
9790 
9791 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
9792 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
9793                                         SourceLocation OpLoc) {
9794   if (Op->isTypeDependent())
9795     return S.Context.DependentTy;
9796 
9797   ExprResult ConvResult = S.UsualUnaryConversions(Op);
9798   if (ConvResult.isInvalid())
9799     return QualType();
9800   Op = ConvResult.get();
9801   QualType OpTy = Op->getType();
9802   QualType Result;
9803 
9804   if (isa<CXXReinterpretCastExpr>(Op)) {
9805     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
9806     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
9807                                      Op->getSourceRange());
9808   }
9809 
9810   if (const PointerType *PT = OpTy->getAs<PointerType>())
9811     Result = PT->getPointeeType();
9812   else if (const ObjCObjectPointerType *OPT =
9813              OpTy->getAs<ObjCObjectPointerType>())
9814     Result = OPT->getPointeeType();
9815   else {
9816     ExprResult PR = S.CheckPlaceholderExpr(Op);
9817     if (PR.isInvalid()) return QualType();
9818     if (PR.get() != Op)
9819       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
9820   }
9821 
9822   if (Result.isNull()) {
9823     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
9824       << OpTy << Op->getSourceRange();
9825     return QualType();
9826   }
9827 
9828   // Note that per both C89 and C99, indirection is always legal, even if Result
9829   // is an incomplete type or void.  It would be possible to warn about
9830   // dereferencing a void pointer, but it's completely well-defined, and such a
9831   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
9832   // for pointers to 'void' but is fine for any other pointer type:
9833   //
9834   // C++ [expr.unary.op]p1:
9835   //   [...] the expression to which [the unary * operator] is applied shall
9836   //   be a pointer to an object type, or a pointer to a function type
9837   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
9838     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
9839       << OpTy << Op->getSourceRange();
9840 
9841   // Dereferences are usually l-values...
9842   VK = VK_LValue;
9843 
9844   // ...except that certain expressions are never l-values in C.
9845   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
9846     VK = VK_RValue;
9847 
9848   return Result;
9849 }
9850 
9851 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
9852   BinaryOperatorKind Opc;
9853   switch (Kind) {
9854   default: llvm_unreachable("Unknown binop!");
9855   case tok::periodstar:           Opc = BO_PtrMemD; break;
9856   case tok::arrowstar:            Opc = BO_PtrMemI; break;
9857   case tok::star:                 Opc = BO_Mul; break;
9858   case tok::slash:                Opc = BO_Div; break;
9859   case tok::percent:              Opc = BO_Rem; break;
9860   case tok::plus:                 Opc = BO_Add; break;
9861   case tok::minus:                Opc = BO_Sub; break;
9862   case tok::lessless:             Opc = BO_Shl; break;
9863   case tok::greatergreater:       Opc = BO_Shr; break;
9864   case tok::lessequal:            Opc = BO_LE; break;
9865   case tok::less:                 Opc = BO_LT; break;
9866   case tok::greaterequal:         Opc = BO_GE; break;
9867   case tok::greater:              Opc = BO_GT; break;
9868   case tok::exclaimequal:         Opc = BO_NE; break;
9869   case tok::equalequal:           Opc = BO_EQ; break;
9870   case tok::amp:                  Opc = BO_And; break;
9871   case tok::caret:                Opc = BO_Xor; break;
9872   case tok::pipe:                 Opc = BO_Or; break;
9873   case tok::ampamp:               Opc = BO_LAnd; break;
9874   case tok::pipepipe:             Opc = BO_LOr; break;
9875   case tok::equal:                Opc = BO_Assign; break;
9876   case tok::starequal:            Opc = BO_MulAssign; break;
9877   case tok::slashequal:           Opc = BO_DivAssign; break;
9878   case tok::percentequal:         Opc = BO_RemAssign; break;
9879   case tok::plusequal:            Opc = BO_AddAssign; break;
9880   case tok::minusequal:           Opc = BO_SubAssign; break;
9881   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
9882   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
9883   case tok::ampequal:             Opc = BO_AndAssign; break;
9884   case tok::caretequal:           Opc = BO_XorAssign; break;
9885   case tok::pipeequal:            Opc = BO_OrAssign; break;
9886   case tok::comma:                Opc = BO_Comma; break;
9887   }
9888   return Opc;
9889 }
9890 
9891 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
9892   tok::TokenKind Kind) {
9893   UnaryOperatorKind Opc;
9894   switch (Kind) {
9895   default: llvm_unreachable("Unknown unary op!");
9896   case tok::plusplus:     Opc = UO_PreInc; break;
9897   case tok::minusminus:   Opc = UO_PreDec; break;
9898   case tok::amp:          Opc = UO_AddrOf; break;
9899   case tok::star:         Opc = UO_Deref; break;
9900   case tok::plus:         Opc = UO_Plus; break;
9901   case tok::minus:        Opc = UO_Minus; break;
9902   case tok::tilde:        Opc = UO_Not; break;
9903   case tok::exclaim:      Opc = UO_LNot; break;
9904   case tok::kw___real:    Opc = UO_Real; break;
9905   case tok::kw___imag:    Opc = UO_Imag; break;
9906   case tok::kw___extension__: Opc = UO_Extension; break;
9907   }
9908   return Opc;
9909 }
9910 
9911 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
9912 /// This warning is only emitted for builtin assignment operations. It is also
9913 /// suppressed in the event of macro expansions.
9914 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
9915                                    SourceLocation OpLoc) {
9916   if (!S.ActiveTemplateInstantiations.empty())
9917     return;
9918   if (OpLoc.isInvalid() || OpLoc.isMacroID())
9919     return;
9920   LHSExpr = LHSExpr->IgnoreParenImpCasts();
9921   RHSExpr = RHSExpr->IgnoreParenImpCasts();
9922   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9923   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9924   if (!LHSDeclRef || !RHSDeclRef ||
9925       LHSDeclRef->getLocation().isMacroID() ||
9926       RHSDeclRef->getLocation().isMacroID())
9927     return;
9928   const ValueDecl *LHSDecl =
9929     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
9930   const ValueDecl *RHSDecl =
9931     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
9932   if (LHSDecl != RHSDecl)
9933     return;
9934   if (LHSDecl->getType().isVolatileQualified())
9935     return;
9936   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
9937     if (RefTy->getPointeeType().isVolatileQualified())
9938       return;
9939 
9940   S.Diag(OpLoc, diag::warn_self_assignment)
9941       << LHSDeclRef->getType()
9942       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9943 }
9944 
9945 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
9946 /// is usually indicative of introspection within the Objective-C pointer.
9947 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
9948                                           SourceLocation OpLoc) {
9949   if (!S.getLangOpts().ObjC1)
9950     return;
9951 
9952   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
9953   const Expr *LHS = L.get();
9954   const Expr *RHS = R.get();
9955 
9956   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9957     ObjCPointerExpr = LHS;
9958     OtherExpr = RHS;
9959   }
9960   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9961     ObjCPointerExpr = RHS;
9962     OtherExpr = LHS;
9963   }
9964 
9965   // This warning is deliberately made very specific to reduce false
9966   // positives with logic that uses '&' for hashing.  This logic mainly
9967   // looks for code trying to introspect into tagged pointers, which
9968   // code should generally never do.
9969   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
9970     unsigned Diag = diag::warn_objc_pointer_masking;
9971     // Determine if we are introspecting the result of performSelectorXXX.
9972     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
9973     // Special case messages to -performSelector and friends, which
9974     // can return non-pointer values boxed in a pointer value.
9975     // Some clients may wish to silence warnings in this subcase.
9976     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
9977       Selector S = ME->getSelector();
9978       StringRef SelArg0 = S.getNameForSlot(0);
9979       if (SelArg0.startswith("performSelector"))
9980         Diag = diag::warn_objc_pointer_masking_performSelector;
9981     }
9982 
9983     S.Diag(OpLoc, Diag)
9984       << ObjCPointerExpr->getSourceRange();
9985   }
9986 }
9987 
9988 static NamedDecl *getDeclFromExpr(Expr *E) {
9989   if (!E)
9990     return nullptr;
9991   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
9992     return DRE->getDecl();
9993   if (auto *ME = dyn_cast<MemberExpr>(E))
9994     return ME->getMemberDecl();
9995   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
9996     return IRE->getDecl();
9997   return nullptr;
9998 }
9999 
10000 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
10001 /// operator @p Opc at location @c TokLoc. This routine only supports
10002 /// built-in operations; ActOnBinOp handles overloaded operators.
10003 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
10004                                     BinaryOperatorKind Opc,
10005                                     Expr *LHSExpr, Expr *RHSExpr) {
10006   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
10007     // The syntax only allows initializer lists on the RHS of assignment,
10008     // so we don't need to worry about accepting invalid code for
10009     // non-assignment operators.
10010     // C++11 5.17p9:
10011     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
10012     //   of x = {} is x = T().
10013     InitializationKind Kind =
10014         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
10015     InitializedEntity Entity =
10016         InitializedEntity::InitializeTemporary(LHSExpr->getType());
10017     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
10018     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
10019     if (Init.isInvalid())
10020       return Init;
10021     RHSExpr = Init.get();
10022   }
10023 
10024   ExprResult LHS = LHSExpr, RHS = RHSExpr;
10025   QualType ResultTy;     // Result type of the binary operator.
10026   // The following two variables are used for compound assignment operators
10027   QualType CompLHSTy;    // Type of LHS after promotions for computation
10028   QualType CompResultTy; // Type of computation result
10029   ExprValueKind VK = VK_RValue;
10030   ExprObjectKind OK = OK_Ordinary;
10031 
10032   if (!getLangOpts().CPlusPlus) {
10033     // C cannot handle TypoExpr nodes on either side of a binop because it
10034     // doesn't handle dependent types properly, so make sure any TypoExprs have
10035     // been dealt with before checking the operands.
10036     LHS = CorrectDelayedTyposInExpr(LHSExpr);
10037     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
10038       if (Opc != BO_Assign)
10039         return ExprResult(E);
10040       // Avoid correcting the RHS to the same Expr as the LHS.
10041       Decl *D = getDeclFromExpr(E);
10042       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
10043     });
10044     if (!LHS.isUsable() || !RHS.isUsable())
10045       return ExprError();
10046   }
10047 
10048   switch (Opc) {
10049   case BO_Assign:
10050     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
10051     if (getLangOpts().CPlusPlus &&
10052         LHS.get()->getObjectKind() != OK_ObjCProperty) {
10053       VK = LHS.get()->getValueKind();
10054       OK = LHS.get()->getObjectKind();
10055     }
10056     if (!ResultTy.isNull()) {
10057       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10058       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
10059     }
10060     RecordModifiableNonNullParam(*this, LHS.get());
10061     break;
10062   case BO_PtrMemD:
10063   case BO_PtrMemI:
10064     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
10065                                             Opc == BO_PtrMemI);
10066     break;
10067   case BO_Mul:
10068   case BO_Div:
10069     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
10070                                            Opc == BO_Div);
10071     break;
10072   case BO_Rem:
10073     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
10074     break;
10075   case BO_Add:
10076     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
10077     break;
10078   case BO_Sub:
10079     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
10080     break;
10081   case BO_Shl:
10082   case BO_Shr:
10083     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
10084     break;
10085   case BO_LE:
10086   case BO_LT:
10087   case BO_GE:
10088   case BO_GT:
10089     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
10090     break;
10091   case BO_EQ:
10092   case BO_NE:
10093     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
10094     break;
10095   case BO_And:
10096     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
10097   case BO_Xor:
10098   case BO_Or:
10099     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
10100     break;
10101   case BO_LAnd:
10102   case BO_LOr:
10103     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
10104     break;
10105   case BO_MulAssign:
10106   case BO_DivAssign:
10107     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
10108                                                Opc == BO_DivAssign);
10109     CompLHSTy = CompResultTy;
10110     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10111       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10112     break;
10113   case BO_RemAssign:
10114     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
10115     CompLHSTy = CompResultTy;
10116     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10117       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10118     break;
10119   case BO_AddAssign:
10120     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
10121     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10122       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10123     break;
10124   case BO_SubAssign:
10125     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
10126     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10127       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10128     break;
10129   case BO_ShlAssign:
10130   case BO_ShrAssign:
10131     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
10132     CompLHSTy = CompResultTy;
10133     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10134       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10135     break;
10136   case BO_AndAssign:
10137   case BO_OrAssign: // fallthrough
10138 	  DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10139   case BO_XorAssign:
10140     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
10141     CompLHSTy = CompResultTy;
10142     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10143       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10144     break;
10145   case BO_Comma:
10146     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
10147     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
10148       VK = RHS.get()->getValueKind();
10149       OK = RHS.get()->getObjectKind();
10150     }
10151     break;
10152   }
10153   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
10154     return ExprError();
10155 
10156   // Check for array bounds violations for both sides of the BinaryOperator
10157   CheckArrayAccess(LHS.get());
10158   CheckArrayAccess(RHS.get());
10159 
10160   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
10161     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
10162                                                  &Context.Idents.get("object_setClass"),
10163                                                  SourceLocation(), LookupOrdinaryName);
10164     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
10165       SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
10166       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
10167       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
10168       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
10169       FixItHint::CreateInsertion(RHSLocEnd, ")");
10170     }
10171     else
10172       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
10173   }
10174   else if (const ObjCIvarRefExpr *OIRE =
10175            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
10176     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
10177 
10178   if (CompResultTy.isNull())
10179     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
10180                                         OK, OpLoc, FPFeatures.fp_contract);
10181   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
10182       OK_ObjCProperty) {
10183     VK = VK_LValue;
10184     OK = LHS.get()->getObjectKind();
10185   }
10186   return new (Context) CompoundAssignOperator(
10187       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
10188       OpLoc, FPFeatures.fp_contract);
10189 }
10190 
10191 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
10192 /// operators are mixed in a way that suggests that the programmer forgot that
10193 /// comparison operators have higher precedence. The most typical example of
10194 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
10195 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
10196                                       SourceLocation OpLoc, Expr *LHSExpr,
10197                                       Expr *RHSExpr) {
10198   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
10199   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
10200 
10201   // Check that one of the sides is a comparison operator.
10202   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
10203   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
10204   if (!isLeftComp && !isRightComp)
10205     return;
10206 
10207   // Bitwise operations are sometimes used as eager logical ops.
10208   // Don't diagnose this.
10209   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
10210   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
10211   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
10212     return;
10213 
10214   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
10215                                                    OpLoc)
10216                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
10217   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
10218   SourceRange ParensRange = isLeftComp ?
10219       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
10220     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
10221 
10222   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
10223     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
10224   SuggestParentheses(Self, OpLoc,
10225     Self.PDiag(diag::note_precedence_silence) << OpStr,
10226     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
10227   SuggestParentheses(Self, OpLoc,
10228     Self.PDiag(diag::note_precedence_bitwise_first)
10229       << BinaryOperator::getOpcodeStr(Opc),
10230     ParensRange);
10231 }
10232 
10233 /// \brief It accepts a '&' expr that is inside a '|' one.
10234 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
10235 /// in parentheses.
10236 static void
10237 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
10238                                        BinaryOperator *Bop) {
10239   assert(Bop->getOpcode() == BO_And);
10240   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
10241       << Bop->getSourceRange() << OpLoc;
10242   SuggestParentheses(Self, Bop->getOperatorLoc(),
10243     Self.PDiag(diag::note_precedence_silence)
10244       << Bop->getOpcodeStr(),
10245     Bop->getSourceRange());
10246 }
10247 
10248 /// \brief It accepts a '&&' expr that is inside a '||' one.
10249 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
10250 /// in parentheses.
10251 static void
10252 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
10253                                        BinaryOperator *Bop) {
10254   assert(Bop->getOpcode() == BO_LAnd);
10255   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
10256       << Bop->getSourceRange() << OpLoc;
10257   SuggestParentheses(Self, Bop->getOperatorLoc(),
10258     Self.PDiag(diag::note_precedence_silence)
10259       << Bop->getOpcodeStr(),
10260     Bop->getSourceRange());
10261 }
10262 
10263 /// \brief Returns true if the given expression can be evaluated as a constant
10264 /// 'true'.
10265 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
10266   bool Res;
10267   return !E->isValueDependent() &&
10268          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
10269 }
10270 
10271 /// \brief Returns true if the given expression can be evaluated as a constant
10272 /// 'false'.
10273 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
10274   bool Res;
10275   return !E->isValueDependent() &&
10276          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
10277 }
10278 
10279 /// \brief Look for '&&' in the left hand of a '||' expr.
10280 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
10281                                              Expr *LHSExpr, Expr *RHSExpr) {
10282   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
10283     if (Bop->getOpcode() == BO_LAnd) {
10284       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
10285       if (EvaluatesAsFalse(S, RHSExpr))
10286         return;
10287       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
10288       if (!EvaluatesAsTrue(S, Bop->getLHS()))
10289         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
10290     } else if (Bop->getOpcode() == BO_LOr) {
10291       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
10292         // If it's "a || b && 1 || c" we didn't warn earlier for
10293         // "a || b && 1", but warn now.
10294         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
10295           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
10296       }
10297     }
10298   }
10299 }
10300 
10301 /// \brief Look for '&&' in the right hand of a '||' expr.
10302 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
10303                                              Expr *LHSExpr, Expr *RHSExpr) {
10304   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
10305     if (Bop->getOpcode() == BO_LAnd) {
10306       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
10307       if (EvaluatesAsFalse(S, LHSExpr))
10308         return;
10309       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
10310       if (!EvaluatesAsTrue(S, Bop->getRHS()))
10311         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
10312     }
10313   }
10314 }
10315 
10316 /// \brief Look for '&' in the left or right hand of a '|' expr.
10317 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
10318                                              Expr *OrArg) {
10319   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
10320     if (Bop->getOpcode() == BO_And)
10321       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
10322   }
10323 }
10324 
10325 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
10326                                     Expr *SubExpr, StringRef Shift) {
10327   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
10328     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
10329       StringRef Op = Bop->getOpcodeStr();
10330       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
10331           << Bop->getSourceRange() << OpLoc << Shift << Op;
10332       SuggestParentheses(S, Bop->getOperatorLoc(),
10333           S.PDiag(diag::note_precedence_silence) << Op,
10334           Bop->getSourceRange());
10335     }
10336   }
10337 }
10338 
10339 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
10340                                  Expr *LHSExpr, Expr *RHSExpr) {
10341   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
10342   if (!OCE)
10343     return;
10344 
10345   FunctionDecl *FD = OCE->getDirectCallee();
10346   if (!FD || !FD->isOverloadedOperator())
10347     return;
10348 
10349   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
10350   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
10351     return;
10352 
10353   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
10354       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
10355       << (Kind == OO_LessLess);
10356   SuggestParentheses(S, OCE->getOperatorLoc(),
10357                      S.PDiag(diag::note_precedence_silence)
10358                          << (Kind == OO_LessLess ? "<<" : ">>"),
10359                      OCE->getSourceRange());
10360   SuggestParentheses(S, OpLoc,
10361                      S.PDiag(diag::note_evaluate_comparison_first),
10362                      SourceRange(OCE->getArg(1)->getLocStart(),
10363                                  RHSExpr->getLocEnd()));
10364 }
10365 
10366 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
10367 /// precedence.
10368 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
10369                                     SourceLocation OpLoc, Expr *LHSExpr,
10370                                     Expr *RHSExpr){
10371   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
10372   if (BinaryOperator::isBitwiseOp(Opc))
10373     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
10374 
10375   // Diagnose "arg1 & arg2 | arg3"
10376   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
10377     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
10378     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
10379   }
10380 
10381   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
10382   // We don't warn for 'assert(a || b && "bad")' since this is safe.
10383   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
10384     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
10385     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
10386   }
10387 
10388   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
10389       || Opc == BO_Shr) {
10390     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
10391     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
10392     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
10393   }
10394 
10395   // Warn on overloaded shift operators and comparisons, such as:
10396   // cout << 5 == 4;
10397   if (BinaryOperator::isComparisonOp(Opc))
10398     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
10399 }
10400 
10401 // Binary Operators.  'Tok' is the token for the operator.
10402 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
10403                             tok::TokenKind Kind,
10404                             Expr *LHSExpr, Expr *RHSExpr) {
10405   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
10406   assert(LHSExpr && "ActOnBinOp(): missing left expression");
10407   assert(RHSExpr && "ActOnBinOp(): missing right expression");
10408 
10409   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
10410   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
10411 
10412   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
10413 }
10414 
10415 /// Build an overloaded binary operator expression in the given scope.
10416 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
10417                                        BinaryOperatorKind Opc,
10418                                        Expr *LHS, Expr *RHS) {
10419   // Find all of the overloaded operators visible from this
10420   // point. We perform both an operator-name lookup from the local
10421   // scope and an argument-dependent lookup based on the types of
10422   // the arguments.
10423   UnresolvedSet<16> Functions;
10424   OverloadedOperatorKind OverOp
10425     = BinaryOperator::getOverloadedOperator(Opc);
10426   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
10427     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
10428                                    RHS->getType(), Functions);
10429 
10430   // Build the (potentially-overloaded, potentially-dependent)
10431   // binary operation.
10432   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
10433 }
10434 
10435 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
10436                             BinaryOperatorKind Opc,
10437                             Expr *LHSExpr, Expr *RHSExpr) {
10438   // We want to end up calling one of checkPseudoObjectAssignment
10439   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
10440   // both expressions are overloadable or either is type-dependent),
10441   // or CreateBuiltinBinOp (in any other case).  We also want to get
10442   // any placeholder types out of the way.
10443 
10444   // Handle pseudo-objects in the LHS.
10445   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
10446     // Assignments with a pseudo-object l-value need special analysis.
10447     if (pty->getKind() == BuiltinType::PseudoObject &&
10448         BinaryOperator::isAssignmentOp(Opc))
10449       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
10450 
10451     // Don't resolve overloads if the other type is overloadable.
10452     if (pty->getKind() == BuiltinType::Overload) {
10453       // We can't actually test that if we still have a placeholder,
10454       // though.  Fortunately, none of the exceptions we see in that
10455       // code below are valid when the LHS is an overload set.  Note
10456       // that an overload set can be dependently-typed, but it never
10457       // instantiates to having an overloadable type.
10458       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
10459       if (resolvedRHS.isInvalid()) return ExprError();
10460       RHSExpr = resolvedRHS.get();
10461 
10462       if (RHSExpr->isTypeDependent() ||
10463           RHSExpr->getType()->isOverloadableType())
10464         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10465     }
10466 
10467     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
10468     if (LHS.isInvalid()) return ExprError();
10469     LHSExpr = LHS.get();
10470   }
10471 
10472   // Handle pseudo-objects in the RHS.
10473   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
10474     // An overload in the RHS can potentially be resolved by the type
10475     // being assigned to.
10476     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
10477       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
10478         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10479 
10480       if (LHSExpr->getType()->isOverloadableType())
10481         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10482 
10483       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
10484     }
10485 
10486     // Don't resolve overloads if the other type is overloadable.
10487     if (pty->getKind() == BuiltinType::Overload &&
10488         LHSExpr->getType()->isOverloadableType())
10489       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10490 
10491     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
10492     if (!resolvedRHS.isUsable()) return ExprError();
10493     RHSExpr = resolvedRHS.get();
10494   }
10495 
10496   if (getLangOpts().CPlusPlus) {
10497     // If either expression is type-dependent, always build an
10498     // overloaded op.
10499     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
10500       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10501 
10502     // Otherwise, build an overloaded op if either expression has an
10503     // overloadable type.
10504     if (LHSExpr->getType()->isOverloadableType() ||
10505         RHSExpr->getType()->isOverloadableType())
10506       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10507   }
10508 
10509   // Build a built-in binary operation.
10510   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
10511 }
10512 
10513 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
10514                                       UnaryOperatorKind Opc,
10515                                       Expr *InputExpr) {
10516   ExprResult Input = InputExpr;
10517   ExprValueKind VK = VK_RValue;
10518   ExprObjectKind OK = OK_Ordinary;
10519   QualType resultType;
10520   switch (Opc) {
10521   case UO_PreInc:
10522   case UO_PreDec:
10523   case UO_PostInc:
10524   case UO_PostDec:
10525     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
10526                                                 OpLoc,
10527                                                 Opc == UO_PreInc ||
10528                                                 Opc == UO_PostInc,
10529                                                 Opc == UO_PreInc ||
10530                                                 Opc == UO_PreDec);
10531     break;
10532   case UO_AddrOf:
10533     resultType = CheckAddressOfOperand(Input, OpLoc);
10534     RecordModifiableNonNullParam(*this, InputExpr);
10535     break;
10536   case UO_Deref: {
10537     Input = DefaultFunctionArrayLvalueConversion(Input.get());
10538     if (Input.isInvalid()) return ExprError();
10539     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
10540     break;
10541   }
10542   case UO_Plus:
10543   case UO_Minus:
10544     Input = UsualUnaryConversions(Input.get());
10545     if (Input.isInvalid()) return ExprError();
10546     resultType = Input.get()->getType();
10547     if (resultType->isDependentType())
10548       break;
10549     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
10550         resultType->isVectorType())
10551       break;
10552     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
10553              Opc == UO_Plus &&
10554              resultType->isPointerType())
10555       break;
10556 
10557     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10558       << resultType << Input.get()->getSourceRange());
10559 
10560   case UO_Not: // bitwise complement
10561     Input = UsualUnaryConversions(Input.get());
10562     if (Input.isInvalid())
10563       return ExprError();
10564     resultType = Input.get()->getType();
10565     if (resultType->isDependentType())
10566       break;
10567     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
10568     if (resultType->isComplexType() || resultType->isComplexIntegerType())
10569       // C99 does not support '~' for complex conjugation.
10570       Diag(OpLoc, diag::ext_integer_complement_complex)
10571           << resultType << Input.get()->getSourceRange();
10572     else if (resultType->hasIntegerRepresentation())
10573       break;
10574     else if (resultType->isExtVectorType()) {
10575       if (Context.getLangOpts().OpenCL) {
10576         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
10577         // on vector float types.
10578         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
10579         if (!T->isIntegerType())
10580           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10581                            << resultType << Input.get()->getSourceRange());
10582       }
10583       break;
10584     } else {
10585       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10586                        << resultType << Input.get()->getSourceRange());
10587     }
10588     break;
10589 
10590   case UO_LNot: // logical negation
10591     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
10592     Input = DefaultFunctionArrayLvalueConversion(Input.get());
10593     if (Input.isInvalid()) return ExprError();
10594     resultType = Input.get()->getType();
10595 
10596     // Though we still have to promote half FP to float...
10597     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
10598       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
10599       resultType = Context.FloatTy;
10600     }
10601 
10602     if (resultType->isDependentType())
10603       break;
10604     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
10605       // C99 6.5.3.3p1: ok, fallthrough;
10606       if (Context.getLangOpts().CPlusPlus) {
10607         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
10608         // operand contextually converted to bool.
10609         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
10610                                   ScalarTypeToBooleanCastKind(resultType));
10611       } else if (Context.getLangOpts().OpenCL &&
10612                  Context.getLangOpts().OpenCLVersion < 120) {
10613         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
10614         // operate on scalar float types.
10615         if (!resultType->isIntegerType())
10616           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10617                            << resultType << Input.get()->getSourceRange());
10618       }
10619     } else if (resultType->isExtVectorType()) {
10620       if (Context.getLangOpts().OpenCL &&
10621           Context.getLangOpts().OpenCLVersion < 120) {
10622         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
10623         // operate on vector float types.
10624         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
10625         if (!T->isIntegerType())
10626           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10627                            << resultType << Input.get()->getSourceRange());
10628       }
10629       // Vector logical not returns the signed variant of the operand type.
10630       resultType = GetSignedVectorType(resultType);
10631       break;
10632     } else {
10633       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10634         << resultType << Input.get()->getSourceRange());
10635     }
10636 
10637     // LNot always has type int. C99 6.5.3.3p5.
10638     // In C++, it's bool. C++ 5.3.1p8
10639     resultType = Context.getLogicalOperationType();
10640     break;
10641   case UO_Real:
10642   case UO_Imag:
10643     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
10644     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
10645     // complex l-values to ordinary l-values and all other values to r-values.
10646     if (Input.isInvalid()) return ExprError();
10647     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
10648       if (Input.get()->getValueKind() != VK_RValue &&
10649           Input.get()->getObjectKind() == OK_Ordinary)
10650         VK = Input.get()->getValueKind();
10651     } else if (!getLangOpts().CPlusPlus) {
10652       // In C, a volatile scalar is read by __imag. In C++, it is not.
10653       Input = DefaultLvalueConversion(Input.get());
10654     }
10655     break;
10656   case UO_Extension:
10657     resultType = Input.get()->getType();
10658     VK = Input.get()->getValueKind();
10659     OK = Input.get()->getObjectKind();
10660     break;
10661   }
10662   if (resultType.isNull() || Input.isInvalid())
10663     return ExprError();
10664 
10665   // Check for array bounds violations in the operand of the UnaryOperator,
10666   // except for the '*' and '&' operators that have to be handled specially
10667   // by CheckArrayAccess (as there are special cases like &array[arraysize]
10668   // that are explicitly defined as valid by the standard).
10669   if (Opc != UO_AddrOf && Opc != UO_Deref)
10670     CheckArrayAccess(Input.get());
10671 
10672   return new (Context)
10673       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
10674 }
10675 
10676 /// \brief Determine whether the given expression is a qualified member
10677 /// access expression, of a form that could be turned into a pointer to member
10678 /// with the address-of operator.
10679 static bool isQualifiedMemberAccess(Expr *E) {
10680   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10681     if (!DRE->getQualifier())
10682       return false;
10683 
10684     ValueDecl *VD = DRE->getDecl();
10685     if (!VD->isCXXClassMember())
10686       return false;
10687 
10688     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
10689       return true;
10690     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
10691       return Method->isInstance();
10692 
10693     return false;
10694   }
10695 
10696   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
10697     if (!ULE->getQualifier())
10698       return false;
10699 
10700     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
10701                                            DEnd = ULE->decls_end();
10702          D != DEnd; ++D) {
10703       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
10704         if (Method->isInstance())
10705           return true;
10706       } else {
10707         // Overload set does not contain methods.
10708         break;
10709       }
10710     }
10711 
10712     return false;
10713   }
10714 
10715   return false;
10716 }
10717 
10718 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
10719                               UnaryOperatorKind Opc, Expr *Input) {
10720   // First things first: handle placeholders so that the
10721   // overloaded-operator check considers the right type.
10722   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
10723     // Increment and decrement of pseudo-object references.
10724     if (pty->getKind() == BuiltinType::PseudoObject &&
10725         UnaryOperator::isIncrementDecrementOp(Opc))
10726       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
10727 
10728     // extension is always a builtin operator.
10729     if (Opc == UO_Extension)
10730       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10731 
10732     // & gets special logic for several kinds of placeholder.
10733     // The builtin code knows what to do.
10734     if (Opc == UO_AddrOf &&
10735         (pty->getKind() == BuiltinType::Overload ||
10736          pty->getKind() == BuiltinType::UnknownAny ||
10737          pty->getKind() == BuiltinType::BoundMember))
10738       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10739 
10740     // Anything else needs to be handled now.
10741     ExprResult Result = CheckPlaceholderExpr(Input);
10742     if (Result.isInvalid()) return ExprError();
10743     Input = Result.get();
10744   }
10745 
10746   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
10747       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
10748       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
10749     // Find all of the overloaded operators visible from this
10750     // point. We perform both an operator-name lookup from the local
10751     // scope and an argument-dependent lookup based on the types of
10752     // the arguments.
10753     UnresolvedSet<16> Functions;
10754     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
10755     if (S && OverOp != OO_None)
10756       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
10757                                    Functions);
10758 
10759     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
10760   }
10761 
10762   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10763 }
10764 
10765 // Unary Operators.  'Tok' is the token for the operator.
10766 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
10767                               tok::TokenKind Op, Expr *Input) {
10768   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
10769 }
10770 
10771 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
10772 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
10773                                 LabelDecl *TheDecl) {
10774   TheDecl->markUsed(Context);
10775   // Create the AST node.  The address of a label always has type 'void*'.
10776   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
10777                                      Context.getPointerType(Context.VoidTy));
10778 }
10779 
10780 /// Given the last statement in a statement-expression, check whether
10781 /// the result is a producing expression (like a call to an
10782 /// ns_returns_retained function) and, if so, rebuild it to hoist the
10783 /// release out of the full-expression.  Otherwise, return null.
10784 /// Cannot fail.
10785 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
10786   // Should always be wrapped with one of these.
10787   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
10788   if (!cleanups) return nullptr;
10789 
10790   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
10791   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
10792     return nullptr;
10793 
10794   // Splice out the cast.  This shouldn't modify any interesting
10795   // features of the statement.
10796   Expr *producer = cast->getSubExpr();
10797   assert(producer->getType() == cast->getType());
10798   assert(producer->getValueKind() == cast->getValueKind());
10799   cleanups->setSubExpr(producer);
10800   return cleanups;
10801 }
10802 
10803 void Sema::ActOnStartStmtExpr() {
10804   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
10805 }
10806 
10807 void Sema::ActOnStmtExprError() {
10808   // Note that function is also called by TreeTransform when leaving a
10809   // StmtExpr scope without rebuilding anything.
10810 
10811   DiscardCleanupsInEvaluationContext();
10812   PopExpressionEvaluationContext();
10813 }
10814 
10815 ExprResult
10816 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
10817                     SourceLocation RPLoc) { // "({..})"
10818   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
10819   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
10820 
10821   if (hasAnyUnrecoverableErrorsInThisFunction())
10822     DiscardCleanupsInEvaluationContext();
10823   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
10824   PopExpressionEvaluationContext();
10825 
10826   // FIXME: there are a variety of strange constraints to enforce here, for
10827   // example, it is not possible to goto into a stmt expression apparently.
10828   // More semantic analysis is needed.
10829 
10830   // If there are sub-stmts in the compound stmt, take the type of the last one
10831   // as the type of the stmtexpr.
10832   QualType Ty = Context.VoidTy;
10833   bool StmtExprMayBindToTemp = false;
10834   if (!Compound->body_empty()) {
10835     Stmt *LastStmt = Compound->body_back();
10836     LabelStmt *LastLabelStmt = nullptr;
10837     // If LastStmt is a label, skip down through into the body.
10838     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
10839       LastLabelStmt = Label;
10840       LastStmt = Label->getSubStmt();
10841     }
10842 
10843     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
10844       // Do function/array conversion on the last expression, but not
10845       // lvalue-to-rvalue.  However, initialize an unqualified type.
10846       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
10847       if (LastExpr.isInvalid())
10848         return ExprError();
10849       Ty = LastExpr.get()->getType().getUnqualifiedType();
10850 
10851       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
10852         // In ARC, if the final expression ends in a consume, splice
10853         // the consume out and bind it later.  In the alternate case
10854         // (when dealing with a retainable type), the result
10855         // initialization will create a produce.  In both cases the
10856         // result will be +1, and we'll need to balance that out with
10857         // a bind.
10858         if (Expr *rebuiltLastStmt
10859               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
10860           LastExpr = rebuiltLastStmt;
10861         } else {
10862           LastExpr = PerformCopyInitialization(
10863                             InitializedEntity::InitializeResult(LPLoc,
10864                                                                 Ty,
10865                                                                 false),
10866                                                    SourceLocation(),
10867                                                LastExpr);
10868         }
10869 
10870         if (LastExpr.isInvalid())
10871           return ExprError();
10872         if (LastExpr.get() != nullptr) {
10873           if (!LastLabelStmt)
10874             Compound->setLastStmt(LastExpr.get());
10875           else
10876             LastLabelStmt->setSubStmt(LastExpr.get());
10877           StmtExprMayBindToTemp = true;
10878         }
10879       }
10880     }
10881   }
10882 
10883   // FIXME: Check that expression type is complete/non-abstract; statement
10884   // expressions are not lvalues.
10885   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
10886   if (StmtExprMayBindToTemp)
10887     return MaybeBindToTemporary(ResStmtExpr);
10888   return ResStmtExpr;
10889 }
10890 
10891 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
10892                                       TypeSourceInfo *TInfo,
10893                                       OffsetOfComponent *CompPtr,
10894                                       unsigned NumComponents,
10895                                       SourceLocation RParenLoc) {
10896   QualType ArgTy = TInfo->getType();
10897   bool Dependent = ArgTy->isDependentType();
10898   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
10899 
10900   // We must have at least one component that refers to the type, and the first
10901   // one is known to be a field designator.  Verify that the ArgTy represents
10902   // a struct/union/class.
10903   if (!Dependent && !ArgTy->isRecordType())
10904     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
10905                        << ArgTy << TypeRange);
10906 
10907   // Type must be complete per C99 7.17p3 because a declaring a variable
10908   // with an incomplete type would be ill-formed.
10909   if (!Dependent
10910       && RequireCompleteType(BuiltinLoc, ArgTy,
10911                              diag::err_offsetof_incomplete_type, TypeRange))
10912     return ExprError();
10913 
10914   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
10915   // GCC extension, diagnose them.
10916   // FIXME: This diagnostic isn't actually visible because the location is in
10917   // a system header!
10918   if (NumComponents != 1)
10919     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
10920       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
10921 
10922   bool DidWarnAboutNonPOD = false;
10923   QualType CurrentType = ArgTy;
10924   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
10925   SmallVector<OffsetOfNode, 4> Comps;
10926   SmallVector<Expr*, 4> Exprs;
10927   for (unsigned i = 0; i != NumComponents; ++i) {
10928     const OffsetOfComponent &OC = CompPtr[i];
10929     if (OC.isBrackets) {
10930       // Offset of an array sub-field.  TODO: Should we allow vector elements?
10931       if (!CurrentType->isDependentType()) {
10932         const ArrayType *AT = Context.getAsArrayType(CurrentType);
10933         if(!AT)
10934           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
10935                            << CurrentType);
10936         CurrentType = AT->getElementType();
10937       } else
10938         CurrentType = Context.DependentTy;
10939 
10940       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
10941       if (IdxRval.isInvalid())
10942         return ExprError();
10943       Expr *Idx = IdxRval.get();
10944 
10945       // The expression must be an integral expression.
10946       // FIXME: An integral constant expression?
10947       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
10948           !Idx->getType()->isIntegerType())
10949         return ExprError(Diag(Idx->getLocStart(),
10950                               diag::err_typecheck_subscript_not_integer)
10951                          << Idx->getSourceRange());
10952 
10953       // Record this array index.
10954       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
10955       Exprs.push_back(Idx);
10956       continue;
10957     }
10958 
10959     // Offset of a field.
10960     if (CurrentType->isDependentType()) {
10961       // We have the offset of a field, but we can't look into the dependent
10962       // type. Just record the identifier of the field.
10963       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
10964       CurrentType = Context.DependentTy;
10965       continue;
10966     }
10967 
10968     // We need to have a complete type to look into.
10969     if (RequireCompleteType(OC.LocStart, CurrentType,
10970                             diag::err_offsetof_incomplete_type))
10971       return ExprError();
10972 
10973     // Look for the designated field.
10974     const RecordType *RC = CurrentType->getAs<RecordType>();
10975     if (!RC)
10976       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
10977                        << CurrentType);
10978     RecordDecl *RD = RC->getDecl();
10979 
10980     // C++ [lib.support.types]p5:
10981     //   The macro offsetof accepts a restricted set of type arguments in this
10982     //   International Standard. type shall be a POD structure or a POD union
10983     //   (clause 9).
10984     // C++11 [support.types]p4:
10985     //   If type is not a standard-layout class (Clause 9), the results are
10986     //   undefined.
10987     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10988       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
10989       unsigned DiagID =
10990         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
10991                             : diag::ext_offsetof_non_pod_type;
10992 
10993       if (!IsSafe && !DidWarnAboutNonPOD &&
10994           DiagRuntimeBehavior(BuiltinLoc, nullptr,
10995                               PDiag(DiagID)
10996                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
10997                               << CurrentType))
10998         DidWarnAboutNonPOD = true;
10999     }
11000 
11001     // Look for the field.
11002     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
11003     LookupQualifiedName(R, RD);
11004     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
11005     IndirectFieldDecl *IndirectMemberDecl = nullptr;
11006     if (!MemberDecl) {
11007       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
11008         MemberDecl = IndirectMemberDecl->getAnonField();
11009     }
11010 
11011     if (!MemberDecl)
11012       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
11013                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
11014                                                               OC.LocEnd));
11015 
11016     // C99 7.17p3:
11017     //   (If the specified member is a bit-field, the behavior is undefined.)
11018     //
11019     // We diagnose this as an error.
11020     if (MemberDecl->isBitField()) {
11021       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
11022         << MemberDecl->getDeclName()
11023         << SourceRange(BuiltinLoc, RParenLoc);
11024       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
11025       return ExprError();
11026     }
11027 
11028     RecordDecl *Parent = MemberDecl->getParent();
11029     if (IndirectMemberDecl)
11030       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
11031 
11032     // If the member was found in a base class, introduce OffsetOfNodes for
11033     // the base class indirections.
11034     CXXBasePaths Paths;
11035     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
11036       if (Paths.getDetectedVirtual()) {
11037         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
11038           << MemberDecl->getDeclName()
11039           << SourceRange(BuiltinLoc, RParenLoc);
11040         return ExprError();
11041       }
11042 
11043       CXXBasePath &Path = Paths.front();
11044       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
11045            B != BEnd; ++B)
11046         Comps.push_back(OffsetOfNode(B->Base));
11047     }
11048 
11049     if (IndirectMemberDecl) {
11050       for (auto *FI : IndirectMemberDecl->chain()) {
11051         assert(isa<FieldDecl>(FI));
11052         Comps.push_back(OffsetOfNode(OC.LocStart,
11053                                      cast<FieldDecl>(FI), OC.LocEnd));
11054       }
11055     } else
11056       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
11057 
11058     CurrentType = MemberDecl->getType().getNonReferenceType();
11059   }
11060 
11061   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
11062                               Comps, Exprs, RParenLoc);
11063 }
11064 
11065 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
11066                                       SourceLocation BuiltinLoc,
11067                                       SourceLocation TypeLoc,
11068                                       ParsedType ParsedArgTy,
11069                                       OffsetOfComponent *CompPtr,
11070                                       unsigned NumComponents,
11071                                       SourceLocation RParenLoc) {
11072 
11073   TypeSourceInfo *ArgTInfo;
11074   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
11075   if (ArgTy.isNull())
11076     return ExprError();
11077 
11078   if (!ArgTInfo)
11079     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
11080 
11081   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
11082                               RParenLoc);
11083 }
11084 
11085 
11086 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
11087                                  Expr *CondExpr,
11088                                  Expr *LHSExpr, Expr *RHSExpr,
11089                                  SourceLocation RPLoc) {
11090   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
11091 
11092   ExprValueKind VK = VK_RValue;
11093   ExprObjectKind OK = OK_Ordinary;
11094   QualType resType;
11095   bool ValueDependent = false;
11096   bool CondIsTrue = false;
11097   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
11098     resType = Context.DependentTy;
11099     ValueDependent = true;
11100   } else {
11101     // The conditional expression is required to be a constant expression.
11102     llvm::APSInt condEval(32);
11103     ExprResult CondICE
11104       = VerifyIntegerConstantExpression(CondExpr, &condEval,
11105           diag::err_typecheck_choose_expr_requires_constant, false);
11106     if (CondICE.isInvalid())
11107       return ExprError();
11108     CondExpr = CondICE.get();
11109     CondIsTrue = condEval.getZExtValue();
11110 
11111     // If the condition is > zero, then the AST type is the same as the LSHExpr.
11112     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
11113 
11114     resType = ActiveExpr->getType();
11115     ValueDependent = ActiveExpr->isValueDependent();
11116     VK = ActiveExpr->getValueKind();
11117     OK = ActiveExpr->getObjectKind();
11118   }
11119 
11120   return new (Context)
11121       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
11122                  CondIsTrue, resType->isDependentType(), ValueDependent);
11123 }
11124 
11125 //===----------------------------------------------------------------------===//
11126 // Clang Extensions.
11127 //===----------------------------------------------------------------------===//
11128 
11129 /// ActOnBlockStart - This callback is invoked when a block literal is started.
11130 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
11131   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
11132 
11133   if (LangOpts.CPlusPlus) {
11134     Decl *ManglingContextDecl;
11135     if (MangleNumberingContext *MCtx =
11136             getCurrentMangleNumberContext(Block->getDeclContext(),
11137                                           ManglingContextDecl)) {
11138       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
11139       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
11140     }
11141   }
11142 
11143   PushBlockScope(CurScope, Block);
11144   CurContext->addDecl(Block);
11145   if (CurScope)
11146     PushDeclContext(CurScope, Block);
11147   else
11148     CurContext = Block;
11149 
11150   getCurBlock()->HasImplicitReturnType = true;
11151 
11152   // Enter a new evaluation context to insulate the block from any
11153   // cleanups from the enclosing full-expression.
11154   PushExpressionEvaluationContext(PotentiallyEvaluated);
11155 }
11156 
11157 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
11158                                Scope *CurScope) {
11159   assert(ParamInfo.getIdentifier() == nullptr &&
11160          "block-id should have no identifier!");
11161   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
11162   BlockScopeInfo *CurBlock = getCurBlock();
11163 
11164   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
11165   QualType T = Sig->getType();
11166 
11167   // FIXME: We should allow unexpanded parameter packs here, but that would,
11168   // in turn, make the block expression contain unexpanded parameter packs.
11169   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
11170     // Drop the parameters.
11171     FunctionProtoType::ExtProtoInfo EPI;
11172     EPI.HasTrailingReturn = false;
11173     EPI.TypeQuals |= DeclSpec::TQ_const;
11174     T = Context.getFunctionType(Context.DependentTy, None, EPI);
11175     Sig = Context.getTrivialTypeSourceInfo(T);
11176   }
11177 
11178   // GetTypeForDeclarator always produces a function type for a block
11179   // literal signature.  Furthermore, it is always a FunctionProtoType
11180   // unless the function was written with a typedef.
11181   assert(T->isFunctionType() &&
11182          "GetTypeForDeclarator made a non-function block signature");
11183 
11184   // Look for an explicit signature in that function type.
11185   FunctionProtoTypeLoc ExplicitSignature;
11186 
11187   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
11188   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
11189 
11190     // Check whether that explicit signature was synthesized by
11191     // GetTypeForDeclarator.  If so, don't save that as part of the
11192     // written signature.
11193     if (ExplicitSignature.getLocalRangeBegin() ==
11194         ExplicitSignature.getLocalRangeEnd()) {
11195       // This would be much cheaper if we stored TypeLocs instead of
11196       // TypeSourceInfos.
11197       TypeLoc Result = ExplicitSignature.getReturnLoc();
11198       unsigned Size = Result.getFullDataSize();
11199       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
11200       Sig->getTypeLoc().initializeFullCopy(Result, Size);
11201 
11202       ExplicitSignature = FunctionProtoTypeLoc();
11203     }
11204   }
11205 
11206   CurBlock->TheDecl->setSignatureAsWritten(Sig);
11207   CurBlock->FunctionType = T;
11208 
11209   const FunctionType *Fn = T->getAs<FunctionType>();
11210   QualType RetTy = Fn->getReturnType();
11211   bool isVariadic =
11212     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
11213 
11214   CurBlock->TheDecl->setIsVariadic(isVariadic);
11215 
11216   // Context.DependentTy is used as a placeholder for a missing block
11217   // return type.  TODO:  what should we do with declarators like:
11218   //   ^ * { ... }
11219   // If the answer is "apply template argument deduction"....
11220   if (RetTy != Context.DependentTy) {
11221     CurBlock->ReturnType = RetTy;
11222     CurBlock->TheDecl->setBlockMissingReturnType(false);
11223     CurBlock->HasImplicitReturnType = false;
11224   }
11225 
11226   // Push block parameters from the declarator if we had them.
11227   SmallVector<ParmVarDecl*, 8> Params;
11228   if (ExplicitSignature) {
11229     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
11230       ParmVarDecl *Param = ExplicitSignature.getParam(I);
11231       if (Param->getIdentifier() == nullptr &&
11232           !Param->isImplicit() &&
11233           !Param->isInvalidDecl() &&
11234           !getLangOpts().CPlusPlus)
11235         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
11236       Params.push_back(Param);
11237     }
11238 
11239   // Fake up parameter variables if we have a typedef, like
11240   //   ^ fntype { ... }
11241   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
11242     for (const auto &I : Fn->param_types()) {
11243       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
11244           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
11245       Params.push_back(Param);
11246     }
11247   }
11248 
11249   // Set the parameters on the block decl.
11250   if (!Params.empty()) {
11251     CurBlock->TheDecl->setParams(Params);
11252     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
11253                              CurBlock->TheDecl->param_end(),
11254                              /*CheckParameterNames=*/false);
11255   }
11256 
11257   // Finally we can process decl attributes.
11258   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
11259 
11260   // Put the parameter variables in scope.
11261   for (auto AI : CurBlock->TheDecl->params()) {
11262     AI->setOwningFunction(CurBlock->TheDecl);
11263 
11264     // If this has an identifier, add it to the scope stack.
11265     if (AI->getIdentifier()) {
11266       CheckShadow(CurBlock->TheScope, AI);
11267 
11268       PushOnScopeChains(AI, CurBlock->TheScope);
11269     }
11270   }
11271 }
11272 
11273 /// ActOnBlockError - If there is an error parsing a block, this callback
11274 /// is invoked to pop the information about the block from the action impl.
11275 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
11276   // Leave the expression-evaluation context.
11277   DiscardCleanupsInEvaluationContext();
11278   PopExpressionEvaluationContext();
11279 
11280   // Pop off CurBlock, handle nested blocks.
11281   PopDeclContext();
11282   PopFunctionScopeInfo();
11283 }
11284 
11285 /// ActOnBlockStmtExpr - This is called when the body of a block statement
11286 /// literal was successfully completed.  ^(int x){...}
11287 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
11288                                     Stmt *Body, Scope *CurScope) {
11289   // If blocks are disabled, emit an error.
11290   if (!LangOpts.Blocks)
11291     Diag(CaretLoc, diag::err_blocks_disable);
11292 
11293   // Leave the expression-evaluation context.
11294   if (hasAnyUnrecoverableErrorsInThisFunction())
11295     DiscardCleanupsInEvaluationContext();
11296   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
11297   PopExpressionEvaluationContext();
11298 
11299   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
11300 
11301   if (BSI->HasImplicitReturnType)
11302     deduceClosureReturnType(*BSI);
11303 
11304   PopDeclContext();
11305 
11306   QualType RetTy = Context.VoidTy;
11307   if (!BSI->ReturnType.isNull())
11308     RetTy = BSI->ReturnType;
11309 
11310   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
11311   QualType BlockTy;
11312 
11313   // Set the captured variables on the block.
11314   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
11315   SmallVector<BlockDecl::Capture, 4> Captures;
11316   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
11317     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
11318     if (Cap.isThisCapture())
11319       continue;
11320     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
11321                               Cap.isNested(), Cap.getInitExpr());
11322     Captures.push_back(NewCap);
11323   }
11324   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
11325                             BSI->CXXThisCaptureIndex != 0);
11326 
11327   // If the user wrote a function type in some form, try to use that.
11328   if (!BSI->FunctionType.isNull()) {
11329     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
11330 
11331     FunctionType::ExtInfo Ext = FTy->getExtInfo();
11332     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
11333 
11334     // Turn protoless block types into nullary block types.
11335     if (isa<FunctionNoProtoType>(FTy)) {
11336       FunctionProtoType::ExtProtoInfo EPI;
11337       EPI.ExtInfo = Ext;
11338       BlockTy = Context.getFunctionType(RetTy, None, EPI);
11339 
11340     // Otherwise, if we don't need to change anything about the function type,
11341     // preserve its sugar structure.
11342     } else if (FTy->getReturnType() == RetTy &&
11343                (!NoReturn || FTy->getNoReturnAttr())) {
11344       BlockTy = BSI->FunctionType;
11345 
11346     // Otherwise, make the minimal modifications to the function type.
11347     } else {
11348       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
11349       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11350       EPI.TypeQuals = 0; // FIXME: silently?
11351       EPI.ExtInfo = Ext;
11352       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
11353     }
11354 
11355   // If we don't have a function type, just build one from nothing.
11356   } else {
11357     FunctionProtoType::ExtProtoInfo EPI;
11358     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
11359     BlockTy = Context.getFunctionType(RetTy, None, EPI);
11360   }
11361 
11362   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
11363                            BSI->TheDecl->param_end());
11364   BlockTy = Context.getBlockPointerType(BlockTy);
11365 
11366   // If needed, diagnose invalid gotos and switches in the block.
11367   if (getCurFunction()->NeedsScopeChecking() &&
11368       !PP.isCodeCompletionEnabled())
11369     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
11370 
11371   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
11372 
11373   // Try to apply the named return value optimization. We have to check again
11374   // if we can do this, though, because blocks keep return statements around
11375   // to deduce an implicit return type.
11376   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
11377       !BSI->TheDecl->isDependentContext())
11378     computeNRVO(Body, BSI);
11379 
11380   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
11381   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11382   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
11383 
11384   // If the block isn't obviously global, i.e. it captures anything at
11385   // all, then we need to do a few things in the surrounding context:
11386   if (Result->getBlockDecl()->hasCaptures()) {
11387     // First, this expression has a new cleanup object.
11388     ExprCleanupObjects.push_back(Result->getBlockDecl());
11389     ExprNeedsCleanups = true;
11390 
11391     // It also gets a branch-protected scope if any of the captured
11392     // variables needs destruction.
11393     for (const auto &CI : Result->getBlockDecl()->captures()) {
11394       const VarDecl *var = CI.getVariable();
11395       if (var->getType().isDestructedType() != QualType::DK_none) {
11396         getCurFunction()->setHasBranchProtectedScope();
11397         break;
11398       }
11399     }
11400   }
11401 
11402   return Result;
11403 }
11404 
11405 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
11406                                         Expr *E, ParsedType Ty,
11407                                         SourceLocation RPLoc) {
11408   TypeSourceInfo *TInfo;
11409   GetTypeFromParser(Ty, &TInfo);
11410   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
11411 }
11412 
11413 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
11414                                 Expr *E, TypeSourceInfo *TInfo,
11415                                 SourceLocation RPLoc) {
11416   Expr *OrigExpr = E;
11417 
11418   // Get the va_list type
11419   QualType VaListType = Context.getBuiltinVaListType();
11420   if (VaListType->isArrayType()) {
11421     // Deal with implicit array decay; for example, on x86-64,
11422     // va_list is an array, but it's supposed to decay to
11423     // a pointer for va_arg.
11424     VaListType = Context.getArrayDecayedType(VaListType);
11425     // Make sure the input expression also decays appropriately.
11426     ExprResult Result = UsualUnaryConversions(E);
11427     if (Result.isInvalid())
11428       return ExprError();
11429     E = Result.get();
11430   } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
11431     // If va_list is a record type and we are compiling in C++ mode,
11432     // check the argument using reference binding.
11433     InitializedEntity Entity
11434       = InitializedEntity::InitializeParameter(Context,
11435           Context.getLValueReferenceType(VaListType), false);
11436     ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
11437     if (Init.isInvalid())
11438       return ExprError();
11439     E = Init.getAs<Expr>();
11440   } else {
11441     // Otherwise, the va_list argument must be an l-value because
11442     // it is modified by va_arg.
11443     if (!E->isTypeDependent() &&
11444         CheckForModifiableLvalue(E, BuiltinLoc, *this))
11445       return ExprError();
11446   }
11447 
11448   if (!E->isTypeDependent() &&
11449       !Context.hasSameType(VaListType, E->getType())) {
11450     return ExprError(Diag(E->getLocStart(),
11451                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
11452       << OrigExpr->getType() << E->getSourceRange());
11453   }
11454 
11455   if (!TInfo->getType()->isDependentType()) {
11456     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
11457                             diag::err_second_parameter_to_va_arg_incomplete,
11458                             TInfo->getTypeLoc()))
11459       return ExprError();
11460 
11461     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
11462                                TInfo->getType(),
11463                                diag::err_second_parameter_to_va_arg_abstract,
11464                                TInfo->getTypeLoc()))
11465       return ExprError();
11466 
11467     if (!TInfo->getType().isPODType(Context)) {
11468       Diag(TInfo->getTypeLoc().getBeginLoc(),
11469            TInfo->getType()->isObjCLifetimeType()
11470              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
11471              : diag::warn_second_parameter_to_va_arg_not_pod)
11472         << TInfo->getType()
11473         << TInfo->getTypeLoc().getSourceRange();
11474     }
11475 
11476     // Check for va_arg where arguments of the given type will be promoted
11477     // (i.e. this va_arg is guaranteed to have undefined behavior).
11478     QualType PromoteType;
11479     if (TInfo->getType()->isPromotableIntegerType()) {
11480       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
11481       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
11482         PromoteType = QualType();
11483     }
11484     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
11485       PromoteType = Context.DoubleTy;
11486     if (!PromoteType.isNull())
11487       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
11488                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
11489                           << TInfo->getType()
11490                           << PromoteType
11491                           << TInfo->getTypeLoc().getSourceRange());
11492   }
11493 
11494   QualType T = TInfo->getType().getNonLValueExprType(Context);
11495   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T);
11496 }
11497 
11498 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
11499   // The type of __null will be int or long, depending on the size of
11500   // pointers on the target.
11501   QualType Ty;
11502   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
11503   if (pw == Context.getTargetInfo().getIntWidth())
11504     Ty = Context.IntTy;
11505   else if (pw == Context.getTargetInfo().getLongWidth())
11506     Ty = Context.LongTy;
11507   else if (pw == Context.getTargetInfo().getLongLongWidth())
11508     Ty = Context.LongLongTy;
11509   else {
11510     llvm_unreachable("I don't know size of pointer!");
11511   }
11512 
11513   return new (Context) GNUNullExpr(Ty, TokenLoc);
11514 }
11515 
11516 bool
11517 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
11518   if (!getLangOpts().ObjC1)
11519     return false;
11520 
11521   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
11522   if (!PT)
11523     return false;
11524 
11525   if (!PT->isObjCIdType()) {
11526     // Check if the destination is the 'NSString' interface.
11527     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
11528     if (!ID || !ID->getIdentifier()->isStr("NSString"))
11529       return false;
11530   }
11531 
11532   // Ignore any parens, implicit casts (should only be
11533   // array-to-pointer decays), and not-so-opaque values.  The last is
11534   // important for making this trigger for property assignments.
11535   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
11536   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
11537     if (OV->getSourceExpr())
11538       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
11539 
11540   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
11541   if (!SL || !SL->isAscii())
11542     return false;
11543   Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
11544     << FixItHint::CreateInsertion(SL->getLocStart(), "@");
11545   Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
11546   return true;
11547 }
11548 
11549 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
11550                                     SourceLocation Loc,
11551                                     QualType DstType, QualType SrcType,
11552                                     Expr *SrcExpr, AssignmentAction Action,
11553                                     bool *Complained) {
11554   if (Complained)
11555     *Complained = false;
11556 
11557   // Decode the result (notice that AST's are still created for extensions).
11558   bool CheckInferredResultType = false;
11559   bool isInvalid = false;
11560   unsigned DiagKind = 0;
11561   FixItHint Hint;
11562   ConversionFixItGenerator ConvHints;
11563   bool MayHaveConvFixit = false;
11564   bool MayHaveFunctionDiff = false;
11565   const ObjCInterfaceDecl *IFace = nullptr;
11566   const ObjCProtocolDecl *PDecl = nullptr;
11567 
11568   switch (ConvTy) {
11569   case Compatible:
11570       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
11571       return false;
11572 
11573   case PointerToInt:
11574     DiagKind = diag::ext_typecheck_convert_pointer_int;
11575     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11576     MayHaveConvFixit = true;
11577     break;
11578   case IntToPointer:
11579     DiagKind = diag::ext_typecheck_convert_int_pointer;
11580     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11581     MayHaveConvFixit = true;
11582     break;
11583   case IncompatiblePointer:
11584       DiagKind =
11585         (Action == AA_Passing_CFAudited ?
11586           diag::err_arc_typecheck_convert_incompatible_pointer :
11587           diag::ext_typecheck_convert_incompatible_pointer);
11588     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
11589       SrcType->isObjCObjectPointerType();
11590     if (Hint.isNull() && !CheckInferredResultType) {
11591       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11592     }
11593     else if (CheckInferredResultType) {
11594       SrcType = SrcType.getUnqualifiedType();
11595       DstType = DstType.getUnqualifiedType();
11596     }
11597     MayHaveConvFixit = true;
11598     break;
11599   case IncompatiblePointerSign:
11600     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
11601     break;
11602   case FunctionVoidPointer:
11603     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
11604     break;
11605   case IncompatiblePointerDiscardsQualifiers: {
11606     // Perform array-to-pointer decay if necessary.
11607     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
11608 
11609     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
11610     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
11611     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
11612       DiagKind = diag::err_typecheck_incompatible_address_space;
11613       break;
11614 
11615 
11616     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
11617       DiagKind = diag::err_typecheck_incompatible_ownership;
11618       break;
11619     }
11620 
11621     llvm_unreachable("unknown error case for discarding qualifiers!");
11622     // fallthrough
11623   }
11624   case CompatiblePointerDiscardsQualifiers:
11625     // If the qualifiers lost were because we were applying the
11626     // (deprecated) C++ conversion from a string literal to a char*
11627     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
11628     // Ideally, this check would be performed in
11629     // checkPointerTypesForAssignment. However, that would require a
11630     // bit of refactoring (so that the second argument is an
11631     // expression, rather than a type), which should be done as part
11632     // of a larger effort to fix checkPointerTypesForAssignment for
11633     // C++ semantics.
11634     if (getLangOpts().CPlusPlus &&
11635         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
11636       return false;
11637     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
11638     break;
11639   case IncompatibleNestedPointerQualifiers:
11640     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
11641     break;
11642   case IntToBlockPointer:
11643     DiagKind = diag::err_int_to_block_pointer;
11644     break;
11645   case IncompatibleBlockPointer:
11646     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
11647     break;
11648   case IncompatibleObjCQualifiedId: {
11649     if (SrcType->isObjCQualifiedIdType()) {
11650       const ObjCObjectPointerType *srcOPT =
11651                 SrcType->getAs<ObjCObjectPointerType>();
11652       for (auto *srcProto : srcOPT->quals()) {
11653         PDecl = srcProto;
11654         break;
11655       }
11656       if (const ObjCInterfaceType *IFaceT =
11657             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
11658         IFace = IFaceT->getDecl();
11659     }
11660     else if (DstType->isObjCQualifiedIdType()) {
11661       const ObjCObjectPointerType *dstOPT =
11662         DstType->getAs<ObjCObjectPointerType>();
11663       for (auto *dstProto : dstOPT->quals()) {
11664         PDecl = dstProto;
11665         break;
11666       }
11667       if (const ObjCInterfaceType *IFaceT =
11668             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
11669         IFace = IFaceT->getDecl();
11670     }
11671     DiagKind = diag::warn_incompatible_qualified_id;
11672     break;
11673   }
11674   case IncompatibleVectors:
11675     DiagKind = diag::warn_incompatible_vectors;
11676     break;
11677   case IncompatibleObjCWeakRef:
11678     DiagKind = diag::err_arc_weak_unavailable_assign;
11679     break;
11680   case Incompatible:
11681     DiagKind = diag::err_typecheck_convert_incompatible;
11682     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11683     MayHaveConvFixit = true;
11684     isInvalid = true;
11685     MayHaveFunctionDiff = true;
11686     break;
11687   }
11688 
11689   QualType FirstType, SecondType;
11690   switch (Action) {
11691   case AA_Assigning:
11692   case AA_Initializing:
11693     // The destination type comes first.
11694     FirstType = DstType;
11695     SecondType = SrcType;
11696     break;
11697 
11698   case AA_Returning:
11699   case AA_Passing:
11700   case AA_Passing_CFAudited:
11701   case AA_Converting:
11702   case AA_Sending:
11703   case AA_Casting:
11704     // The source type comes first.
11705     FirstType = SrcType;
11706     SecondType = DstType;
11707     break;
11708   }
11709 
11710   PartialDiagnostic FDiag = PDiag(DiagKind);
11711   if (Action == AA_Passing_CFAudited)
11712     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
11713   else
11714     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
11715 
11716   // If we can fix the conversion, suggest the FixIts.
11717   assert(ConvHints.isNull() || Hint.isNull());
11718   if (!ConvHints.isNull()) {
11719     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
11720          HE = ConvHints.Hints.end(); HI != HE; ++HI)
11721       FDiag << *HI;
11722   } else {
11723     FDiag << Hint;
11724   }
11725   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
11726 
11727   if (MayHaveFunctionDiff)
11728     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
11729 
11730   Diag(Loc, FDiag);
11731   if (DiagKind == diag::warn_incompatible_qualified_id &&
11732       PDecl && IFace && !IFace->hasDefinition())
11733       Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
11734         << IFace->getName() << PDecl->getName();
11735 
11736   if (SecondType == Context.OverloadTy)
11737     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
11738                               FirstType);
11739 
11740   if (CheckInferredResultType)
11741     EmitRelatedResultTypeNote(SrcExpr);
11742 
11743   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
11744     EmitRelatedResultTypeNoteForReturn(DstType);
11745 
11746   if (Complained)
11747     *Complained = true;
11748   return isInvalid;
11749 }
11750 
11751 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11752                                                  llvm::APSInt *Result) {
11753   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
11754   public:
11755     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
11756       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
11757     }
11758   } Diagnoser;
11759 
11760   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
11761 }
11762 
11763 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
11764                                                  llvm::APSInt *Result,
11765                                                  unsigned DiagID,
11766                                                  bool AllowFold) {
11767   class IDDiagnoser : public VerifyICEDiagnoser {
11768     unsigned DiagID;
11769 
11770   public:
11771     IDDiagnoser(unsigned DiagID)
11772       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
11773 
11774     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
11775       S.Diag(Loc, DiagID) << SR;
11776     }
11777   } Diagnoser(DiagID);
11778 
11779   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
11780 }
11781 
11782 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
11783                                             SourceRange SR) {
11784   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
11785 }
11786 
11787 ExprResult
11788 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
11789                                       VerifyICEDiagnoser &Diagnoser,
11790                                       bool AllowFold) {
11791   SourceLocation DiagLoc = E->getLocStart();
11792 
11793   if (getLangOpts().CPlusPlus11) {
11794     // C++11 [expr.const]p5:
11795     //   If an expression of literal class type is used in a context where an
11796     //   integral constant expression is required, then that class type shall
11797     //   have a single non-explicit conversion function to an integral or
11798     //   unscoped enumeration type
11799     ExprResult Converted;
11800     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
11801     public:
11802       CXX11ConvertDiagnoser(bool Silent)
11803           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
11804                                 Silent, true) {}
11805 
11806       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11807                                            QualType T) override {
11808         return S.Diag(Loc, diag::err_ice_not_integral) << T;
11809       }
11810 
11811       SemaDiagnosticBuilder diagnoseIncomplete(
11812           Sema &S, SourceLocation Loc, QualType T) override {
11813         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
11814       }
11815 
11816       SemaDiagnosticBuilder diagnoseExplicitConv(
11817           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11818         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
11819       }
11820 
11821       SemaDiagnosticBuilder noteExplicitConv(
11822           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11823         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11824                  << ConvTy->isEnumeralType() << ConvTy;
11825       }
11826 
11827       SemaDiagnosticBuilder diagnoseAmbiguous(
11828           Sema &S, SourceLocation Loc, QualType T) override {
11829         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
11830       }
11831 
11832       SemaDiagnosticBuilder noteAmbiguous(
11833           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11834         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11835                  << ConvTy->isEnumeralType() << ConvTy;
11836       }
11837 
11838       SemaDiagnosticBuilder diagnoseConversion(
11839           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11840         llvm_unreachable("conversion functions are permitted");
11841       }
11842     } ConvertDiagnoser(Diagnoser.Suppress);
11843 
11844     Converted = PerformContextualImplicitConversion(DiagLoc, E,
11845                                                     ConvertDiagnoser);
11846     if (Converted.isInvalid())
11847       return Converted;
11848     E = Converted.get();
11849     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
11850       return ExprError();
11851   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
11852     // An ICE must be of integral or unscoped enumeration type.
11853     if (!Diagnoser.Suppress)
11854       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11855     return ExprError();
11856   }
11857 
11858   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
11859   // in the non-ICE case.
11860   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
11861     if (Result)
11862       *Result = E->EvaluateKnownConstInt(Context);
11863     return E;
11864   }
11865 
11866   Expr::EvalResult EvalResult;
11867   SmallVector<PartialDiagnosticAt, 8> Notes;
11868   EvalResult.Diag = &Notes;
11869 
11870   // Try to evaluate the expression, and produce diagnostics explaining why it's
11871   // not a constant expression as a side-effect.
11872   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
11873                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
11874 
11875   // In C++11, we can rely on diagnostics being produced for any expression
11876   // which is not a constant expression. If no diagnostics were produced, then
11877   // this is a constant expression.
11878   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
11879     if (Result)
11880       *Result = EvalResult.Val.getInt();
11881     return E;
11882   }
11883 
11884   // If our only note is the usual "invalid subexpression" note, just point
11885   // the caret at its location rather than producing an essentially
11886   // redundant note.
11887   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11888         diag::note_invalid_subexpr_in_const_expr) {
11889     DiagLoc = Notes[0].first;
11890     Notes.clear();
11891   }
11892 
11893   if (!Folded || !AllowFold) {
11894     if (!Diagnoser.Suppress) {
11895       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11896       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11897         Diag(Notes[I].first, Notes[I].second);
11898     }
11899 
11900     return ExprError();
11901   }
11902 
11903   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
11904   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11905     Diag(Notes[I].first, Notes[I].second);
11906 
11907   if (Result)
11908     *Result = EvalResult.Val.getInt();
11909   return E;
11910 }
11911 
11912 namespace {
11913   // Handle the case where we conclude a expression which we speculatively
11914   // considered to be unevaluated is actually evaluated.
11915   class TransformToPE : public TreeTransform<TransformToPE> {
11916     typedef TreeTransform<TransformToPE> BaseTransform;
11917 
11918   public:
11919     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
11920 
11921     // Make sure we redo semantic analysis
11922     bool AlwaysRebuild() { return true; }
11923 
11924     // Make sure we handle LabelStmts correctly.
11925     // FIXME: This does the right thing, but maybe we need a more general
11926     // fix to TreeTransform?
11927     StmtResult TransformLabelStmt(LabelStmt *S) {
11928       S->getDecl()->setStmt(nullptr);
11929       return BaseTransform::TransformLabelStmt(S);
11930     }
11931 
11932     // We need to special-case DeclRefExprs referring to FieldDecls which
11933     // are not part of a member pointer formation; normal TreeTransforming
11934     // doesn't catch this case because of the way we represent them in the AST.
11935     // FIXME: This is a bit ugly; is it really the best way to handle this
11936     // case?
11937     //
11938     // Error on DeclRefExprs referring to FieldDecls.
11939     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
11940       if (isa<FieldDecl>(E->getDecl()) &&
11941           !SemaRef.isUnevaluatedContext())
11942         return SemaRef.Diag(E->getLocation(),
11943                             diag::err_invalid_non_static_member_use)
11944             << E->getDecl() << E->getSourceRange();
11945 
11946       return BaseTransform::TransformDeclRefExpr(E);
11947     }
11948 
11949     // Exception: filter out member pointer formation
11950     ExprResult TransformUnaryOperator(UnaryOperator *E) {
11951       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
11952         return E;
11953 
11954       return BaseTransform::TransformUnaryOperator(E);
11955     }
11956 
11957     ExprResult TransformLambdaExpr(LambdaExpr *E) {
11958       // Lambdas never need to be transformed.
11959       return E;
11960     }
11961   };
11962 }
11963 
11964 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
11965   assert(isUnevaluatedContext() &&
11966          "Should only transform unevaluated expressions");
11967   ExprEvalContexts.back().Context =
11968       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
11969   if (isUnevaluatedContext())
11970     return E;
11971   return TransformToPE(*this).TransformExpr(E);
11972 }
11973 
11974 void
11975 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11976                                       Decl *LambdaContextDecl,
11977                                       bool IsDecltype) {
11978   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(),
11979                                 ExprNeedsCleanups, LambdaContextDecl,
11980                                 IsDecltype);
11981   ExprNeedsCleanups = false;
11982   if (!MaybeODRUseExprs.empty())
11983     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
11984 }
11985 
11986 void
11987 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11988                                       ReuseLambdaContextDecl_t,
11989                                       bool IsDecltype) {
11990   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
11991   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
11992 }
11993 
11994 void Sema::PopExpressionEvaluationContext() {
11995   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
11996   unsigned NumTypos = Rec.NumTypos;
11997 
11998   if (!Rec.Lambdas.empty()) {
11999     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12000       unsigned D;
12001       if (Rec.isUnevaluated()) {
12002         // C++11 [expr.prim.lambda]p2:
12003         //   A lambda-expression shall not appear in an unevaluated operand
12004         //   (Clause 5).
12005         D = diag::err_lambda_unevaluated_operand;
12006       } else {
12007         // C++1y [expr.const]p2:
12008         //   A conditional-expression e is a core constant expression unless the
12009         //   evaluation of e, following the rules of the abstract machine, would
12010         //   evaluate [...] a lambda-expression.
12011         D = diag::err_lambda_in_constant_expression;
12012       }
12013       for (const auto *L : Rec.Lambdas)
12014         Diag(L->getLocStart(), D);
12015     } else {
12016       // Mark the capture expressions odr-used. This was deferred
12017       // during lambda expression creation.
12018       for (auto *Lambda : Rec.Lambdas) {
12019         for (auto *C : Lambda->capture_inits())
12020           MarkDeclarationsReferencedInExpr(C);
12021       }
12022     }
12023   }
12024 
12025   // When are coming out of an unevaluated context, clear out any
12026   // temporaries that we may have created as part of the evaluation of
12027   // the expression in that context: they aren't relevant because they
12028   // will never be constructed.
12029   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12030     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
12031                              ExprCleanupObjects.end());
12032     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
12033     CleanupVarDeclMarking();
12034     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
12035   // Otherwise, merge the contexts together.
12036   } else {
12037     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
12038     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
12039                             Rec.SavedMaybeODRUseExprs.end());
12040   }
12041 
12042   // Pop the current expression evaluation context off the stack.
12043   ExprEvalContexts.pop_back();
12044 
12045   if (!ExprEvalContexts.empty())
12046     ExprEvalContexts.back().NumTypos += NumTypos;
12047   else
12048     assert(NumTypos == 0 && "There are outstanding typos after popping the "
12049                             "last ExpressionEvaluationContextRecord");
12050 }
12051 
12052 void Sema::DiscardCleanupsInEvaluationContext() {
12053   ExprCleanupObjects.erase(
12054          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
12055          ExprCleanupObjects.end());
12056   ExprNeedsCleanups = false;
12057   MaybeODRUseExprs.clear();
12058 }
12059 
12060 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
12061   if (!E->getType()->isVariablyModifiedType())
12062     return E;
12063   return TransformToPotentiallyEvaluated(E);
12064 }
12065 
12066 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
12067   // Do not mark anything as "used" within a dependent context; wait for
12068   // an instantiation.
12069   if (SemaRef.CurContext->isDependentContext())
12070     return false;
12071 
12072   switch (SemaRef.ExprEvalContexts.back().Context) {
12073     case Sema::Unevaluated:
12074     case Sema::UnevaluatedAbstract:
12075       // We are in an expression that is not potentially evaluated; do nothing.
12076       // (Depending on how you read the standard, we actually do need to do
12077       // something here for null pointer constants, but the standard's
12078       // definition of a null pointer constant is completely crazy.)
12079       return false;
12080 
12081     case Sema::ConstantEvaluated:
12082     case Sema::PotentiallyEvaluated:
12083       // We are in a potentially evaluated expression (or a constant-expression
12084       // in C++03); we need to do implicit template instantiation, implicitly
12085       // define class members, and mark most declarations as used.
12086       return true;
12087 
12088     case Sema::PotentiallyEvaluatedIfUsed:
12089       // Referenced declarations will only be used if the construct in the
12090       // containing expression is used.
12091       return false;
12092   }
12093   llvm_unreachable("Invalid context");
12094 }
12095 
12096 /// \brief Mark a function referenced, and check whether it is odr-used
12097 /// (C++ [basic.def.odr]p2, C99 6.9p3)
12098 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
12099                                   bool OdrUse) {
12100   assert(Func && "No function?");
12101 
12102   Func->setReferenced();
12103 
12104   // C++11 [basic.def.odr]p3:
12105   //   A function whose name appears as a potentially-evaluated expression is
12106   //   odr-used if it is the unique lookup result or the selected member of a
12107   //   set of overloaded functions [...].
12108   //
12109   // We (incorrectly) mark overload resolution as an unevaluated context, so we
12110   // can just check that here. Skip the rest of this function if we've already
12111   // marked the function as used.
12112   if (Func->isUsed(/*CheckUsedAttr=*/false) ||
12113       !IsPotentiallyEvaluatedContext(*this)) {
12114     // C++11 [temp.inst]p3:
12115     //   Unless a function template specialization has been explicitly
12116     //   instantiated or explicitly specialized, the function template
12117     //   specialization is implicitly instantiated when the specialization is
12118     //   referenced in a context that requires a function definition to exist.
12119     //
12120     // We consider constexpr function templates to be referenced in a context
12121     // that requires a definition to exist whenever they are referenced.
12122     //
12123     // FIXME: This instantiates constexpr functions too frequently. If this is
12124     // really an unevaluated context (and we're not just in the definition of a
12125     // function template or overload resolution or other cases which we
12126     // incorrectly consider to be unevaluated contexts), and we're not in a
12127     // subexpression which we actually need to evaluate (for instance, a
12128     // template argument, array bound or an expression in a braced-init-list),
12129     // we are not permitted to instantiate this constexpr function definition.
12130     //
12131     // FIXME: This also implicitly defines special members too frequently. They
12132     // are only supposed to be implicitly defined if they are odr-used, but they
12133     // are not odr-used from constant expressions in unevaluated contexts.
12134     // However, they cannot be referenced if they are deleted, and they are
12135     // deleted whenever the implicit definition of the special member would
12136     // fail.
12137     if (!Func->isConstexpr() || Func->getBody())
12138       return;
12139     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
12140     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
12141       return;
12142   }
12143 
12144   // Note that this declaration has been used.
12145   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
12146     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
12147     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
12148       if (Constructor->isDefaultConstructor()) {
12149         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
12150           return;
12151         DefineImplicitDefaultConstructor(Loc, Constructor);
12152       } else if (Constructor->isCopyConstructor()) {
12153         DefineImplicitCopyConstructor(Loc, Constructor);
12154       } else if (Constructor->isMoveConstructor()) {
12155         DefineImplicitMoveConstructor(Loc, Constructor);
12156       }
12157     } else if (Constructor->getInheritedConstructor()) {
12158       DefineInheritingConstructor(Loc, Constructor);
12159     }
12160   } else if (CXXDestructorDecl *Destructor =
12161                  dyn_cast<CXXDestructorDecl>(Func)) {
12162     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
12163     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
12164       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
12165         return;
12166       DefineImplicitDestructor(Loc, Destructor);
12167     }
12168     if (Destructor->isVirtual() && getLangOpts().AppleKext)
12169       MarkVTableUsed(Loc, Destructor->getParent());
12170   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
12171     if (MethodDecl->isOverloadedOperator() &&
12172         MethodDecl->getOverloadedOperator() == OO_Equal) {
12173       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
12174       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
12175         if (MethodDecl->isCopyAssignmentOperator())
12176           DefineImplicitCopyAssignment(Loc, MethodDecl);
12177         else
12178           DefineImplicitMoveAssignment(Loc, MethodDecl);
12179       }
12180     } else if (isa<CXXConversionDecl>(MethodDecl) &&
12181                MethodDecl->getParent()->isLambda()) {
12182       CXXConversionDecl *Conversion =
12183           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
12184       if (Conversion->isLambdaToBlockPointerConversion())
12185         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
12186       else
12187         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
12188     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
12189       MarkVTableUsed(Loc, MethodDecl->getParent());
12190   }
12191 
12192   // Recursive functions should be marked when used from another function.
12193   // FIXME: Is this really right?
12194   if (CurContext == Func) return;
12195 
12196   // Resolve the exception specification for any function which is
12197   // used: CodeGen will need it.
12198   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
12199   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
12200     ResolveExceptionSpec(Loc, FPT);
12201 
12202   if (!OdrUse) return;
12203 
12204   // Implicit instantiation of function templates and member functions of
12205   // class templates.
12206   if (Func->isImplicitlyInstantiable()) {
12207     bool AlreadyInstantiated = false;
12208     SourceLocation PointOfInstantiation = Loc;
12209     if (FunctionTemplateSpecializationInfo *SpecInfo
12210                               = Func->getTemplateSpecializationInfo()) {
12211       if (SpecInfo->getPointOfInstantiation().isInvalid())
12212         SpecInfo->setPointOfInstantiation(Loc);
12213       else if (SpecInfo->getTemplateSpecializationKind()
12214                  == TSK_ImplicitInstantiation) {
12215         AlreadyInstantiated = true;
12216         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
12217       }
12218     } else if (MemberSpecializationInfo *MSInfo
12219                                 = Func->getMemberSpecializationInfo()) {
12220       if (MSInfo->getPointOfInstantiation().isInvalid())
12221         MSInfo->setPointOfInstantiation(Loc);
12222       else if (MSInfo->getTemplateSpecializationKind()
12223                  == TSK_ImplicitInstantiation) {
12224         AlreadyInstantiated = true;
12225         PointOfInstantiation = MSInfo->getPointOfInstantiation();
12226       }
12227     }
12228 
12229     if (!AlreadyInstantiated || Func->isConstexpr()) {
12230       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
12231           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
12232           ActiveTemplateInstantiations.size())
12233         PendingLocalImplicitInstantiations.push_back(
12234             std::make_pair(Func, PointOfInstantiation));
12235       else if (Func->isConstexpr())
12236         // Do not defer instantiations of constexpr functions, to avoid the
12237         // expression evaluator needing to call back into Sema if it sees a
12238         // call to such a function.
12239         InstantiateFunctionDefinition(PointOfInstantiation, Func);
12240       else {
12241         PendingInstantiations.push_back(std::make_pair(Func,
12242                                                        PointOfInstantiation));
12243         // Notify the consumer that a function was implicitly instantiated.
12244         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
12245       }
12246     }
12247   } else {
12248     // Walk redefinitions, as some of them may be instantiable.
12249     for (auto i : Func->redecls()) {
12250       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
12251         MarkFunctionReferenced(Loc, i);
12252     }
12253   }
12254 
12255   // Keep track of used but undefined functions.
12256   if (!Func->isDefined()) {
12257     if (mightHaveNonExternalLinkage(Func))
12258       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
12259     else if (Func->getMostRecentDecl()->isInlined() &&
12260              !LangOpts.GNUInline &&
12261              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
12262       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
12263   }
12264 
12265   // Normally the most current decl is marked used while processing the use and
12266   // any subsequent decls are marked used by decl merging. This fails with
12267   // template instantiation since marking can happen at the end of the file
12268   // and, because of the two phase lookup, this function is called with at
12269   // decl in the middle of a decl chain. We loop to maintain the invariant
12270   // that once a decl is used, all decls after it are also used.
12271   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
12272     F->markUsed(Context);
12273     if (F == Func)
12274       break;
12275   }
12276 }
12277 
12278 static void
12279 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
12280                                    VarDecl *var, DeclContext *DC) {
12281   DeclContext *VarDC = var->getDeclContext();
12282 
12283   //  If the parameter still belongs to the translation unit, then
12284   //  we're actually just using one parameter in the declaration of
12285   //  the next.
12286   if (isa<ParmVarDecl>(var) &&
12287       isa<TranslationUnitDecl>(VarDC))
12288     return;
12289 
12290   // For C code, don't diagnose about capture if we're not actually in code
12291   // right now; it's impossible to write a non-constant expression outside of
12292   // function context, so we'll get other (more useful) diagnostics later.
12293   //
12294   // For C++, things get a bit more nasty... it would be nice to suppress this
12295   // diagnostic for certain cases like using a local variable in an array bound
12296   // for a member of a local class, but the correct predicate is not obvious.
12297   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
12298     return;
12299 
12300   if (isa<CXXMethodDecl>(VarDC) &&
12301       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
12302     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
12303       << var->getIdentifier();
12304   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
12305     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
12306       << var->getIdentifier() << fn->getDeclName();
12307   } else if (isa<BlockDecl>(VarDC)) {
12308     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
12309       << var->getIdentifier();
12310   } else {
12311     // FIXME: Is there any other context where a local variable can be
12312     // declared?
12313     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
12314       << var->getIdentifier();
12315   }
12316 
12317   S.Diag(var->getLocation(), diag::note_entity_declared_at)
12318       << var->getIdentifier();
12319 
12320   // FIXME: Add additional diagnostic info about class etc. which prevents
12321   // capture.
12322 }
12323 
12324 
12325 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
12326                                       bool &SubCapturesAreNested,
12327                                       QualType &CaptureType,
12328                                       QualType &DeclRefType) {
12329    // Check whether we've already captured it.
12330   if (CSI->CaptureMap.count(Var)) {
12331     // If we found a capture, any subcaptures are nested.
12332     SubCapturesAreNested = true;
12333 
12334     // Retrieve the capture type for this variable.
12335     CaptureType = CSI->getCapture(Var).getCaptureType();
12336 
12337     // Compute the type of an expression that refers to this variable.
12338     DeclRefType = CaptureType.getNonReferenceType();
12339 
12340     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
12341     if (Cap.isCopyCapture() &&
12342         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
12343       DeclRefType.addConst();
12344     return true;
12345   }
12346   return false;
12347 }
12348 
12349 // Only block literals, captured statements, and lambda expressions can
12350 // capture; other scopes don't work.
12351 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
12352                                  SourceLocation Loc,
12353                                  const bool Diagnose, Sema &S) {
12354   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
12355     return getLambdaAwareParentOfDeclContext(DC);
12356   else if (Var->hasLocalStorage()) {
12357     if (Diagnose)
12358        diagnoseUncapturableValueReference(S, Loc, Var, DC);
12359   }
12360   return nullptr;
12361 }
12362 
12363 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
12364 // certain types of variables (unnamed, variably modified types etc.)
12365 // so check for eligibility.
12366 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
12367                                  SourceLocation Loc,
12368                                  const bool Diagnose, Sema &S) {
12369 
12370   bool IsBlock = isa<BlockScopeInfo>(CSI);
12371   bool IsLambda = isa<LambdaScopeInfo>(CSI);
12372 
12373   // Lambdas are not allowed to capture unnamed variables
12374   // (e.g. anonymous unions).
12375   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
12376   // assuming that's the intent.
12377   if (IsLambda && !Var->getDeclName()) {
12378     if (Diagnose) {
12379       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
12380       S.Diag(Var->getLocation(), diag::note_declared_at);
12381     }
12382     return false;
12383   }
12384 
12385   // Prohibit variably-modified types in blocks; they're difficult to deal with.
12386   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
12387     if (Diagnose) {
12388       S.Diag(Loc, diag::err_ref_vm_type);
12389       S.Diag(Var->getLocation(), diag::note_previous_decl)
12390         << Var->getDeclName();
12391     }
12392     return false;
12393   }
12394   // Prohibit structs with flexible array members too.
12395   // We cannot capture what is in the tail end of the struct.
12396   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
12397     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
12398       if (Diagnose) {
12399         if (IsBlock)
12400           S.Diag(Loc, diag::err_ref_flexarray_type);
12401         else
12402           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
12403             << Var->getDeclName();
12404         S.Diag(Var->getLocation(), diag::note_previous_decl)
12405           << Var->getDeclName();
12406       }
12407       return false;
12408     }
12409   }
12410   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
12411   // Lambdas and captured statements are not allowed to capture __block
12412   // variables; they don't support the expected semantics.
12413   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
12414     if (Diagnose) {
12415       S.Diag(Loc, diag::err_capture_block_variable)
12416         << Var->getDeclName() << !IsLambda;
12417       S.Diag(Var->getLocation(), diag::note_previous_decl)
12418         << Var->getDeclName();
12419     }
12420     return false;
12421   }
12422 
12423   return true;
12424 }
12425 
12426 // Returns true if the capture by block was successful.
12427 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
12428                                  SourceLocation Loc,
12429                                  const bool BuildAndDiagnose,
12430                                  QualType &CaptureType,
12431                                  QualType &DeclRefType,
12432                                  const bool Nested,
12433                                  Sema &S) {
12434   Expr *CopyExpr = nullptr;
12435   bool ByRef = false;
12436 
12437   // Blocks are not allowed to capture arrays.
12438   if (CaptureType->isArrayType()) {
12439     if (BuildAndDiagnose) {
12440       S.Diag(Loc, diag::err_ref_array_type);
12441       S.Diag(Var->getLocation(), diag::note_previous_decl)
12442       << Var->getDeclName();
12443     }
12444     return false;
12445   }
12446 
12447   // Forbid the block-capture of autoreleasing variables.
12448   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12449     if (BuildAndDiagnose) {
12450       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
12451         << /*block*/ 0;
12452       S.Diag(Var->getLocation(), diag::note_previous_decl)
12453         << Var->getDeclName();
12454     }
12455     return false;
12456   }
12457   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
12458   if (HasBlocksAttr || CaptureType->isReferenceType()) {
12459     // Block capture by reference does not change the capture or
12460     // declaration reference types.
12461     ByRef = true;
12462   } else {
12463     // Block capture by copy introduces 'const'.
12464     CaptureType = CaptureType.getNonReferenceType().withConst();
12465     DeclRefType = CaptureType;
12466 
12467     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
12468       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
12469         // The capture logic needs the destructor, so make sure we mark it.
12470         // Usually this is unnecessary because most local variables have
12471         // their destructors marked at declaration time, but parameters are
12472         // an exception because it's technically only the call site that
12473         // actually requires the destructor.
12474         if (isa<ParmVarDecl>(Var))
12475           S.FinalizeVarWithDestructor(Var, Record);
12476 
12477         // Enter a new evaluation context to insulate the copy
12478         // full-expression.
12479         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
12480 
12481         // According to the blocks spec, the capture of a variable from
12482         // the stack requires a const copy constructor.  This is not true
12483         // of the copy/move done to move a __block variable to the heap.
12484         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
12485                                                   DeclRefType.withConst(),
12486                                                   VK_LValue, Loc);
12487 
12488         ExprResult Result
12489           = S.PerformCopyInitialization(
12490               InitializedEntity::InitializeBlock(Var->getLocation(),
12491                                                   CaptureType, false),
12492               Loc, DeclRef);
12493 
12494         // Build a full-expression copy expression if initialization
12495         // succeeded and used a non-trivial constructor.  Recover from
12496         // errors by pretending that the copy isn't necessary.
12497         if (!Result.isInvalid() &&
12498             !cast<CXXConstructExpr>(Result.get())->getConstructor()
12499                 ->isTrivial()) {
12500           Result = S.MaybeCreateExprWithCleanups(Result);
12501           CopyExpr = Result.get();
12502         }
12503       }
12504     }
12505   }
12506 
12507   // Actually capture the variable.
12508   if (BuildAndDiagnose)
12509     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
12510                     SourceLocation(), CaptureType, CopyExpr);
12511 
12512   return true;
12513 
12514 }
12515 
12516 
12517 /// \brief Capture the given variable in the captured region.
12518 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
12519                                     VarDecl *Var,
12520                                     SourceLocation Loc,
12521                                     const bool BuildAndDiagnose,
12522                                     QualType &CaptureType,
12523                                     QualType &DeclRefType,
12524                                     const bool RefersToCapturedVariable,
12525                                     Sema &S) {
12526 
12527   // By default, capture variables by reference.
12528   bool ByRef = true;
12529   // Using an LValue reference type is consistent with Lambdas (see below).
12530   CaptureType = S.Context.getLValueReferenceType(DeclRefType);
12531   Expr *CopyExpr = nullptr;
12532   if (BuildAndDiagnose) {
12533     // The current implementation assumes that all variables are captured
12534     // by references. Since there is no capture by copy, no expression
12535     // evaluation will be needed.
12536     RecordDecl *RD = RSI->TheRecordDecl;
12537 
12538     FieldDecl *Field
12539       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
12540                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
12541                           nullptr, false, ICIS_NoInit);
12542     Field->setImplicit(true);
12543     Field->setAccess(AS_private);
12544     RD->addDecl(Field);
12545 
12546     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
12547                                             DeclRefType, VK_LValue, Loc);
12548     Var->setReferenced(true);
12549     Var->markUsed(S.Context);
12550   }
12551 
12552   // Actually capture the variable.
12553   if (BuildAndDiagnose)
12554     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
12555                     SourceLocation(), CaptureType, CopyExpr);
12556 
12557 
12558   return true;
12559 }
12560 
12561 /// \brief Create a field within the lambda class for the variable
12562 /// being captured.
12563 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, VarDecl *Var,
12564                                     QualType FieldType, QualType DeclRefType,
12565                                     SourceLocation Loc,
12566                                     bool RefersToCapturedVariable) {
12567   CXXRecordDecl *Lambda = LSI->Lambda;
12568 
12569   // Build the non-static data member.
12570   FieldDecl *Field
12571     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
12572                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
12573                         nullptr, false, ICIS_NoInit);
12574   Field->setImplicit(true);
12575   Field->setAccess(AS_private);
12576   Lambda->addDecl(Field);
12577 }
12578 
12579 /// \brief Capture the given variable in the lambda.
12580 static bool captureInLambda(LambdaScopeInfo *LSI,
12581                             VarDecl *Var,
12582                             SourceLocation Loc,
12583                             const bool BuildAndDiagnose,
12584                             QualType &CaptureType,
12585                             QualType &DeclRefType,
12586                             const bool RefersToCapturedVariable,
12587                             const Sema::TryCaptureKind Kind,
12588                             SourceLocation EllipsisLoc,
12589                             const bool IsTopScope,
12590                             Sema &S) {
12591 
12592   // Determine whether we are capturing by reference or by value.
12593   bool ByRef = false;
12594   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
12595     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
12596   } else {
12597     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
12598   }
12599 
12600   // Compute the type of the field that will capture this variable.
12601   if (ByRef) {
12602     // C++11 [expr.prim.lambda]p15:
12603     //   An entity is captured by reference if it is implicitly or
12604     //   explicitly captured but not captured by copy. It is
12605     //   unspecified whether additional unnamed non-static data
12606     //   members are declared in the closure type for entities
12607     //   captured by reference.
12608     //
12609     // FIXME: It is not clear whether we want to build an lvalue reference
12610     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
12611     // to do the former, while EDG does the latter. Core issue 1249 will
12612     // clarify, but for now we follow GCC because it's a more permissive and
12613     // easily defensible position.
12614     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
12615   } else {
12616     // C++11 [expr.prim.lambda]p14:
12617     //   For each entity captured by copy, an unnamed non-static
12618     //   data member is declared in the closure type. The
12619     //   declaration order of these members is unspecified. The type
12620     //   of such a data member is the type of the corresponding
12621     //   captured entity if the entity is not a reference to an
12622     //   object, or the referenced type otherwise. [Note: If the
12623     //   captured entity is a reference to a function, the
12624     //   corresponding data member is also a reference to a
12625     //   function. - end note ]
12626     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
12627       if (!RefType->getPointeeType()->isFunctionType())
12628         CaptureType = RefType->getPointeeType();
12629     }
12630 
12631     // Forbid the lambda copy-capture of autoreleasing variables.
12632     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12633       if (BuildAndDiagnose) {
12634         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
12635         S.Diag(Var->getLocation(), diag::note_previous_decl)
12636           << Var->getDeclName();
12637       }
12638       return false;
12639     }
12640 
12641     // Make sure that by-copy captures are of a complete and non-abstract type.
12642     if (BuildAndDiagnose) {
12643       if (!CaptureType->isDependentType() &&
12644           S.RequireCompleteType(Loc, CaptureType,
12645                                 diag::err_capture_of_incomplete_type,
12646                                 Var->getDeclName()))
12647         return false;
12648 
12649       if (S.RequireNonAbstractType(Loc, CaptureType,
12650                                    diag::err_capture_of_abstract_type))
12651         return false;
12652     }
12653   }
12654 
12655   // Capture this variable in the lambda.
12656   if (BuildAndDiagnose)
12657     addAsFieldToClosureType(S, LSI, Var, CaptureType, DeclRefType, Loc,
12658                             RefersToCapturedVariable);
12659 
12660   // Compute the type of a reference to this captured variable.
12661   if (ByRef)
12662     DeclRefType = CaptureType.getNonReferenceType();
12663   else {
12664     // C++ [expr.prim.lambda]p5:
12665     //   The closure type for a lambda-expression has a public inline
12666     //   function call operator [...]. This function call operator is
12667     //   declared const (9.3.1) if and only if the lambda-expression’s
12668     //   parameter-declaration-clause is not followed by mutable.
12669     DeclRefType = CaptureType.getNonReferenceType();
12670     if (!LSI->Mutable && !CaptureType->isReferenceType())
12671       DeclRefType.addConst();
12672   }
12673 
12674   // Add the capture.
12675   if (BuildAndDiagnose)
12676     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
12677                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
12678 
12679   return true;
12680 }
12681 
12682 bool Sema::tryCaptureVariable(
12683     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
12684     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
12685     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
12686   // An init-capture is notionally from the context surrounding its
12687   // declaration, but its parent DC is the lambda class.
12688   DeclContext *VarDC = Var->getDeclContext();
12689   if (Var->isInitCapture())
12690     VarDC = VarDC->getParent();
12691 
12692   DeclContext *DC = CurContext;
12693   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
12694       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
12695   // We need to sync up the Declaration Context with the
12696   // FunctionScopeIndexToStopAt
12697   if (FunctionScopeIndexToStopAt) {
12698     unsigned FSIndex = FunctionScopes.size() - 1;
12699     while (FSIndex != MaxFunctionScopesIndex) {
12700       DC = getLambdaAwareParentOfDeclContext(DC);
12701       --FSIndex;
12702     }
12703   }
12704 
12705 
12706   // If the variable is declared in the current context, there is no need to
12707   // capture it.
12708   if (VarDC == DC) return true;
12709 
12710   // Capture global variables if it is required to use private copy of this
12711   // variable.
12712   bool IsGlobal = !Var->hasLocalStorage();
12713   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var)))
12714     return true;
12715 
12716   // Walk up the stack to determine whether we can capture the variable,
12717   // performing the "simple" checks that don't depend on type. We stop when
12718   // we've either hit the declared scope of the variable or find an existing
12719   // capture of that variable.  We start from the innermost capturing-entity
12720   // (the DC) and ensure that all intervening capturing-entities
12721   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
12722   // declcontext can either capture the variable or have already captured
12723   // the variable.
12724   CaptureType = Var->getType();
12725   DeclRefType = CaptureType.getNonReferenceType();
12726   bool Nested = false;
12727   bool Explicit = (Kind != TryCapture_Implicit);
12728   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
12729   do {
12730     // Only block literals, captured statements, and lambda expressions can
12731     // capture; other scopes don't work.
12732     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
12733                                                               ExprLoc,
12734                                                               BuildAndDiagnose,
12735                                                               *this);
12736     // We need to check for the parent *first* because, if we *have*
12737     // private-captured a global variable, we need to recursively capture it in
12738     // intermediate blocks, lambdas, etc.
12739     if (!ParentDC) {
12740       if (IsGlobal) {
12741         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
12742         break;
12743       }
12744       return true;
12745     }
12746 
12747     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
12748     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
12749 
12750 
12751     // Check whether we've already captured it.
12752     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
12753                                              DeclRefType))
12754       break;
12755     // If we are instantiating a generic lambda call operator body,
12756     // we do not want to capture new variables.  What was captured
12757     // during either a lambdas transformation or initial parsing
12758     // should be used.
12759     if (isGenericLambdaCallOperatorSpecialization(DC)) {
12760       if (BuildAndDiagnose) {
12761         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12762         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
12763           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12764           Diag(Var->getLocation(), diag::note_previous_decl)
12765              << Var->getDeclName();
12766           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
12767         } else
12768           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
12769       }
12770       return true;
12771     }
12772     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
12773     // certain types of variables (unnamed, variably modified types etc.)
12774     // so check for eligibility.
12775     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
12776        return true;
12777 
12778     // Try to capture variable-length arrays types.
12779     if (Var->getType()->isVariablyModifiedType()) {
12780       // We're going to walk down into the type and look for VLA
12781       // expressions.
12782       QualType QTy = Var->getType();
12783       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
12784         QTy = PVD->getOriginalType();
12785       do {
12786         const Type *Ty = QTy.getTypePtr();
12787         switch (Ty->getTypeClass()) {
12788 #define TYPE(Class, Base)
12789 #define ABSTRACT_TYPE(Class, Base)
12790 #define NON_CANONICAL_TYPE(Class, Base)
12791 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
12792 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
12793 #include "clang/AST/TypeNodes.def"
12794           QTy = QualType();
12795           break;
12796         // These types are never variably-modified.
12797         case Type::Builtin:
12798         case Type::Complex:
12799         case Type::Vector:
12800         case Type::ExtVector:
12801         case Type::Record:
12802         case Type::Enum:
12803         case Type::Elaborated:
12804         case Type::TemplateSpecialization:
12805         case Type::ObjCObject:
12806         case Type::ObjCInterface:
12807         case Type::ObjCObjectPointer:
12808           llvm_unreachable("type class is never variably-modified!");
12809         case Type::Adjusted:
12810           QTy = cast<AdjustedType>(Ty)->getOriginalType();
12811           break;
12812         case Type::Decayed:
12813           QTy = cast<DecayedType>(Ty)->getPointeeType();
12814           break;
12815         case Type::Pointer:
12816           QTy = cast<PointerType>(Ty)->getPointeeType();
12817           break;
12818         case Type::BlockPointer:
12819           QTy = cast<BlockPointerType>(Ty)->getPointeeType();
12820           break;
12821         case Type::LValueReference:
12822         case Type::RValueReference:
12823           QTy = cast<ReferenceType>(Ty)->getPointeeType();
12824           break;
12825         case Type::MemberPointer:
12826           QTy = cast<MemberPointerType>(Ty)->getPointeeType();
12827           break;
12828         case Type::ConstantArray:
12829         case Type::IncompleteArray:
12830           // Losing element qualification here is fine.
12831           QTy = cast<ArrayType>(Ty)->getElementType();
12832           break;
12833         case Type::VariableArray: {
12834           // Losing element qualification here is fine.
12835           const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
12836 
12837           // Unknown size indication requires no size computation.
12838           // Otherwise, evaluate and record it.
12839           if (auto Size = VAT->getSizeExpr()) {
12840             if (!CSI->isVLATypeCaptured(VAT)) {
12841               RecordDecl *CapRecord = nullptr;
12842               if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
12843                 CapRecord = LSI->Lambda;
12844               } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
12845                 CapRecord = CRSI->TheRecordDecl;
12846               }
12847               if (CapRecord) {
12848                 auto ExprLoc = Size->getExprLoc();
12849                 auto SizeType = Context.getSizeType();
12850                 // Build the non-static data member.
12851                 auto Field = FieldDecl::Create(
12852                     Context, CapRecord, ExprLoc, ExprLoc,
12853                     /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
12854                     /*BW*/ nullptr, /*Mutable*/ false,
12855                     /*InitStyle*/ ICIS_NoInit);
12856                 Field->setImplicit(true);
12857                 Field->setAccess(AS_private);
12858                 Field->setCapturedVLAType(VAT);
12859                 CapRecord->addDecl(Field);
12860 
12861                 CSI->addVLATypeCapture(ExprLoc, SizeType);
12862               }
12863             }
12864           }
12865           QTy = VAT->getElementType();
12866           break;
12867         }
12868         case Type::FunctionProto:
12869         case Type::FunctionNoProto:
12870           QTy = cast<FunctionType>(Ty)->getReturnType();
12871           break;
12872         case Type::Paren:
12873         case Type::TypeOf:
12874         case Type::UnaryTransform:
12875         case Type::Attributed:
12876         case Type::SubstTemplateTypeParm:
12877         case Type::PackExpansion:
12878           // Keep walking after single level desugaring.
12879           QTy = QTy.getSingleStepDesugaredType(getASTContext());
12880           break;
12881         case Type::Typedef:
12882           QTy = cast<TypedefType>(Ty)->desugar();
12883           break;
12884         case Type::Decltype:
12885           QTy = cast<DecltypeType>(Ty)->desugar();
12886           break;
12887         case Type::Auto:
12888           QTy = cast<AutoType>(Ty)->getDeducedType();
12889           break;
12890         case Type::TypeOfExpr:
12891           QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
12892           break;
12893         case Type::Atomic:
12894           QTy = cast<AtomicType>(Ty)->getValueType();
12895           break;
12896         }
12897       } while (!QTy.isNull() && QTy->isVariablyModifiedType());
12898     }
12899 
12900     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
12901       // No capture-default, and this is not an explicit capture
12902       // so cannot capture this variable.
12903       if (BuildAndDiagnose) {
12904         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12905         Diag(Var->getLocation(), diag::note_previous_decl)
12906           << Var->getDeclName();
12907         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
12908              diag::note_lambda_decl);
12909         // FIXME: If we error out because an outer lambda can not implicitly
12910         // capture a variable that an inner lambda explicitly captures, we
12911         // should have the inner lambda do the explicit capture - because
12912         // it makes for cleaner diagnostics later.  This would purely be done
12913         // so that the diagnostic does not misleadingly claim that a variable
12914         // can not be captured by a lambda implicitly even though it is captured
12915         // explicitly.  Suggestion:
12916         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
12917         //    at the function head
12918         //  - cache the StartingDeclContext - this must be a lambda
12919         //  - captureInLambda in the innermost lambda the variable.
12920       }
12921       return true;
12922     }
12923 
12924     FunctionScopesIndex--;
12925     DC = ParentDC;
12926     Explicit = false;
12927   } while (!VarDC->Equals(DC));
12928 
12929   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
12930   // computing the type of the capture at each step, checking type-specific
12931   // requirements, and adding captures if requested.
12932   // If the variable had already been captured previously, we start capturing
12933   // at the lambda nested within that one.
12934   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
12935        ++I) {
12936     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
12937 
12938     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
12939       if (!captureInBlock(BSI, Var, ExprLoc,
12940                           BuildAndDiagnose, CaptureType,
12941                           DeclRefType, Nested, *this))
12942         return true;
12943       Nested = true;
12944     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
12945       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
12946                                    BuildAndDiagnose, CaptureType,
12947                                    DeclRefType, Nested, *this))
12948         return true;
12949       Nested = true;
12950     } else {
12951       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12952       if (!captureInLambda(LSI, Var, ExprLoc,
12953                            BuildAndDiagnose, CaptureType,
12954                            DeclRefType, Nested, Kind, EllipsisLoc,
12955                             /*IsTopScope*/I == N - 1, *this))
12956         return true;
12957       Nested = true;
12958     }
12959   }
12960   return false;
12961 }
12962 
12963 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
12964                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
12965   QualType CaptureType;
12966   QualType DeclRefType;
12967   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
12968                             /*BuildAndDiagnose=*/true, CaptureType,
12969                             DeclRefType, nullptr);
12970 }
12971 
12972 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
12973   QualType CaptureType;
12974   QualType DeclRefType;
12975   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
12976                              /*BuildAndDiagnose=*/false, CaptureType,
12977                              DeclRefType, nullptr);
12978 }
12979 
12980 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
12981   QualType CaptureType;
12982   QualType DeclRefType;
12983 
12984   // Determine whether we can capture this variable.
12985   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
12986                          /*BuildAndDiagnose=*/false, CaptureType,
12987                          DeclRefType, nullptr))
12988     return QualType();
12989 
12990   return DeclRefType;
12991 }
12992 
12993 
12994 
12995 // If either the type of the variable or the initializer is dependent,
12996 // return false. Otherwise, determine whether the variable is a constant
12997 // expression. Use this if you need to know if a variable that might or
12998 // might not be dependent is truly a constant expression.
12999 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
13000     ASTContext &Context) {
13001 
13002   if (Var->getType()->isDependentType())
13003     return false;
13004   const VarDecl *DefVD = nullptr;
13005   Var->getAnyInitializer(DefVD);
13006   if (!DefVD)
13007     return false;
13008   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
13009   Expr *Init = cast<Expr>(Eval->Value);
13010   if (Init->isValueDependent())
13011     return false;
13012   return IsVariableAConstantExpression(Var, Context);
13013 }
13014 
13015 
13016 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
13017   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
13018   // an object that satisfies the requirements for appearing in a
13019   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
13020   // is immediately applied."  This function handles the lvalue-to-rvalue
13021   // conversion part.
13022   MaybeODRUseExprs.erase(E->IgnoreParens());
13023 
13024   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
13025   // to a variable that is a constant expression, and if so, identify it as
13026   // a reference to a variable that does not involve an odr-use of that
13027   // variable.
13028   if (LambdaScopeInfo *LSI = getCurLambda()) {
13029     Expr *SansParensExpr = E->IgnoreParens();
13030     VarDecl *Var = nullptr;
13031     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
13032       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
13033     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
13034       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
13035 
13036     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
13037       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
13038   }
13039 }
13040 
13041 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
13042   Res = CorrectDelayedTyposInExpr(Res);
13043 
13044   if (!Res.isUsable())
13045     return Res;
13046 
13047   // If a constant-expression is a reference to a variable where we delay
13048   // deciding whether it is an odr-use, just assume we will apply the
13049   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
13050   // (a non-type template argument), we have special handling anyway.
13051   UpdateMarkingForLValueToRValue(Res.get());
13052   return Res;
13053 }
13054 
13055 void Sema::CleanupVarDeclMarking() {
13056   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
13057                                         e = MaybeODRUseExprs.end();
13058        i != e; ++i) {
13059     VarDecl *Var;
13060     SourceLocation Loc;
13061     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
13062       Var = cast<VarDecl>(DRE->getDecl());
13063       Loc = DRE->getLocation();
13064     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
13065       Var = cast<VarDecl>(ME->getMemberDecl());
13066       Loc = ME->getMemberLoc();
13067     } else {
13068       llvm_unreachable("Unexpected expression");
13069     }
13070 
13071     MarkVarDeclODRUsed(Var, Loc, *this,
13072                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
13073   }
13074 
13075   MaybeODRUseExprs.clear();
13076 }
13077 
13078 
13079 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
13080                                     VarDecl *Var, Expr *E) {
13081   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
13082          "Invalid Expr argument to DoMarkVarDeclReferenced");
13083   Var->setReferenced();
13084 
13085   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
13086   bool MarkODRUsed = true;
13087 
13088   // If the context is not potentially evaluated, this is not an odr-use and
13089   // does not trigger instantiation.
13090   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
13091     if (SemaRef.isUnevaluatedContext())
13092       return;
13093 
13094     // If we don't yet know whether this context is going to end up being an
13095     // evaluated context, and we're referencing a variable from an enclosing
13096     // scope, add a potential capture.
13097     //
13098     // FIXME: Is this necessary? These contexts are only used for default
13099     // arguments, where local variables can't be used.
13100     const bool RefersToEnclosingScope =
13101         (SemaRef.CurContext != Var->getDeclContext() &&
13102          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
13103     if (RefersToEnclosingScope) {
13104       if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
13105         // If a variable could potentially be odr-used, defer marking it so
13106         // until we finish analyzing the full expression for any
13107         // lvalue-to-rvalue
13108         // or discarded value conversions that would obviate odr-use.
13109         // Add it to the list of potential captures that will be analyzed
13110         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
13111         // unless the variable is a reference that was initialized by a constant
13112         // expression (this will never need to be captured or odr-used).
13113         assert(E && "Capture variable should be used in an expression.");
13114         if (!Var->getType()->isReferenceType() ||
13115             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
13116           LSI->addPotentialCapture(E->IgnoreParens());
13117       }
13118     }
13119 
13120     if (!isTemplateInstantiation(TSK))
13121     	return;
13122 
13123     // Instantiate, but do not mark as odr-used, variable templates.
13124     MarkODRUsed = false;
13125   }
13126 
13127   VarTemplateSpecializationDecl *VarSpec =
13128       dyn_cast<VarTemplateSpecializationDecl>(Var);
13129   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
13130          "Can't instantiate a partial template specialization.");
13131 
13132   // Perform implicit instantiation of static data members, static data member
13133   // templates of class templates, and variable template specializations. Delay
13134   // instantiations of variable templates, except for those that could be used
13135   // in a constant expression.
13136   if (isTemplateInstantiation(TSK)) {
13137     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
13138 
13139     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
13140       if (Var->getPointOfInstantiation().isInvalid()) {
13141         // This is a modification of an existing AST node. Notify listeners.
13142         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
13143           L->StaticDataMemberInstantiated(Var);
13144       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
13145         // Don't bother trying to instantiate it again, unless we might need
13146         // its initializer before we get to the end of the TU.
13147         TryInstantiating = false;
13148     }
13149 
13150     if (Var->getPointOfInstantiation().isInvalid())
13151       Var->setTemplateSpecializationKind(TSK, Loc);
13152 
13153     if (TryInstantiating) {
13154       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
13155       bool InstantiationDependent = false;
13156       bool IsNonDependent =
13157           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
13158                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
13159                   : true;
13160 
13161       // Do not instantiate specializations that are still type-dependent.
13162       if (IsNonDependent) {
13163         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
13164           // Do not defer instantiations of variables which could be used in a
13165           // constant expression.
13166           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
13167         } else {
13168           SemaRef.PendingInstantiations
13169               .push_back(std::make_pair(Var, PointOfInstantiation));
13170         }
13171       }
13172     }
13173   }
13174 
13175   if(!MarkODRUsed) return;
13176 
13177   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
13178   // the requirements for appearing in a constant expression (5.19) and, if
13179   // it is an object, the lvalue-to-rvalue conversion (4.1)
13180   // is immediately applied."  We check the first part here, and
13181   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
13182   // Note that we use the C++11 definition everywhere because nothing in
13183   // C++03 depends on whether we get the C++03 version correct. The second
13184   // part does not apply to references, since they are not objects.
13185   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
13186     // A reference initialized by a constant expression can never be
13187     // odr-used, so simply ignore it.
13188     if (!Var->getType()->isReferenceType())
13189       SemaRef.MaybeODRUseExprs.insert(E);
13190   } else
13191     MarkVarDeclODRUsed(Var, Loc, SemaRef,
13192                        /*MaxFunctionScopeIndex ptr*/ nullptr);
13193 }
13194 
13195 /// \brief Mark a variable referenced, and check whether it is odr-used
13196 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
13197 /// used directly for normal expressions referring to VarDecl.
13198 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
13199   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
13200 }
13201 
13202 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
13203                                Decl *D, Expr *E, bool OdrUse) {
13204   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
13205     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
13206     return;
13207   }
13208 
13209   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
13210 
13211   // If this is a call to a method via a cast, also mark the method in the
13212   // derived class used in case codegen can devirtualize the call.
13213   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13214   if (!ME)
13215     return;
13216   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
13217   if (!MD)
13218     return;
13219   // Only attempt to devirtualize if this is truly a virtual call.
13220   bool IsVirtualCall = MD->isVirtual() && !ME->hasQualifier();
13221   if (!IsVirtualCall)
13222     return;
13223   const Expr *Base = ME->getBase();
13224   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
13225   if (!MostDerivedClassDecl)
13226     return;
13227   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
13228   if (!DM || DM->isPure())
13229     return;
13230   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
13231 }
13232 
13233 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
13234 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
13235   // TODO: update this with DR# once a defect report is filed.
13236   // C++11 defect. The address of a pure member should not be an ODR use, even
13237   // if it's a qualified reference.
13238   bool OdrUse = true;
13239   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
13240     if (Method->isVirtual())
13241       OdrUse = false;
13242   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
13243 }
13244 
13245 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
13246 void Sema::MarkMemberReferenced(MemberExpr *E) {
13247   // C++11 [basic.def.odr]p2:
13248   //   A non-overloaded function whose name appears as a potentially-evaluated
13249   //   expression or a member of a set of candidate functions, if selected by
13250   //   overload resolution when referred to from a potentially-evaluated
13251   //   expression, is odr-used, unless it is a pure virtual function and its
13252   //   name is not explicitly qualified.
13253   bool OdrUse = true;
13254   if (!E->hasQualifier()) {
13255     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
13256       if (Method->isPure())
13257         OdrUse = false;
13258   }
13259   SourceLocation Loc = E->getMemberLoc().isValid() ?
13260                             E->getMemberLoc() : E->getLocStart();
13261   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
13262 }
13263 
13264 /// \brief Perform marking for a reference to an arbitrary declaration.  It
13265 /// marks the declaration referenced, and performs odr-use checking for
13266 /// functions and variables. This method should not be used when building a
13267 /// normal expression which refers to a variable.
13268 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
13269   if (OdrUse) {
13270     if (auto *VD = dyn_cast<VarDecl>(D)) {
13271       MarkVariableReferenced(Loc, VD);
13272       return;
13273     }
13274   }
13275   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
13276     MarkFunctionReferenced(Loc, FD, OdrUse);
13277     return;
13278   }
13279   D->setReferenced();
13280 }
13281 
13282 namespace {
13283   // Mark all of the declarations referenced
13284   // FIXME: Not fully implemented yet! We need to have a better understanding
13285   // of when we're entering
13286   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
13287     Sema &S;
13288     SourceLocation Loc;
13289 
13290   public:
13291     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
13292 
13293     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
13294 
13295     bool TraverseTemplateArgument(const TemplateArgument &Arg);
13296     bool TraverseRecordType(RecordType *T);
13297   };
13298 }
13299 
13300 bool MarkReferencedDecls::TraverseTemplateArgument(
13301     const TemplateArgument &Arg) {
13302   if (Arg.getKind() == TemplateArgument::Declaration) {
13303     if (Decl *D = Arg.getAsDecl())
13304       S.MarkAnyDeclReferenced(Loc, D, true);
13305   }
13306 
13307   return Inherited::TraverseTemplateArgument(Arg);
13308 }
13309 
13310 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
13311   if (ClassTemplateSpecializationDecl *Spec
13312                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
13313     const TemplateArgumentList &Args = Spec->getTemplateArgs();
13314     return TraverseTemplateArguments(Args.data(), Args.size());
13315   }
13316 
13317   return true;
13318 }
13319 
13320 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
13321   MarkReferencedDecls Marker(*this, Loc);
13322   Marker.TraverseType(Context.getCanonicalType(T));
13323 }
13324 
13325 namespace {
13326   /// \brief Helper class that marks all of the declarations referenced by
13327   /// potentially-evaluated subexpressions as "referenced".
13328   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
13329     Sema &S;
13330     bool SkipLocalVariables;
13331 
13332   public:
13333     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
13334 
13335     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
13336       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
13337 
13338     void VisitDeclRefExpr(DeclRefExpr *E) {
13339       // If we were asked not to visit local variables, don't.
13340       if (SkipLocalVariables) {
13341         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
13342           if (VD->hasLocalStorage())
13343             return;
13344       }
13345 
13346       S.MarkDeclRefReferenced(E);
13347     }
13348 
13349     void VisitMemberExpr(MemberExpr *E) {
13350       S.MarkMemberReferenced(E);
13351       Inherited::VisitMemberExpr(E);
13352     }
13353 
13354     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
13355       S.MarkFunctionReferenced(E->getLocStart(),
13356             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
13357       Visit(E->getSubExpr());
13358     }
13359 
13360     void VisitCXXNewExpr(CXXNewExpr *E) {
13361       if (E->getOperatorNew())
13362         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
13363       if (E->getOperatorDelete())
13364         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
13365       Inherited::VisitCXXNewExpr(E);
13366     }
13367 
13368     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
13369       if (E->getOperatorDelete())
13370         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
13371       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
13372       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
13373         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
13374         S.MarkFunctionReferenced(E->getLocStart(),
13375                                     S.LookupDestructor(Record));
13376       }
13377 
13378       Inherited::VisitCXXDeleteExpr(E);
13379     }
13380 
13381     void VisitCXXConstructExpr(CXXConstructExpr *E) {
13382       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
13383       Inherited::VisitCXXConstructExpr(E);
13384     }
13385 
13386     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
13387       Visit(E->getExpr());
13388     }
13389 
13390     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13391       Inherited::VisitImplicitCastExpr(E);
13392 
13393       if (E->getCastKind() == CK_LValueToRValue)
13394         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
13395     }
13396   };
13397 }
13398 
13399 /// \brief Mark any declarations that appear within this expression or any
13400 /// potentially-evaluated subexpressions as "referenced".
13401 ///
13402 /// \param SkipLocalVariables If true, don't mark local variables as
13403 /// 'referenced'.
13404 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
13405                                             bool SkipLocalVariables) {
13406   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
13407 }
13408 
13409 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
13410 /// of the program being compiled.
13411 ///
13412 /// This routine emits the given diagnostic when the code currently being
13413 /// type-checked is "potentially evaluated", meaning that there is a
13414 /// possibility that the code will actually be executable. Code in sizeof()
13415 /// expressions, code used only during overload resolution, etc., are not
13416 /// potentially evaluated. This routine will suppress such diagnostics or,
13417 /// in the absolutely nutty case of potentially potentially evaluated
13418 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
13419 /// later.
13420 ///
13421 /// This routine should be used for all diagnostics that describe the run-time
13422 /// behavior of a program, such as passing a non-POD value through an ellipsis.
13423 /// Failure to do so will likely result in spurious diagnostics or failures
13424 /// during overload resolution or within sizeof/alignof/typeof/typeid.
13425 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
13426                                const PartialDiagnostic &PD) {
13427   switch (ExprEvalContexts.back().Context) {
13428   case Unevaluated:
13429   case UnevaluatedAbstract:
13430     // The argument will never be evaluated, so don't complain.
13431     break;
13432 
13433   case ConstantEvaluated:
13434     // Relevant diagnostics should be produced by constant evaluation.
13435     break;
13436 
13437   case PotentiallyEvaluated:
13438   case PotentiallyEvaluatedIfUsed:
13439     if (Statement && getCurFunctionOrMethodDecl()) {
13440       FunctionScopes.back()->PossiblyUnreachableDiags.
13441         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
13442     }
13443     else
13444       Diag(Loc, PD);
13445 
13446     return true;
13447   }
13448 
13449   return false;
13450 }
13451 
13452 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
13453                                CallExpr *CE, FunctionDecl *FD) {
13454   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
13455     return false;
13456 
13457   // If we're inside a decltype's expression, don't check for a valid return
13458   // type or construct temporaries until we know whether this is the last call.
13459   if (ExprEvalContexts.back().IsDecltype) {
13460     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
13461     return false;
13462   }
13463 
13464   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
13465     FunctionDecl *FD;
13466     CallExpr *CE;
13467 
13468   public:
13469     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
13470       : FD(FD), CE(CE) { }
13471 
13472     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
13473       if (!FD) {
13474         S.Diag(Loc, diag::err_call_incomplete_return)
13475           << T << CE->getSourceRange();
13476         return;
13477       }
13478 
13479       S.Diag(Loc, diag::err_call_function_incomplete_return)
13480         << CE->getSourceRange() << FD->getDeclName() << T;
13481       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
13482           << FD->getDeclName();
13483     }
13484   } Diagnoser(FD, CE);
13485 
13486   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
13487     return true;
13488 
13489   return false;
13490 }
13491 
13492 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
13493 // will prevent this condition from triggering, which is what we want.
13494 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
13495   SourceLocation Loc;
13496 
13497   unsigned diagnostic = diag::warn_condition_is_assignment;
13498   bool IsOrAssign = false;
13499 
13500   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
13501     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
13502       return;
13503 
13504     IsOrAssign = Op->getOpcode() == BO_OrAssign;
13505 
13506     // Greylist some idioms by putting them into a warning subcategory.
13507     if (ObjCMessageExpr *ME
13508           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
13509       Selector Sel = ME->getSelector();
13510 
13511       // self = [<foo> init...]
13512       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
13513         diagnostic = diag::warn_condition_is_idiomatic_assignment;
13514 
13515       // <foo> = [<bar> nextObject]
13516       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
13517         diagnostic = diag::warn_condition_is_idiomatic_assignment;
13518     }
13519 
13520     Loc = Op->getOperatorLoc();
13521   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
13522     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
13523       return;
13524 
13525     IsOrAssign = Op->getOperator() == OO_PipeEqual;
13526     Loc = Op->getOperatorLoc();
13527   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
13528     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
13529   else {
13530     // Not an assignment.
13531     return;
13532   }
13533 
13534   Diag(Loc, diagnostic) << E->getSourceRange();
13535 
13536   SourceLocation Open = E->getLocStart();
13537   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
13538   Diag(Loc, diag::note_condition_assign_silence)
13539         << FixItHint::CreateInsertion(Open, "(")
13540         << FixItHint::CreateInsertion(Close, ")");
13541 
13542   if (IsOrAssign)
13543     Diag(Loc, diag::note_condition_or_assign_to_comparison)
13544       << FixItHint::CreateReplacement(Loc, "!=");
13545   else
13546     Diag(Loc, diag::note_condition_assign_to_comparison)
13547       << FixItHint::CreateReplacement(Loc, "==");
13548 }
13549 
13550 /// \brief Redundant parentheses over an equality comparison can indicate
13551 /// that the user intended an assignment used as condition.
13552 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
13553   // Don't warn if the parens came from a macro.
13554   SourceLocation parenLoc = ParenE->getLocStart();
13555   if (parenLoc.isInvalid() || parenLoc.isMacroID())
13556     return;
13557   // Don't warn for dependent expressions.
13558   if (ParenE->isTypeDependent())
13559     return;
13560 
13561   Expr *E = ParenE->IgnoreParens();
13562 
13563   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
13564     if (opE->getOpcode() == BO_EQ &&
13565         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
13566                                                            == Expr::MLV_Valid) {
13567       SourceLocation Loc = opE->getOperatorLoc();
13568 
13569       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
13570       SourceRange ParenERange = ParenE->getSourceRange();
13571       Diag(Loc, diag::note_equality_comparison_silence)
13572         << FixItHint::CreateRemoval(ParenERange.getBegin())
13573         << FixItHint::CreateRemoval(ParenERange.getEnd());
13574       Diag(Loc, diag::note_equality_comparison_to_assign)
13575         << FixItHint::CreateReplacement(Loc, "=");
13576     }
13577 }
13578 
13579 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
13580   DiagnoseAssignmentAsCondition(E);
13581   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
13582     DiagnoseEqualityWithExtraParens(parenE);
13583 
13584   ExprResult result = CheckPlaceholderExpr(E);
13585   if (result.isInvalid()) return ExprError();
13586   E = result.get();
13587 
13588   if (!E->isTypeDependent()) {
13589     if (getLangOpts().CPlusPlus)
13590       return CheckCXXBooleanCondition(E); // C++ 6.4p4
13591 
13592     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
13593     if (ERes.isInvalid())
13594       return ExprError();
13595     E = ERes.get();
13596 
13597     QualType T = E->getType();
13598     if (!T->isScalarType()) { // C99 6.8.4.1p1
13599       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
13600         << T << E->getSourceRange();
13601       return ExprError();
13602     }
13603     CheckBoolLikeConversion(E, Loc);
13604   }
13605 
13606   return E;
13607 }
13608 
13609 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
13610                                        Expr *SubExpr) {
13611   if (!SubExpr)
13612     return ExprError();
13613 
13614   return CheckBooleanCondition(SubExpr, Loc);
13615 }
13616 
13617 namespace {
13618   /// A visitor for rebuilding a call to an __unknown_any expression
13619   /// to have an appropriate type.
13620   struct RebuildUnknownAnyFunction
13621     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
13622 
13623     Sema &S;
13624 
13625     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
13626 
13627     ExprResult VisitStmt(Stmt *S) {
13628       llvm_unreachable("unexpected statement!");
13629     }
13630 
13631     ExprResult VisitExpr(Expr *E) {
13632       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
13633         << E->getSourceRange();
13634       return ExprError();
13635     }
13636 
13637     /// Rebuild an expression which simply semantically wraps another
13638     /// expression which it shares the type and value kind of.
13639     template <class T> ExprResult rebuildSugarExpr(T *E) {
13640       ExprResult SubResult = Visit(E->getSubExpr());
13641       if (SubResult.isInvalid()) return ExprError();
13642 
13643       Expr *SubExpr = SubResult.get();
13644       E->setSubExpr(SubExpr);
13645       E->setType(SubExpr->getType());
13646       E->setValueKind(SubExpr->getValueKind());
13647       assert(E->getObjectKind() == OK_Ordinary);
13648       return E;
13649     }
13650 
13651     ExprResult VisitParenExpr(ParenExpr *E) {
13652       return rebuildSugarExpr(E);
13653     }
13654 
13655     ExprResult VisitUnaryExtension(UnaryOperator *E) {
13656       return rebuildSugarExpr(E);
13657     }
13658 
13659     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
13660       ExprResult SubResult = Visit(E->getSubExpr());
13661       if (SubResult.isInvalid()) return ExprError();
13662 
13663       Expr *SubExpr = SubResult.get();
13664       E->setSubExpr(SubExpr);
13665       E->setType(S.Context.getPointerType(SubExpr->getType()));
13666       assert(E->getValueKind() == VK_RValue);
13667       assert(E->getObjectKind() == OK_Ordinary);
13668       return E;
13669     }
13670 
13671     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
13672       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
13673 
13674       E->setType(VD->getType());
13675 
13676       assert(E->getValueKind() == VK_RValue);
13677       if (S.getLangOpts().CPlusPlus &&
13678           !(isa<CXXMethodDecl>(VD) &&
13679             cast<CXXMethodDecl>(VD)->isInstance()))
13680         E->setValueKind(VK_LValue);
13681 
13682       return E;
13683     }
13684 
13685     ExprResult VisitMemberExpr(MemberExpr *E) {
13686       return resolveDecl(E, E->getMemberDecl());
13687     }
13688 
13689     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
13690       return resolveDecl(E, E->getDecl());
13691     }
13692   };
13693 }
13694 
13695 /// Given a function expression of unknown-any type, try to rebuild it
13696 /// to have a function type.
13697 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
13698   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
13699   if (Result.isInvalid()) return ExprError();
13700   return S.DefaultFunctionArrayConversion(Result.get());
13701 }
13702 
13703 namespace {
13704   /// A visitor for rebuilding an expression of type __unknown_anytype
13705   /// into one which resolves the type directly on the referring
13706   /// expression.  Strict preservation of the original source
13707   /// structure is not a goal.
13708   struct RebuildUnknownAnyExpr
13709     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
13710 
13711     Sema &S;
13712 
13713     /// The current destination type.
13714     QualType DestType;
13715 
13716     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
13717       : S(S), DestType(CastType) {}
13718 
13719     ExprResult VisitStmt(Stmt *S) {
13720       llvm_unreachable("unexpected statement!");
13721     }
13722 
13723     ExprResult VisitExpr(Expr *E) {
13724       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13725         << E->getSourceRange();
13726       return ExprError();
13727     }
13728 
13729     ExprResult VisitCallExpr(CallExpr *E);
13730     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
13731 
13732     /// Rebuild an expression which simply semantically wraps another
13733     /// expression which it shares the type and value kind of.
13734     template <class T> ExprResult rebuildSugarExpr(T *E) {
13735       ExprResult SubResult = Visit(E->getSubExpr());
13736       if (SubResult.isInvalid()) return ExprError();
13737       Expr *SubExpr = SubResult.get();
13738       E->setSubExpr(SubExpr);
13739       E->setType(SubExpr->getType());
13740       E->setValueKind(SubExpr->getValueKind());
13741       assert(E->getObjectKind() == OK_Ordinary);
13742       return E;
13743     }
13744 
13745     ExprResult VisitParenExpr(ParenExpr *E) {
13746       return rebuildSugarExpr(E);
13747     }
13748 
13749     ExprResult VisitUnaryExtension(UnaryOperator *E) {
13750       return rebuildSugarExpr(E);
13751     }
13752 
13753     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
13754       const PointerType *Ptr = DestType->getAs<PointerType>();
13755       if (!Ptr) {
13756         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
13757           << E->getSourceRange();
13758         return ExprError();
13759       }
13760       assert(E->getValueKind() == VK_RValue);
13761       assert(E->getObjectKind() == OK_Ordinary);
13762       E->setType(DestType);
13763 
13764       // Build the sub-expression as if it were an object of the pointee type.
13765       DestType = Ptr->getPointeeType();
13766       ExprResult SubResult = Visit(E->getSubExpr());
13767       if (SubResult.isInvalid()) return ExprError();
13768       E->setSubExpr(SubResult.get());
13769       return E;
13770     }
13771 
13772     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
13773 
13774     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
13775 
13776     ExprResult VisitMemberExpr(MemberExpr *E) {
13777       return resolveDecl(E, E->getMemberDecl());
13778     }
13779 
13780     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
13781       return resolveDecl(E, E->getDecl());
13782     }
13783   };
13784 }
13785 
13786 /// Rebuilds a call expression which yielded __unknown_anytype.
13787 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
13788   Expr *CalleeExpr = E->getCallee();
13789 
13790   enum FnKind {
13791     FK_MemberFunction,
13792     FK_FunctionPointer,
13793     FK_BlockPointer
13794   };
13795 
13796   FnKind Kind;
13797   QualType CalleeType = CalleeExpr->getType();
13798   if (CalleeType == S.Context.BoundMemberTy) {
13799     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
13800     Kind = FK_MemberFunction;
13801     CalleeType = Expr::findBoundMemberType(CalleeExpr);
13802   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
13803     CalleeType = Ptr->getPointeeType();
13804     Kind = FK_FunctionPointer;
13805   } else {
13806     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
13807     Kind = FK_BlockPointer;
13808   }
13809   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
13810 
13811   // Verify that this is a legal result type of a function.
13812   if (DestType->isArrayType() || DestType->isFunctionType()) {
13813     unsigned diagID = diag::err_func_returning_array_function;
13814     if (Kind == FK_BlockPointer)
13815       diagID = diag::err_block_returning_array_function;
13816 
13817     S.Diag(E->getExprLoc(), diagID)
13818       << DestType->isFunctionType() << DestType;
13819     return ExprError();
13820   }
13821 
13822   // Otherwise, go ahead and set DestType as the call's result.
13823   E->setType(DestType.getNonLValueExprType(S.Context));
13824   E->setValueKind(Expr::getValueKindForType(DestType));
13825   assert(E->getObjectKind() == OK_Ordinary);
13826 
13827   // Rebuild the function type, replacing the result type with DestType.
13828   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
13829   if (Proto) {
13830     // __unknown_anytype(...) is a special case used by the debugger when
13831     // it has no idea what a function's signature is.
13832     //
13833     // We want to build this call essentially under the K&R
13834     // unprototyped rules, but making a FunctionNoProtoType in C++
13835     // would foul up all sorts of assumptions.  However, we cannot
13836     // simply pass all arguments as variadic arguments, nor can we
13837     // portably just call the function under a non-variadic type; see
13838     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
13839     // However, it turns out that in practice it is generally safe to
13840     // call a function declared as "A foo(B,C,D);" under the prototype
13841     // "A foo(B,C,D,...);".  The only known exception is with the
13842     // Windows ABI, where any variadic function is implicitly cdecl
13843     // regardless of its normal CC.  Therefore we change the parameter
13844     // types to match the types of the arguments.
13845     //
13846     // This is a hack, but it is far superior to moving the
13847     // corresponding target-specific code from IR-gen to Sema/AST.
13848 
13849     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
13850     SmallVector<QualType, 8> ArgTypes;
13851     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
13852       ArgTypes.reserve(E->getNumArgs());
13853       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
13854         Expr *Arg = E->getArg(i);
13855         QualType ArgType = Arg->getType();
13856         if (E->isLValue()) {
13857           ArgType = S.Context.getLValueReferenceType(ArgType);
13858         } else if (E->isXValue()) {
13859           ArgType = S.Context.getRValueReferenceType(ArgType);
13860         }
13861         ArgTypes.push_back(ArgType);
13862       }
13863       ParamTypes = ArgTypes;
13864     }
13865     DestType = S.Context.getFunctionType(DestType, ParamTypes,
13866                                          Proto->getExtProtoInfo());
13867   } else {
13868     DestType = S.Context.getFunctionNoProtoType(DestType,
13869                                                 FnType->getExtInfo());
13870   }
13871 
13872   // Rebuild the appropriate pointer-to-function type.
13873   switch (Kind) {
13874   case FK_MemberFunction:
13875     // Nothing to do.
13876     break;
13877 
13878   case FK_FunctionPointer:
13879     DestType = S.Context.getPointerType(DestType);
13880     break;
13881 
13882   case FK_BlockPointer:
13883     DestType = S.Context.getBlockPointerType(DestType);
13884     break;
13885   }
13886 
13887   // Finally, we can recurse.
13888   ExprResult CalleeResult = Visit(CalleeExpr);
13889   if (!CalleeResult.isUsable()) return ExprError();
13890   E->setCallee(CalleeResult.get());
13891 
13892   // Bind a temporary if necessary.
13893   return S.MaybeBindToTemporary(E);
13894 }
13895 
13896 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
13897   // Verify that this is a legal result type of a call.
13898   if (DestType->isArrayType() || DestType->isFunctionType()) {
13899     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
13900       << DestType->isFunctionType() << DestType;
13901     return ExprError();
13902   }
13903 
13904   // Rewrite the method result type if available.
13905   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
13906     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
13907     Method->setReturnType(DestType);
13908   }
13909 
13910   // Change the type of the message.
13911   E->setType(DestType.getNonReferenceType());
13912   E->setValueKind(Expr::getValueKindForType(DestType));
13913 
13914   return S.MaybeBindToTemporary(E);
13915 }
13916 
13917 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
13918   // The only case we should ever see here is a function-to-pointer decay.
13919   if (E->getCastKind() == CK_FunctionToPointerDecay) {
13920     assert(E->getValueKind() == VK_RValue);
13921     assert(E->getObjectKind() == OK_Ordinary);
13922 
13923     E->setType(DestType);
13924 
13925     // Rebuild the sub-expression as the pointee (function) type.
13926     DestType = DestType->castAs<PointerType>()->getPointeeType();
13927 
13928     ExprResult Result = Visit(E->getSubExpr());
13929     if (!Result.isUsable()) return ExprError();
13930 
13931     E->setSubExpr(Result.get());
13932     return E;
13933   } else if (E->getCastKind() == CK_LValueToRValue) {
13934     assert(E->getValueKind() == VK_RValue);
13935     assert(E->getObjectKind() == OK_Ordinary);
13936 
13937     assert(isa<BlockPointerType>(E->getType()));
13938 
13939     E->setType(DestType);
13940 
13941     // The sub-expression has to be a lvalue reference, so rebuild it as such.
13942     DestType = S.Context.getLValueReferenceType(DestType);
13943 
13944     ExprResult Result = Visit(E->getSubExpr());
13945     if (!Result.isUsable()) return ExprError();
13946 
13947     E->setSubExpr(Result.get());
13948     return E;
13949   } else {
13950     llvm_unreachable("Unhandled cast type!");
13951   }
13952 }
13953 
13954 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
13955   ExprValueKind ValueKind = VK_LValue;
13956   QualType Type = DestType;
13957 
13958   // We know how to make this work for certain kinds of decls:
13959 
13960   //  - functions
13961   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
13962     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
13963       DestType = Ptr->getPointeeType();
13964       ExprResult Result = resolveDecl(E, VD);
13965       if (Result.isInvalid()) return ExprError();
13966       return S.ImpCastExprToType(Result.get(), Type,
13967                                  CK_FunctionToPointerDecay, VK_RValue);
13968     }
13969 
13970     if (!Type->isFunctionType()) {
13971       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
13972         << VD << E->getSourceRange();
13973       return ExprError();
13974     }
13975     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
13976       // We must match the FunctionDecl's type to the hack introduced in
13977       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
13978       // type. See the lengthy commentary in that routine.
13979       QualType FDT = FD->getType();
13980       const FunctionType *FnType = FDT->castAs<FunctionType>();
13981       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
13982       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13983       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
13984         SourceLocation Loc = FD->getLocation();
13985         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
13986                                       FD->getDeclContext(),
13987                                       Loc, Loc, FD->getNameInfo().getName(),
13988                                       DestType, FD->getTypeSourceInfo(),
13989                                       SC_None, false/*isInlineSpecified*/,
13990                                       FD->hasPrototype(),
13991                                       false/*isConstexprSpecified*/);
13992 
13993         if (FD->getQualifier())
13994           NewFD->setQualifierInfo(FD->getQualifierLoc());
13995 
13996         SmallVector<ParmVarDecl*, 16> Params;
13997         for (const auto &AI : FT->param_types()) {
13998           ParmVarDecl *Param =
13999             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
14000           Param->setScopeInfo(0, Params.size());
14001           Params.push_back(Param);
14002         }
14003         NewFD->setParams(Params);
14004         DRE->setDecl(NewFD);
14005         VD = DRE->getDecl();
14006       }
14007     }
14008 
14009     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
14010       if (MD->isInstance()) {
14011         ValueKind = VK_RValue;
14012         Type = S.Context.BoundMemberTy;
14013       }
14014 
14015     // Function references aren't l-values in C.
14016     if (!S.getLangOpts().CPlusPlus)
14017       ValueKind = VK_RValue;
14018 
14019   //  - variables
14020   } else if (isa<VarDecl>(VD)) {
14021     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
14022       Type = RefTy->getPointeeType();
14023     } else if (Type->isFunctionType()) {
14024       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
14025         << VD << E->getSourceRange();
14026       return ExprError();
14027     }
14028 
14029   //  - nothing else
14030   } else {
14031     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
14032       << VD << E->getSourceRange();
14033     return ExprError();
14034   }
14035 
14036   // Modifying the declaration like this is friendly to IR-gen but
14037   // also really dangerous.
14038   VD->setType(DestType);
14039   E->setType(Type);
14040   E->setValueKind(ValueKind);
14041   return E;
14042 }
14043 
14044 /// Check a cast of an unknown-any type.  We intentionally only
14045 /// trigger this for C-style casts.
14046 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
14047                                      Expr *CastExpr, CastKind &CastKind,
14048                                      ExprValueKind &VK, CXXCastPath &Path) {
14049   // Rewrite the casted expression from scratch.
14050   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
14051   if (!result.isUsable()) return ExprError();
14052 
14053   CastExpr = result.get();
14054   VK = CastExpr->getValueKind();
14055   CastKind = CK_NoOp;
14056 
14057   return CastExpr;
14058 }
14059 
14060 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
14061   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
14062 }
14063 
14064 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
14065                                     Expr *arg, QualType &paramType) {
14066   // If the syntactic form of the argument is not an explicit cast of
14067   // any sort, just do default argument promotion.
14068   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
14069   if (!castArg) {
14070     ExprResult result = DefaultArgumentPromotion(arg);
14071     if (result.isInvalid()) return ExprError();
14072     paramType = result.get()->getType();
14073     return result;
14074   }
14075 
14076   // Otherwise, use the type that was written in the explicit cast.
14077   assert(!arg->hasPlaceholderType());
14078   paramType = castArg->getTypeAsWritten();
14079 
14080   // Copy-initialize a parameter of that type.
14081   InitializedEntity entity =
14082     InitializedEntity::InitializeParameter(Context, paramType,
14083                                            /*consumed*/ false);
14084   return PerformCopyInitialization(entity, callLoc, arg);
14085 }
14086 
14087 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
14088   Expr *orig = E;
14089   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
14090   while (true) {
14091     E = E->IgnoreParenImpCasts();
14092     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
14093       E = call->getCallee();
14094       diagID = diag::err_uncasted_call_of_unknown_any;
14095     } else {
14096       break;
14097     }
14098   }
14099 
14100   SourceLocation loc;
14101   NamedDecl *d;
14102   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
14103     loc = ref->getLocation();
14104     d = ref->getDecl();
14105   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
14106     loc = mem->getMemberLoc();
14107     d = mem->getMemberDecl();
14108   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
14109     diagID = diag::err_uncasted_call_of_unknown_any;
14110     loc = msg->getSelectorStartLoc();
14111     d = msg->getMethodDecl();
14112     if (!d) {
14113       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
14114         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
14115         << orig->getSourceRange();
14116       return ExprError();
14117     }
14118   } else {
14119     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14120       << E->getSourceRange();
14121     return ExprError();
14122   }
14123 
14124   S.Diag(loc, diagID) << d << orig->getSourceRange();
14125 
14126   // Never recoverable.
14127   return ExprError();
14128 }
14129 
14130 /// Check for operands with placeholder types and complain if found.
14131 /// Returns true if there was an error and no recovery was possible.
14132 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
14133   if (!getLangOpts().CPlusPlus) {
14134     // C cannot handle TypoExpr nodes on either side of a binop because it
14135     // doesn't handle dependent types properly, so make sure any TypoExprs have
14136     // been dealt with before checking the operands.
14137     ExprResult Result = CorrectDelayedTyposInExpr(E);
14138     if (!Result.isUsable()) return ExprError();
14139     E = Result.get();
14140   }
14141 
14142   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
14143   if (!placeholderType) return E;
14144 
14145   switch (placeholderType->getKind()) {
14146 
14147   // Overloaded expressions.
14148   case BuiltinType::Overload: {
14149     // Try to resolve a single function template specialization.
14150     // This is obligatory.
14151     ExprResult result = E;
14152     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
14153       return result;
14154 
14155     // If that failed, try to recover with a call.
14156     } else {
14157       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
14158                            /*complain*/ true);
14159       return result;
14160     }
14161   }
14162 
14163   // Bound member functions.
14164   case BuiltinType::BoundMember: {
14165     ExprResult result = E;
14166     const Expr *BME = E->IgnoreParens();
14167     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
14168     // Try to give a nicer diagnostic if it is a bound member that we recognize.
14169     if (isa<CXXPseudoDestructorExpr>(BME)) {
14170       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
14171     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
14172       if (ME->getMemberNameInfo().getName().getNameKind() ==
14173           DeclarationName::CXXDestructorName)
14174         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
14175     }
14176     tryToRecoverWithCall(result, PD,
14177                          /*complain*/ true);
14178     return result;
14179   }
14180 
14181   // ARC unbridged casts.
14182   case BuiltinType::ARCUnbridgedCast: {
14183     Expr *realCast = stripARCUnbridgedCast(E);
14184     diagnoseARCUnbridgedCast(realCast);
14185     return realCast;
14186   }
14187 
14188   // Expressions of unknown type.
14189   case BuiltinType::UnknownAny:
14190     return diagnoseUnknownAnyExpr(*this, E);
14191 
14192   // Pseudo-objects.
14193   case BuiltinType::PseudoObject:
14194     return checkPseudoObjectRValue(E);
14195 
14196   case BuiltinType::BuiltinFn: {
14197     // Accept __noop without parens by implicitly converting it to a call expr.
14198     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
14199     if (DRE) {
14200       auto *FD = cast<FunctionDecl>(DRE->getDecl());
14201       if (FD->getBuiltinID() == Builtin::BI__noop) {
14202         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
14203                               CK_BuiltinFnToFnPtr).get();
14204         return new (Context) CallExpr(Context, E, None, Context.IntTy,
14205                                       VK_RValue, SourceLocation());
14206       }
14207     }
14208 
14209     Diag(E->getLocStart(), diag::err_builtin_fn_use);
14210     return ExprError();
14211   }
14212 
14213   // Everything else should be impossible.
14214 #define BUILTIN_TYPE(Id, SingletonId) \
14215   case BuiltinType::Id:
14216 #define PLACEHOLDER_TYPE(Id, SingletonId)
14217 #include "clang/AST/BuiltinTypes.def"
14218     break;
14219   }
14220 
14221   llvm_unreachable("invalid placeholder type!");
14222 }
14223 
14224 bool Sema::CheckCaseExpression(Expr *E) {
14225   if (E->isTypeDependent())
14226     return true;
14227   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
14228     return E->getType()->isIntegralOrEnumerationType();
14229   return false;
14230 }
14231 
14232 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
14233 ExprResult
14234 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
14235   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
14236          "Unknown Objective-C Boolean value!");
14237   QualType BoolT = Context.ObjCBuiltinBoolTy;
14238   if (!Context.getBOOLDecl()) {
14239     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
14240                         Sema::LookupOrdinaryName);
14241     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
14242       NamedDecl *ND = Result.getFoundDecl();
14243       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
14244         Context.setBOOLDecl(TD);
14245     }
14246   }
14247   if (Context.getBOOLDecl())
14248     BoolT = Context.getBOOLType();
14249   return new (Context)
14250       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
14251 }
14252