1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements extra semantic analysis beyond what is enforced
10 //  by the C type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/FormatString.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/NonTrivialTypeVisitor.h"
32 #include "clang/AST/OperationKinds.h"
33 #include "clang/AST/RecordLayout.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/TypeLoc.h"
38 #include "clang/AST/UnresolvedSet.h"
39 #include "clang/Basic/AddressSpaces.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetBuiltins.h"
53 #include "clang/Basic/TargetCXXABI.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/TypeTraits.h"
56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Initialization.h"
58 #include "clang/Sema/Lookup.h"
59 #include "clang/Sema/Ownership.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/ScopeInfo.h"
62 #include "clang/Sema/Sema.h"
63 #include "clang/Sema/SemaInternal.h"
64 #include "llvm/ADT/APFloat.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/FoldingSet.h"
70 #include "llvm/ADT/None.h"
71 #include "llvm/ADT/Optional.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/ADT/StringSet.h"
79 #include "llvm/ADT/StringSwitch.h"
80 #include "llvm/ADT/Triple.h"
81 #include "llvm/Support/AtomicOrdering.h"
82 #include "llvm/Support/Casting.h"
83 #include "llvm/Support/Compiler.h"
84 #include "llvm/Support/ConvertUTF.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/Format.h"
87 #include "llvm/Support/Locale.h"
88 #include "llvm/Support/MathExtras.h"
89 #include "llvm/Support/SaveAndRestore.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include <algorithm>
92 #include <bitset>
93 #include <cassert>
94 #include <cctype>
95 #include <cstddef>
96 #include <cstdint>
97 #include <functional>
98 #include <limits>
99 #include <string>
100 #include <tuple>
101 #include <utility>
102 
103 using namespace clang;
104 using namespace sema;
105 
106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
107                                                     unsigned ByteNo) const {
108   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
109                                Context.getTargetInfo());
110 }
111 
112 /// Checks that a call expression's argument count is the desired number.
113 /// This is useful when doing custom type-checking.  Returns true on error.
114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
115   unsigned argCount = call->getNumArgs();
116   if (argCount == desiredArgCount) return false;
117 
118   if (argCount < desiredArgCount)
119     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
120            << 0 /*function call*/ << desiredArgCount << argCount
121            << call->getSourceRange();
122 
123   // Highlight all the excess arguments.
124   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
125                     call->getArg(argCount - 1)->getEndLoc());
126 
127   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
128     << 0 /*function call*/ << desiredArgCount << argCount
129     << call->getArg(1)->getSourceRange();
130 }
131 
132 /// Check that the first argument to __builtin_annotation is an integer
133 /// and the second argument is a non-wide string literal.
134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
135   if (checkArgCount(S, TheCall, 2))
136     return true;
137 
138   // First argument should be an integer.
139   Expr *ValArg = TheCall->getArg(0);
140   QualType Ty = ValArg->getType();
141   if (!Ty->isIntegerType()) {
142     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
143         << ValArg->getSourceRange();
144     return true;
145   }
146 
147   // Second argument should be a constant string.
148   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
149   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
150   if (!Literal || !Literal->isAscii()) {
151     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
152         << StrArg->getSourceRange();
153     return true;
154   }
155 
156   TheCall->setType(Ty);
157   return false;
158 }
159 
160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
161   // We need at least one argument.
162   if (TheCall->getNumArgs() < 1) {
163     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
164         << 0 << 1 << TheCall->getNumArgs()
165         << TheCall->getCallee()->getSourceRange();
166     return true;
167   }
168 
169   // All arguments should be wide string literals.
170   for (Expr *Arg : TheCall->arguments()) {
171     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
172     if (!Literal || !Literal->isWide()) {
173       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
174           << Arg->getSourceRange();
175       return true;
176     }
177   }
178 
179   return false;
180 }
181 
182 /// Check that the argument to __builtin_addressof is a glvalue, and set the
183 /// result type to the corresponding pointer type.
184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
185   if (checkArgCount(S, TheCall, 1))
186     return true;
187 
188   ExprResult Arg(TheCall->getArg(0));
189   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
190   if (ResultType.isNull())
191     return true;
192 
193   TheCall->setArg(0, Arg.get());
194   TheCall->setType(ResultType);
195   return false;
196 }
197 
198 /// Check the number of arguments and set the result type to
199 /// the argument type.
200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
201   if (checkArgCount(S, TheCall, 1))
202     return true;
203 
204   TheCall->setType(TheCall->getArg(0)->getType());
205   return false;
206 }
207 
208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
210 /// type (but not a function pointer) and that the alignment is a power-of-two.
211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
212   if (checkArgCount(S, TheCall, 2))
213     return true;
214 
215   clang::Expr *Source = TheCall->getArg(0);
216   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
217 
218   auto IsValidIntegerType = [](QualType Ty) {
219     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
220   };
221   QualType SrcTy = Source->getType();
222   // We should also be able to use it with arrays (but not functions!).
223   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
224     SrcTy = S.Context.getDecayedType(SrcTy);
225   }
226   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
227       SrcTy->isFunctionPointerType()) {
228     // FIXME: this is not quite the right error message since we don't allow
229     // floating point types, or member pointers.
230     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
231         << SrcTy;
232     return true;
233   }
234 
235   clang::Expr *AlignOp = TheCall->getArg(1);
236   if (!IsValidIntegerType(AlignOp->getType())) {
237     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
238         << AlignOp->getType();
239     return true;
240   }
241   Expr::EvalResult AlignResult;
242   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
243   // We can't check validity of alignment if it is value dependent.
244   if (!AlignOp->isValueDependent() &&
245       AlignOp->EvaluateAsInt(AlignResult, S.Context,
246                              Expr::SE_AllowSideEffects)) {
247     llvm::APSInt AlignValue = AlignResult.Val.getInt();
248     llvm::APSInt MaxValue(
249         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
250     if (AlignValue < 1) {
251       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
252       return true;
253     }
254     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
255       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
256           << toString(MaxValue, 10);
257       return true;
258     }
259     if (!AlignValue.isPowerOf2()) {
260       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
261       return true;
262     }
263     if (AlignValue == 1) {
264       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
265           << IsBooleanAlignBuiltin;
266     }
267   }
268 
269   ExprResult SrcArg = S.PerformCopyInitialization(
270       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
271       SourceLocation(), Source);
272   if (SrcArg.isInvalid())
273     return true;
274   TheCall->setArg(0, SrcArg.get());
275   ExprResult AlignArg =
276       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
277                                       S.Context, AlignOp->getType(), false),
278                                   SourceLocation(), AlignOp);
279   if (AlignArg.isInvalid())
280     return true;
281   TheCall->setArg(1, AlignArg.get());
282   // For align_up/align_down, the return type is the same as the (potentially
283   // decayed) argument type including qualifiers. For is_aligned(), the result
284   // is always bool.
285   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
286   return false;
287 }
288 
289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
290                                 unsigned BuiltinID) {
291   if (checkArgCount(S, TheCall, 3))
292     return true;
293 
294   // First two arguments should be integers.
295   for (unsigned I = 0; I < 2; ++I) {
296     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
297     if (Arg.isInvalid()) return true;
298     TheCall->setArg(I, Arg.get());
299 
300     QualType Ty = Arg.get()->getType();
301     if (!Ty->isIntegerType()) {
302       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
303           << Ty << Arg.get()->getSourceRange();
304       return true;
305     }
306   }
307 
308   // Third argument should be a pointer to a non-const integer.
309   // IRGen correctly handles volatile, restrict, and address spaces, and
310   // the other qualifiers aren't possible.
311   {
312     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
313     if (Arg.isInvalid()) return true;
314     TheCall->setArg(2, Arg.get());
315 
316     QualType Ty = Arg.get()->getType();
317     const auto *PtrTy = Ty->getAs<PointerType>();
318     if (!PtrTy ||
319         !PtrTy->getPointeeType()->isIntegerType() ||
320         PtrTy->getPointeeType().isConstQualified()) {
321       S.Diag(Arg.get()->getBeginLoc(),
322              diag::err_overflow_builtin_must_be_ptr_int)
323         << Ty << Arg.get()->getSourceRange();
324       return true;
325     }
326   }
327 
328   // Disallow signed ExtIntType args larger than 128 bits to mul function until
329   // we improve backend support.
330   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
331     for (unsigned I = 0; I < 3; ++I) {
332       const auto Arg = TheCall->getArg(I);
333       // Third argument will be a pointer.
334       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
335       if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
336           S.getASTContext().getIntWidth(Ty) > 128)
337         return S.Diag(Arg->getBeginLoc(),
338                       diag::err_overflow_builtin_ext_int_max_size)
339                << 128;
340     }
341   }
342 
343   return false;
344 }
345 
346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
347   if (checkArgCount(S, BuiltinCall, 2))
348     return true;
349 
350   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
351   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
352   Expr *Call = BuiltinCall->getArg(0);
353   Expr *Chain = BuiltinCall->getArg(1);
354 
355   if (Call->getStmtClass() != Stmt::CallExprClass) {
356     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
357         << Call->getSourceRange();
358     return true;
359   }
360 
361   auto CE = cast<CallExpr>(Call);
362   if (CE->getCallee()->getType()->isBlockPointerType()) {
363     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
364         << Call->getSourceRange();
365     return true;
366   }
367 
368   const Decl *TargetDecl = CE->getCalleeDecl();
369   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
370     if (FD->getBuiltinID()) {
371       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
372           << Call->getSourceRange();
373       return true;
374     }
375 
376   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
377     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
378         << Call->getSourceRange();
379     return true;
380   }
381 
382   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
383   if (ChainResult.isInvalid())
384     return true;
385   if (!ChainResult.get()->getType()->isPointerType()) {
386     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
387         << Chain->getSourceRange();
388     return true;
389   }
390 
391   QualType ReturnTy = CE->getCallReturnType(S.Context);
392   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
393   QualType BuiltinTy = S.Context.getFunctionType(
394       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
395   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
396 
397   Builtin =
398       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
399 
400   BuiltinCall->setType(CE->getType());
401   BuiltinCall->setValueKind(CE->getValueKind());
402   BuiltinCall->setObjectKind(CE->getObjectKind());
403   BuiltinCall->setCallee(Builtin);
404   BuiltinCall->setArg(1, ChainResult.get());
405 
406   return false;
407 }
408 
409 namespace {
410 
411 class EstimateSizeFormatHandler
412     : public analyze_format_string::FormatStringHandler {
413   size_t Size;
414 
415 public:
416   EstimateSizeFormatHandler(StringRef Format)
417       : Size(std::min(Format.find(0), Format.size()) +
418              1 /* null byte always written by sprintf */) {}
419 
420   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
421                              const char *, unsigned SpecifierLen) override {
422 
423     const size_t FieldWidth = computeFieldWidth(FS);
424     const size_t Precision = computePrecision(FS);
425 
426     // The actual format.
427     switch (FS.getConversionSpecifier().getKind()) {
428     // Just a char.
429     case analyze_format_string::ConversionSpecifier::cArg:
430     case analyze_format_string::ConversionSpecifier::CArg:
431       Size += std::max(FieldWidth, (size_t)1);
432       break;
433     // Just an integer.
434     case analyze_format_string::ConversionSpecifier::dArg:
435     case analyze_format_string::ConversionSpecifier::DArg:
436     case analyze_format_string::ConversionSpecifier::iArg:
437     case analyze_format_string::ConversionSpecifier::oArg:
438     case analyze_format_string::ConversionSpecifier::OArg:
439     case analyze_format_string::ConversionSpecifier::uArg:
440     case analyze_format_string::ConversionSpecifier::UArg:
441     case analyze_format_string::ConversionSpecifier::xArg:
442     case analyze_format_string::ConversionSpecifier::XArg:
443       Size += std::max(FieldWidth, Precision);
444       break;
445 
446     // %g style conversion switches between %f or %e style dynamically.
447     // %f always takes less space, so default to it.
448     case analyze_format_string::ConversionSpecifier::gArg:
449     case analyze_format_string::ConversionSpecifier::GArg:
450 
451     // Floating point number in the form '[+]ddd.ddd'.
452     case analyze_format_string::ConversionSpecifier::fArg:
453     case analyze_format_string::ConversionSpecifier::FArg:
454       Size += std::max(FieldWidth, 1 /* integer part */ +
455                                        (Precision ? 1 + Precision
456                                                   : 0) /* period + decimal */);
457       break;
458 
459     // Floating point number in the form '[-]d.ddde[+-]dd'.
460     case analyze_format_string::ConversionSpecifier::eArg:
461     case analyze_format_string::ConversionSpecifier::EArg:
462       Size +=
463           std::max(FieldWidth,
464                    1 /* integer part */ +
465                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
466                        1 /* e or E letter */ + 2 /* exponent */);
467       break;
468 
469     // Floating point number in the form '[-]0xh.hhhhp±dd'.
470     case analyze_format_string::ConversionSpecifier::aArg:
471     case analyze_format_string::ConversionSpecifier::AArg:
472       Size +=
473           std::max(FieldWidth,
474                    2 /* 0x */ + 1 /* integer part */ +
475                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
476                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
477       break;
478 
479     // Just a string.
480     case analyze_format_string::ConversionSpecifier::sArg:
481     case analyze_format_string::ConversionSpecifier::SArg:
482       Size += FieldWidth;
483       break;
484 
485     // Just a pointer in the form '0xddd'.
486     case analyze_format_string::ConversionSpecifier::pArg:
487       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
488       break;
489 
490     // A plain percent.
491     case analyze_format_string::ConversionSpecifier::PercentArg:
492       Size += 1;
493       break;
494 
495     default:
496       break;
497     }
498 
499     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
500 
501     if (FS.hasAlternativeForm()) {
502       switch (FS.getConversionSpecifier().getKind()) {
503       default:
504         break;
505       // Force a leading '0'.
506       case analyze_format_string::ConversionSpecifier::oArg:
507         Size += 1;
508         break;
509       // Force a leading '0x'.
510       case analyze_format_string::ConversionSpecifier::xArg:
511       case analyze_format_string::ConversionSpecifier::XArg:
512         Size += 2;
513         break;
514       // Force a period '.' before decimal, even if precision is 0.
515       case analyze_format_string::ConversionSpecifier::aArg:
516       case analyze_format_string::ConversionSpecifier::AArg:
517       case analyze_format_string::ConversionSpecifier::eArg:
518       case analyze_format_string::ConversionSpecifier::EArg:
519       case analyze_format_string::ConversionSpecifier::fArg:
520       case analyze_format_string::ConversionSpecifier::FArg:
521       case analyze_format_string::ConversionSpecifier::gArg:
522       case analyze_format_string::ConversionSpecifier::GArg:
523         Size += (Precision ? 0 : 1);
524         break;
525       }
526     }
527     assert(SpecifierLen <= Size && "no underflow");
528     Size -= SpecifierLen;
529     return true;
530   }
531 
532   size_t getSizeLowerBound() const { return Size; }
533 
534 private:
535   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
536     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
537     size_t FieldWidth = 0;
538     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
539       FieldWidth = FW.getConstantAmount();
540     return FieldWidth;
541   }
542 
543   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
544     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
545     size_t Precision = 0;
546 
547     // See man 3 printf for default precision value based on the specifier.
548     switch (FW.getHowSpecified()) {
549     case analyze_format_string::OptionalAmount::NotSpecified:
550       switch (FS.getConversionSpecifier().getKind()) {
551       default:
552         break;
553       case analyze_format_string::ConversionSpecifier::dArg: // %d
554       case analyze_format_string::ConversionSpecifier::DArg: // %D
555       case analyze_format_string::ConversionSpecifier::iArg: // %i
556         Precision = 1;
557         break;
558       case analyze_format_string::ConversionSpecifier::oArg: // %d
559       case analyze_format_string::ConversionSpecifier::OArg: // %D
560       case analyze_format_string::ConversionSpecifier::uArg: // %d
561       case analyze_format_string::ConversionSpecifier::UArg: // %D
562       case analyze_format_string::ConversionSpecifier::xArg: // %d
563       case analyze_format_string::ConversionSpecifier::XArg: // %D
564         Precision = 1;
565         break;
566       case analyze_format_string::ConversionSpecifier::fArg: // %f
567       case analyze_format_string::ConversionSpecifier::FArg: // %F
568       case analyze_format_string::ConversionSpecifier::eArg: // %e
569       case analyze_format_string::ConversionSpecifier::EArg: // %E
570       case analyze_format_string::ConversionSpecifier::gArg: // %g
571       case analyze_format_string::ConversionSpecifier::GArg: // %G
572         Precision = 6;
573         break;
574       case analyze_format_string::ConversionSpecifier::pArg: // %d
575         Precision = 1;
576         break;
577       }
578       break;
579     case analyze_format_string::OptionalAmount::Constant:
580       Precision = FW.getConstantAmount();
581       break;
582     default:
583       break;
584     }
585     return Precision;
586   }
587 };
588 
589 } // namespace
590 
591 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
592 /// __builtin_*_chk function, then use the object size argument specified in the
593 /// source. Otherwise, infer the object size using __builtin_object_size.
594 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
595                                                CallExpr *TheCall) {
596   // FIXME: There are some more useful checks we could be doing here:
597   //  - Evaluate strlen of strcpy arguments, use as object size.
598 
599   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
600       isConstantEvaluated())
601     return;
602 
603   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
604   if (!BuiltinID)
605     return;
606 
607   const TargetInfo &TI = getASTContext().getTargetInfo();
608   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
609 
610   unsigned DiagID = 0;
611   bool IsChkVariant = false;
612   Optional<llvm::APSInt> UsedSize;
613   unsigned SizeIndex, ObjectIndex;
614   switch (BuiltinID) {
615   default:
616     return;
617   case Builtin::BIsprintf:
618   case Builtin::BI__builtin___sprintf_chk: {
619     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
620     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
621 
622     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
623 
624       if (!Format->isAscii() && !Format->isUTF8())
625         return;
626 
627       StringRef FormatStrRef = Format->getString();
628       EstimateSizeFormatHandler H(FormatStrRef);
629       const char *FormatBytes = FormatStrRef.data();
630       const ConstantArrayType *T =
631           Context.getAsConstantArrayType(Format->getType());
632       assert(T && "String literal not of constant array type!");
633       size_t TypeSize = T->getSize().getZExtValue();
634 
635       // In case there's a null byte somewhere.
636       size_t StrLen =
637           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
638       if (!analyze_format_string::ParsePrintfString(
639               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
640               Context.getTargetInfo(), false)) {
641         DiagID = diag::warn_fortify_source_format_overflow;
642         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
643                        .extOrTrunc(SizeTypeWidth);
644         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
645           IsChkVariant = true;
646           ObjectIndex = 2;
647         } else {
648           IsChkVariant = false;
649           ObjectIndex = 0;
650         }
651         break;
652       }
653     }
654     return;
655   }
656   case Builtin::BI__builtin___memcpy_chk:
657   case Builtin::BI__builtin___memmove_chk:
658   case Builtin::BI__builtin___memset_chk:
659   case Builtin::BI__builtin___strlcat_chk:
660   case Builtin::BI__builtin___strlcpy_chk:
661   case Builtin::BI__builtin___strncat_chk:
662   case Builtin::BI__builtin___strncpy_chk:
663   case Builtin::BI__builtin___stpncpy_chk:
664   case Builtin::BI__builtin___memccpy_chk:
665   case Builtin::BI__builtin___mempcpy_chk: {
666     DiagID = diag::warn_builtin_chk_overflow;
667     IsChkVariant = true;
668     SizeIndex = TheCall->getNumArgs() - 2;
669     ObjectIndex = TheCall->getNumArgs() - 1;
670     break;
671   }
672 
673   case Builtin::BI__builtin___snprintf_chk:
674   case Builtin::BI__builtin___vsnprintf_chk: {
675     DiagID = diag::warn_builtin_chk_overflow;
676     IsChkVariant = true;
677     SizeIndex = 1;
678     ObjectIndex = 3;
679     break;
680   }
681 
682   case Builtin::BIstrncat:
683   case Builtin::BI__builtin_strncat:
684   case Builtin::BIstrncpy:
685   case Builtin::BI__builtin_strncpy:
686   case Builtin::BIstpncpy:
687   case Builtin::BI__builtin_stpncpy: {
688     // Whether these functions overflow depends on the runtime strlen of the
689     // string, not just the buffer size, so emitting the "always overflow"
690     // diagnostic isn't quite right. We should still diagnose passing a buffer
691     // size larger than the destination buffer though; this is a runtime abort
692     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
693     DiagID = diag::warn_fortify_source_size_mismatch;
694     SizeIndex = TheCall->getNumArgs() - 1;
695     ObjectIndex = 0;
696     break;
697   }
698 
699   case Builtin::BImemcpy:
700   case Builtin::BI__builtin_memcpy:
701   case Builtin::BImemmove:
702   case Builtin::BI__builtin_memmove:
703   case Builtin::BImemset:
704   case Builtin::BI__builtin_memset:
705   case Builtin::BImempcpy:
706   case Builtin::BI__builtin_mempcpy: {
707     DiagID = diag::warn_fortify_source_overflow;
708     SizeIndex = TheCall->getNumArgs() - 1;
709     ObjectIndex = 0;
710     break;
711   }
712   case Builtin::BIsnprintf:
713   case Builtin::BI__builtin_snprintf:
714   case Builtin::BIvsnprintf:
715   case Builtin::BI__builtin_vsnprintf: {
716     DiagID = diag::warn_fortify_source_size_mismatch;
717     SizeIndex = 1;
718     ObjectIndex = 0;
719     break;
720   }
721   }
722 
723   llvm::APSInt ObjectSize;
724   // For __builtin___*_chk, the object size is explicitly provided by the caller
725   // (usually using __builtin_object_size). Use that value to check this call.
726   if (IsChkVariant) {
727     Expr::EvalResult Result;
728     Expr *SizeArg = TheCall->getArg(ObjectIndex);
729     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
730       return;
731     ObjectSize = Result.Val.getInt();
732 
733   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
734   } else {
735     // If the parameter has a pass_object_size attribute, then we should use its
736     // (potentially) more strict checking mode. Otherwise, conservatively assume
737     // type 0.
738     int BOSType = 0;
739     if (const auto *POS =
740             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
741       BOSType = POS->getType();
742 
743     Expr *ObjArg = TheCall->getArg(ObjectIndex);
744     uint64_t Result;
745     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
746       return;
747     // Get the object size in the target's size_t width.
748     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
749   }
750 
751   // Evaluate the number of bytes of the object that this call will use.
752   if (!UsedSize) {
753     Expr::EvalResult Result;
754     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
755     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
756       return;
757     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
758   }
759 
760   if (UsedSize.getValue().ule(ObjectSize))
761     return;
762 
763   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
764   // Skim off the details of whichever builtin was called to produce a better
765   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
766   if (IsChkVariant) {
767     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
768     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
769   } else if (FunctionName.startswith("__builtin_")) {
770     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
771   }
772 
773   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
774                       PDiag(DiagID)
775                           << FunctionName << toString(ObjectSize, /*Radix=*/10)
776                           << toString(UsedSize.getValue(), /*Radix=*/10));
777 }
778 
779 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
780                                      Scope::ScopeFlags NeededScopeFlags,
781                                      unsigned DiagID) {
782   // Scopes aren't available during instantiation. Fortunately, builtin
783   // functions cannot be template args so they cannot be formed through template
784   // instantiation. Therefore checking once during the parse is sufficient.
785   if (SemaRef.inTemplateInstantiation())
786     return false;
787 
788   Scope *S = SemaRef.getCurScope();
789   while (S && !S->isSEHExceptScope())
790     S = S->getParent();
791   if (!S || !(S->getFlags() & NeededScopeFlags)) {
792     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
793     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
794         << DRE->getDecl()->getIdentifier();
795     return true;
796   }
797 
798   return false;
799 }
800 
801 static inline bool isBlockPointer(Expr *Arg) {
802   return Arg->getType()->isBlockPointerType();
803 }
804 
805 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
806 /// void*, which is a requirement of device side enqueue.
807 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
808   const BlockPointerType *BPT =
809       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
810   ArrayRef<QualType> Params =
811       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
812   unsigned ArgCounter = 0;
813   bool IllegalParams = false;
814   // Iterate through the block parameters until either one is found that is not
815   // a local void*, or the block is valid.
816   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
817        I != E; ++I, ++ArgCounter) {
818     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
819         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
820             LangAS::opencl_local) {
821       // Get the location of the error. If a block literal has been passed
822       // (BlockExpr) then we can point straight to the offending argument,
823       // else we just point to the variable reference.
824       SourceLocation ErrorLoc;
825       if (isa<BlockExpr>(BlockArg)) {
826         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
827         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
828       } else if (isa<DeclRefExpr>(BlockArg)) {
829         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
830       }
831       S.Diag(ErrorLoc,
832              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
833       IllegalParams = true;
834     }
835   }
836 
837   return IllegalParams;
838 }
839 
840 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
841   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
842     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
843         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
844     return true;
845   }
846   return false;
847 }
848 
849 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
850   if (checkArgCount(S, TheCall, 2))
851     return true;
852 
853   if (checkOpenCLSubgroupExt(S, TheCall))
854     return true;
855 
856   // First argument is an ndrange_t type.
857   Expr *NDRangeArg = TheCall->getArg(0);
858   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
859     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
860         << TheCall->getDirectCallee() << "'ndrange_t'";
861     return true;
862   }
863 
864   Expr *BlockArg = TheCall->getArg(1);
865   if (!isBlockPointer(BlockArg)) {
866     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
867         << TheCall->getDirectCallee() << "block";
868     return true;
869   }
870   return checkOpenCLBlockArgs(S, BlockArg);
871 }
872 
873 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
874 /// get_kernel_work_group_size
875 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
876 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
877   if (checkArgCount(S, TheCall, 1))
878     return true;
879 
880   Expr *BlockArg = TheCall->getArg(0);
881   if (!isBlockPointer(BlockArg)) {
882     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
883         << TheCall->getDirectCallee() << "block";
884     return true;
885   }
886   return checkOpenCLBlockArgs(S, BlockArg);
887 }
888 
889 /// Diagnose integer type and any valid implicit conversion to it.
890 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
891                                       const QualType &IntType);
892 
893 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
894                                             unsigned Start, unsigned End) {
895   bool IllegalParams = false;
896   for (unsigned I = Start; I <= End; ++I)
897     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
898                                               S.Context.getSizeType());
899   return IllegalParams;
900 }
901 
902 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
903 /// 'local void*' parameter of passed block.
904 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
905                                            Expr *BlockArg,
906                                            unsigned NumNonVarArgs) {
907   const BlockPointerType *BPT =
908       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
909   unsigned NumBlockParams =
910       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
911   unsigned TotalNumArgs = TheCall->getNumArgs();
912 
913   // For each argument passed to the block, a corresponding uint needs to
914   // be passed to describe the size of the local memory.
915   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
916     S.Diag(TheCall->getBeginLoc(),
917            diag::err_opencl_enqueue_kernel_local_size_args);
918     return true;
919   }
920 
921   // Check that the sizes of the local memory are specified by integers.
922   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
923                                          TotalNumArgs - 1);
924 }
925 
926 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
927 /// overload formats specified in Table 6.13.17.1.
928 /// int enqueue_kernel(queue_t queue,
929 ///                    kernel_enqueue_flags_t flags,
930 ///                    const ndrange_t ndrange,
931 ///                    void (^block)(void))
932 /// int enqueue_kernel(queue_t queue,
933 ///                    kernel_enqueue_flags_t flags,
934 ///                    const ndrange_t ndrange,
935 ///                    uint num_events_in_wait_list,
936 ///                    clk_event_t *event_wait_list,
937 ///                    clk_event_t *event_ret,
938 ///                    void (^block)(void))
939 /// int enqueue_kernel(queue_t queue,
940 ///                    kernel_enqueue_flags_t flags,
941 ///                    const ndrange_t ndrange,
942 ///                    void (^block)(local void*, ...),
943 ///                    uint size0, ...)
944 /// int enqueue_kernel(queue_t queue,
945 ///                    kernel_enqueue_flags_t flags,
946 ///                    const ndrange_t ndrange,
947 ///                    uint num_events_in_wait_list,
948 ///                    clk_event_t *event_wait_list,
949 ///                    clk_event_t *event_ret,
950 ///                    void (^block)(local void*, ...),
951 ///                    uint size0, ...)
952 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
953   unsigned NumArgs = TheCall->getNumArgs();
954 
955   if (NumArgs < 4) {
956     S.Diag(TheCall->getBeginLoc(),
957            diag::err_typecheck_call_too_few_args_at_least)
958         << 0 << 4 << NumArgs;
959     return true;
960   }
961 
962   Expr *Arg0 = TheCall->getArg(0);
963   Expr *Arg1 = TheCall->getArg(1);
964   Expr *Arg2 = TheCall->getArg(2);
965   Expr *Arg3 = TheCall->getArg(3);
966 
967   // First argument always needs to be a queue_t type.
968   if (!Arg0->getType()->isQueueT()) {
969     S.Diag(TheCall->getArg(0)->getBeginLoc(),
970            diag::err_opencl_builtin_expected_type)
971         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
972     return true;
973   }
974 
975   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
976   if (!Arg1->getType()->isIntegerType()) {
977     S.Diag(TheCall->getArg(1)->getBeginLoc(),
978            diag::err_opencl_builtin_expected_type)
979         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
980     return true;
981   }
982 
983   // Third argument is always an ndrange_t type.
984   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
985     S.Diag(TheCall->getArg(2)->getBeginLoc(),
986            diag::err_opencl_builtin_expected_type)
987         << TheCall->getDirectCallee() << "'ndrange_t'";
988     return true;
989   }
990 
991   // With four arguments, there is only one form that the function could be
992   // called in: no events and no variable arguments.
993   if (NumArgs == 4) {
994     // check that the last argument is the right block type.
995     if (!isBlockPointer(Arg3)) {
996       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
997           << TheCall->getDirectCallee() << "block";
998       return true;
999     }
1000     // we have a block type, check the prototype
1001     const BlockPointerType *BPT =
1002         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1003     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1004       S.Diag(Arg3->getBeginLoc(),
1005              diag::err_opencl_enqueue_kernel_blocks_no_args);
1006       return true;
1007     }
1008     return false;
1009   }
1010   // we can have block + varargs.
1011   if (isBlockPointer(Arg3))
1012     return (checkOpenCLBlockArgs(S, Arg3) ||
1013             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1014   // last two cases with either exactly 7 args or 7 args and varargs.
1015   if (NumArgs >= 7) {
1016     // check common block argument.
1017     Expr *Arg6 = TheCall->getArg(6);
1018     if (!isBlockPointer(Arg6)) {
1019       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1020           << TheCall->getDirectCallee() << "block";
1021       return true;
1022     }
1023     if (checkOpenCLBlockArgs(S, Arg6))
1024       return true;
1025 
1026     // Forth argument has to be any integer type.
1027     if (!Arg3->getType()->isIntegerType()) {
1028       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1029              diag::err_opencl_builtin_expected_type)
1030           << TheCall->getDirectCallee() << "integer";
1031       return true;
1032     }
1033     // check remaining common arguments.
1034     Expr *Arg4 = TheCall->getArg(4);
1035     Expr *Arg5 = TheCall->getArg(5);
1036 
1037     // Fifth argument is always passed as a pointer to clk_event_t.
1038     if (!Arg4->isNullPointerConstant(S.Context,
1039                                      Expr::NPC_ValueDependentIsNotNull) &&
1040         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1041       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1042              diag::err_opencl_builtin_expected_type)
1043           << TheCall->getDirectCallee()
1044           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1045       return true;
1046     }
1047 
1048     // Sixth argument is always passed as a pointer to clk_event_t.
1049     if (!Arg5->isNullPointerConstant(S.Context,
1050                                      Expr::NPC_ValueDependentIsNotNull) &&
1051         !(Arg5->getType()->isPointerType() &&
1052           Arg5->getType()->getPointeeType()->isClkEventT())) {
1053       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1054              diag::err_opencl_builtin_expected_type)
1055           << TheCall->getDirectCallee()
1056           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1057       return true;
1058     }
1059 
1060     if (NumArgs == 7)
1061       return false;
1062 
1063     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1064   }
1065 
1066   // None of the specific case has been detected, give generic error
1067   S.Diag(TheCall->getBeginLoc(),
1068          diag::err_opencl_enqueue_kernel_incorrect_args);
1069   return true;
1070 }
1071 
1072 /// Returns OpenCL access qual.
1073 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1074     return D->getAttr<OpenCLAccessAttr>();
1075 }
1076 
1077 /// Returns true if pipe element type is different from the pointer.
1078 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1079   const Expr *Arg0 = Call->getArg(0);
1080   // First argument type should always be pipe.
1081   if (!Arg0->getType()->isPipeType()) {
1082     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1083         << Call->getDirectCallee() << Arg0->getSourceRange();
1084     return true;
1085   }
1086   OpenCLAccessAttr *AccessQual =
1087       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1088   // Validates the access qualifier is compatible with the call.
1089   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1090   // read_only and write_only, and assumed to be read_only if no qualifier is
1091   // specified.
1092   switch (Call->getDirectCallee()->getBuiltinID()) {
1093   case Builtin::BIread_pipe:
1094   case Builtin::BIreserve_read_pipe:
1095   case Builtin::BIcommit_read_pipe:
1096   case Builtin::BIwork_group_reserve_read_pipe:
1097   case Builtin::BIsub_group_reserve_read_pipe:
1098   case Builtin::BIwork_group_commit_read_pipe:
1099   case Builtin::BIsub_group_commit_read_pipe:
1100     if (!(!AccessQual || AccessQual->isReadOnly())) {
1101       S.Diag(Arg0->getBeginLoc(),
1102              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1103           << "read_only" << Arg0->getSourceRange();
1104       return true;
1105     }
1106     break;
1107   case Builtin::BIwrite_pipe:
1108   case Builtin::BIreserve_write_pipe:
1109   case Builtin::BIcommit_write_pipe:
1110   case Builtin::BIwork_group_reserve_write_pipe:
1111   case Builtin::BIsub_group_reserve_write_pipe:
1112   case Builtin::BIwork_group_commit_write_pipe:
1113   case Builtin::BIsub_group_commit_write_pipe:
1114     if (!(AccessQual && AccessQual->isWriteOnly())) {
1115       S.Diag(Arg0->getBeginLoc(),
1116              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1117           << "write_only" << Arg0->getSourceRange();
1118       return true;
1119     }
1120     break;
1121   default:
1122     break;
1123   }
1124   return false;
1125 }
1126 
1127 /// Returns true if pipe element type is different from the pointer.
1128 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1129   const Expr *Arg0 = Call->getArg(0);
1130   const Expr *ArgIdx = Call->getArg(Idx);
1131   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1132   const QualType EltTy = PipeTy->getElementType();
1133   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1134   // The Idx argument should be a pointer and the type of the pointer and
1135   // the type of pipe element should also be the same.
1136   if (!ArgTy ||
1137       !S.Context.hasSameType(
1138           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1139     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1140         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1141         << ArgIdx->getType() << ArgIdx->getSourceRange();
1142     return true;
1143   }
1144   return false;
1145 }
1146 
1147 // Performs semantic analysis for the read/write_pipe call.
1148 // \param S Reference to the semantic analyzer.
1149 // \param Call A pointer to the builtin call.
1150 // \return True if a semantic error has been found, false otherwise.
1151 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1152   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1153   // functions have two forms.
1154   switch (Call->getNumArgs()) {
1155   case 2:
1156     if (checkOpenCLPipeArg(S, Call))
1157       return true;
1158     // The call with 2 arguments should be
1159     // read/write_pipe(pipe T, T*).
1160     // Check packet type T.
1161     if (checkOpenCLPipePacketType(S, Call, 1))
1162       return true;
1163     break;
1164 
1165   case 4: {
1166     if (checkOpenCLPipeArg(S, Call))
1167       return true;
1168     // The call with 4 arguments should be
1169     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1170     // Check reserve_id_t.
1171     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1172       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1173           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1174           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1175       return true;
1176     }
1177 
1178     // Check the index.
1179     const Expr *Arg2 = Call->getArg(2);
1180     if (!Arg2->getType()->isIntegerType() &&
1181         !Arg2->getType()->isUnsignedIntegerType()) {
1182       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1183           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1184           << Arg2->getType() << Arg2->getSourceRange();
1185       return true;
1186     }
1187 
1188     // Check packet type T.
1189     if (checkOpenCLPipePacketType(S, Call, 3))
1190       return true;
1191   } break;
1192   default:
1193     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1194         << Call->getDirectCallee() << Call->getSourceRange();
1195     return true;
1196   }
1197 
1198   return false;
1199 }
1200 
1201 // Performs a semantic analysis on the {work_group_/sub_group_
1202 //        /_}reserve_{read/write}_pipe
1203 // \param S Reference to the semantic analyzer.
1204 // \param Call The call to the builtin function to be analyzed.
1205 // \return True if a semantic error was found, false otherwise.
1206 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1207   if (checkArgCount(S, Call, 2))
1208     return true;
1209 
1210   if (checkOpenCLPipeArg(S, Call))
1211     return true;
1212 
1213   // Check the reserve size.
1214   if (!Call->getArg(1)->getType()->isIntegerType() &&
1215       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1216     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1217         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1218         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1219     return true;
1220   }
1221 
1222   // Since return type of reserve_read/write_pipe built-in function is
1223   // reserve_id_t, which is not defined in the builtin def file , we used int
1224   // as return type and need to override the return type of these functions.
1225   Call->setType(S.Context.OCLReserveIDTy);
1226 
1227   return false;
1228 }
1229 
1230 // Performs a semantic analysis on {work_group_/sub_group_
1231 //        /_}commit_{read/write}_pipe
1232 // \param S Reference to the semantic analyzer.
1233 // \param Call The call to the builtin function to be analyzed.
1234 // \return True if a semantic error was found, false otherwise.
1235 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1236   if (checkArgCount(S, Call, 2))
1237     return true;
1238 
1239   if (checkOpenCLPipeArg(S, Call))
1240     return true;
1241 
1242   // Check reserve_id_t.
1243   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1244     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1245         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1246         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1247     return true;
1248   }
1249 
1250   return false;
1251 }
1252 
1253 // Performs a semantic analysis on the call to built-in Pipe
1254 //        Query Functions.
1255 // \param S Reference to the semantic analyzer.
1256 // \param Call The call to the builtin function to be analyzed.
1257 // \return True if a semantic error was found, false otherwise.
1258 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1259   if (checkArgCount(S, Call, 1))
1260     return true;
1261 
1262   if (!Call->getArg(0)->getType()->isPipeType()) {
1263     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1264         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1265     return true;
1266   }
1267 
1268   return false;
1269 }
1270 
1271 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1272 // Performs semantic analysis for the to_global/local/private call.
1273 // \param S Reference to the semantic analyzer.
1274 // \param BuiltinID ID of the builtin function.
1275 // \param Call A pointer to the builtin call.
1276 // \return True if a semantic error has been found, false otherwise.
1277 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1278                                     CallExpr *Call) {
1279   if (checkArgCount(S, Call, 1))
1280     return true;
1281 
1282   auto RT = Call->getArg(0)->getType();
1283   if (!RT->isPointerType() || RT->getPointeeType()
1284       .getAddressSpace() == LangAS::opencl_constant) {
1285     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1286         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1287     return true;
1288   }
1289 
1290   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1291     S.Diag(Call->getArg(0)->getBeginLoc(),
1292            diag::warn_opencl_generic_address_space_arg)
1293         << Call->getDirectCallee()->getNameInfo().getAsString()
1294         << Call->getArg(0)->getSourceRange();
1295   }
1296 
1297   RT = RT->getPointeeType();
1298   auto Qual = RT.getQualifiers();
1299   switch (BuiltinID) {
1300   case Builtin::BIto_global:
1301     Qual.setAddressSpace(LangAS::opencl_global);
1302     break;
1303   case Builtin::BIto_local:
1304     Qual.setAddressSpace(LangAS::opencl_local);
1305     break;
1306   case Builtin::BIto_private:
1307     Qual.setAddressSpace(LangAS::opencl_private);
1308     break;
1309   default:
1310     llvm_unreachable("Invalid builtin function");
1311   }
1312   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1313       RT.getUnqualifiedType(), Qual)));
1314 
1315   return false;
1316 }
1317 
1318 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1319   if (checkArgCount(S, TheCall, 1))
1320     return ExprError();
1321 
1322   // Compute __builtin_launder's parameter type from the argument.
1323   // The parameter type is:
1324   //  * The type of the argument if it's not an array or function type,
1325   //  Otherwise,
1326   //  * The decayed argument type.
1327   QualType ParamTy = [&]() {
1328     QualType ArgTy = TheCall->getArg(0)->getType();
1329     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1330       return S.Context.getPointerType(Ty->getElementType());
1331     if (ArgTy->isFunctionType()) {
1332       return S.Context.getPointerType(ArgTy);
1333     }
1334     return ArgTy;
1335   }();
1336 
1337   TheCall->setType(ParamTy);
1338 
1339   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1340     if (!ParamTy->isPointerType())
1341       return 0;
1342     if (ParamTy->isFunctionPointerType())
1343       return 1;
1344     if (ParamTy->isVoidPointerType())
1345       return 2;
1346     return llvm::Optional<unsigned>{};
1347   }();
1348   if (DiagSelect.hasValue()) {
1349     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1350         << DiagSelect.getValue() << TheCall->getSourceRange();
1351     return ExprError();
1352   }
1353 
1354   // We either have an incomplete class type, or we have a class template
1355   // whose instantiation has not been forced. Example:
1356   //
1357   //   template <class T> struct Foo { T value; };
1358   //   Foo<int> *p = nullptr;
1359   //   auto *d = __builtin_launder(p);
1360   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1361                             diag::err_incomplete_type))
1362     return ExprError();
1363 
1364   assert(ParamTy->getPointeeType()->isObjectType() &&
1365          "Unhandled non-object pointer case");
1366 
1367   InitializedEntity Entity =
1368       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1369   ExprResult Arg =
1370       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1371   if (Arg.isInvalid())
1372     return ExprError();
1373   TheCall->setArg(0, Arg.get());
1374 
1375   return TheCall;
1376 }
1377 
1378 // Emit an error and return true if the current architecture is not in the list
1379 // of supported architectures.
1380 static bool
1381 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1382                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1383   llvm::Triple::ArchType CurArch =
1384       S.getASTContext().getTargetInfo().getTriple().getArch();
1385   if (llvm::is_contained(SupportedArchs, CurArch))
1386     return false;
1387   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1388       << TheCall->getSourceRange();
1389   return true;
1390 }
1391 
1392 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1393                                  SourceLocation CallSiteLoc);
1394 
1395 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1396                                       CallExpr *TheCall) {
1397   switch (TI.getTriple().getArch()) {
1398   default:
1399     // Some builtins don't require additional checking, so just consider these
1400     // acceptable.
1401     return false;
1402   case llvm::Triple::arm:
1403   case llvm::Triple::armeb:
1404   case llvm::Triple::thumb:
1405   case llvm::Triple::thumbeb:
1406     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1407   case llvm::Triple::aarch64:
1408   case llvm::Triple::aarch64_32:
1409   case llvm::Triple::aarch64_be:
1410     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1411   case llvm::Triple::bpfeb:
1412   case llvm::Triple::bpfel:
1413     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1414   case llvm::Triple::hexagon:
1415     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1416   case llvm::Triple::mips:
1417   case llvm::Triple::mipsel:
1418   case llvm::Triple::mips64:
1419   case llvm::Triple::mips64el:
1420     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1421   case llvm::Triple::systemz:
1422     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1423   case llvm::Triple::x86:
1424   case llvm::Triple::x86_64:
1425     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1426   case llvm::Triple::ppc:
1427   case llvm::Triple::ppcle:
1428   case llvm::Triple::ppc64:
1429   case llvm::Triple::ppc64le:
1430     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1431   case llvm::Triple::amdgcn:
1432     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1433   case llvm::Triple::riscv32:
1434   case llvm::Triple::riscv64:
1435     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1436   }
1437 }
1438 
1439 ExprResult
1440 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1441                                CallExpr *TheCall) {
1442   ExprResult TheCallResult(TheCall);
1443 
1444   // Find out if any arguments are required to be integer constant expressions.
1445   unsigned ICEArguments = 0;
1446   ASTContext::GetBuiltinTypeError Error;
1447   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1448   if (Error != ASTContext::GE_None)
1449     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1450 
1451   // If any arguments are required to be ICE's, check and diagnose.
1452   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1453     // Skip arguments not required to be ICE's.
1454     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1455 
1456     llvm::APSInt Result;
1457     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1458       return true;
1459     ICEArguments &= ~(1 << ArgNo);
1460   }
1461 
1462   switch (BuiltinID) {
1463   case Builtin::BI__builtin___CFStringMakeConstantString:
1464     assert(TheCall->getNumArgs() == 1 &&
1465            "Wrong # arguments to builtin CFStringMakeConstantString");
1466     if (CheckObjCString(TheCall->getArg(0)))
1467       return ExprError();
1468     break;
1469   case Builtin::BI__builtin_ms_va_start:
1470   case Builtin::BI__builtin_stdarg_start:
1471   case Builtin::BI__builtin_va_start:
1472     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1473       return ExprError();
1474     break;
1475   case Builtin::BI__va_start: {
1476     switch (Context.getTargetInfo().getTriple().getArch()) {
1477     case llvm::Triple::aarch64:
1478     case llvm::Triple::arm:
1479     case llvm::Triple::thumb:
1480       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1481         return ExprError();
1482       break;
1483     default:
1484       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1485         return ExprError();
1486       break;
1487     }
1488     break;
1489   }
1490 
1491   // The acquire, release, and no fence variants are ARM and AArch64 only.
1492   case Builtin::BI_interlockedbittestandset_acq:
1493   case Builtin::BI_interlockedbittestandset_rel:
1494   case Builtin::BI_interlockedbittestandset_nf:
1495   case Builtin::BI_interlockedbittestandreset_acq:
1496   case Builtin::BI_interlockedbittestandreset_rel:
1497   case Builtin::BI_interlockedbittestandreset_nf:
1498     if (CheckBuiltinTargetSupport(
1499             *this, BuiltinID, TheCall,
1500             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1501       return ExprError();
1502     break;
1503 
1504   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1505   case Builtin::BI_bittest64:
1506   case Builtin::BI_bittestandcomplement64:
1507   case Builtin::BI_bittestandreset64:
1508   case Builtin::BI_bittestandset64:
1509   case Builtin::BI_interlockedbittestandreset64:
1510   case Builtin::BI_interlockedbittestandset64:
1511     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1512                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1513                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1514       return ExprError();
1515     break;
1516 
1517   case Builtin::BI__builtin_isgreater:
1518   case Builtin::BI__builtin_isgreaterequal:
1519   case Builtin::BI__builtin_isless:
1520   case Builtin::BI__builtin_islessequal:
1521   case Builtin::BI__builtin_islessgreater:
1522   case Builtin::BI__builtin_isunordered:
1523     if (SemaBuiltinUnorderedCompare(TheCall))
1524       return ExprError();
1525     break;
1526   case Builtin::BI__builtin_fpclassify:
1527     if (SemaBuiltinFPClassification(TheCall, 6))
1528       return ExprError();
1529     break;
1530   case Builtin::BI__builtin_isfinite:
1531   case Builtin::BI__builtin_isinf:
1532   case Builtin::BI__builtin_isinf_sign:
1533   case Builtin::BI__builtin_isnan:
1534   case Builtin::BI__builtin_isnormal:
1535   case Builtin::BI__builtin_signbit:
1536   case Builtin::BI__builtin_signbitf:
1537   case Builtin::BI__builtin_signbitl:
1538     if (SemaBuiltinFPClassification(TheCall, 1))
1539       return ExprError();
1540     break;
1541   case Builtin::BI__builtin_shufflevector:
1542     return SemaBuiltinShuffleVector(TheCall);
1543     // TheCall will be freed by the smart pointer here, but that's fine, since
1544     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1545   case Builtin::BI__builtin_prefetch:
1546     if (SemaBuiltinPrefetch(TheCall))
1547       return ExprError();
1548     break;
1549   case Builtin::BI__builtin_alloca_with_align:
1550     if (SemaBuiltinAllocaWithAlign(TheCall))
1551       return ExprError();
1552     LLVM_FALLTHROUGH;
1553   case Builtin::BI__builtin_alloca:
1554     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1555         << TheCall->getDirectCallee();
1556     break;
1557   case Builtin::BI__arithmetic_fence:
1558     if (SemaBuiltinArithmeticFence(TheCall))
1559       return ExprError();
1560     break;
1561   case Builtin::BI__assume:
1562   case Builtin::BI__builtin_assume:
1563     if (SemaBuiltinAssume(TheCall))
1564       return ExprError();
1565     break;
1566   case Builtin::BI__builtin_assume_aligned:
1567     if (SemaBuiltinAssumeAligned(TheCall))
1568       return ExprError();
1569     break;
1570   case Builtin::BI__builtin_dynamic_object_size:
1571   case Builtin::BI__builtin_object_size:
1572     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1573       return ExprError();
1574     break;
1575   case Builtin::BI__builtin_longjmp:
1576     if (SemaBuiltinLongjmp(TheCall))
1577       return ExprError();
1578     break;
1579   case Builtin::BI__builtin_setjmp:
1580     if (SemaBuiltinSetjmp(TheCall))
1581       return ExprError();
1582     break;
1583   case Builtin::BI__builtin_classify_type:
1584     if (checkArgCount(*this, TheCall, 1)) return true;
1585     TheCall->setType(Context.IntTy);
1586     break;
1587   case Builtin::BI__builtin_complex:
1588     if (SemaBuiltinComplex(TheCall))
1589       return ExprError();
1590     break;
1591   case Builtin::BI__builtin_constant_p: {
1592     if (checkArgCount(*this, TheCall, 1)) return true;
1593     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1594     if (Arg.isInvalid()) return true;
1595     TheCall->setArg(0, Arg.get());
1596     TheCall->setType(Context.IntTy);
1597     break;
1598   }
1599   case Builtin::BI__builtin_launder:
1600     return SemaBuiltinLaunder(*this, TheCall);
1601   case Builtin::BI__sync_fetch_and_add:
1602   case Builtin::BI__sync_fetch_and_add_1:
1603   case Builtin::BI__sync_fetch_and_add_2:
1604   case Builtin::BI__sync_fetch_and_add_4:
1605   case Builtin::BI__sync_fetch_and_add_8:
1606   case Builtin::BI__sync_fetch_and_add_16:
1607   case Builtin::BI__sync_fetch_and_sub:
1608   case Builtin::BI__sync_fetch_and_sub_1:
1609   case Builtin::BI__sync_fetch_and_sub_2:
1610   case Builtin::BI__sync_fetch_and_sub_4:
1611   case Builtin::BI__sync_fetch_and_sub_8:
1612   case Builtin::BI__sync_fetch_and_sub_16:
1613   case Builtin::BI__sync_fetch_and_or:
1614   case Builtin::BI__sync_fetch_and_or_1:
1615   case Builtin::BI__sync_fetch_and_or_2:
1616   case Builtin::BI__sync_fetch_and_or_4:
1617   case Builtin::BI__sync_fetch_and_or_8:
1618   case Builtin::BI__sync_fetch_and_or_16:
1619   case Builtin::BI__sync_fetch_and_and:
1620   case Builtin::BI__sync_fetch_and_and_1:
1621   case Builtin::BI__sync_fetch_and_and_2:
1622   case Builtin::BI__sync_fetch_and_and_4:
1623   case Builtin::BI__sync_fetch_and_and_8:
1624   case Builtin::BI__sync_fetch_and_and_16:
1625   case Builtin::BI__sync_fetch_and_xor:
1626   case Builtin::BI__sync_fetch_and_xor_1:
1627   case Builtin::BI__sync_fetch_and_xor_2:
1628   case Builtin::BI__sync_fetch_and_xor_4:
1629   case Builtin::BI__sync_fetch_and_xor_8:
1630   case Builtin::BI__sync_fetch_and_xor_16:
1631   case Builtin::BI__sync_fetch_and_nand:
1632   case Builtin::BI__sync_fetch_and_nand_1:
1633   case Builtin::BI__sync_fetch_and_nand_2:
1634   case Builtin::BI__sync_fetch_and_nand_4:
1635   case Builtin::BI__sync_fetch_and_nand_8:
1636   case Builtin::BI__sync_fetch_and_nand_16:
1637   case Builtin::BI__sync_add_and_fetch:
1638   case Builtin::BI__sync_add_and_fetch_1:
1639   case Builtin::BI__sync_add_and_fetch_2:
1640   case Builtin::BI__sync_add_and_fetch_4:
1641   case Builtin::BI__sync_add_and_fetch_8:
1642   case Builtin::BI__sync_add_and_fetch_16:
1643   case Builtin::BI__sync_sub_and_fetch:
1644   case Builtin::BI__sync_sub_and_fetch_1:
1645   case Builtin::BI__sync_sub_and_fetch_2:
1646   case Builtin::BI__sync_sub_and_fetch_4:
1647   case Builtin::BI__sync_sub_and_fetch_8:
1648   case Builtin::BI__sync_sub_and_fetch_16:
1649   case Builtin::BI__sync_and_and_fetch:
1650   case Builtin::BI__sync_and_and_fetch_1:
1651   case Builtin::BI__sync_and_and_fetch_2:
1652   case Builtin::BI__sync_and_and_fetch_4:
1653   case Builtin::BI__sync_and_and_fetch_8:
1654   case Builtin::BI__sync_and_and_fetch_16:
1655   case Builtin::BI__sync_or_and_fetch:
1656   case Builtin::BI__sync_or_and_fetch_1:
1657   case Builtin::BI__sync_or_and_fetch_2:
1658   case Builtin::BI__sync_or_and_fetch_4:
1659   case Builtin::BI__sync_or_and_fetch_8:
1660   case Builtin::BI__sync_or_and_fetch_16:
1661   case Builtin::BI__sync_xor_and_fetch:
1662   case Builtin::BI__sync_xor_and_fetch_1:
1663   case Builtin::BI__sync_xor_and_fetch_2:
1664   case Builtin::BI__sync_xor_and_fetch_4:
1665   case Builtin::BI__sync_xor_and_fetch_8:
1666   case Builtin::BI__sync_xor_and_fetch_16:
1667   case Builtin::BI__sync_nand_and_fetch:
1668   case Builtin::BI__sync_nand_and_fetch_1:
1669   case Builtin::BI__sync_nand_and_fetch_2:
1670   case Builtin::BI__sync_nand_and_fetch_4:
1671   case Builtin::BI__sync_nand_and_fetch_8:
1672   case Builtin::BI__sync_nand_and_fetch_16:
1673   case Builtin::BI__sync_val_compare_and_swap:
1674   case Builtin::BI__sync_val_compare_and_swap_1:
1675   case Builtin::BI__sync_val_compare_and_swap_2:
1676   case Builtin::BI__sync_val_compare_and_swap_4:
1677   case Builtin::BI__sync_val_compare_and_swap_8:
1678   case Builtin::BI__sync_val_compare_and_swap_16:
1679   case Builtin::BI__sync_bool_compare_and_swap:
1680   case Builtin::BI__sync_bool_compare_and_swap_1:
1681   case Builtin::BI__sync_bool_compare_and_swap_2:
1682   case Builtin::BI__sync_bool_compare_and_swap_4:
1683   case Builtin::BI__sync_bool_compare_and_swap_8:
1684   case Builtin::BI__sync_bool_compare_and_swap_16:
1685   case Builtin::BI__sync_lock_test_and_set:
1686   case Builtin::BI__sync_lock_test_and_set_1:
1687   case Builtin::BI__sync_lock_test_and_set_2:
1688   case Builtin::BI__sync_lock_test_and_set_4:
1689   case Builtin::BI__sync_lock_test_and_set_8:
1690   case Builtin::BI__sync_lock_test_and_set_16:
1691   case Builtin::BI__sync_lock_release:
1692   case Builtin::BI__sync_lock_release_1:
1693   case Builtin::BI__sync_lock_release_2:
1694   case Builtin::BI__sync_lock_release_4:
1695   case Builtin::BI__sync_lock_release_8:
1696   case Builtin::BI__sync_lock_release_16:
1697   case Builtin::BI__sync_swap:
1698   case Builtin::BI__sync_swap_1:
1699   case Builtin::BI__sync_swap_2:
1700   case Builtin::BI__sync_swap_4:
1701   case Builtin::BI__sync_swap_8:
1702   case Builtin::BI__sync_swap_16:
1703     return SemaBuiltinAtomicOverloaded(TheCallResult);
1704   case Builtin::BI__sync_synchronize:
1705     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1706         << TheCall->getCallee()->getSourceRange();
1707     break;
1708   case Builtin::BI__builtin_nontemporal_load:
1709   case Builtin::BI__builtin_nontemporal_store:
1710     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1711   case Builtin::BI__builtin_memcpy_inline: {
1712     clang::Expr *SizeOp = TheCall->getArg(2);
1713     // We warn about copying to or from `nullptr` pointers when `size` is
1714     // greater than 0. When `size` is value dependent we cannot evaluate its
1715     // value so we bail out.
1716     if (SizeOp->isValueDependent())
1717       break;
1718     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1719       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1720       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1721     }
1722     break;
1723   }
1724 #define BUILTIN(ID, TYPE, ATTRS)
1725 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1726   case Builtin::BI##ID: \
1727     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1728 #include "clang/Basic/Builtins.def"
1729   case Builtin::BI__annotation:
1730     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1731       return ExprError();
1732     break;
1733   case Builtin::BI__builtin_annotation:
1734     if (SemaBuiltinAnnotation(*this, TheCall))
1735       return ExprError();
1736     break;
1737   case Builtin::BI__builtin_addressof:
1738     if (SemaBuiltinAddressof(*this, TheCall))
1739       return ExprError();
1740     break;
1741   case Builtin::BI__builtin_is_aligned:
1742   case Builtin::BI__builtin_align_up:
1743   case Builtin::BI__builtin_align_down:
1744     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1745       return ExprError();
1746     break;
1747   case Builtin::BI__builtin_add_overflow:
1748   case Builtin::BI__builtin_sub_overflow:
1749   case Builtin::BI__builtin_mul_overflow:
1750     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1751       return ExprError();
1752     break;
1753   case Builtin::BI__builtin_operator_new:
1754   case Builtin::BI__builtin_operator_delete: {
1755     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1756     ExprResult Res =
1757         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1758     if (Res.isInvalid())
1759       CorrectDelayedTyposInExpr(TheCallResult.get());
1760     return Res;
1761   }
1762   case Builtin::BI__builtin_dump_struct: {
1763     // We first want to ensure we are called with 2 arguments
1764     if (checkArgCount(*this, TheCall, 2))
1765       return ExprError();
1766     // Ensure that the first argument is of type 'struct XX *'
1767     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1768     const QualType PtrArgType = PtrArg->getType();
1769     if (!PtrArgType->isPointerType() ||
1770         !PtrArgType->getPointeeType()->isRecordType()) {
1771       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1772           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1773           << "structure pointer";
1774       return ExprError();
1775     }
1776 
1777     // Ensure that the second argument is of type 'FunctionType'
1778     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1779     const QualType FnPtrArgType = FnPtrArg->getType();
1780     if (!FnPtrArgType->isPointerType()) {
1781       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1782           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1783           << FnPtrArgType << "'int (*)(const char *, ...)'";
1784       return ExprError();
1785     }
1786 
1787     const auto *FuncType =
1788         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1789 
1790     if (!FuncType) {
1791       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1792           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1793           << FnPtrArgType << "'int (*)(const char *, ...)'";
1794       return ExprError();
1795     }
1796 
1797     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1798       if (!FT->getNumParams()) {
1799         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1800             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1801             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1802         return ExprError();
1803       }
1804       QualType PT = FT->getParamType(0);
1805       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1806           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1807           !PT->getPointeeType().isConstQualified()) {
1808         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1809             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1810             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1811         return ExprError();
1812       }
1813     }
1814 
1815     TheCall->setType(Context.IntTy);
1816     break;
1817   }
1818   case Builtin::BI__builtin_expect_with_probability: {
1819     // We first want to ensure we are called with 3 arguments
1820     if (checkArgCount(*this, TheCall, 3))
1821       return ExprError();
1822     // then check probability is constant float in range [0.0, 1.0]
1823     const Expr *ProbArg = TheCall->getArg(2);
1824     SmallVector<PartialDiagnosticAt, 8> Notes;
1825     Expr::EvalResult Eval;
1826     Eval.Diag = &Notes;
1827     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1828         !Eval.Val.isFloat()) {
1829       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1830           << ProbArg->getSourceRange();
1831       for (const PartialDiagnosticAt &PDiag : Notes)
1832         Diag(PDiag.first, PDiag.second);
1833       return ExprError();
1834     }
1835     llvm::APFloat Probability = Eval.Val.getFloat();
1836     bool LoseInfo = false;
1837     Probability.convert(llvm::APFloat::IEEEdouble(),
1838                         llvm::RoundingMode::Dynamic, &LoseInfo);
1839     if (!(Probability >= llvm::APFloat(0.0) &&
1840           Probability <= llvm::APFloat(1.0))) {
1841       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1842           << ProbArg->getSourceRange();
1843       return ExprError();
1844     }
1845     break;
1846   }
1847   case Builtin::BI__builtin_preserve_access_index:
1848     if (SemaBuiltinPreserveAI(*this, TheCall))
1849       return ExprError();
1850     break;
1851   case Builtin::BI__builtin_call_with_static_chain:
1852     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1853       return ExprError();
1854     break;
1855   case Builtin::BI__exception_code:
1856   case Builtin::BI_exception_code:
1857     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1858                                  diag::err_seh___except_block))
1859       return ExprError();
1860     break;
1861   case Builtin::BI__exception_info:
1862   case Builtin::BI_exception_info:
1863     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1864                                  diag::err_seh___except_filter))
1865       return ExprError();
1866     break;
1867   case Builtin::BI__GetExceptionInfo:
1868     if (checkArgCount(*this, TheCall, 1))
1869       return ExprError();
1870 
1871     if (CheckCXXThrowOperand(
1872             TheCall->getBeginLoc(),
1873             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1874             TheCall))
1875       return ExprError();
1876 
1877     TheCall->setType(Context.VoidPtrTy);
1878     break;
1879   // OpenCL v2.0, s6.13.16 - Pipe functions
1880   case Builtin::BIread_pipe:
1881   case Builtin::BIwrite_pipe:
1882     // Since those two functions are declared with var args, we need a semantic
1883     // check for the argument.
1884     if (SemaBuiltinRWPipe(*this, TheCall))
1885       return ExprError();
1886     break;
1887   case Builtin::BIreserve_read_pipe:
1888   case Builtin::BIreserve_write_pipe:
1889   case Builtin::BIwork_group_reserve_read_pipe:
1890   case Builtin::BIwork_group_reserve_write_pipe:
1891     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1892       return ExprError();
1893     break;
1894   case Builtin::BIsub_group_reserve_read_pipe:
1895   case Builtin::BIsub_group_reserve_write_pipe:
1896     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1897         SemaBuiltinReserveRWPipe(*this, TheCall))
1898       return ExprError();
1899     break;
1900   case Builtin::BIcommit_read_pipe:
1901   case Builtin::BIcommit_write_pipe:
1902   case Builtin::BIwork_group_commit_read_pipe:
1903   case Builtin::BIwork_group_commit_write_pipe:
1904     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1905       return ExprError();
1906     break;
1907   case Builtin::BIsub_group_commit_read_pipe:
1908   case Builtin::BIsub_group_commit_write_pipe:
1909     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1910         SemaBuiltinCommitRWPipe(*this, TheCall))
1911       return ExprError();
1912     break;
1913   case Builtin::BIget_pipe_num_packets:
1914   case Builtin::BIget_pipe_max_packets:
1915     if (SemaBuiltinPipePackets(*this, TheCall))
1916       return ExprError();
1917     break;
1918   case Builtin::BIto_global:
1919   case Builtin::BIto_local:
1920   case Builtin::BIto_private:
1921     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1922       return ExprError();
1923     break;
1924   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1925   case Builtin::BIenqueue_kernel:
1926     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1927       return ExprError();
1928     break;
1929   case Builtin::BIget_kernel_work_group_size:
1930   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1931     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1932       return ExprError();
1933     break;
1934   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1935   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1936     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1937       return ExprError();
1938     break;
1939   case Builtin::BI__builtin_os_log_format:
1940     Cleanup.setExprNeedsCleanups(true);
1941     LLVM_FALLTHROUGH;
1942   case Builtin::BI__builtin_os_log_format_buffer_size:
1943     if (SemaBuiltinOSLogFormat(TheCall))
1944       return ExprError();
1945     break;
1946   case Builtin::BI__builtin_frame_address:
1947   case Builtin::BI__builtin_return_address: {
1948     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1949       return ExprError();
1950 
1951     // -Wframe-address warning if non-zero passed to builtin
1952     // return/frame address.
1953     Expr::EvalResult Result;
1954     if (!TheCall->getArg(0)->isValueDependent() &&
1955         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1956         Result.Val.getInt() != 0)
1957       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1958           << ((BuiltinID == Builtin::BI__builtin_return_address)
1959                   ? "__builtin_return_address"
1960                   : "__builtin_frame_address")
1961           << TheCall->getSourceRange();
1962     break;
1963   }
1964 
1965   case Builtin::BI__builtin_matrix_transpose:
1966     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1967 
1968   case Builtin::BI__builtin_matrix_column_major_load:
1969     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1970 
1971   case Builtin::BI__builtin_matrix_column_major_store:
1972     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1973 
1974   case Builtin::BI__builtin_get_device_side_mangled_name: {
1975     auto Check = [](CallExpr *TheCall) {
1976       if (TheCall->getNumArgs() != 1)
1977         return false;
1978       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
1979       if (!DRE)
1980         return false;
1981       auto *D = DRE->getDecl();
1982       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
1983         return false;
1984       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
1985              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
1986     };
1987     if (!Check(TheCall)) {
1988       Diag(TheCall->getBeginLoc(),
1989            diag::err_hip_invalid_args_builtin_mangled_name);
1990       return ExprError();
1991     }
1992   }
1993   }
1994 
1995   // Since the target specific builtins for each arch overlap, only check those
1996   // of the arch we are compiling for.
1997   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1998     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1999       assert(Context.getAuxTargetInfo() &&
2000              "Aux Target Builtin, but not an aux target?");
2001 
2002       if (CheckTSBuiltinFunctionCall(
2003               *Context.getAuxTargetInfo(),
2004               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2005         return ExprError();
2006     } else {
2007       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2008                                      TheCall))
2009         return ExprError();
2010     }
2011   }
2012 
2013   return TheCallResult;
2014 }
2015 
2016 // Get the valid immediate range for the specified NEON type code.
2017 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2018   NeonTypeFlags Type(t);
2019   int IsQuad = ForceQuad ? true : Type.isQuad();
2020   switch (Type.getEltType()) {
2021   case NeonTypeFlags::Int8:
2022   case NeonTypeFlags::Poly8:
2023     return shift ? 7 : (8 << IsQuad) - 1;
2024   case NeonTypeFlags::Int16:
2025   case NeonTypeFlags::Poly16:
2026     return shift ? 15 : (4 << IsQuad) - 1;
2027   case NeonTypeFlags::Int32:
2028     return shift ? 31 : (2 << IsQuad) - 1;
2029   case NeonTypeFlags::Int64:
2030   case NeonTypeFlags::Poly64:
2031     return shift ? 63 : (1 << IsQuad) - 1;
2032   case NeonTypeFlags::Poly128:
2033     return shift ? 127 : (1 << IsQuad) - 1;
2034   case NeonTypeFlags::Float16:
2035     assert(!shift && "cannot shift float types!");
2036     return (4 << IsQuad) - 1;
2037   case NeonTypeFlags::Float32:
2038     assert(!shift && "cannot shift float types!");
2039     return (2 << IsQuad) - 1;
2040   case NeonTypeFlags::Float64:
2041     assert(!shift && "cannot shift float types!");
2042     return (1 << IsQuad) - 1;
2043   case NeonTypeFlags::BFloat16:
2044     assert(!shift && "cannot shift float types!");
2045     return (4 << IsQuad) - 1;
2046   }
2047   llvm_unreachable("Invalid NeonTypeFlag!");
2048 }
2049 
2050 /// getNeonEltType - Return the QualType corresponding to the elements of
2051 /// the vector type specified by the NeonTypeFlags.  This is used to check
2052 /// the pointer arguments for Neon load/store intrinsics.
2053 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2054                                bool IsPolyUnsigned, bool IsInt64Long) {
2055   switch (Flags.getEltType()) {
2056   case NeonTypeFlags::Int8:
2057     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2058   case NeonTypeFlags::Int16:
2059     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2060   case NeonTypeFlags::Int32:
2061     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2062   case NeonTypeFlags::Int64:
2063     if (IsInt64Long)
2064       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2065     else
2066       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2067                                 : Context.LongLongTy;
2068   case NeonTypeFlags::Poly8:
2069     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2070   case NeonTypeFlags::Poly16:
2071     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2072   case NeonTypeFlags::Poly64:
2073     if (IsInt64Long)
2074       return Context.UnsignedLongTy;
2075     else
2076       return Context.UnsignedLongLongTy;
2077   case NeonTypeFlags::Poly128:
2078     break;
2079   case NeonTypeFlags::Float16:
2080     return Context.HalfTy;
2081   case NeonTypeFlags::Float32:
2082     return Context.FloatTy;
2083   case NeonTypeFlags::Float64:
2084     return Context.DoubleTy;
2085   case NeonTypeFlags::BFloat16:
2086     return Context.BFloat16Ty;
2087   }
2088   llvm_unreachable("Invalid NeonTypeFlag!");
2089 }
2090 
2091 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2092   // Range check SVE intrinsics that take immediate values.
2093   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2094 
2095   switch (BuiltinID) {
2096   default:
2097     return false;
2098 #define GET_SVE_IMMEDIATE_CHECK
2099 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2100 #undef GET_SVE_IMMEDIATE_CHECK
2101   }
2102 
2103   // Perform all the immediate checks for this builtin call.
2104   bool HasError = false;
2105   for (auto &I : ImmChecks) {
2106     int ArgNum, CheckTy, ElementSizeInBits;
2107     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2108 
2109     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2110 
2111     // Function that checks whether the operand (ArgNum) is an immediate
2112     // that is one of the predefined values.
2113     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2114                                    int ErrDiag) -> bool {
2115       // We can't check the value of a dependent argument.
2116       Expr *Arg = TheCall->getArg(ArgNum);
2117       if (Arg->isTypeDependent() || Arg->isValueDependent())
2118         return false;
2119 
2120       // Check constant-ness first.
2121       llvm::APSInt Imm;
2122       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2123         return true;
2124 
2125       if (!CheckImm(Imm.getSExtValue()))
2126         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2127       return false;
2128     };
2129 
2130     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2131     case SVETypeFlags::ImmCheck0_31:
2132       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2133         HasError = true;
2134       break;
2135     case SVETypeFlags::ImmCheck0_13:
2136       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2137         HasError = true;
2138       break;
2139     case SVETypeFlags::ImmCheck1_16:
2140       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2141         HasError = true;
2142       break;
2143     case SVETypeFlags::ImmCheck0_7:
2144       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2145         HasError = true;
2146       break;
2147     case SVETypeFlags::ImmCheckExtract:
2148       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2149                                       (2048 / ElementSizeInBits) - 1))
2150         HasError = true;
2151       break;
2152     case SVETypeFlags::ImmCheckShiftRight:
2153       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2154         HasError = true;
2155       break;
2156     case SVETypeFlags::ImmCheckShiftRightNarrow:
2157       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2158                                       ElementSizeInBits / 2))
2159         HasError = true;
2160       break;
2161     case SVETypeFlags::ImmCheckShiftLeft:
2162       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2163                                       ElementSizeInBits - 1))
2164         HasError = true;
2165       break;
2166     case SVETypeFlags::ImmCheckLaneIndex:
2167       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2168                                       (128 / (1 * ElementSizeInBits)) - 1))
2169         HasError = true;
2170       break;
2171     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2172       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2173                                       (128 / (2 * ElementSizeInBits)) - 1))
2174         HasError = true;
2175       break;
2176     case SVETypeFlags::ImmCheckLaneIndexDot:
2177       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2178                                       (128 / (4 * ElementSizeInBits)) - 1))
2179         HasError = true;
2180       break;
2181     case SVETypeFlags::ImmCheckComplexRot90_270:
2182       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2183                               diag::err_rotation_argument_to_cadd))
2184         HasError = true;
2185       break;
2186     case SVETypeFlags::ImmCheckComplexRotAll90:
2187       if (CheckImmediateInSet(
2188               [](int64_t V) {
2189                 return V == 0 || V == 90 || V == 180 || V == 270;
2190               },
2191               diag::err_rotation_argument_to_cmla))
2192         HasError = true;
2193       break;
2194     case SVETypeFlags::ImmCheck0_1:
2195       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2196         HasError = true;
2197       break;
2198     case SVETypeFlags::ImmCheck0_2:
2199       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2200         HasError = true;
2201       break;
2202     case SVETypeFlags::ImmCheck0_3:
2203       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2204         HasError = true;
2205       break;
2206     }
2207   }
2208 
2209   return HasError;
2210 }
2211 
2212 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2213                                         unsigned BuiltinID, CallExpr *TheCall) {
2214   llvm::APSInt Result;
2215   uint64_t mask = 0;
2216   unsigned TV = 0;
2217   int PtrArgNum = -1;
2218   bool HasConstPtr = false;
2219   switch (BuiltinID) {
2220 #define GET_NEON_OVERLOAD_CHECK
2221 #include "clang/Basic/arm_neon.inc"
2222 #include "clang/Basic/arm_fp16.inc"
2223 #undef GET_NEON_OVERLOAD_CHECK
2224   }
2225 
2226   // For NEON intrinsics which are overloaded on vector element type, validate
2227   // the immediate which specifies which variant to emit.
2228   unsigned ImmArg = TheCall->getNumArgs()-1;
2229   if (mask) {
2230     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2231       return true;
2232 
2233     TV = Result.getLimitedValue(64);
2234     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2235       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2236              << TheCall->getArg(ImmArg)->getSourceRange();
2237   }
2238 
2239   if (PtrArgNum >= 0) {
2240     // Check that pointer arguments have the specified type.
2241     Expr *Arg = TheCall->getArg(PtrArgNum);
2242     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2243       Arg = ICE->getSubExpr();
2244     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2245     QualType RHSTy = RHS.get()->getType();
2246 
2247     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2248     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2249                           Arch == llvm::Triple::aarch64_32 ||
2250                           Arch == llvm::Triple::aarch64_be;
2251     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2252     QualType EltTy =
2253         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2254     if (HasConstPtr)
2255       EltTy = EltTy.withConst();
2256     QualType LHSTy = Context.getPointerType(EltTy);
2257     AssignConvertType ConvTy;
2258     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2259     if (RHS.isInvalid())
2260       return true;
2261     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2262                                  RHS.get(), AA_Assigning))
2263       return true;
2264   }
2265 
2266   // For NEON intrinsics which take an immediate value as part of the
2267   // instruction, range check them here.
2268   unsigned i = 0, l = 0, u = 0;
2269   switch (BuiltinID) {
2270   default:
2271     return false;
2272   #define GET_NEON_IMMEDIATE_CHECK
2273   #include "clang/Basic/arm_neon.inc"
2274   #include "clang/Basic/arm_fp16.inc"
2275   #undef GET_NEON_IMMEDIATE_CHECK
2276   }
2277 
2278   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2279 }
2280 
2281 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2282   switch (BuiltinID) {
2283   default:
2284     return false;
2285   #include "clang/Basic/arm_mve_builtin_sema.inc"
2286   }
2287 }
2288 
2289 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2290                                        CallExpr *TheCall) {
2291   bool Err = false;
2292   switch (BuiltinID) {
2293   default:
2294     return false;
2295 #include "clang/Basic/arm_cde_builtin_sema.inc"
2296   }
2297 
2298   if (Err)
2299     return true;
2300 
2301   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2302 }
2303 
2304 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2305                                         const Expr *CoprocArg, bool WantCDE) {
2306   if (isConstantEvaluated())
2307     return false;
2308 
2309   // We can't check the value of a dependent argument.
2310   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2311     return false;
2312 
2313   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2314   int64_t CoprocNo = CoprocNoAP.getExtValue();
2315   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2316 
2317   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2318   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2319 
2320   if (IsCDECoproc != WantCDE)
2321     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2322            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2323 
2324   return false;
2325 }
2326 
2327 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2328                                         unsigned MaxWidth) {
2329   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2330           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2331           BuiltinID == ARM::BI__builtin_arm_strex ||
2332           BuiltinID == ARM::BI__builtin_arm_stlex ||
2333           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2334           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2335           BuiltinID == AArch64::BI__builtin_arm_strex ||
2336           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2337          "unexpected ARM builtin");
2338   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2339                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2340                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2341                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2342 
2343   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2344 
2345   // Ensure that we have the proper number of arguments.
2346   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2347     return true;
2348 
2349   // Inspect the pointer argument of the atomic builtin.  This should always be
2350   // a pointer type, whose element is an integral scalar or pointer type.
2351   // Because it is a pointer type, we don't have to worry about any implicit
2352   // casts here.
2353   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2354   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2355   if (PointerArgRes.isInvalid())
2356     return true;
2357   PointerArg = PointerArgRes.get();
2358 
2359   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2360   if (!pointerType) {
2361     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2362         << PointerArg->getType() << PointerArg->getSourceRange();
2363     return true;
2364   }
2365 
2366   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2367   // task is to insert the appropriate casts into the AST. First work out just
2368   // what the appropriate type is.
2369   QualType ValType = pointerType->getPointeeType();
2370   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2371   if (IsLdrex)
2372     AddrType.addConst();
2373 
2374   // Issue a warning if the cast is dodgy.
2375   CastKind CastNeeded = CK_NoOp;
2376   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2377     CastNeeded = CK_BitCast;
2378     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2379         << PointerArg->getType() << Context.getPointerType(AddrType)
2380         << AA_Passing << PointerArg->getSourceRange();
2381   }
2382 
2383   // Finally, do the cast and replace the argument with the corrected version.
2384   AddrType = Context.getPointerType(AddrType);
2385   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2386   if (PointerArgRes.isInvalid())
2387     return true;
2388   PointerArg = PointerArgRes.get();
2389 
2390   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2391 
2392   // In general, we allow ints, floats and pointers to be loaded and stored.
2393   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2394       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2395     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2396         << PointerArg->getType() << PointerArg->getSourceRange();
2397     return true;
2398   }
2399 
2400   // But ARM doesn't have instructions to deal with 128-bit versions.
2401   if (Context.getTypeSize(ValType) > MaxWidth) {
2402     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2403     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2404         << PointerArg->getType() << PointerArg->getSourceRange();
2405     return true;
2406   }
2407 
2408   switch (ValType.getObjCLifetime()) {
2409   case Qualifiers::OCL_None:
2410   case Qualifiers::OCL_ExplicitNone:
2411     // okay
2412     break;
2413 
2414   case Qualifiers::OCL_Weak:
2415   case Qualifiers::OCL_Strong:
2416   case Qualifiers::OCL_Autoreleasing:
2417     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2418         << ValType << PointerArg->getSourceRange();
2419     return true;
2420   }
2421 
2422   if (IsLdrex) {
2423     TheCall->setType(ValType);
2424     return false;
2425   }
2426 
2427   // Initialize the argument to be stored.
2428   ExprResult ValArg = TheCall->getArg(0);
2429   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2430       Context, ValType, /*consume*/ false);
2431   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2432   if (ValArg.isInvalid())
2433     return true;
2434   TheCall->setArg(0, ValArg.get());
2435 
2436   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2437   // but the custom checker bypasses all default analysis.
2438   TheCall->setType(Context.IntTy);
2439   return false;
2440 }
2441 
2442 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2443                                        CallExpr *TheCall) {
2444   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2445       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2446       BuiltinID == ARM::BI__builtin_arm_strex ||
2447       BuiltinID == ARM::BI__builtin_arm_stlex) {
2448     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2449   }
2450 
2451   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2452     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2453       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2454   }
2455 
2456   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2457       BuiltinID == ARM::BI__builtin_arm_wsr64)
2458     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2459 
2460   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2461       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2462       BuiltinID == ARM::BI__builtin_arm_wsr ||
2463       BuiltinID == ARM::BI__builtin_arm_wsrp)
2464     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2465 
2466   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2467     return true;
2468   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2469     return true;
2470   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2471     return true;
2472 
2473   // For intrinsics which take an immediate value as part of the instruction,
2474   // range check them here.
2475   // FIXME: VFP Intrinsics should error if VFP not present.
2476   switch (BuiltinID) {
2477   default: return false;
2478   case ARM::BI__builtin_arm_ssat:
2479     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2480   case ARM::BI__builtin_arm_usat:
2481     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2482   case ARM::BI__builtin_arm_ssat16:
2483     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2484   case ARM::BI__builtin_arm_usat16:
2485     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2486   case ARM::BI__builtin_arm_vcvtr_f:
2487   case ARM::BI__builtin_arm_vcvtr_d:
2488     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2489   case ARM::BI__builtin_arm_dmb:
2490   case ARM::BI__builtin_arm_dsb:
2491   case ARM::BI__builtin_arm_isb:
2492   case ARM::BI__builtin_arm_dbg:
2493     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2494   case ARM::BI__builtin_arm_cdp:
2495   case ARM::BI__builtin_arm_cdp2:
2496   case ARM::BI__builtin_arm_mcr:
2497   case ARM::BI__builtin_arm_mcr2:
2498   case ARM::BI__builtin_arm_mrc:
2499   case ARM::BI__builtin_arm_mrc2:
2500   case ARM::BI__builtin_arm_mcrr:
2501   case ARM::BI__builtin_arm_mcrr2:
2502   case ARM::BI__builtin_arm_mrrc:
2503   case ARM::BI__builtin_arm_mrrc2:
2504   case ARM::BI__builtin_arm_ldc:
2505   case ARM::BI__builtin_arm_ldcl:
2506   case ARM::BI__builtin_arm_ldc2:
2507   case ARM::BI__builtin_arm_ldc2l:
2508   case ARM::BI__builtin_arm_stc:
2509   case ARM::BI__builtin_arm_stcl:
2510   case ARM::BI__builtin_arm_stc2:
2511   case ARM::BI__builtin_arm_stc2l:
2512     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2513            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2514                                         /*WantCDE*/ false);
2515   }
2516 }
2517 
2518 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2519                                            unsigned BuiltinID,
2520                                            CallExpr *TheCall) {
2521   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2522       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2523       BuiltinID == AArch64::BI__builtin_arm_strex ||
2524       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2525     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2526   }
2527 
2528   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2529     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2530       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2531       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2532       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2533   }
2534 
2535   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2536       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2537     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2538 
2539   // Memory Tagging Extensions (MTE) Intrinsics
2540   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2541       BuiltinID == AArch64::BI__builtin_arm_addg ||
2542       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2543       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2544       BuiltinID == AArch64::BI__builtin_arm_stg ||
2545       BuiltinID == AArch64::BI__builtin_arm_subp) {
2546     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2547   }
2548 
2549   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2550       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2551       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2552       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2553     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2554 
2555   // Only check the valid encoding range. Any constant in this range would be
2556   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2557   // an exception for incorrect registers. This matches MSVC behavior.
2558   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2559       BuiltinID == AArch64::BI_WriteStatusReg)
2560     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2561 
2562   if (BuiltinID == AArch64::BI__getReg)
2563     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2564 
2565   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2566     return true;
2567 
2568   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2569     return true;
2570 
2571   // For intrinsics which take an immediate value as part of the instruction,
2572   // range check them here.
2573   unsigned i = 0, l = 0, u = 0;
2574   switch (BuiltinID) {
2575   default: return false;
2576   case AArch64::BI__builtin_arm_dmb:
2577   case AArch64::BI__builtin_arm_dsb:
2578   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2579   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2580   }
2581 
2582   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2583 }
2584 
2585 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2586   if (Arg->getType()->getAsPlaceholderType())
2587     return false;
2588 
2589   // The first argument needs to be a record field access.
2590   // If it is an array element access, we delay decision
2591   // to BPF backend to check whether the access is a
2592   // field access or not.
2593   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2594           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2595           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2596 }
2597 
2598 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2599                             QualType VectorTy, QualType EltTy) {
2600   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2601   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2602     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2603         << Call->getSourceRange() << VectorEltTy << EltTy;
2604     return false;
2605   }
2606   return true;
2607 }
2608 
2609 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2610   QualType ArgType = Arg->getType();
2611   if (ArgType->getAsPlaceholderType())
2612     return false;
2613 
2614   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2615   // format:
2616   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2617   //   2. <type> var;
2618   //      __builtin_preserve_type_info(var, flag);
2619   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2620       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2621     return false;
2622 
2623   // Typedef type.
2624   if (ArgType->getAs<TypedefType>())
2625     return true;
2626 
2627   // Record type or Enum type.
2628   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2629   if (const auto *RT = Ty->getAs<RecordType>()) {
2630     if (!RT->getDecl()->getDeclName().isEmpty())
2631       return true;
2632   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2633     if (!ET->getDecl()->getDeclName().isEmpty())
2634       return true;
2635   }
2636 
2637   return false;
2638 }
2639 
2640 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2641   QualType ArgType = Arg->getType();
2642   if (ArgType->getAsPlaceholderType())
2643     return false;
2644 
2645   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2646   // format:
2647   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2648   //                                 flag);
2649   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2650   if (!UO)
2651     return false;
2652 
2653   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2654   if (!CE)
2655     return false;
2656   if (CE->getCastKind() != CK_IntegralToPointer &&
2657       CE->getCastKind() != CK_NullToPointer)
2658     return false;
2659 
2660   // The integer must be from an EnumConstantDecl.
2661   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2662   if (!DR)
2663     return false;
2664 
2665   const EnumConstantDecl *Enumerator =
2666       dyn_cast<EnumConstantDecl>(DR->getDecl());
2667   if (!Enumerator)
2668     return false;
2669 
2670   // The type must be EnumType.
2671   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2672   const auto *ET = Ty->getAs<EnumType>();
2673   if (!ET)
2674     return false;
2675 
2676   // The enum value must be supported.
2677   for (auto *EDI : ET->getDecl()->enumerators()) {
2678     if (EDI == Enumerator)
2679       return true;
2680   }
2681 
2682   return false;
2683 }
2684 
2685 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2686                                        CallExpr *TheCall) {
2687   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2688           BuiltinID == BPF::BI__builtin_btf_type_id ||
2689           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2690           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2691          "unexpected BPF builtin");
2692 
2693   if (checkArgCount(*this, TheCall, 2))
2694     return true;
2695 
2696   // The second argument needs to be a constant int
2697   Expr *Arg = TheCall->getArg(1);
2698   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2699   diag::kind kind;
2700   if (!Value) {
2701     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2702       kind = diag::err_preserve_field_info_not_const;
2703     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2704       kind = diag::err_btf_type_id_not_const;
2705     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2706       kind = diag::err_preserve_type_info_not_const;
2707     else
2708       kind = diag::err_preserve_enum_value_not_const;
2709     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2710     return true;
2711   }
2712 
2713   // The first argument
2714   Arg = TheCall->getArg(0);
2715   bool InvalidArg = false;
2716   bool ReturnUnsignedInt = true;
2717   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2718     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2719       InvalidArg = true;
2720       kind = diag::err_preserve_field_info_not_field;
2721     }
2722   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2723     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2724       InvalidArg = true;
2725       kind = diag::err_preserve_type_info_invalid;
2726     }
2727   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2728     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2729       InvalidArg = true;
2730       kind = diag::err_preserve_enum_value_invalid;
2731     }
2732     ReturnUnsignedInt = false;
2733   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2734     ReturnUnsignedInt = false;
2735   }
2736 
2737   if (InvalidArg) {
2738     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2739     return true;
2740   }
2741 
2742   if (ReturnUnsignedInt)
2743     TheCall->setType(Context.UnsignedIntTy);
2744   else
2745     TheCall->setType(Context.UnsignedLongTy);
2746   return false;
2747 }
2748 
2749 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2750   struct ArgInfo {
2751     uint8_t OpNum;
2752     bool IsSigned;
2753     uint8_t BitWidth;
2754     uint8_t Align;
2755   };
2756   struct BuiltinInfo {
2757     unsigned BuiltinID;
2758     ArgInfo Infos[2];
2759   };
2760 
2761   static BuiltinInfo Infos[] = {
2762     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2763     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2764     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2765     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2766     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2767     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2768     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2769     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2770     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2771     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2772     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2773 
2774     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2776     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2777     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2778     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2779     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2780     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2782     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2783     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2784     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2785 
2786     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2816     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2838                                                       {{ 1, false, 6,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2846                                                       {{ 1, false, 5,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2853                                                        { 2, false, 5,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2855                                                        { 2, false, 6,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2857                                                        { 3, false, 5,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2859                                                        { 3, false, 6,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2876                                                       {{ 2, false, 4,  0 },
2877                                                        { 3, false, 5,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2879                                                       {{ 2, false, 4,  0 },
2880                                                        { 3, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2882                                                       {{ 2, false, 4,  0 },
2883                                                        { 3, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2885                                                       {{ 2, false, 4,  0 },
2886                                                        { 3, false, 5,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2898                                                        { 2, false, 5,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2900                                                        { 2, false, 6,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2910                                                       {{ 1, false, 4,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2913                                                       {{ 1, false, 4,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2923     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2924     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2927     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2930     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2931     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2934                                                       {{ 3, false, 1,  0 }} },
2935     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2939                                                       {{ 3, false, 1,  0 }} },
2940     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2941     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2942     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2943     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2944                                                       {{ 3, false, 1,  0 }} },
2945   };
2946 
2947   // Use a dynamically initialized static to sort the table exactly once on
2948   // first run.
2949   static const bool SortOnce =
2950       (llvm::sort(Infos,
2951                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2952                    return LHS.BuiltinID < RHS.BuiltinID;
2953                  }),
2954        true);
2955   (void)SortOnce;
2956 
2957   const BuiltinInfo *F = llvm::partition_point(
2958       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2959   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2960     return false;
2961 
2962   bool Error = false;
2963 
2964   for (const ArgInfo &A : F->Infos) {
2965     // Ignore empty ArgInfo elements.
2966     if (A.BitWidth == 0)
2967       continue;
2968 
2969     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2970     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2971     if (!A.Align) {
2972       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2973     } else {
2974       unsigned M = 1 << A.Align;
2975       Min *= M;
2976       Max *= M;
2977       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2978                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2979     }
2980   }
2981   return Error;
2982 }
2983 
2984 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2985                                            CallExpr *TheCall) {
2986   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2987 }
2988 
2989 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2990                                         unsigned BuiltinID, CallExpr *TheCall) {
2991   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2992          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2993 }
2994 
2995 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2996                                CallExpr *TheCall) {
2997 
2998   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2999       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3000     if (!TI.hasFeature("dsp"))
3001       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3002   }
3003 
3004   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3005       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3006     if (!TI.hasFeature("dspr2"))
3007       return Diag(TheCall->getBeginLoc(),
3008                   diag::err_mips_builtin_requires_dspr2);
3009   }
3010 
3011   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3012       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3013     if (!TI.hasFeature("msa"))
3014       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3015   }
3016 
3017   return false;
3018 }
3019 
3020 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3021 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3022 // ordering for DSP is unspecified. MSA is ordered by the data format used
3023 // by the underlying instruction i.e., df/m, df/n and then by size.
3024 //
3025 // FIXME: The size tests here should instead be tablegen'd along with the
3026 //        definitions from include/clang/Basic/BuiltinsMips.def.
3027 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3028 //        be too.
3029 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3030   unsigned i = 0, l = 0, u = 0, m = 0;
3031   switch (BuiltinID) {
3032   default: return false;
3033   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3034   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3035   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3036   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3037   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3038   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3039   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3040   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3041   // df/m field.
3042   // These intrinsics take an unsigned 3 bit immediate.
3043   case Mips::BI__builtin_msa_bclri_b:
3044   case Mips::BI__builtin_msa_bnegi_b:
3045   case Mips::BI__builtin_msa_bseti_b:
3046   case Mips::BI__builtin_msa_sat_s_b:
3047   case Mips::BI__builtin_msa_sat_u_b:
3048   case Mips::BI__builtin_msa_slli_b:
3049   case Mips::BI__builtin_msa_srai_b:
3050   case Mips::BI__builtin_msa_srari_b:
3051   case Mips::BI__builtin_msa_srli_b:
3052   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3053   case Mips::BI__builtin_msa_binsli_b:
3054   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3055   // These intrinsics take an unsigned 4 bit immediate.
3056   case Mips::BI__builtin_msa_bclri_h:
3057   case Mips::BI__builtin_msa_bnegi_h:
3058   case Mips::BI__builtin_msa_bseti_h:
3059   case Mips::BI__builtin_msa_sat_s_h:
3060   case Mips::BI__builtin_msa_sat_u_h:
3061   case Mips::BI__builtin_msa_slli_h:
3062   case Mips::BI__builtin_msa_srai_h:
3063   case Mips::BI__builtin_msa_srari_h:
3064   case Mips::BI__builtin_msa_srli_h:
3065   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3066   case Mips::BI__builtin_msa_binsli_h:
3067   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3068   // These intrinsics take an unsigned 5 bit immediate.
3069   // The first block of intrinsics actually have an unsigned 5 bit field,
3070   // not a df/n field.
3071   case Mips::BI__builtin_msa_cfcmsa:
3072   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3073   case Mips::BI__builtin_msa_clei_u_b:
3074   case Mips::BI__builtin_msa_clei_u_h:
3075   case Mips::BI__builtin_msa_clei_u_w:
3076   case Mips::BI__builtin_msa_clei_u_d:
3077   case Mips::BI__builtin_msa_clti_u_b:
3078   case Mips::BI__builtin_msa_clti_u_h:
3079   case Mips::BI__builtin_msa_clti_u_w:
3080   case Mips::BI__builtin_msa_clti_u_d:
3081   case Mips::BI__builtin_msa_maxi_u_b:
3082   case Mips::BI__builtin_msa_maxi_u_h:
3083   case Mips::BI__builtin_msa_maxi_u_w:
3084   case Mips::BI__builtin_msa_maxi_u_d:
3085   case Mips::BI__builtin_msa_mini_u_b:
3086   case Mips::BI__builtin_msa_mini_u_h:
3087   case Mips::BI__builtin_msa_mini_u_w:
3088   case Mips::BI__builtin_msa_mini_u_d:
3089   case Mips::BI__builtin_msa_addvi_b:
3090   case Mips::BI__builtin_msa_addvi_h:
3091   case Mips::BI__builtin_msa_addvi_w:
3092   case Mips::BI__builtin_msa_addvi_d:
3093   case Mips::BI__builtin_msa_bclri_w:
3094   case Mips::BI__builtin_msa_bnegi_w:
3095   case Mips::BI__builtin_msa_bseti_w:
3096   case Mips::BI__builtin_msa_sat_s_w:
3097   case Mips::BI__builtin_msa_sat_u_w:
3098   case Mips::BI__builtin_msa_slli_w:
3099   case Mips::BI__builtin_msa_srai_w:
3100   case Mips::BI__builtin_msa_srari_w:
3101   case Mips::BI__builtin_msa_srli_w:
3102   case Mips::BI__builtin_msa_srlri_w:
3103   case Mips::BI__builtin_msa_subvi_b:
3104   case Mips::BI__builtin_msa_subvi_h:
3105   case Mips::BI__builtin_msa_subvi_w:
3106   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3107   case Mips::BI__builtin_msa_binsli_w:
3108   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3109   // These intrinsics take an unsigned 6 bit immediate.
3110   case Mips::BI__builtin_msa_bclri_d:
3111   case Mips::BI__builtin_msa_bnegi_d:
3112   case Mips::BI__builtin_msa_bseti_d:
3113   case Mips::BI__builtin_msa_sat_s_d:
3114   case Mips::BI__builtin_msa_sat_u_d:
3115   case Mips::BI__builtin_msa_slli_d:
3116   case Mips::BI__builtin_msa_srai_d:
3117   case Mips::BI__builtin_msa_srari_d:
3118   case Mips::BI__builtin_msa_srli_d:
3119   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3120   case Mips::BI__builtin_msa_binsli_d:
3121   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3122   // These intrinsics take a signed 5 bit immediate.
3123   case Mips::BI__builtin_msa_ceqi_b:
3124   case Mips::BI__builtin_msa_ceqi_h:
3125   case Mips::BI__builtin_msa_ceqi_w:
3126   case Mips::BI__builtin_msa_ceqi_d:
3127   case Mips::BI__builtin_msa_clti_s_b:
3128   case Mips::BI__builtin_msa_clti_s_h:
3129   case Mips::BI__builtin_msa_clti_s_w:
3130   case Mips::BI__builtin_msa_clti_s_d:
3131   case Mips::BI__builtin_msa_clei_s_b:
3132   case Mips::BI__builtin_msa_clei_s_h:
3133   case Mips::BI__builtin_msa_clei_s_w:
3134   case Mips::BI__builtin_msa_clei_s_d:
3135   case Mips::BI__builtin_msa_maxi_s_b:
3136   case Mips::BI__builtin_msa_maxi_s_h:
3137   case Mips::BI__builtin_msa_maxi_s_w:
3138   case Mips::BI__builtin_msa_maxi_s_d:
3139   case Mips::BI__builtin_msa_mini_s_b:
3140   case Mips::BI__builtin_msa_mini_s_h:
3141   case Mips::BI__builtin_msa_mini_s_w:
3142   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3143   // These intrinsics take an unsigned 8 bit immediate.
3144   case Mips::BI__builtin_msa_andi_b:
3145   case Mips::BI__builtin_msa_nori_b:
3146   case Mips::BI__builtin_msa_ori_b:
3147   case Mips::BI__builtin_msa_shf_b:
3148   case Mips::BI__builtin_msa_shf_h:
3149   case Mips::BI__builtin_msa_shf_w:
3150   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3151   case Mips::BI__builtin_msa_bseli_b:
3152   case Mips::BI__builtin_msa_bmnzi_b:
3153   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3154   // df/n format
3155   // These intrinsics take an unsigned 4 bit immediate.
3156   case Mips::BI__builtin_msa_copy_s_b:
3157   case Mips::BI__builtin_msa_copy_u_b:
3158   case Mips::BI__builtin_msa_insve_b:
3159   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3160   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3161   // These intrinsics take an unsigned 3 bit immediate.
3162   case Mips::BI__builtin_msa_copy_s_h:
3163   case Mips::BI__builtin_msa_copy_u_h:
3164   case Mips::BI__builtin_msa_insve_h:
3165   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3166   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3167   // These intrinsics take an unsigned 2 bit immediate.
3168   case Mips::BI__builtin_msa_copy_s_w:
3169   case Mips::BI__builtin_msa_copy_u_w:
3170   case Mips::BI__builtin_msa_insve_w:
3171   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3172   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3173   // These intrinsics take an unsigned 1 bit immediate.
3174   case Mips::BI__builtin_msa_copy_s_d:
3175   case Mips::BI__builtin_msa_copy_u_d:
3176   case Mips::BI__builtin_msa_insve_d:
3177   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3178   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3179   // Memory offsets and immediate loads.
3180   // These intrinsics take a signed 10 bit immediate.
3181   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3182   case Mips::BI__builtin_msa_ldi_h:
3183   case Mips::BI__builtin_msa_ldi_w:
3184   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3185   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3186   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3187   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3188   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3189   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3190   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3191   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3192   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3193   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3194   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3195   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3196   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3197   }
3198 
3199   if (!m)
3200     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3201 
3202   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3203          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3204 }
3205 
3206 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3207 /// advancing the pointer over the consumed characters. The decoded type is
3208 /// returned. If the decoded type represents a constant integer with a
3209 /// constraint on its value then Mask is set to that value. The type descriptors
3210 /// used in Str are specific to PPC MMA builtins and are documented in the file
3211 /// defining the PPC builtins.
3212 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3213                                         unsigned &Mask) {
3214   bool RequireICE = false;
3215   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3216   switch (*Str++) {
3217   case 'V':
3218     return Context.getVectorType(Context.UnsignedCharTy, 16,
3219                                  VectorType::VectorKind::AltiVecVector);
3220   case 'i': {
3221     char *End;
3222     unsigned size = strtoul(Str, &End, 10);
3223     assert(End != Str && "Missing constant parameter constraint");
3224     Str = End;
3225     Mask = size;
3226     return Context.IntTy;
3227   }
3228   case 'W': {
3229     char *End;
3230     unsigned size = strtoul(Str, &End, 10);
3231     assert(End != Str && "Missing PowerPC MMA type size");
3232     Str = End;
3233     QualType Type;
3234     switch (size) {
3235   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3236     case size: Type = Context.Id##Ty; break;
3237   #include "clang/Basic/PPCTypes.def"
3238     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3239     }
3240     bool CheckVectorArgs = false;
3241     while (!CheckVectorArgs) {
3242       switch (*Str++) {
3243       case '*':
3244         Type = Context.getPointerType(Type);
3245         break;
3246       case 'C':
3247         Type = Type.withConst();
3248         break;
3249       default:
3250         CheckVectorArgs = true;
3251         --Str;
3252         break;
3253       }
3254     }
3255     return Type;
3256   }
3257   default:
3258     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3259   }
3260 }
3261 
3262 static bool isPPC_64Builtin(unsigned BuiltinID) {
3263   // These builtins only work on PPC 64bit targets.
3264   switch (BuiltinID) {
3265   case PPC::BI__builtin_divde:
3266   case PPC::BI__builtin_divdeu:
3267   case PPC::BI__builtin_bpermd:
3268   case PPC::BI__builtin_ppc_ldarx:
3269   case PPC::BI__builtin_ppc_stdcx:
3270     return true;
3271   }
3272   return false;
3273 }
3274 
3275 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3276                              StringRef FeatureToCheck, unsigned DiagID) {
3277   if (!S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3278     return S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3279   return false;
3280 }
3281 
3282 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3283                                        CallExpr *TheCall) {
3284   unsigned i = 0, l = 0, u = 0;
3285   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3286 
3287   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3288     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3289            << TheCall->getSourceRange();
3290 
3291   switch (BuiltinID) {
3292   default: return false;
3293   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3294   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3295     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3296            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3297   case PPC::BI__builtin_altivec_dss:
3298     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3299   case PPC::BI__builtin_tbegin:
3300   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3301   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3302   case PPC::BI__builtin_tabortwc:
3303   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3304   case PPC::BI__builtin_tabortwci:
3305   case PPC::BI__builtin_tabortdci:
3306     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3307            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3308   case PPC::BI__builtin_altivec_dst:
3309   case PPC::BI__builtin_altivec_dstt:
3310   case PPC::BI__builtin_altivec_dstst:
3311   case PPC::BI__builtin_altivec_dststt:
3312     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3313   case PPC::BI__builtin_vsx_xxpermdi:
3314   case PPC::BI__builtin_vsx_xxsldwi:
3315     return SemaBuiltinVSX(TheCall);
3316   case PPC::BI__builtin_divwe:
3317   case PPC::BI__builtin_divweu:
3318   case PPC::BI__builtin_divde:
3319   case PPC::BI__builtin_divdeu:
3320     return SemaFeatureCheck(*this, TheCall, "extdiv",
3321                             diag::err_ppc_builtin_only_on_pwr7);
3322   case PPC::BI__builtin_bpermd:
3323     return SemaFeatureCheck(*this, TheCall, "bpermd",
3324                             diag::err_ppc_builtin_only_on_pwr7);
3325   case PPC::BI__builtin_unpack_vector_int128:
3326     return SemaFeatureCheck(*this, TheCall, "vsx",
3327                             diag::err_ppc_builtin_only_on_pwr7) ||
3328            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3329   case PPC::BI__builtin_pack_vector_int128:
3330     return SemaFeatureCheck(*this, TheCall, "vsx",
3331                             diag::err_ppc_builtin_only_on_pwr7);
3332   case PPC::BI__builtin_altivec_vgnb:
3333      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3334   case PPC::BI__builtin_altivec_vec_replace_elt:
3335   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3336     QualType VecTy = TheCall->getArg(0)->getType();
3337     QualType EltTy = TheCall->getArg(1)->getType();
3338     unsigned Width = Context.getIntWidth(EltTy);
3339     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3340            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3341   }
3342   case PPC::BI__builtin_vsx_xxeval:
3343      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3344   case PPC::BI__builtin_altivec_vsldbi:
3345      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3346   case PPC::BI__builtin_altivec_vsrdbi:
3347      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3348   case PPC::BI__builtin_vsx_xxpermx:
3349      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3350 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \
3351   case PPC::BI__builtin_##Name: \
3352     return SemaBuiltinPPCMMACall(TheCall, Types);
3353 #include "clang/Basic/BuiltinsPPC.def"
3354   }
3355   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3356 }
3357 
3358 // Check if the given type is a non-pointer PPC MMA type. This function is used
3359 // in Sema to prevent invalid uses of restricted PPC MMA types.
3360 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3361   if (Type->isPointerType() || Type->isArrayType())
3362     return false;
3363 
3364   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3365 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3366   if (false
3367 #include "clang/Basic/PPCTypes.def"
3368      ) {
3369     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3370     return true;
3371   }
3372   return false;
3373 }
3374 
3375 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3376                                           CallExpr *TheCall) {
3377   // position of memory order and scope arguments in the builtin
3378   unsigned OrderIndex, ScopeIndex;
3379   switch (BuiltinID) {
3380   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3381   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3382   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3383   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3384     OrderIndex = 2;
3385     ScopeIndex = 3;
3386     break;
3387   case AMDGPU::BI__builtin_amdgcn_fence:
3388     OrderIndex = 0;
3389     ScopeIndex = 1;
3390     break;
3391   default:
3392     return false;
3393   }
3394 
3395   ExprResult Arg = TheCall->getArg(OrderIndex);
3396   auto ArgExpr = Arg.get();
3397   Expr::EvalResult ArgResult;
3398 
3399   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3400     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3401            << ArgExpr->getType();
3402   auto Ord = ArgResult.Val.getInt().getZExtValue();
3403 
3404   // Check valididty of memory ordering as per C11 / C++11's memody model.
3405   // Only fence needs check. Atomic dec/inc allow all memory orders.
3406   if (!llvm::isValidAtomicOrderingCABI(Ord))
3407     return Diag(ArgExpr->getBeginLoc(),
3408                 diag::warn_atomic_op_has_invalid_memory_order)
3409            << ArgExpr->getSourceRange();
3410   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3411   case llvm::AtomicOrderingCABI::relaxed:
3412   case llvm::AtomicOrderingCABI::consume:
3413     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3414       return Diag(ArgExpr->getBeginLoc(),
3415                   diag::warn_atomic_op_has_invalid_memory_order)
3416              << ArgExpr->getSourceRange();
3417     break;
3418   case llvm::AtomicOrderingCABI::acquire:
3419   case llvm::AtomicOrderingCABI::release:
3420   case llvm::AtomicOrderingCABI::acq_rel:
3421   case llvm::AtomicOrderingCABI::seq_cst:
3422     break;
3423   }
3424 
3425   Arg = TheCall->getArg(ScopeIndex);
3426   ArgExpr = Arg.get();
3427   Expr::EvalResult ArgResult1;
3428   // Check that sync scope is a constant literal
3429   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3430     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3431            << ArgExpr->getType();
3432 
3433   return false;
3434 }
3435 
3436 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3437   llvm::APSInt Result;
3438 
3439   // We can't check the value of a dependent argument.
3440   Expr *Arg = TheCall->getArg(ArgNum);
3441   if (Arg->isTypeDependent() || Arg->isValueDependent())
3442     return false;
3443 
3444   // Check constant-ness first.
3445   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3446     return true;
3447 
3448   int64_t Val = Result.getSExtValue();
3449   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3450     return false;
3451 
3452   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3453          << Arg->getSourceRange();
3454 }
3455 
3456 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3457                                          unsigned BuiltinID,
3458                                          CallExpr *TheCall) {
3459   // CodeGenFunction can also detect this, but this gives a better error
3460   // message.
3461   bool FeatureMissing = false;
3462   SmallVector<StringRef> ReqFeatures;
3463   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3464   Features.split(ReqFeatures, ',');
3465 
3466   // Check if each required feature is included
3467   for (StringRef F : ReqFeatures) {
3468     if (TI.hasFeature(F))
3469       continue;
3470 
3471     // If the feature is 64bit, alter the string so it will print better in
3472     // the diagnostic.
3473     if (F == "64bit")
3474       F = "RV64";
3475 
3476     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3477     F.consume_front("experimental-");
3478     std::string FeatureStr = F.str();
3479     FeatureStr[0] = std::toupper(FeatureStr[0]);
3480 
3481     // Error message
3482     FeatureMissing = true;
3483     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3484         << TheCall->getSourceRange() << StringRef(FeatureStr);
3485   }
3486 
3487   if (FeatureMissing)
3488     return true;
3489 
3490   switch (BuiltinID) {
3491   case RISCV::BI__builtin_rvv_vsetvli:
3492     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3493            CheckRISCVLMUL(TheCall, 2);
3494   case RISCV::BI__builtin_rvv_vsetvlimax:
3495     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3496            CheckRISCVLMUL(TheCall, 1);
3497   case RISCV::BI__builtin_rvv_vget_v_i8m2_i8m1:
3498   case RISCV::BI__builtin_rvv_vget_v_i16m2_i16m1:
3499   case RISCV::BI__builtin_rvv_vget_v_i32m2_i32m1:
3500   case RISCV::BI__builtin_rvv_vget_v_i64m2_i64m1:
3501   case RISCV::BI__builtin_rvv_vget_v_f32m2_f32m1:
3502   case RISCV::BI__builtin_rvv_vget_v_f64m2_f64m1:
3503   case RISCV::BI__builtin_rvv_vget_v_u8m2_u8m1:
3504   case RISCV::BI__builtin_rvv_vget_v_u16m2_u16m1:
3505   case RISCV::BI__builtin_rvv_vget_v_u32m2_u32m1:
3506   case RISCV::BI__builtin_rvv_vget_v_u64m2_u64m1:
3507   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m2:
3508   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m2:
3509   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m2:
3510   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m2:
3511   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m2:
3512   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m2:
3513   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m2:
3514   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m2:
3515   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m2:
3516   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m2:
3517   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m4:
3518   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m4:
3519   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m4:
3520   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m4:
3521   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m4:
3522   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m4:
3523   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m4:
3524   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m4:
3525   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m4:
3526   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m4:
3527     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3528   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m1:
3529   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m1:
3530   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m1:
3531   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m1:
3532   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m1:
3533   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m1:
3534   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m1:
3535   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m1:
3536   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m1:
3537   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m1:
3538   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m2:
3539   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m2:
3540   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m2:
3541   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m2:
3542   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m2:
3543   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m2:
3544   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m2:
3545   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m2:
3546   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m2:
3547   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m2:
3548     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3549   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m1:
3550   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m1:
3551   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m1:
3552   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m1:
3553   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m1:
3554   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m1:
3555   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m1:
3556   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m1:
3557   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m1:
3558   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m1:
3559     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3560   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m2:
3561   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m2:
3562   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m2:
3563   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m2:
3564   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m2:
3565   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m2:
3566   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m2:
3567   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m2:
3568   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m2:
3569   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m2:
3570   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m4:
3571   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m4:
3572   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m4:
3573   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m4:
3574   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m4:
3575   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m4:
3576   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m4:
3577   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m4:
3578   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m4:
3579   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m4:
3580   case RISCV::BI__builtin_rvv_vset_v_i8m4_i8m8:
3581   case RISCV::BI__builtin_rvv_vset_v_i16m4_i16m8:
3582   case RISCV::BI__builtin_rvv_vset_v_i32m4_i32m8:
3583   case RISCV::BI__builtin_rvv_vset_v_i64m4_i64m8:
3584   case RISCV::BI__builtin_rvv_vset_v_f32m4_f32m8:
3585   case RISCV::BI__builtin_rvv_vset_v_f64m4_f64m8:
3586   case RISCV::BI__builtin_rvv_vset_v_u8m4_u8m8:
3587   case RISCV::BI__builtin_rvv_vset_v_u16m4_u16m8:
3588   case RISCV::BI__builtin_rvv_vset_v_u32m4_u32m8:
3589   case RISCV::BI__builtin_rvv_vset_v_u64m4_u64m8:
3590     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3591   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m4:
3592   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m4:
3593   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m4:
3594   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m4:
3595   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m4:
3596   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m4:
3597   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m4:
3598   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m4:
3599   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m4:
3600   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m4:
3601   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m8:
3602   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m8:
3603   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m8:
3604   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m8:
3605   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m8:
3606   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m8:
3607   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m8:
3608   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m8:
3609   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m8:
3610   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m8:
3611     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3612   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m8:
3613   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m8:
3614   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m8:
3615   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m8:
3616   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m8:
3617   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m8:
3618   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m8:
3619   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m8:
3620   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m8:
3621   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m8:
3622     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3623   }
3624 
3625   return false;
3626 }
3627 
3628 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3629                                            CallExpr *TheCall) {
3630   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3631     Expr *Arg = TheCall->getArg(0);
3632     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3633       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3634         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3635                << Arg->getSourceRange();
3636   }
3637 
3638   // For intrinsics which take an immediate value as part of the instruction,
3639   // range check them here.
3640   unsigned i = 0, l = 0, u = 0;
3641   switch (BuiltinID) {
3642   default: return false;
3643   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3644   case SystemZ::BI__builtin_s390_verimb:
3645   case SystemZ::BI__builtin_s390_verimh:
3646   case SystemZ::BI__builtin_s390_verimf:
3647   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3648   case SystemZ::BI__builtin_s390_vfaeb:
3649   case SystemZ::BI__builtin_s390_vfaeh:
3650   case SystemZ::BI__builtin_s390_vfaef:
3651   case SystemZ::BI__builtin_s390_vfaebs:
3652   case SystemZ::BI__builtin_s390_vfaehs:
3653   case SystemZ::BI__builtin_s390_vfaefs:
3654   case SystemZ::BI__builtin_s390_vfaezb:
3655   case SystemZ::BI__builtin_s390_vfaezh:
3656   case SystemZ::BI__builtin_s390_vfaezf:
3657   case SystemZ::BI__builtin_s390_vfaezbs:
3658   case SystemZ::BI__builtin_s390_vfaezhs:
3659   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3660   case SystemZ::BI__builtin_s390_vfisb:
3661   case SystemZ::BI__builtin_s390_vfidb:
3662     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3663            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3664   case SystemZ::BI__builtin_s390_vftcisb:
3665   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3666   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3667   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3668   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3669   case SystemZ::BI__builtin_s390_vstrcb:
3670   case SystemZ::BI__builtin_s390_vstrch:
3671   case SystemZ::BI__builtin_s390_vstrcf:
3672   case SystemZ::BI__builtin_s390_vstrczb:
3673   case SystemZ::BI__builtin_s390_vstrczh:
3674   case SystemZ::BI__builtin_s390_vstrczf:
3675   case SystemZ::BI__builtin_s390_vstrcbs:
3676   case SystemZ::BI__builtin_s390_vstrchs:
3677   case SystemZ::BI__builtin_s390_vstrcfs:
3678   case SystemZ::BI__builtin_s390_vstrczbs:
3679   case SystemZ::BI__builtin_s390_vstrczhs:
3680   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3681   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3682   case SystemZ::BI__builtin_s390_vfminsb:
3683   case SystemZ::BI__builtin_s390_vfmaxsb:
3684   case SystemZ::BI__builtin_s390_vfmindb:
3685   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3686   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3687   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3688   }
3689   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3690 }
3691 
3692 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3693 /// This checks that the target supports __builtin_cpu_supports and
3694 /// that the string argument is constant and valid.
3695 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3696                                    CallExpr *TheCall) {
3697   Expr *Arg = TheCall->getArg(0);
3698 
3699   // Check if the argument is a string literal.
3700   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3701     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3702            << Arg->getSourceRange();
3703 
3704   // Check the contents of the string.
3705   StringRef Feature =
3706       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3707   if (!TI.validateCpuSupports(Feature))
3708     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3709            << Arg->getSourceRange();
3710   return false;
3711 }
3712 
3713 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3714 /// This checks that the target supports __builtin_cpu_is and
3715 /// that the string argument is constant and valid.
3716 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3717   Expr *Arg = TheCall->getArg(0);
3718 
3719   // Check if the argument is a string literal.
3720   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3721     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3722            << Arg->getSourceRange();
3723 
3724   // Check the contents of the string.
3725   StringRef Feature =
3726       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3727   if (!TI.validateCpuIs(Feature))
3728     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3729            << Arg->getSourceRange();
3730   return false;
3731 }
3732 
3733 // Check if the rounding mode is legal.
3734 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3735   // Indicates if this instruction has rounding control or just SAE.
3736   bool HasRC = false;
3737 
3738   unsigned ArgNum = 0;
3739   switch (BuiltinID) {
3740   default:
3741     return false;
3742   case X86::BI__builtin_ia32_vcvttsd2si32:
3743   case X86::BI__builtin_ia32_vcvttsd2si64:
3744   case X86::BI__builtin_ia32_vcvttsd2usi32:
3745   case X86::BI__builtin_ia32_vcvttsd2usi64:
3746   case X86::BI__builtin_ia32_vcvttss2si32:
3747   case X86::BI__builtin_ia32_vcvttss2si64:
3748   case X86::BI__builtin_ia32_vcvttss2usi32:
3749   case X86::BI__builtin_ia32_vcvttss2usi64:
3750     ArgNum = 1;
3751     break;
3752   case X86::BI__builtin_ia32_maxpd512:
3753   case X86::BI__builtin_ia32_maxps512:
3754   case X86::BI__builtin_ia32_minpd512:
3755   case X86::BI__builtin_ia32_minps512:
3756     ArgNum = 2;
3757     break;
3758   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3759   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3760   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3761   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3762   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3763   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3764   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3765   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3766   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3767   case X86::BI__builtin_ia32_exp2pd_mask:
3768   case X86::BI__builtin_ia32_exp2ps_mask:
3769   case X86::BI__builtin_ia32_getexppd512_mask:
3770   case X86::BI__builtin_ia32_getexpps512_mask:
3771   case X86::BI__builtin_ia32_rcp28pd_mask:
3772   case X86::BI__builtin_ia32_rcp28ps_mask:
3773   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3774   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3775   case X86::BI__builtin_ia32_vcomisd:
3776   case X86::BI__builtin_ia32_vcomiss:
3777   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3778     ArgNum = 3;
3779     break;
3780   case X86::BI__builtin_ia32_cmppd512_mask:
3781   case X86::BI__builtin_ia32_cmpps512_mask:
3782   case X86::BI__builtin_ia32_cmpsd_mask:
3783   case X86::BI__builtin_ia32_cmpss_mask:
3784   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3785   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3786   case X86::BI__builtin_ia32_getexpss128_round_mask:
3787   case X86::BI__builtin_ia32_getmantpd512_mask:
3788   case X86::BI__builtin_ia32_getmantps512_mask:
3789   case X86::BI__builtin_ia32_maxsd_round_mask:
3790   case X86::BI__builtin_ia32_maxss_round_mask:
3791   case X86::BI__builtin_ia32_minsd_round_mask:
3792   case X86::BI__builtin_ia32_minss_round_mask:
3793   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3794   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3795   case X86::BI__builtin_ia32_reducepd512_mask:
3796   case X86::BI__builtin_ia32_reduceps512_mask:
3797   case X86::BI__builtin_ia32_rndscalepd_mask:
3798   case X86::BI__builtin_ia32_rndscaleps_mask:
3799   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3800   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3801     ArgNum = 4;
3802     break;
3803   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3804   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3805   case X86::BI__builtin_ia32_fixupimmps512_mask:
3806   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3807   case X86::BI__builtin_ia32_fixupimmsd_mask:
3808   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3809   case X86::BI__builtin_ia32_fixupimmss_mask:
3810   case X86::BI__builtin_ia32_fixupimmss_maskz:
3811   case X86::BI__builtin_ia32_getmantsd_round_mask:
3812   case X86::BI__builtin_ia32_getmantss_round_mask:
3813   case X86::BI__builtin_ia32_rangepd512_mask:
3814   case X86::BI__builtin_ia32_rangeps512_mask:
3815   case X86::BI__builtin_ia32_rangesd128_round_mask:
3816   case X86::BI__builtin_ia32_rangess128_round_mask:
3817   case X86::BI__builtin_ia32_reducesd_mask:
3818   case X86::BI__builtin_ia32_reducess_mask:
3819   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3820   case X86::BI__builtin_ia32_rndscaless_round_mask:
3821     ArgNum = 5;
3822     break;
3823   case X86::BI__builtin_ia32_vcvtsd2si64:
3824   case X86::BI__builtin_ia32_vcvtsd2si32:
3825   case X86::BI__builtin_ia32_vcvtsd2usi32:
3826   case X86::BI__builtin_ia32_vcvtsd2usi64:
3827   case X86::BI__builtin_ia32_vcvtss2si32:
3828   case X86::BI__builtin_ia32_vcvtss2si64:
3829   case X86::BI__builtin_ia32_vcvtss2usi32:
3830   case X86::BI__builtin_ia32_vcvtss2usi64:
3831   case X86::BI__builtin_ia32_sqrtpd512:
3832   case X86::BI__builtin_ia32_sqrtps512:
3833     ArgNum = 1;
3834     HasRC = true;
3835     break;
3836   case X86::BI__builtin_ia32_addpd512:
3837   case X86::BI__builtin_ia32_addps512:
3838   case X86::BI__builtin_ia32_divpd512:
3839   case X86::BI__builtin_ia32_divps512:
3840   case X86::BI__builtin_ia32_mulpd512:
3841   case X86::BI__builtin_ia32_mulps512:
3842   case X86::BI__builtin_ia32_subpd512:
3843   case X86::BI__builtin_ia32_subps512:
3844   case X86::BI__builtin_ia32_cvtsi2sd64:
3845   case X86::BI__builtin_ia32_cvtsi2ss32:
3846   case X86::BI__builtin_ia32_cvtsi2ss64:
3847   case X86::BI__builtin_ia32_cvtusi2sd64:
3848   case X86::BI__builtin_ia32_cvtusi2ss32:
3849   case X86::BI__builtin_ia32_cvtusi2ss64:
3850     ArgNum = 2;
3851     HasRC = true;
3852     break;
3853   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3854   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3855   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3856   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3857   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3858   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3859   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3860   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3861   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3862   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3863   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3864   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3865   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3866   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3867   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3868     ArgNum = 3;
3869     HasRC = true;
3870     break;
3871   case X86::BI__builtin_ia32_addss_round_mask:
3872   case X86::BI__builtin_ia32_addsd_round_mask:
3873   case X86::BI__builtin_ia32_divss_round_mask:
3874   case X86::BI__builtin_ia32_divsd_round_mask:
3875   case X86::BI__builtin_ia32_mulss_round_mask:
3876   case X86::BI__builtin_ia32_mulsd_round_mask:
3877   case X86::BI__builtin_ia32_subss_round_mask:
3878   case X86::BI__builtin_ia32_subsd_round_mask:
3879   case X86::BI__builtin_ia32_scalefpd512_mask:
3880   case X86::BI__builtin_ia32_scalefps512_mask:
3881   case X86::BI__builtin_ia32_scalefsd_round_mask:
3882   case X86::BI__builtin_ia32_scalefss_round_mask:
3883   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3884   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3885   case X86::BI__builtin_ia32_sqrtss_round_mask:
3886   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3887   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3888   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3889   case X86::BI__builtin_ia32_vfmaddss3_mask:
3890   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3891   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3892   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3893   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3894   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3895   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3896   case X86::BI__builtin_ia32_vfmaddps512_mask:
3897   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3898   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3899   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3900   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3901   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3902   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3903   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3904   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3905   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3906   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3907   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3908     ArgNum = 4;
3909     HasRC = true;
3910     break;
3911   }
3912 
3913   llvm::APSInt Result;
3914 
3915   // We can't check the value of a dependent argument.
3916   Expr *Arg = TheCall->getArg(ArgNum);
3917   if (Arg->isTypeDependent() || Arg->isValueDependent())
3918     return false;
3919 
3920   // Check constant-ness first.
3921   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3922     return true;
3923 
3924   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3925   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3926   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3927   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3928   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3929       Result == 8/*ROUND_NO_EXC*/ ||
3930       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3931       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3932     return false;
3933 
3934   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3935          << Arg->getSourceRange();
3936 }
3937 
3938 // Check if the gather/scatter scale is legal.
3939 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3940                                              CallExpr *TheCall) {
3941   unsigned ArgNum = 0;
3942   switch (BuiltinID) {
3943   default:
3944     return false;
3945   case X86::BI__builtin_ia32_gatherpfdpd:
3946   case X86::BI__builtin_ia32_gatherpfdps:
3947   case X86::BI__builtin_ia32_gatherpfqpd:
3948   case X86::BI__builtin_ia32_gatherpfqps:
3949   case X86::BI__builtin_ia32_scatterpfdpd:
3950   case X86::BI__builtin_ia32_scatterpfdps:
3951   case X86::BI__builtin_ia32_scatterpfqpd:
3952   case X86::BI__builtin_ia32_scatterpfqps:
3953     ArgNum = 3;
3954     break;
3955   case X86::BI__builtin_ia32_gatherd_pd:
3956   case X86::BI__builtin_ia32_gatherd_pd256:
3957   case X86::BI__builtin_ia32_gatherq_pd:
3958   case X86::BI__builtin_ia32_gatherq_pd256:
3959   case X86::BI__builtin_ia32_gatherd_ps:
3960   case X86::BI__builtin_ia32_gatherd_ps256:
3961   case X86::BI__builtin_ia32_gatherq_ps:
3962   case X86::BI__builtin_ia32_gatherq_ps256:
3963   case X86::BI__builtin_ia32_gatherd_q:
3964   case X86::BI__builtin_ia32_gatherd_q256:
3965   case X86::BI__builtin_ia32_gatherq_q:
3966   case X86::BI__builtin_ia32_gatherq_q256:
3967   case X86::BI__builtin_ia32_gatherd_d:
3968   case X86::BI__builtin_ia32_gatherd_d256:
3969   case X86::BI__builtin_ia32_gatherq_d:
3970   case X86::BI__builtin_ia32_gatherq_d256:
3971   case X86::BI__builtin_ia32_gather3div2df:
3972   case X86::BI__builtin_ia32_gather3div2di:
3973   case X86::BI__builtin_ia32_gather3div4df:
3974   case X86::BI__builtin_ia32_gather3div4di:
3975   case X86::BI__builtin_ia32_gather3div4sf:
3976   case X86::BI__builtin_ia32_gather3div4si:
3977   case X86::BI__builtin_ia32_gather3div8sf:
3978   case X86::BI__builtin_ia32_gather3div8si:
3979   case X86::BI__builtin_ia32_gather3siv2df:
3980   case X86::BI__builtin_ia32_gather3siv2di:
3981   case X86::BI__builtin_ia32_gather3siv4df:
3982   case X86::BI__builtin_ia32_gather3siv4di:
3983   case X86::BI__builtin_ia32_gather3siv4sf:
3984   case X86::BI__builtin_ia32_gather3siv4si:
3985   case X86::BI__builtin_ia32_gather3siv8sf:
3986   case X86::BI__builtin_ia32_gather3siv8si:
3987   case X86::BI__builtin_ia32_gathersiv8df:
3988   case X86::BI__builtin_ia32_gathersiv16sf:
3989   case X86::BI__builtin_ia32_gatherdiv8df:
3990   case X86::BI__builtin_ia32_gatherdiv16sf:
3991   case X86::BI__builtin_ia32_gathersiv8di:
3992   case X86::BI__builtin_ia32_gathersiv16si:
3993   case X86::BI__builtin_ia32_gatherdiv8di:
3994   case X86::BI__builtin_ia32_gatherdiv16si:
3995   case X86::BI__builtin_ia32_scatterdiv2df:
3996   case X86::BI__builtin_ia32_scatterdiv2di:
3997   case X86::BI__builtin_ia32_scatterdiv4df:
3998   case X86::BI__builtin_ia32_scatterdiv4di:
3999   case X86::BI__builtin_ia32_scatterdiv4sf:
4000   case X86::BI__builtin_ia32_scatterdiv4si:
4001   case X86::BI__builtin_ia32_scatterdiv8sf:
4002   case X86::BI__builtin_ia32_scatterdiv8si:
4003   case X86::BI__builtin_ia32_scattersiv2df:
4004   case X86::BI__builtin_ia32_scattersiv2di:
4005   case X86::BI__builtin_ia32_scattersiv4df:
4006   case X86::BI__builtin_ia32_scattersiv4di:
4007   case X86::BI__builtin_ia32_scattersiv4sf:
4008   case X86::BI__builtin_ia32_scattersiv4si:
4009   case X86::BI__builtin_ia32_scattersiv8sf:
4010   case X86::BI__builtin_ia32_scattersiv8si:
4011   case X86::BI__builtin_ia32_scattersiv8df:
4012   case X86::BI__builtin_ia32_scattersiv16sf:
4013   case X86::BI__builtin_ia32_scatterdiv8df:
4014   case X86::BI__builtin_ia32_scatterdiv16sf:
4015   case X86::BI__builtin_ia32_scattersiv8di:
4016   case X86::BI__builtin_ia32_scattersiv16si:
4017   case X86::BI__builtin_ia32_scatterdiv8di:
4018   case X86::BI__builtin_ia32_scatterdiv16si:
4019     ArgNum = 4;
4020     break;
4021   }
4022 
4023   llvm::APSInt Result;
4024 
4025   // We can't check the value of a dependent argument.
4026   Expr *Arg = TheCall->getArg(ArgNum);
4027   if (Arg->isTypeDependent() || Arg->isValueDependent())
4028     return false;
4029 
4030   // Check constant-ness first.
4031   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4032     return true;
4033 
4034   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4035     return false;
4036 
4037   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4038          << Arg->getSourceRange();
4039 }
4040 
4041 enum { TileRegLow = 0, TileRegHigh = 7 };
4042 
4043 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4044                                              ArrayRef<int> ArgNums) {
4045   for (int ArgNum : ArgNums) {
4046     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4047       return true;
4048   }
4049   return false;
4050 }
4051 
4052 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4053                                         ArrayRef<int> ArgNums) {
4054   // Because the max number of tile register is TileRegHigh + 1, so here we use
4055   // each bit to represent the usage of them in bitset.
4056   std::bitset<TileRegHigh + 1> ArgValues;
4057   for (int ArgNum : ArgNums) {
4058     Expr *Arg = TheCall->getArg(ArgNum);
4059     if (Arg->isTypeDependent() || Arg->isValueDependent())
4060       continue;
4061 
4062     llvm::APSInt Result;
4063     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4064       return true;
4065     int ArgExtValue = Result.getExtValue();
4066     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4067            "Incorrect tile register num.");
4068     if (ArgValues.test(ArgExtValue))
4069       return Diag(TheCall->getBeginLoc(),
4070                   diag::err_x86_builtin_tile_arg_duplicate)
4071              << TheCall->getArg(ArgNum)->getSourceRange();
4072     ArgValues.set(ArgExtValue);
4073   }
4074   return false;
4075 }
4076 
4077 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4078                                                 ArrayRef<int> ArgNums) {
4079   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4080          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4081 }
4082 
4083 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4084   switch (BuiltinID) {
4085   default:
4086     return false;
4087   case X86::BI__builtin_ia32_tileloadd64:
4088   case X86::BI__builtin_ia32_tileloaddt164:
4089   case X86::BI__builtin_ia32_tilestored64:
4090   case X86::BI__builtin_ia32_tilezero:
4091     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4092   case X86::BI__builtin_ia32_tdpbssd:
4093   case X86::BI__builtin_ia32_tdpbsud:
4094   case X86::BI__builtin_ia32_tdpbusd:
4095   case X86::BI__builtin_ia32_tdpbuud:
4096   case X86::BI__builtin_ia32_tdpbf16ps:
4097     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4098   }
4099 }
4100 static bool isX86_32Builtin(unsigned BuiltinID) {
4101   // These builtins only work on x86-32 targets.
4102   switch (BuiltinID) {
4103   case X86::BI__builtin_ia32_readeflags_u32:
4104   case X86::BI__builtin_ia32_writeeflags_u32:
4105     return true;
4106   }
4107 
4108   return false;
4109 }
4110 
4111 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4112                                        CallExpr *TheCall) {
4113   if (BuiltinID == X86::BI__builtin_cpu_supports)
4114     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4115 
4116   if (BuiltinID == X86::BI__builtin_cpu_is)
4117     return SemaBuiltinCpuIs(*this, TI, TheCall);
4118 
4119   // Check for 32-bit only builtins on a 64-bit target.
4120   const llvm::Triple &TT = TI.getTriple();
4121   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4122     return Diag(TheCall->getCallee()->getBeginLoc(),
4123                 diag::err_32_bit_builtin_64_bit_tgt);
4124 
4125   // If the intrinsic has rounding or SAE make sure its valid.
4126   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4127     return true;
4128 
4129   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4130   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4131     return true;
4132 
4133   // If the intrinsic has a tile arguments, make sure they are valid.
4134   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4135     return true;
4136 
4137   // For intrinsics which take an immediate value as part of the instruction,
4138   // range check them here.
4139   int i = 0, l = 0, u = 0;
4140   switch (BuiltinID) {
4141   default:
4142     return false;
4143   case X86::BI__builtin_ia32_vec_ext_v2si:
4144   case X86::BI__builtin_ia32_vec_ext_v2di:
4145   case X86::BI__builtin_ia32_vextractf128_pd256:
4146   case X86::BI__builtin_ia32_vextractf128_ps256:
4147   case X86::BI__builtin_ia32_vextractf128_si256:
4148   case X86::BI__builtin_ia32_extract128i256:
4149   case X86::BI__builtin_ia32_extractf64x4_mask:
4150   case X86::BI__builtin_ia32_extracti64x4_mask:
4151   case X86::BI__builtin_ia32_extractf32x8_mask:
4152   case X86::BI__builtin_ia32_extracti32x8_mask:
4153   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4154   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4155   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4156   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4157     i = 1; l = 0; u = 1;
4158     break;
4159   case X86::BI__builtin_ia32_vec_set_v2di:
4160   case X86::BI__builtin_ia32_vinsertf128_pd256:
4161   case X86::BI__builtin_ia32_vinsertf128_ps256:
4162   case X86::BI__builtin_ia32_vinsertf128_si256:
4163   case X86::BI__builtin_ia32_insert128i256:
4164   case X86::BI__builtin_ia32_insertf32x8:
4165   case X86::BI__builtin_ia32_inserti32x8:
4166   case X86::BI__builtin_ia32_insertf64x4:
4167   case X86::BI__builtin_ia32_inserti64x4:
4168   case X86::BI__builtin_ia32_insertf64x2_256:
4169   case X86::BI__builtin_ia32_inserti64x2_256:
4170   case X86::BI__builtin_ia32_insertf32x4_256:
4171   case X86::BI__builtin_ia32_inserti32x4_256:
4172     i = 2; l = 0; u = 1;
4173     break;
4174   case X86::BI__builtin_ia32_vpermilpd:
4175   case X86::BI__builtin_ia32_vec_ext_v4hi:
4176   case X86::BI__builtin_ia32_vec_ext_v4si:
4177   case X86::BI__builtin_ia32_vec_ext_v4sf:
4178   case X86::BI__builtin_ia32_vec_ext_v4di:
4179   case X86::BI__builtin_ia32_extractf32x4_mask:
4180   case X86::BI__builtin_ia32_extracti32x4_mask:
4181   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4182   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4183     i = 1; l = 0; u = 3;
4184     break;
4185   case X86::BI_mm_prefetch:
4186   case X86::BI__builtin_ia32_vec_ext_v8hi:
4187   case X86::BI__builtin_ia32_vec_ext_v8si:
4188     i = 1; l = 0; u = 7;
4189     break;
4190   case X86::BI__builtin_ia32_sha1rnds4:
4191   case X86::BI__builtin_ia32_blendpd:
4192   case X86::BI__builtin_ia32_shufpd:
4193   case X86::BI__builtin_ia32_vec_set_v4hi:
4194   case X86::BI__builtin_ia32_vec_set_v4si:
4195   case X86::BI__builtin_ia32_vec_set_v4di:
4196   case X86::BI__builtin_ia32_shuf_f32x4_256:
4197   case X86::BI__builtin_ia32_shuf_f64x2_256:
4198   case X86::BI__builtin_ia32_shuf_i32x4_256:
4199   case X86::BI__builtin_ia32_shuf_i64x2_256:
4200   case X86::BI__builtin_ia32_insertf64x2_512:
4201   case X86::BI__builtin_ia32_inserti64x2_512:
4202   case X86::BI__builtin_ia32_insertf32x4:
4203   case X86::BI__builtin_ia32_inserti32x4:
4204     i = 2; l = 0; u = 3;
4205     break;
4206   case X86::BI__builtin_ia32_vpermil2pd:
4207   case X86::BI__builtin_ia32_vpermil2pd256:
4208   case X86::BI__builtin_ia32_vpermil2ps:
4209   case X86::BI__builtin_ia32_vpermil2ps256:
4210     i = 3; l = 0; u = 3;
4211     break;
4212   case X86::BI__builtin_ia32_cmpb128_mask:
4213   case X86::BI__builtin_ia32_cmpw128_mask:
4214   case X86::BI__builtin_ia32_cmpd128_mask:
4215   case X86::BI__builtin_ia32_cmpq128_mask:
4216   case X86::BI__builtin_ia32_cmpb256_mask:
4217   case X86::BI__builtin_ia32_cmpw256_mask:
4218   case X86::BI__builtin_ia32_cmpd256_mask:
4219   case X86::BI__builtin_ia32_cmpq256_mask:
4220   case X86::BI__builtin_ia32_cmpb512_mask:
4221   case X86::BI__builtin_ia32_cmpw512_mask:
4222   case X86::BI__builtin_ia32_cmpd512_mask:
4223   case X86::BI__builtin_ia32_cmpq512_mask:
4224   case X86::BI__builtin_ia32_ucmpb128_mask:
4225   case X86::BI__builtin_ia32_ucmpw128_mask:
4226   case X86::BI__builtin_ia32_ucmpd128_mask:
4227   case X86::BI__builtin_ia32_ucmpq128_mask:
4228   case X86::BI__builtin_ia32_ucmpb256_mask:
4229   case X86::BI__builtin_ia32_ucmpw256_mask:
4230   case X86::BI__builtin_ia32_ucmpd256_mask:
4231   case X86::BI__builtin_ia32_ucmpq256_mask:
4232   case X86::BI__builtin_ia32_ucmpb512_mask:
4233   case X86::BI__builtin_ia32_ucmpw512_mask:
4234   case X86::BI__builtin_ia32_ucmpd512_mask:
4235   case X86::BI__builtin_ia32_ucmpq512_mask:
4236   case X86::BI__builtin_ia32_vpcomub:
4237   case X86::BI__builtin_ia32_vpcomuw:
4238   case X86::BI__builtin_ia32_vpcomud:
4239   case X86::BI__builtin_ia32_vpcomuq:
4240   case X86::BI__builtin_ia32_vpcomb:
4241   case X86::BI__builtin_ia32_vpcomw:
4242   case X86::BI__builtin_ia32_vpcomd:
4243   case X86::BI__builtin_ia32_vpcomq:
4244   case X86::BI__builtin_ia32_vec_set_v8hi:
4245   case X86::BI__builtin_ia32_vec_set_v8si:
4246     i = 2; l = 0; u = 7;
4247     break;
4248   case X86::BI__builtin_ia32_vpermilpd256:
4249   case X86::BI__builtin_ia32_roundps:
4250   case X86::BI__builtin_ia32_roundpd:
4251   case X86::BI__builtin_ia32_roundps256:
4252   case X86::BI__builtin_ia32_roundpd256:
4253   case X86::BI__builtin_ia32_getmantpd128_mask:
4254   case X86::BI__builtin_ia32_getmantpd256_mask:
4255   case X86::BI__builtin_ia32_getmantps128_mask:
4256   case X86::BI__builtin_ia32_getmantps256_mask:
4257   case X86::BI__builtin_ia32_getmantpd512_mask:
4258   case X86::BI__builtin_ia32_getmantps512_mask:
4259   case X86::BI__builtin_ia32_vec_ext_v16qi:
4260   case X86::BI__builtin_ia32_vec_ext_v16hi:
4261     i = 1; l = 0; u = 15;
4262     break;
4263   case X86::BI__builtin_ia32_pblendd128:
4264   case X86::BI__builtin_ia32_blendps:
4265   case X86::BI__builtin_ia32_blendpd256:
4266   case X86::BI__builtin_ia32_shufpd256:
4267   case X86::BI__builtin_ia32_roundss:
4268   case X86::BI__builtin_ia32_roundsd:
4269   case X86::BI__builtin_ia32_rangepd128_mask:
4270   case X86::BI__builtin_ia32_rangepd256_mask:
4271   case X86::BI__builtin_ia32_rangepd512_mask:
4272   case X86::BI__builtin_ia32_rangeps128_mask:
4273   case X86::BI__builtin_ia32_rangeps256_mask:
4274   case X86::BI__builtin_ia32_rangeps512_mask:
4275   case X86::BI__builtin_ia32_getmantsd_round_mask:
4276   case X86::BI__builtin_ia32_getmantss_round_mask:
4277   case X86::BI__builtin_ia32_vec_set_v16qi:
4278   case X86::BI__builtin_ia32_vec_set_v16hi:
4279     i = 2; l = 0; u = 15;
4280     break;
4281   case X86::BI__builtin_ia32_vec_ext_v32qi:
4282     i = 1; l = 0; u = 31;
4283     break;
4284   case X86::BI__builtin_ia32_cmpps:
4285   case X86::BI__builtin_ia32_cmpss:
4286   case X86::BI__builtin_ia32_cmppd:
4287   case X86::BI__builtin_ia32_cmpsd:
4288   case X86::BI__builtin_ia32_cmpps256:
4289   case X86::BI__builtin_ia32_cmppd256:
4290   case X86::BI__builtin_ia32_cmpps128_mask:
4291   case X86::BI__builtin_ia32_cmppd128_mask:
4292   case X86::BI__builtin_ia32_cmpps256_mask:
4293   case X86::BI__builtin_ia32_cmppd256_mask:
4294   case X86::BI__builtin_ia32_cmpps512_mask:
4295   case X86::BI__builtin_ia32_cmppd512_mask:
4296   case X86::BI__builtin_ia32_cmpsd_mask:
4297   case X86::BI__builtin_ia32_cmpss_mask:
4298   case X86::BI__builtin_ia32_vec_set_v32qi:
4299     i = 2; l = 0; u = 31;
4300     break;
4301   case X86::BI__builtin_ia32_permdf256:
4302   case X86::BI__builtin_ia32_permdi256:
4303   case X86::BI__builtin_ia32_permdf512:
4304   case X86::BI__builtin_ia32_permdi512:
4305   case X86::BI__builtin_ia32_vpermilps:
4306   case X86::BI__builtin_ia32_vpermilps256:
4307   case X86::BI__builtin_ia32_vpermilpd512:
4308   case X86::BI__builtin_ia32_vpermilps512:
4309   case X86::BI__builtin_ia32_pshufd:
4310   case X86::BI__builtin_ia32_pshufd256:
4311   case X86::BI__builtin_ia32_pshufd512:
4312   case X86::BI__builtin_ia32_pshufhw:
4313   case X86::BI__builtin_ia32_pshufhw256:
4314   case X86::BI__builtin_ia32_pshufhw512:
4315   case X86::BI__builtin_ia32_pshuflw:
4316   case X86::BI__builtin_ia32_pshuflw256:
4317   case X86::BI__builtin_ia32_pshuflw512:
4318   case X86::BI__builtin_ia32_vcvtps2ph:
4319   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4320   case X86::BI__builtin_ia32_vcvtps2ph256:
4321   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4322   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4323   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4324   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4325   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4326   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4327   case X86::BI__builtin_ia32_rndscaleps_mask:
4328   case X86::BI__builtin_ia32_rndscalepd_mask:
4329   case X86::BI__builtin_ia32_reducepd128_mask:
4330   case X86::BI__builtin_ia32_reducepd256_mask:
4331   case X86::BI__builtin_ia32_reducepd512_mask:
4332   case X86::BI__builtin_ia32_reduceps128_mask:
4333   case X86::BI__builtin_ia32_reduceps256_mask:
4334   case X86::BI__builtin_ia32_reduceps512_mask:
4335   case X86::BI__builtin_ia32_prold512:
4336   case X86::BI__builtin_ia32_prolq512:
4337   case X86::BI__builtin_ia32_prold128:
4338   case X86::BI__builtin_ia32_prold256:
4339   case X86::BI__builtin_ia32_prolq128:
4340   case X86::BI__builtin_ia32_prolq256:
4341   case X86::BI__builtin_ia32_prord512:
4342   case X86::BI__builtin_ia32_prorq512:
4343   case X86::BI__builtin_ia32_prord128:
4344   case X86::BI__builtin_ia32_prord256:
4345   case X86::BI__builtin_ia32_prorq128:
4346   case X86::BI__builtin_ia32_prorq256:
4347   case X86::BI__builtin_ia32_fpclasspd128_mask:
4348   case X86::BI__builtin_ia32_fpclasspd256_mask:
4349   case X86::BI__builtin_ia32_fpclassps128_mask:
4350   case X86::BI__builtin_ia32_fpclassps256_mask:
4351   case X86::BI__builtin_ia32_fpclassps512_mask:
4352   case X86::BI__builtin_ia32_fpclasspd512_mask:
4353   case X86::BI__builtin_ia32_fpclasssd_mask:
4354   case X86::BI__builtin_ia32_fpclassss_mask:
4355   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4356   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4357   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4358   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4359   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4360   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4361   case X86::BI__builtin_ia32_kshiftliqi:
4362   case X86::BI__builtin_ia32_kshiftlihi:
4363   case X86::BI__builtin_ia32_kshiftlisi:
4364   case X86::BI__builtin_ia32_kshiftlidi:
4365   case X86::BI__builtin_ia32_kshiftriqi:
4366   case X86::BI__builtin_ia32_kshiftrihi:
4367   case X86::BI__builtin_ia32_kshiftrisi:
4368   case X86::BI__builtin_ia32_kshiftridi:
4369     i = 1; l = 0; u = 255;
4370     break;
4371   case X86::BI__builtin_ia32_vperm2f128_pd256:
4372   case X86::BI__builtin_ia32_vperm2f128_ps256:
4373   case X86::BI__builtin_ia32_vperm2f128_si256:
4374   case X86::BI__builtin_ia32_permti256:
4375   case X86::BI__builtin_ia32_pblendw128:
4376   case X86::BI__builtin_ia32_pblendw256:
4377   case X86::BI__builtin_ia32_blendps256:
4378   case X86::BI__builtin_ia32_pblendd256:
4379   case X86::BI__builtin_ia32_palignr128:
4380   case X86::BI__builtin_ia32_palignr256:
4381   case X86::BI__builtin_ia32_palignr512:
4382   case X86::BI__builtin_ia32_alignq512:
4383   case X86::BI__builtin_ia32_alignd512:
4384   case X86::BI__builtin_ia32_alignd128:
4385   case X86::BI__builtin_ia32_alignd256:
4386   case X86::BI__builtin_ia32_alignq128:
4387   case X86::BI__builtin_ia32_alignq256:
4388   case X86::BI__builtin_ia32_vcomisd:
4389   case X86::BI__builtin_ia32_vcomiss:
4390   case X86::BI__builtin_ia32_shuf_f32x4:
4391   case X86::BI__builtin_ia32_shuf_f64x2:
4392   case X86::BI__builtin_ia32_shuf_i32x4:
4393   case X86::BI__builtin_ia32_shuf_i64x2:
4394   case X86::BI__builtin_ia32_shufpd512:
4395   case X86::BI__builtin_ia32_shufps:
4396   case X86::BI__builtin_ia32_shufps256:
4397   case X86::BI__builtin_ia32_shufps512:
4398   case X86::BI__builtin_ia32_dbpsadbw128:
4399   case X86::BI__builtin_ia32_dbpsadbw256:
4400   case X86::BI__builtin_ia32_dbpsadbw512:
4401   case X86::BI__builtin_ia32_vpshldd128:
4402   case X86::BI__builtin_ia32_vpshldd256:
4403   case X86::BI__builtin_ia32_vpshldd512:
4404   case X86::BI__builtin_ia32_vpshldq128:
4405   case X86::BI__builtin_ia32_vpshldq256:
4406   case X86::BI__builtin_ia32_vpshldq512:
4407   case X86::BI__builtin_ia32_vpshldw128:
4408   case X86::BI__builtin_ia32_vpshldw256:
4409   case X86::BI__builtin_ia32_vpshldw512:
4410   case X86::BI__builtin_ia32_vpshrdd128:
4411   case X86::BI__builtin_ia32_vpshrdd256:
4412   case X86::BI__builtin_ia32_vpshrdd512:
4413   case X86::BI__builtin_ia32_vpshrdq128:
4414   case X86::BI__builtin_ia32_vpshrdq256:
4415   case X86::BI__builtin_ia32_vpshrdq512:
4416   case X86::BI__builtin_ia32_vpshrdw128:
4417   case X86::BI__builtin_ia32_vpshrdw256:
4418   case X86::BI__builtin_ia32_vpshrdw512:
4419     i = 2; l = 0; u = 255;
4420     break;
4421   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4422   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4423   case X86::BI__builtin_ia32_fixupimmps512_mask:
4424   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4425   case X86::BI__builtin_ia32_fixupimmsd_mask:
4426   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4427   case X86::BI__builtin_ia32_fixupimmss_mask:
4428   case X86::BI__builtin_ia32_fixupimmss_maskz:
4429   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4430   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4431   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4432   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4433   case X86::BI__builtin_ia32_fixupimmps128_mask:
4434   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4435   case X86::BI__builtin_ia32_fixupimmps256_mask:
4436   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4437   case X86::BI__builtin_ia32_pternlogd512_mask:
4438   case X86::BI__builtin_ia32_pternlogd512_maskz:
4439   case X86::BI__builtin_ia32_pternlogq512_mask:
4440   case X86::BI__builtin_ia32_pternlogq512_maskz:
4441   case X86::BI__builtin_ia32_pternlogd128_mask:
4442   case X86::BI__builtin_ia32_pternlogd128_maskz:
4443   case X86::BI__builtin_ia32_pternlogd256_mask:
4444   case X86::BI__builtin_ia32_pternlogd256_maskz:
4445   case X86::BI__builtin_ia32_pternlogq128_mask:
4446   case X86::BI__builtin_ia32_pternlogq128_maskz:
4447   case X86::BI__builtin_ia32_pternlogq256_mask:
4448   case X86::BI__builtin_ia32_pternlogq256_maskz:
4449     i = 3; l = 0; u = 255;
4450     break;
4451   case X86::BI__builtin_ia32_gatherpfdpd:
4452   case X86::BI__builtin_ia32_gatherpfdps:
4453   case X86::BI__builtin_ia32_gatherpfqpd:
4454   case X86::BI__builtin_ia32_gatherpfqps:
4455   case X86::BI__builtin_ia32_scatterpfdpd:
4456   case X86::BI__builtin_ia32_scatterpfdps:
4457   case X86::BI__builtin_ia32_scatterpfqpd:
4458   case X86::BI__builtin_ia32_scatterpfqps:
4459     i = 4; l = 2; u = 3;
4460     break;
4461   case X86::BI__builtin_ia32_reducesd_mask:
4462   case X86::BI__builtin_ia32_reducess_mask:
4463   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4464   case X86::BI__builtin_ia32_rndscaless_round_mask:
4465     i = 4; l = 0; u = 255;
4466     break;
4467   }
4468 
4469   // Note that we don't force a hard error on the range check here, allowing
4470   // template-generated or macro-generated dead code to potentially have out-of-
4471   // range values. These need to code generate, but don't need to necessarily
4472   // make any sense. We use a warning that defaults to an error.
4473   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4474 }
4475 
4476 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4477 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4478 /// Returns true when the format fits the function and the FormatStringInfo has
4479 /// been populated.
4480 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4481                                FormatStringInfo *FSI) {
4482   FSI->HasVAListArg = Format->getFirstArg() == 0;
4483   FSI->FormatIdx = Format->getFormatIdx() - 1;
4484   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4485 
4486   // The way the format attribute works in GCC, the implicit this argument
4487   // of member functions is counted. However, it doesn't appear in our own
4488   // lists, so decrement format_idx in that case.
4489   if (IsCXXMember) {
4490     if(FSI->FormatIdx == 0)
4491       return false;
4492     --FSI->FormatIdx;
4493     if (FSI->FirstDataArg != 0)
4494       --FSI->FirstDataArg;
4495   }
4496   return true;
4497 }
4498 
4499 /// Checks if a the given expression evaluates to null.
4500 ///
4501 /// Returns true if the value evaluates to null.
4502 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4503   // If the expression has non-null type, it doesn't evaluate to null.
4504   if (auto nullability
4505         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4506     if (*nullability == NullabilityKind::NonNull)
4507       return false;
4508   }
4509 
4510   // As a special case, transparent unions initialized with zero are
4511   // considered null for the purposes of the nonnull attribute.
4512   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4513     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4514       if (const CompoundLiteralExpr *CLE =
4515           dyn_cast<CompoundLiteralExpr>(Expr))
4516         if (const InitListExpr *ILE =
4517             dyn_cast<InitListExpr>(CLE->getInitializer()))
4518           Expr = ILE->getInit(0);
4519   }
4520 
4521   bool Result;
4522   return (!Expr->isValueDependent() &&
4523           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4524           !Result);
4525 }
4526 
4527 static void CheckNonNullArgument(Sema &S,
4528                                  const Expr *ArgExpr,
4529                                  SourceLocation CallSiteLoc) {
4530   if (CheckNonNullExpr(S, ArgExpr))
4531     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4532                           S.PDiag(diag::warn_null_arg)
4533                               << ArgExpr->getSourceRange());
4534 }
4535 
4536 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4537   FormatStringInfo FSI;
4538   if ((GetFormatStringType(Format) == FST_NSString) &&
4539       getFormatStringInfo(Format, false, &FSI)) {
4540     Idx = FSI.FormatIdx;
4541     return true;
4542   }
4543   return false;
4544 }
4545 
4546 /// Diagnose use of %s directive in an NSString which is being passed
4547 /// as formatting string to formatting method.
4548 static void
4549 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4550                                         const NamedDecl *FDecl,
4551                                         Expr **Args,
4552                                         unsigned NumArgs) {
4553   unsigned Idx = 0;
4554   bool Format = false;
4555   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4556   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4557     Idx = 2;
4558     Format = true;
4559   }
4560   else
4561     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4562       if (S.GetFormatNSStringIdx(I, Idx)) {
4563         Format = true;
4564         break;
4565       }
4566     }
4567   if (!Format || NumArgs <= Idx)
4568     return;
4569   const Expr *FormatExpr = Args[Idx];
4570   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4571     FormatExpr = CSCE->getSubExpr();
4572   const StringLiteral *FormatString;
4573   if (const ObjCStringLiteral *OSL =
4574       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4575     FormatString = OSL->getString();
4576   else
4577     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4578   if (!FormatString)
4579     return;
4580   if (S.FormatStringHasSArg(FormatString)) {
4581     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4582       << "%s" << 1 << 1;
4583     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4584       << FDecl->getDeclName();
4585   }
4586 }
4587 
4588 /// Determine whether the given type has a non-null nullability annotation.
4589 static bool isNonNullType(ASTContext &ctx, QualType type) {
4590   if (auto nullability = type->getNullability(ctx))
4591     return *nullability == NullabilityKind::NonNull;
4592 
4593   return false;
4594 }
4595 
4596 static void CheckNonNullArguments(Sema &S,
4597                                   const NamedDecl *FDecl,
4598                                   const FunctionProtoType *Proto,
4599                                   ArrayRef<const Expr *> Args,
4600                                   SourceLocation CallSiteLoc) {
4601   assert((FDecl || Proto) && "Need a function declaration or prototype");
4602 
4603   // Already checked by by constant evaluator.
4604   if (S.isConstantEvaluated())
4605     return;
4606   // Check the attributes attached to the method/function itself.
4607   llvm::SmallBitVector NonNullArgs;
4608   if (FDecl) {
4609     // Handle the nonnull attribute on the function/method declaration itself.
4610     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4611       if (!NonNull->args_size()) {
4612         // Easy case: all pointer arguments are nonnull.
4613         for (const auto *Arg : Args)
4614           if (S.isValidPointerAttrType(Arg->getType()))
4615             CheckNonNullArgument(S, Arg, CallSiteLoc);
4616         return;
4617       }
4618 
4619       for (const ParamIdx &Idx : NonNull->args()) {
4620         unsigned IdxAST = Idx.getASTIndex();
4621         if (IdxAST >= Args.size())
4622           continue;
4623         if (NonNullArgs.empty())
4624           NonNullArgs.resize(Args.size());
4625         NonNullArgs.set(IdxAST);
4626       }
4627     }
4628   }
4629 
4630   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4631     // Handle the nonnull attribute on the parameters of the
4632     // function/method.
4633     ArrayRef<ParmVarDecl*> parms;
4634     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4635       parms = FD->parameters();
4636     else
4637       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4638 
4639     unsigned ParamIndex = 0;
4640     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4641          I != E; ++I, ++ParamIndex) {
4642       const ParmVarDecl *PVD = *I;
4643       if (PVD->hasAttr<NonNullAttr>() ||
4644           isNonNullType(S.Context, PVD->getType())) {
4645         if (NonNullArgs.empty())
4646           NonNullArgs.resize(Args.size());
4647 
4648         NonNullArgs.set(ParamIndex);
4649       }
4650     }
4651   } else {
4652     // If we have a non-function, non-method declaration but no
4653     // function prototype, try to dig out the function prototype.
4654     if (!Proto) {
4655       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4656         QualType type = VD->getType().getNonReferenceType();
4657         if (auto pointerType = type->getAs<PointerType>())
4658           type = pointerType->getPointeeType();
4659         else if (auto blockType = type->getAs<BlockPointerType>())
4660           type = blockType->getPointeeType();
4661         // FIXME: data member pointers?
4662 
4663         // Dig out the function prototype, if there is one.
4664         Proto = type->getAs<FunctionProtoType>();
4665       }
4666     }
4667 
4668     // Fill in non-null argument information from the nullability
4669     // information on the parameter types (if we have them).
4670     if (Proto) {
4671       unsigned Index = 0;
4672       for (auto paramType : Proto->getParamTypes()) {
4673         if (isNonNullType(S.Context, paramType)) {
4674           if (NonNullArgs.empty())
4675             NonNullArgs.resize(Args.size());
4676 
4677           NonNullArgs.set(Index);
4678         }
4679 
4680         ++Index;
4681       }
4682     }
4683   }
4684 
4685   // Check for non-null arguments.
4686   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4687        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4688     if (NonNullArgs[ArgIndex])
4689       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4690   }
4691 }
4692 
4693 /// Warn if a pointer or reference argument passed to a function points to an
4694 /// object that is less aligned than the parameter. This can happen when
4695 /// creating a typedef with a lower alignment than the original type and then
4696 /// calling functions defined in terms of the original type.
4697 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4698                              StringRef ParamName, QualType ArgTy,
4699                              QualType ParamTy) {
4700 
4701   // If a function accepts a pointer or reference type
4702   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4703     return;
4704 
4705   // If the parameter is a pointer type, get the pointee type for the
4706   // argument too. If the parameter is a reference type, don't try to get
4707   // the pointee type for the argument.
4708   if (ParamTy->isPointerType())
4709     ArgTy = ArgTy->getPointeeType();
4710 
4711   // Remove reference or pointer
4712   ParamTy = ParamTy->getPointeeType();
4713 
4714   // Find expected alignment, and the actual alignment of the passed object.
4715   // getTypeAlignInChars requires complete types
4716   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
4717       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
4718       ArgTy->isUndeducedType())
4719     return;
4720 
4721   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4722   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4723 
4724   // If the argument is less aligned than the parameter, there is a
4725   // potential alignment issue.
4726   if (ArgAlign < ParamAlign)
4727     Diag(Loc, diag::warn_param_mismatched_alignment)
4728         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4729         << ParamName << FDecl;
4730 }
4731 
4732 /// Handles the checks for format strings, non-POD arguments to vararg
4733 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4734 /// attributes.
4735 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4736                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4737                      bool IsMemberFunction, SourceLocation Loc,
4738                      SourceRange Range, VariadicCallType CallType) {
4739   // FIXME: We should check as much as we can in the template definition.
4740   if (CurContext->isDependentContext())
4741     return;
4742 
4743   // Printf and scanf checking.
4744   llvm::SmallBitVector CheckedVarArgs;
4745   if (FDecl) {
4746     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4747       // Only create vector if there are format attributes.
4748       CheckedVarArgs.resize(Args.size());
4749 
4750       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4751                            CheckedVarArgs);
4752     }
4753   }
4754 
4755   // Refuse POD arguments that weren't caught by the format string
4756   // checks above.
4757   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4758   if (CallType != VariadicDoesNotApply &&
4759       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4760     unsigned NumParams = Proto ? Proto->getNumParams()
4761                        : FDecl && isa<FunctionDecl>(FDecl)
4762                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4763                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4764                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4765                        : 0;
4766 
4767     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4768       // Args[ArgIdx] can be null in malformed code.
4769       if (const Expr *Arg = Args[ArgIdx]) {
4770         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4771           checkVariadicArgument(Arg, CallType);
4772       }
4773     }
4774   }
4775 
4776   if (FDecl || Proto) {
4777     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4778 
4779     // Type safety checking.
4780     if (FDecl) {
4781       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4782         CheckArgumentWithTypeTag(I, Args, Loc);
4783     }
4784   }
4785 
4786   // Check that passed arguments match the alignment of original arguments.
4787   // Try to get the missing prototype from the declaration.
4788   if (!Proto && FDecl) {
4789     const auto *FT = FDecl->getFunctionType();
4790     if (isa_and_nonnull<FunctionProtoType>(FT))
4791       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4792   }
4793   if (Proto) {
4794     // For variadic functions, we may have more args than parameters.
4795     // For some K&R functions, we may have less args than parameters.
4796     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4797     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4798       // Args[ArgIdx] can be null in malformed code.
4799       if (const Expr *Arg = Args[ArgIdx]) {
4800         if (Arg->containsErrors())
4801           continue;
4802 
4803         QualType ParamTy = Proto->getParamType(ArgIdx);
4804         QualType ArgTy = Arg->getType();
4805         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4806                           ArgTy, ParamTy);
4807       }
4808     }
4809   }
4810 
4811   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4812     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4813     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4814     if (!Arg->isValueDependent()) {
4815       Expr::EvalResult Align;
4816       if (Arg->EvaluateAsInt(Align, Context)) {
4817         const llvm::APSInt &I = Align.Val.getInt();
4818         if (!I.isPowerOf2())
4819           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4820               << Arg->getSourceRange();
4821 
4822         if (I > Sema::MaximumAlignment)
4823           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4824               << Arg->getSourceRange() << Sema::MaximumAlignment;
4825       }
4826     }
4827   }
4828 
4829   if (FD)
4830     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4831 }
4832 
4833 /// CheckConstructorCall - Check a constructor call for correctness and safety
4834 /// properties not enforced by the C type system.
4835 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4836                                 ArrayRef<const Expr *> Args,
4837                                 const FunctionProtoType *Proto,
4838                                 SourceLocation Loc) {
4839   VariadicCallType CallType =
4840       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4841 
4842   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4843   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4844                     Context.getPointerType(Ctor->getThisObjectType()));
4845 
4846   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4847             Loc, SourceRange(), CallType);
4848 }
4849 
4850 /// CheckFunctionCall - Check a direct function call for various correctness
4851 /// and safety properties not strictly enforced by the C type system.
4852 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4853                              const FunctionProtoType *Proto) {
4854   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4855                               isa<CXXMethodDecl>(FDecl);
4856   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4857                           IsMemberOperatorCall;
4858   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4859                                                   TheCall->getCallee());
4860   Expr** Args = TheCall->getArgs();
4861   unsigned NumArgs = TheCall->getNumArgs();
4862 
4863   Expr *ImplicitThis = nullptr;
4864   if (IsMemberOperatorCall) {
4865     // If this is a call to a member operator, hide the first argument
4866     // from checkCall.
4867     // FIXME: Our choice of AST representation here is less than ideal.
4868     ImplicitThis = Args[0];
4869     ++Args;
4870     --NumArgs;
4871   } else if (IsMemberFunction)
4872     ImplicitThis =
4873         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4874 
4875   if (ImplicitThis) {
4876     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4877     // used.
4878     QualType ThisType = ImplicitThis->getType();
4879     if (!ThisType->isPointerType()) {
4880       assert(!ThisType->isReferenceType());
4881       ThisType = Context.getPointerType(ThisType);
4882     }
4883 
4884     QualType ThisTypeFromDecl =
4885         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
4886 
4887     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4888                       ThisTypeFromDecl);
4889   }
4890 
4891   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4892             IsMemberFunction, TheCall->getRParenLoc(),
4893             TheCall->getCallee()->getSourceRange(), CallType);
4894 
4895   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4896   // None of the checks below are needed for functions that don't have
4897   // simple names (e.g., C++ conversion functions).
4898   if (!FnInfo)
4899     return false;
4900 
4901   CheckTCBEnforcement(TheCall, FDecl);
4902 
4903   CheckAbsoluteValueFunction(TheCall, FDecl);
4904   CheckMaxUnsignedZero(TheCall, FDecl);
4905 
4906   if (getLangOpts().ObjC)
4907     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4908 
4909   unsigned CMId = FDecl->getMemoryFunctionKind();
4910 
4911   // Handle memory setting and copying functions.
4912   switch (CMId) {
4913   case 0:
4914     return false;
4915   case Builtin::BIstrlcpy: // fallthrough
4916   case Builtin::BIstrlcat:
4917     CheckStrlcpycatArguments(TheCall, FnInfo);
4918     break;
4919   case Builtin::BIstrncat:
4920     CheckStrncatArguments(TheCall, FnInfo);
4921     break;
4922   case Builtin::BIfree:
4923     CheckFreeArguments(TheCall);
4924     break;
4925   default:
4926     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4927   }
4928 
4929   return false;
4930 }
4931 
4932 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4933                                ArrayRef<const Expr *> Args) {
4934   VariadicCallType CallType =
4935       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4936 
4937   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4938             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4939             CallType);
4940 
4941   return false;
4942 }
4943 
4944 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4945                             const FunctionProtoType *Proto) {
4946   QualType Ty;
4947   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4948     Ty = V->getType().getNonReferenceType();
4949   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4950     Ty = F->getType().getNonReferenceType();
4951   else
4952     return false;
4953 
4954   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4955       !Ty->isFunctionProtoType())
4956     return false;
4957 
4958   VariadicCallType CallType;
4959   if (!Proto || !Proto->isVariadic()) {
4960     CallType = VariadicDoesNotApply;
4961   } else if (Ty->isBlockPointerType()) {
4962     CallType = VariadicBlock;
4963   } else { // Ty->isFunctionPointerType()
4964     CallType = VariadicFunction;
4965   }
4966 
4967   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4968             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4969             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4970             TheCall->getCallee()->getSourceRange(), CallType);
4971 
4972   return false;
4973 }
4974 
4975 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4976 /// such as function pointers returned from functions.
4977 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4978   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4979                                                   TheCall->getCallee());
4980   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4981             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4982             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4983             TheCall->getCallee()->getSourceRange(), CallType);
4984 
4985   return false;
4986 }
4987 
4988 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4989   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4990     return false;
4991 
4992   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4993   switch (Op) {
4994   case AtomicExpr::AO__c11_atomic_init:
4995   case AtomicExpr::AO__opencl_atomic_init:
4996     llvm_unreachable("There is no ordering argument for an init");
4997 
4998   case AtomicExpr::AO__c11_atomic_load:
4999   case AtomicExpr::AO__opencl_atomic_load:
5000   case AtomicExpr::AO__atomic_load_n:
5001   case AtomicExpr::AO__atomic_load:
5002     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5003            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5004 
5005   case AtomicExpr::AO__c11_atomic_store:
5006   case AtomicExpr::AO__opencl_atomic_store:
5007   case AtomicExpr::AO__atomic_store:
5008   case AtomicExpr::AO__atomic_store_n:
5009     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5010            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5011            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5012 
5013   default:
5014     return true;
5015   }
5016 }
5017 
5018 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5019                                          AtomicExpr::AtomicOp Op) {
5020   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5021   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5022   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5023   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5024                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5025                          Op);
5026 }
5027 
5028 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5029                                  SourceLocation RParenLoc, MultiExprArg Args,
5030                                  AtomicExpr::AtomicOp Op,
5031                                  AtomicArgumentOrder ArgOrder) {
5032   // All the non-OpenCL operations take one of the following forms.
5033   // The OpenCL operations take the __c11 forms with one extra argument for
5034   // synchronization scope.
5035   enum {
5036     // C    __c11_atomic_init(A *, C)
5037     Init,
5038 
5039     // C    __c11_atomic_load(A *, int)
5040     Load,
5041 
5042     // void __atomic_load(A *, CP, int)
5043     LoadCopy,
5044 
5045     // void __atomic_store(A *, CP, int)
5046     Copy,
5047 
5048     // C    __c11_atomic_add(A *, M, int)
5049     Arithmetic,
5050 
5051     // C    __atomic_exchange_n(A *, CP, int)
5052     Xchg,
5053 
5054     // void __atomic_exchange(A *, C *, CP, int)
5055     GNUXchg,
5056 
5057     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5058     C11CmpXchg,
5059 
5060     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5061     GNUCmpXchg
5062   } Form = Init;
5063 
5064   const unsigned NumForm = GNUCmpXchg + 1;
5065   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5066   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5067   // where:
5068   //   C is an appropriate type,
5069   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5070   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5071   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5072   //   the int parameters are for orderings.
5073 
5074   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5075       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5076       "need to update code for modified forms");
5077   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5078                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5079                         AtomicExpr::AO__atomic_load,
5080                 "need to update code for modified C11 atomics");
5081   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5082                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5083   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5084                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5085                IsOpenCL;
5086   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5087              Op == AtomicExpr::AO__atomic_store_n ||
5088              Op == AtomicExpr::AO__atomic_exchange_n ||
5089              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5090   bool IsAddSub = false;
5091 
5092   switch (Op) {
5093   case AtomicExpr::AO__c11_atomic_init:
5094   case AtomicExpr::AO__opencl_atomic_init:
5095     Form = Init;
5096     break;
5097 
5098   case AtomicExpr::AO__c11_atomic_load:
5099   case AtomicExpr::AO__opencl_atomic_load:
5100   case AtomicExpr::AO__atomic_load_n:
5101     Form = Load;
5102     break;
5103 
5104   case AtomicExpr::AO__atomic_load:
5105     Form = LoadCopy;
5106     break;
5107 
5108   case AtomicExpr::AO__c11_atomic_store:
5109   case AtomicExpr::AO__opencl_atomic_store:
5110   case AtomicExpr::AO__atomic_store:
5111   case AtomicExpr::AO__atomic_store_n:
5112     Form = Copy;
5113     break;
5114 
5115   case AtomicExpr::AO__c11_atomic_fetch_add:
5116   case AtomicExpr::AO__c11_atomic_fetch_sub:
5117   case AtomicExpr::AO__opencl_atomic_fetch_add:
5118   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5119   case AtomicExpr::AO__atomic_fetch_add:
5120   case AtomicExpr::AO__atomic_fetch_sub:
5121   case AtomicExpr::AO__atomic_add_fetch:
5122   case AtomicExpr::AO__atomic_sub_fetch:
5123     IsAddSub = true;
5124     Form = Arithmetic;
5125     break;
5126   case AtomicExpr::AO__c11_atomic_fetch_and:
5127   case AtomicExpr::AO__c11_atomic_fetch_or:
5128   case AtomicExpr::AO__c11_atomic_fetch_xor:
5129   case AtomicExpr::AO__opencl_atomic_fetch_and:
5130   case AtomicExpr::AO__opencl_atomic_fetch_or:
5131   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5132   case AtomicExpr::AO__atomic_fetch_and:
5133   case AtomicExpr::AO__atomic_fetch_or:
5134   case AtomicExpr::AO__atomic_fetch_xor:
5135   case AtomicExpr::AO__atomic_fetch_nand:
5136   case AtomicExpr::AO__atomic_and_fetch:
5137   case AtomicExpr::AO__atomic_or_fetch:
5138   case AtomicExpr::AO__atomic_xor_fetch:
5139   case AtomicExpr::AO__atomic_nand_fetch:
5140     Form = Arithmetic;
5141     break;
5142   case AtomicExpr::AO__c11_atomic_fetch_min:
5143   case AtomicExpr::AO__c11_atomic_fetch_max:
5144   case AtomicExpr::AO__opencl_atomic_fetch_min:
5145   case AtomicExpr::AO__opencl_atomic_fetch_max:
5146   case AtomicExpr::AO__atomic_min_fetch:
5147   case AtomicExpr::AO__atomic_max_fetch:
5148   case AtomicExpr::AO__atomic_fetch_min:
5149   case AtomicExpr::AO__atomic_fetch_max:
5150     Form = Arithmetic;
5151     break;
5152 
5153   case AtomicExpr::AO__c11_atomic_exchange:
5154   case AtomicExpr::AO__opencl_atomic_exchange:
5155   case AtomicExpr::AO__atomic_exchange_n:
5156     Form = Xchg;
5157     break;
5158 
5159   case AtomicExpr::AO__atomic_exchange:
5160     Form = GNUXchg;
5161     break;
5162 
5163   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5164   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5165   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5166   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5167     Form = C11CmpXchg;
5168     break;
5169 
5170   case AtomicExpr::AO__atomic_compare_exchange:
5171   case AtomicExpr::AO__atomic_compare_exchange_n:
5172     Form = GNUCmpXchg;
5173     break;
5174   }
5175 
5176   unsigned AdjustedNumArgs = NumArgs[Form];
5177   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
5178     ++AdjustedNumArgs;
5179   // Check we have the right number of arguments.
5180   if (Args.size() < AdjustedNumArgs) {
5181     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5182         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5183         << ExprRange;
5184     return ExprError();
5185   } else if (Args.size() > AdjustedNumArgs) {
5186     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5187          diag::err_typecheck_call_too_many_args)
5188         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5189         << ExprRange;
5190     return ExprError();
5191   }
5192 
5193   // Inspect the first argument of the atomic operation.
5194   Expr *Ptr = Args[0];
5195   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5196   if (ConvertedPtr.isInvalid())
5197     return ExprError();
5198 
5199   Ptr = ConvertedPtr.get();
5200   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5201   if (!pointerType) {
5202     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5203         << Ptr->getType() << Ptr->getSourceRange();
5204     return ExprError();
5205   }
5206 
5207   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5208   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5209   QualType ValType = AtomTy; // 'C'
5210   if (IsC11) {
5211     if (!AtomTy->isAtomicType()) {
5212       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5213           << Ptr->getType() << Ptr->getSourceRange();
5214       return ExprError();
5215     }
5216     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5217         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5218       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5219           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5220           << Ptr->getSourceRange();
5221       return ExprError();
5222     }
5223     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5224   } else if (Form != Load && Form != LoadCopy) {
5225     if (ValType.isConstQualified()) {
5226       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5227           << Ptr->getType() << Ptr->getSourceRange();
5228       return ExprError();
5229     }
5230   }
5231 
5232   // For an arithmetic operation, the implied arithmetic must be well-formed.
5233   if (Form == Arithmetic) {
5234     // gcc does not enforce these rules for GNU atomics, but we do so for
5235     // sanity.
5236     auto IsAllowedValueType = [&](QualType ValType) {
5237       if (ValType->isIntegerType())
5238         return true;
5239       if (ValType->isPointerType())
5240         return true;
5241       if (!ValType->isFloatingType())
5242         return false;
5243       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5244       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5245           &Context.getTargetInfo().getLongDoubleFormat() ==
5246               &llvm::APFloat::x87DoubleExtended())
5247         return false;
5248       return true;
5249     };
5250     if (IsAddSub && !IsAllowedValueType(ValType)) {
5251       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5252           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5253       return ExprError();
5254     }
5255     if (!IsAddSub && !ValType->isIntegerType()) {
5256       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5257           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5258       return ExprError();
5259     }
5260     if (IsC11 && ValType->isPointerType() &&
5261         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5262                             diag::err_incomplete_type)) {
5263       return ExprError();
5264     }
5265   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5266     // For __atomic_*_n operations, the value type must be a scalar integral or
5267     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5268     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5269         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5270     return ExprError();
5271   }
5272 
5273   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5274       !AtomTy->isScalarType()) {
5275     // For GNU atomics, require a trivially-copyable type. This is not part of
5276     // the GNU atomics specification, but we enforce it for sanity.
5277     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5278         << Ptr->getType() << Ptr->getSourceRange();
5279     return ExprError();
5280   }
5281 
5282   switch (ValType.getObjCLifetime()) {
5283   case Qualifiers::OCL_None:
5284   case Qualifiers::OCL_ExplicitNone:
5285     // okay
5286     break;
5287 
5288   case Qualifiers::OCL_Weak:
5289   case Qualifiers::OCL_Strong:
5290   case Qualifiers::OCL_Autoreleasing:
5291     // FIXME: Can this happen? By this point, ValType should be known
5292     // to be trivially copyable.
5293     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5294         << ValType << Ptr->getSourceRange();
5295     return ExprError();
5296   }
5297 
5298   // All atomic operations have an overload which takes a pointer to a volatile
5299   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5300   // into the result or the other operands. Similarly atomic_load takes a
5301   // pointer to a const 'A'.
5302   ValType.removeLocalVolatile();
5303   ValType.removeLocalConst();
5304   QualType ResultType = ValType;
5305   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5306       Form == Init)
5307     ResultType = Context.VoidTy;
5308   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5309     ResultType = Context.BoolTy;
5310 
5311   // The type of a parameter passed 'by value'. In the GNU atomics, such
5312   // arguments are actually passed as pointers.
5313   QualType ByValType = ValType; // 'CP'
5314   bool IsPassedByAddress = false;
5315   if (!IsC11 && !IsN) {
5316     ByValType = Ptr->getType();
5317     IsPassedByAddress = true;
5318   }
5319 
5320   SmallVector<Expr *, 5> APIOrderedArgs;
5321   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5322     APIOrderedArgs.push_back(Args[0]);
5323     switch (Form) {
5324     case Init:
5325     case Load:
5326       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5327       break;
5328     case LoadCopy:
5329     case Copy:
5330     case Arithmetic:
5331     case Xchg:
5332       APIOrderedArgs.push_back(Args[2]); // Val1
5333       APIOrderedArgs.push_back(Args[1]); // Order
5334       break;
5335     case GNUXchg:
5336       APIOrderedArgs.push_back(Args[2]); // Val1
5337       APIOrderedArgs.push_back(Args[3]); // Val2
5338       APIOrderedArgs.push_back(Args[1]); // Order
5339       break;
5340     case C11CmpXchg:
5341       APIOrderedArgs.push_back(Args[2]); // Val1
5342       APIOrderedArgs.push_back(Args[4]); // Val2
5343       APIOrderedArgs.push_back(Args[1]); // Order
5344       APIOrderedArgs.push_back(Args[3]); // OrderFail
5345       break;
5346     case GNUCmpXchg:
5347       APIOrderedArgs.push_back(Args[2]); // Val1
5348       APIOrderedArgs.push_back(Args[4]); // Val2
5349       APIOrderedArgs.push_back(Args[5]); // Weak
5350       APIOrderedArgs.push_back(Args[1]); // Order
5351       APIOrderedArgs.push_back(Args[3]); // OrderFail
5352       break;
5353     }
5354   } else
5355     APIOrderedArgs.append(Args.begin(), Args.end());
5356 
5357   // The first argument's non-CV pointer type is used to deduce the type of
5358   // subsequent arguments, except for:
5359   //  - weak flag (always converted to bool)
5360   //  - memory order (always converted to int)
5361   //  - scope  (always converted to int)
5362   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5363     QualType Ty;
5364     if (i < NumVals[Form] + 1) {
5365       switch (i) {
5366       case 0:
5367         // The first argument is always a pointer. It has a fixed type.
5368         // It is always dereferenced, a nullptr is undefined.
5369         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5370         // Nothing else to do: we already know all we want about this pointer.
5371         continue;
5372       case 1:
5373         // The second argument is the non-atomic operand. For arithmetic, this
5374         // is always passed by value, and for a compare_exchange it is always
5375         // passed by address. For the rest, GNU uses by-address and C11 uses
5376         // by-value.
5377         assert(Form != Load);
5378         if (Form == Arithmetic && ValType->isPointerType())
5379           Ty = Context.getPointerDiffType();
5380         else if (Form == Init || Form == Arithmetic)
5381           Ty = ValType;
5382         else if (Form == Copy || Form == Xchg) {
5383           if (IsPassedByAddress) {
5384             // The value pointer is always dereferenced, a nullptr is undefined.
5385             CheckNonNullArgument(*this, APIOrderedArgs[i],
5386                                  ExprRange.getBegin());
5387           }
5388           Ty = ByValType;
5389         } else {
5390           Expr *ValArg = APIOrderedArgs[i];
5391           // The value pointer is always dereferenced, a nullptr is undefined.
5392           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5393           LangAS AS = LangAS::Default;
5394           // Keep address space of non-atomic pointer type.
5395           if (const PointerType *PtrTy =
5396                   ValArg->getType()->getAs<PointerType>()) {
5397             AS = PtrTy->getPointeeType().getAddressSpace();
5398           }
5399           Ty = Context.getPointerType(
5400               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5401         }
5402         break;
5403       case 2:
5404         // The third argument to compare_exchange / GNU exchange is the desired
5405         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5406         if (IsPassedByAddress)
5407           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5408         Ty = ByValType;
5409         break;
5410       case 3:
5411         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5412         Ty = Context.BoolTy;
5413         break;
5414       }
5415     } else {
5416       // The order(s) and scope are always converted to int.
5417       Ty = Context.IntTy;
5418     }
5419 
5420     InitializedEntity Entity =
5421         InitializedEntity::InitializeParameter(Context, Ty, false);
5422     ExprResult Arg = APIOrderedArgs[i];
5423     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5424     if (Arg.isInvalid())
5425       return true;
5426     APIOrderedArgs[i] = Arg.get();
5427   }
5428 
5429   // Permute the arguments into a 'consistent' order.
5430   SmallVector<Expr*, 5> SubExprs;
5431   SubExprs.push_back(Ptr);
5432   switch (Form) {
5433   case Init:
5434     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5435     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5436     break;
5437   case Load:
5438     SubExprs.push_back(APIOrderedArgs[1]); // Order
5439     break;
5440   case LoadCopy:
5441   case Copy:
5442   case Arithmetic:
5443   case Xchg:
5444     SubExprs.push_back(APIOrderedArgs[2]); // Order
5445     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5446     break;
5447   case GNUXchg:
5448     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5449     SubExprs.push_back(APIOrderedArgs[3]); // Order
5450     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5451     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5452     break;
5453   case C11CmpXchg:
5454     SubExprs.push_back(APIOrderedArgs[3]); // Order
5455     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5456     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5457     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5458     break;
5459   case GNUCmpXchg:
5460     SubExprs.push_back(APIOrderedArgs[4]); // Order
5461     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5462     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5463     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5464     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5465     break;
5466   }
5467 
5468   if (SubExprs.size() >= 2 && Form != Init) {
5469     if (Optional<llvm::APSInt> Result =
5470             SubExprs[1]->getIntegerConstantExpr(Context))
5471       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5472         Diag(SubExprs[1]->getBeginLoc(),
5473              diag::warn_atomic_op_has_invalid_memory_order)
5474             << SubExprs[1]->getSourceRange();
5475   }
5476 
5477   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5478     auto *Scope = Args[Args.size() - 1];
5479     if (Optional<llvm::APSInt> Result =
5480             Scope->getIntegerConstantExpr(Context)) {
5481       if (!ScopeModel->isValid(Result->getZExtValue()))
5482         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5483             << Scope->getSourceRange();
5484     }
5485     SubExprs.push_back(Scope);
5486   }
5487 
5488   AtomicExpr *AE = new (Context)
5489       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5490 
5491   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5492        Op == AtomicExpr::AO__c11_atomic_store ||
5493        Op == AtomicExpr::AO__opencl_atomic_load ||
5494        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5495       Context.AtomicUsesUnsupportedLibcall(AE))
5496     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5497         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5498              Op == AtomicExpr::AO__opencl_atomic_load)
5499                 ? 0
5500                 : 1);
5501 
5502   if (ValType->isExtIntType()) {
5503     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5504     return ExprError();
5505   }
5506 
5507   return AE;
5508 }
5509 
5510 /// checkBuiltinArgument - Given a call to a builtin function, perform
5511 /// normal type-checking on the given argument, updating the call in
5512 /// place.  This is useful when a builtin function requires custom
5513 /// type-checking for some of its arguments but not necessarily all of
5514 /// them.
5515 ///
5516 /// Returns true on error.
5517 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5518   FunctionDecl *Fn = E->getDirectCallee();
5519   assert(Fn && "builtin call without direct callee!");
5520 
5521   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5522   InitializedEntity Entity =
5523     InitializedEntity::InitializeParameter(S.Context, Param);
5524 
5525   ExprResult Arg = E->getArg(0);
5526   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5527   if (Arg.isInvalid())
5528     return true;
5529 
5530   E->setArg(ArgIndex, Arg.get());
5531   return false;
5532 }
5533 
5534 /// We have a call to a function like __sync_fetch_and_add, which is an
5535 /// overloaded function based on the pointer type of its first argument.
5536 /// The main BuildCallExpr routines have already promoted the types of
5537 /// arguments because all of these calls are prototyped as void(...).
5538 ///
5539 /// This function goes through and does final semantic checking for these
5540 /// builtins, as well as generating any warnings.
5541 ExprResult
5542 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5543   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5544   Expr *Callee = TheCall->getCallee();
5545   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5546   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5547 
5548   // Ensure that we have at least one argument to do type inference from.
5549   if (TheCall->getNumArgs() < 1) {
5550     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5551         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5552     return ExprError();
5553   }
5554 
5555   // Inspect the first argument of the atomic builtin.  This should always be
5556   // a pointer type, whose element is an integral scalar or pointer type.
5557   // Because it is a pointer type, we don't have to worry about any implicit
5558   // casts here.
5559   // FIXME: We don't allow floating point scalars as input.
5560   Expr *FirstArg = TheCall->getArg(0);
5561   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5562   if (FirstArgResult.isInvalid())
5563     return ExprError();
5564   FirstArg = FirstArgResult.get();
5565   TheCall->setArg(0, FirstArg);
5566 
5567   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5568   if (!pointerType) {
5569     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5570         << FirstArg->getType() << FirstArg->getSourceRange();
5571     return ExprError();
5572   }
5573 
5574   QualType ValType = pointerType->getPointeeType();
5575   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5576       !ValType->isBlockPointerType()) {
5577     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5578         << FirstArg->getType() << FirstArg->getSourceRange();
5579     return ExprError();
5580   }
5581 
5582   if (ValType.isConstQualified()) {
5583     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5584         << FirstArg->getType() << FirstArg->getSourceRange();
5585     return ExprError();
5586   }
5587 
5588   switch (ValType.getObjCLifetime()) {
5589   case Qualifiers::OCL_None:
5590   case Qualifiers::OCL_ExplicitNone:
5591     // okay
5592     break;
5593 
5594   case Qualifiers::OCL_Weak:
5595   case Qualifiers::OCL_Strong:
5596   case Qualifiers::OCL_Autoreleasing:
5597     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5598         << ValType << FirstArg->getSourceRange();
5599     return ExprError();
5600   }
5601 
5602   // Strip any qualifiers off ValType.
5603   ValType = ValType.getUnqualifiedType();
5604 
5605   // The majority of builtins return a value, but a few have special return
5606   // types, so allow them to override appropriately below.
5607   QualType ResultType = ValType;
5608 
5609   // We need to figure out which concrete builtin this maps onto.  For example,
5610   // __sync_fetch_and_add with a 2 byte object turns into
5611   // __sync_fetch_and_add_2.
5612 #define BUILTIN_ROW(x) \
5613   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5614     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5615 
5616   static const unsigned BuiltinIndices[][5] = {
5617     BUILTIN_ROW(__sync_fetch_and_add),
5618     BUILTIN_ROW(__sync_fetch_and_sub),
5619     BUILTIN_ROW(__sync_fetch_and_or),
5620     BUILTIN_ROW(__sync_fetch_and_and),
5621     BUILTIN_ROW(__sync_fetch_and_xor),
5622     BUILTIN_ROW(__sync_fetch_and_nand),
5623 
5624     BUILTIN_ROW(__sync_add_and_fetch),
5625     BUILTIN_ROW(__sync_sub_and_fetch),
5626     BUILTIN_ROW(__sync_and_and_fetch),
5627     BUILTIN_ROW(__sync_or_and_fetch),
5628     BUILTIN_ROW(__sync_xor_and_fetch),
5629     BUILTIN_ROW(__sync_nand_and_fetch),
5630 
5631     BUILTIN_ROW(__sync_val_compare_and_swap),
5632     BUILTIN_ROW(__sync_bool_compare_and_swap),
5633     BUILTIN_ROW(__sync_lock_test_and_set),
5634     BUILTIN_ROW(__sync_lock_release),
5635     BUILTIN_ROW(__sync_swap)
5636   };
5637 #undef BUILTIN_ROW
5638 
5639   // Determine the index of the size.
5640   unsigned SizeIndex;
5641   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5642   case 1: SizeIndex = 0; break;
5643   case 2: SizeIndex = 1; break;
5644   case 4: SizeIndex = 2; break;
5645   case 8: SizeIndex = 3; break;
5646   case 16: SizeIndex = 4; break;
5647   default:
5648     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5649         << FirstArg->getType() << FirstArg->getSourceRange();
5650     return ExprError();
5651   }
5652 
5653   // Each of these builtins has one pointer argument, followed by some number of
5654   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5655   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5656   // as the number of fixed args.
5657   unsigned BuiltinID = FDecl->getBuiltinID();
5658   unsigned BuiltinIndex, NumFixed = 1;
5659   bool WarnAboutSemanticsChange = false;
5660   switch (BuiltinID) {
5661   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5662   case Builtin::BI__sync_fetch_and_add:
5663   case Builtin::BI__sync_fetch_and_add_1:
5664   case Builtin::BI__sync_fetch_and_add_2:
5665   case Builtin::BI__sync_fetch_and_add_4:
5666   case Builtin::BI__sync_fetch_and_add_8:
5667   case Builtin::BI__sync_fetch_and_add_16:
5668     BuiltinIndex = 0;
5669     break;
5670 
5671   case Builtin::BI__sync_fetch_and_sub:
5672   case Builtin::BI__sync_fetch_and_sub_1:
5673   case Builtin::BI__sync_fetch_and_sub_2:
5674   case Builtin::BI__sync_fetch_and_sub_4:
5675   case Builtin::BI__sync_fetch_and_sub_8:
5676   case Builtin::BI__sync_fetch_and_sub_16:
5677     BuiltinIndex = 1;
5678     break;
5679 
5680   case Builtin::BI__sync_fetch_and_or:
5681   case Builtin::BI__sync_fetch_and_or_1:
5682   case Builtin::BI__sync_fetch_and_or_2:
5683   case Builtin::BI__sync_fetch_and_or_4:
5684   case Builtin::BI__sync_fetch_and_or_8:
5685   case Builtin::BI__sync_fetch_and_or_16:
5686     BuiltinIndex = 2;
5687     break;
5688 
5689   case Builtin::BI__sync_fetch_and_and:
5690   case Builtin::BI__sync_fetch_and_and_1:
5691   case Builtin::BI__sync_fetch_and_and_2:
5692   case Builtin::BI__sync_fetch_and_and_4:
5693   case Builtin::BI__sync_fetch_and_and_8:
5694   case Builtin::BI__sync_fetch_and_and_16:
5695     BuiltinIndex = 3;
5696     break;
5697 
5698   case Builtin::BI__sync_fetch_and_xor:
5699   case Builtin::BI__sync_fetch_and_xor_1:
5700   case Builtin::BI__sync_fetch_and_xor_2:
5701   case Builtin::BI__sync_fetch_and_xor_4:
5702   case Builtin::BI__sync_fetch_and_xor_8:
5703   case Builtin::BI__sync_fetch_and_xor_16:
5704     BuiltinIndex = 4;
5705     break;
5706 
5707   case Builtin::BI__sync_fetch_and_nand:
5708   case Builtin::BI__sync_fetch_and_nand_1:
5709   case Builtin::BI__sync_fetch_and_nand_2:
5710   case Builtin::BI__sync_fetch_and_nand_4:
5711   case Builtin::BI__sync_fetch_and_nand_8:
5712   case Builtin::BI__sync_fetch_and_nand_16:
5713     BuiltinIndex = 5;
5714     WarnAboutSemanticsChange = true;
5715     break;
5716 
5717   case Builtin::BI__sync_add_and_fetch:
5718   case Builtin::BI__sync_add_and_fetch_1:
5719   case Builtin::BI__sync_add_and_fetch_2:
5720   case Builtin::BI__sync_add_and_fetch_4:
5721   case Builtin::BI__sync_add_and_fetch_8:
5722   case Builtin::BI__sync_add_and_fetch_16:
5723     BuiltinIndex = 6;
5724     break;
5725 
5726   case Builtin::BI__sync_sub_and_fetch:
5727   case Builtin::BI__sync_sub_and_fetch_1:
5728   case Builtin::BI__sync_sub_and_fetch_2:
5729   case Builtin::BI__sync_sub_and_fetch_4:
5730   case Builtin::BI__sync_sub_and_fetch_8:
5731   case Builtin::BI__sync_sub_and_fetch_16:
5732     BuiltinIndex = 7;
5733     break;
5734 
5735   case Builtin::BI__sync_and_and_fetch:
5736   case Builtin::BI__sync_and_and_fetch_1:
5737   case Builtin::BI__sync_and_and_fetch_2:
5738   case Builtin::BI__sync_and_and_fetch_4:
5739   case Builtin::BI__sync_and_and_fetch_8:
5740   case Builtin::BI__sync_and_and_fetch_16:
5741     BuiltinIndex = 8;
5742     break;
5743 
5744   case Builtin::BI__sync_or_and_fetch:
5745   case Builtin::BI__sync_or_and_fetch_1:
5746   case Builtin::BI__sync_or_and_fetch_2:
5747   case Builtin::BI__sync_or_and_fetch_4:
5748   case Builtin::BI__sync_or_and_fetch_8:
5749   case Builtin::BI__sync_or_and_fetch_16:
5750     BuiltinIndex = 9;
5751     break;
5752 
5753   case Builtin::BI__sync_xor_and_fetch:
5754   case Builtin::BI__sync_xor_and_fetch_1:
5755   case Builtin::BI__sync_xor_and_fetch_2:
5756   case Builtin::BI__sync_xor_and_fetch_4:
5757   case Builtin::BI__sync_xor_and_fetch_8:
5758   case Builtin::BI__sync_xor_and_fetch_16:
5759     BuiltinIndex = 10;
5760     break;
5761 
5762   case Builtin::BI__sync_nand_and_fetch:
5763   case Builtin::BI__sync_nand_and_fetch_1:
5764   case Builtin::BI__sync_nand_and_fetch_2:
5765   case Builtin::BI__sync_nand_and_fetch_4:
5766   case Builtin::BI__sync_nand_and_fetch_8:
5767   case Builtin::BI__sync_nand_and_fetch_16:
5768     BuiltinIndex = 11;
5769     WarnAboutSemanticsChange = true;
5770     break;
5771 
5772   case Builtin::BI__sync_val_compare_and_swap:
5773   case Builtin::BI__sync_val_compare_and_swap_1:
5774   case Builtin::BI__sync_val_compare_and_swap_2:
5775   case Builtin::BI__sync_val_compare_and_swap_4:
5776   case Builtin::BI__sync_val_compare_and_swap_8:
5777   case Builtin::BI__sync_val_compare_and_swap_16:
5778     BuiltinIndex = 12;
5779     NumFixed = 2;
5780     break;
5781 
5782   case Builtin::BI__sync_bool_compare_and_swap:
5783   case Builtin::BI__sync_bool_compare_and_swap_1:
5784   case Builtin::BI__sync_bool_compare_and_swap_2:
5785   case Builtin::BI__sync_bool_compare_and_swap_4:
5786   case Builtin::BI__sync_bool_compare_and_swap_8:
5787   case Builtin::BI__sync_bool_compare_and_swap_16:
5788     BuiltinIndex = 13;
5789     NumFixed = 2;
5790     ResultType = Context.BoolTy;
5791     break;
5792 
5793   case Builtin::BI__sync_lock_test_and_set:
5794   case Builtin::BI__sync_lock_test_and_set_1:
5795   case Builtin::BI__sync_lock_test_and_set_2:
5796   case Builtin::BI__sync_lock_test_and_set_4:
5797   case Builtin::BI__sync_lock_test_and_set_8:
5798   case Builtin::BI__sync_lock_test_and_set_16:
5799     BuiltinIndex = 14;
5800     break;
5801 
5802   case Builtin::BI__sync_lock_release:
5803   case Builtin::BI__sync_lock_release_1:
5804   case Builtin::BI__sync_lock_release_2:
5805   case Builtin::BI__sync_lock_release_4:
5806   case Builtin::BI__sync_lock_release_8:
5807   case Builtin::BI__sync_lock_release_16:
5808     BuiltinIndex = 15;
5809     NumFixed = 0;
5810     ResultType = Context.VoidTy;
5811     break;
5812 
5813   case Builtin::BI__sync_swap:
5814   case Builtin::BI__sync_swap_1:
5815   case Builtin::BI__sync_swap_2:
5816   case Builtin::BI__sync_swap_4:
5817   case Builtin::BI__sync_swap_8:
5818   case Builtin::BI__sync_swap_16:
5819     BuiltinIndex = 16;
5820     break;
5821   }
5822 
5823   // Now that we know how many fixed arguments we expect, first check that we
5824   // have at least that many.
5825   if (TheCall->getNumArgs() < 1+NumFixed) {
5826     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5827         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5828         << Callee->getSourceRange();
5829     return ExprError();
5830   }
5831 
5832   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5833       << Callee->getSourceRange();
5834 
5835   if (WarnAboutSemanticsChange) {
5836     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5837         << Callee->getSourceRange();
5838   }
5839 
5840   // Get the decl for the concrete builtin from this, we can tell what the
5841   // concrete integer type we should convert to is.
5842   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5843   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5844   FunctionDecl *NewBuiltinDecl;
5845   if (NewBuiltinID == BuiltinID)
5846     NewBuiltinDecl = FDecl;
5847   else {
5848     // Perform builtin lookup to avoid redeclaring it.
5849     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5850     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5851     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5852     assert(Res.getFoundDecl());
5853     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5854     if (!NewBuiltinDecl)
5855       return ExprError();
5856   }
5857 
5858   // The first argument --- the pointer --- has a fixed type; we
5859   // deduce the types of the rest of the arguments accordingly.  Walk
5860   // the remaining arguments, converting them to the deduced value type.
5861   for (unsigned i = 0; i != NumFixed; ++i) {
5862     ExprResult Arg = TheCall->getArg(i+1);
5863 
5864     // GCC does an implicit conversion to the pointer or integer ValType.  This
5865     // can fail in some cases (1i -> int**), check for this error case now.
5866     // Initialize the argument.
5867     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5868                                                    ValType, /*consume*/ false);
5869     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5870     if (Arg.isInvalid())
5871       return ExprError();
5872 
5873     // Okay, we have something that *can* be converted to the right type.  Check
5874     // to see if there is a potentially weird extension going on here.  This can
5875     // happen when you do an atomic operation on something like an char* and
5876     // pass in 42.  The 42 gets converted to char.  This is even more strange
5877     // for things like 45.123 -> char, etc.
5878     // FIXME: Do this check.
5879     TheCall->setArg(i+1, Arg.get());
5880   }
5881 
5882   // Create a new DeclRefExpr to refer to the new decl.
5883   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5884       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5885       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5886       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5887 
5888   // Set the callee in the CallExpr.
5889   // FIXME: This loses syntactic information.
5890   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5891   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5892                                               CK_BuiltinFnToFnPtr);
5893   TheCall->setCallee(PromotedCall.get());
5894 
5895   // Change the result type of the call to match the original value type. This
5896   // is arbitrary, but the codegen for these builtins ins design to handle it
5897   // gracefully.
5898   TheCall->setType(ResultType);
5899 
5900   // Prohibit use of _ExtInt with atomic builtins.
5901   // The arguments would have already been converted to the first argument's
5902   // type, so only need to check the first argument.
5903   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
5904   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
5905     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5906     return ExprError();
5907   }
5908 
5909   return TheCallResult;
5910 }
5911 
5912 /// SemaBuiltinNontemporalOverloaded - We have a call to
5913 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5914 /// overloaded function based on the pointer type of its last argument.
5915 ///
5916 /// This function goes through and does final semantic checking for these
5917 /// builtins.
5918 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5919   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5920   DeclRefExpr *DRE =
5921       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5922   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5923   unsigned BuiltinID = FDecl->getBuiltinID();
5924   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5925           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5926          "Unexpected nontemporal load/store builtin!");
5927   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5928   unsigned numArgs = isStore ? 2 : 1;
5929 
5930   // Ensure that we have the proper number of arguments.
5931   if (checkArgCount(*this, TheCall, numArgs))
5932     return ExprError();
5933 
5934   // Inspect the last argument of the nontemporal builtin.  This should always
5935   // be a pointer type, from which we imply the type of the memory access.
5936   // Because it is a pointer type, we don't have to worry about any implicit
5937   // casts here.
5938   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5939   ExprResult PointerArgResult =
5940       DefaultFunctionArrayLvalueConversion(PointerArg);
5941 
5942   if (PointerArgResult.isInvalid())
5943     return ExprError();
5944   PointerArg = PointerArgResult.get();
5945   TheCall->setArg(numArgs - 1, PointerArg);
5946 
5947   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5948   if (!pointerType) {
5949     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5950         << PointerArg->getType() << PointerArg->getSourceRange();
5951     return ExprError();
5952   }
5953 
5954   QualType ValType = pointerType->getPointeeType();
5955 
5956   // Strip any qualifiers off ValType.
5957   ValType = ValType.getUnqualifiedType();
5958   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5959       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5960       !ValType->isVectorType()) {
5961     Diag(DRE->getBeginLoc(),
5962          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5963         << PointerArg->getType() << PointerArg->getSourceRange();
5964     return ExprError();
5965   }
5966 
5967   if (!isStore) {
5968     TheCall->setType(ValType);
5969     return TheCallResult;
5970   }
5971 
5972   ExprResult ValArg = TheCall->getArg(0);
5973   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5974       Context, ValType, /*consume*/ false);
5975   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5976   if (ValArg.isInvalid())
5977     return ExprError();
5978 
5979   TheCall->setArg(0, ValArg.get());
5980   TheCall->setType(Context.VoidTy);
5981   return TheCallResult;
5982 }
5983 
5984 /// CheckObjCString - Checks that the argument to the builtin
5985 /// CFString constructor is correct
5986 /// Note: It might also make sense to do the UTF-16 conversion here (would
5987 /// simplify the backend).
5988 bool Sema::CheckObjCString(Expr *Arg) {
5989   Arg = Arg->IgnoreParenCasts();
5990   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5991 
5992   if (!Literal || !Literal->isAscii()) {
5993     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5994         << Arg->getSourceRange();
5995     return true;
5996   }
5997 
5998   if (Literal->containsNonAsciiOrNull()) {
5999     StringRef String = Literal->getString();
6000     unsigned NumBytes = String.size();
6001     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6002     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6003     llvm::UTF16 *ToPtr = &ToBuf[0];
6004 
6005     llvm::ConversionResult Result =
6006         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6007                                  ToPtr + NumBytes, llvm::strictConversion);
6008     // Check for conversion failure.
6009     if (Result != llvm::conversionOK)
6010       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6011           << Arg->getSourceRange();
6012   }
6013   return false;
6014 }
6015 
6016 /// CheckObjCString - Checks that the format string argument to the os_log()
6017 /// and os_trace() functions is correct, and converts it to const char *.
6018 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6019   Arg = Arg->IgnoreParenCasts();
6020   auto *Literal = dyn_cast<StringLiteral>(Arg);
6021   if (!Literal) {
6022     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6023       Literal = ObjcLiteral->getString();
6024     }
6025   }
6026 
6027   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6028     return ExprError(
6029         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6030         << Arg->getSourceRange());
6031   }
6032 
6033   ExprResult Result(Literal);
6034   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6035   InitializedEntity Entity =
6036       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6037   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6038   return Result;
6039 }
6040 
6041 /// Check that the user is calling the appropriate va_start builtin for the
6042 /// target and calling convention.
6043 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6044   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6045   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6046   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6047                     TT.getArch() == llvm::Triple::aarch64_32);
6048   bool IsWindows = TT.isOSWindows();
6049   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6050   if (IsX64 || IsAArch64) {
6051     CallingConv CC = CC_C;
6052     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6053       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6054     if (IsMSVAStart) {
6055       // Don't allow this in System V ABI functions.
6056       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6057         return S.Diag(Fn->getBeginLoc(),
6058                       diag::err_ms_va_start_used_in_sysv_function);
6059     } else {
6060       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6061       // On x64 Windows, don't allow this in System V ABI functions.
6062       // (Yes, that means there's no corresponding way to support variadic
6063       // System V ABI functions on Windows.)
6064       if ((IsWindows && CC == CC_X86_64SysV) ||
6065           (!IsWindows && CC == CC_Win64))
6066         return S.Diag(Fn->getBeginLoc(),
6067                       diag::err_va_start_used_in_wrong_abi_function)
6068                << !IsWindows;
6069     }
6070     return false;
6071   }
6072 
6073   if (IsMSVAStart)
6074     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6075   return false;
6076 }
6077 
6078 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6079                                              ParmVarDecl **LastParam = nullptr) {
6080   // Determine whether the current function, block, or obj-c method is variadic
6081   // and get its parameter list.
6082   bool IsVariadic = false;
6083   ArrayRef<ParmVarDecl *> Params;
6084   DeclContext *Caller = S.CurContext;
6085   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6086     IsVariadic = Block->isVariadic();
6087     Params = Block->parameters();
6088   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6089     IsVariadic = FD->isVariadic();
6090     Params = FD->parameters();
6091   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6092     IsVariadic = MD->isVariadic();
6093     // FIXME: This isn't correct for methods (results in bogus warning).
6094     Params = MD->parameters();
6095   } else if (isa<CapturedDecl>(Caller)) {
6096     // We don't support va_start in a CapturedDecl.
6097     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6098     return true;
6099   } else {
6100     // This must be some other declcontext that parses exprs.
6101     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6102     return true;
6103   }
6104 
6105   if (!IsVariadic) {
6106     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6107     return true;
6108   }
6109 
6110   if (LastParam)
6111     *LastParam = Params.empty() ? nullptr : Params.back();
6112 
6113   return false;
6114 }
6115 
6116 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6117 /// for validity.  Emit an error and return true on failure; return false
6118 /// on success.
6119 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6120   Expr *Fn = TheCall->getCallee();
6121 
6122   if (checkVAStartABI(*this, BuiltinID, Fn))
6123     return true;
6124 
6125   if (checkArgCount(*this, TheCall, 2))
6126     return true;
6127 
6128   // Type-check the first argument normally.
6129   if (checkBuiltinArgument(*this, TheCall, 0))
6130     return true;
6131 
6132   // Check that the current function is variadic, and get its last parameter.
6133   ParmVarDecl *LastParam;
6134   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6135     return true;
6136 
6137   // Verify that the second argument to the builtin is the last argument of the
6138   // current function or method.
6139   bool SecondArgIsLastNamedArgument = false;
6140   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6141 
6142   // These are valid if SecondArgIsLastNamedArgument is false after the next
6143   // block.
6144   QualType Type;
6145   SourceLocation ParamLoc;
6146   bool IsCRegister = false;
6147 
6148   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6149     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6150       SecondArgIsLastNamedArgument = PV == LastParam;
6151 
6152       Type = PV->getType();
6153       ParamLoc = PV->getLocation();
6154       IsCRegister =
6155           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6156     }
6157   }
6158 
6159   if (!SecondArgIsLastNamedArgument)
6160     Diag(TheCall->getArg(1)->getBeginLoc(),
6161          diag::warn_second_arg_of_va_start_not_last_named_param);
6162   else if (IsCRegister || Type->isReferenceType() ||
6163            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6164              // Promotable integers are UB, but enumerations need a bit of
6165              // extra checking to see what their promotable type actually is.
6166              if (!Type->isPromotableIntegerType())
6167                return false;
6168              if (!Type->isEnumeralType())
6169                return true;
6170              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6171              return !(ED &&
6172                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6173            }()) {
6174     unsigned Reason = 0;
6175     if (Type->isReferenceType())  Reason = 1;
6176     else if (IsCRegister)         Reason = 2;
6177     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6178     Diag(ParamLoc, diag::note_parameter_type) << Type;
6179   }
6180 
6181   TheCall->setType(Context.VoidTy);
6182   return false;
6183 }
6184 
6185 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6186   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6187   //                 const char *named_addr);
6188 
6189   Expr *Func = Call->getCallee();
6190 
6191   if (Call->getNumArgs() < 3)
6192     return Diag(Call->getEndLoc(),
6193                 diag::err_typecheck_call_too_few_args_at_least)
6194            << 0 /*function call*/ << 3 << Call->getNumArgs();
6195 
6196   // Type-check the first argument normally.
6197   if (checkBuiltinArgument(*this, Call, 0))
6198     return true;
6199 
6200   // Check that the current function is variadic.
6201   if (checkVAStartIsInVariadicFunction(*this, Func))
6202     return true;
6203 
6204   // __va_start on Windows does not validate the parameter qualifiers
6205 
6206   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6207   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6208 
6209   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6210   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6211 
6212   const QualType &ConstCharPtrTy =
6213       Context.getPointerType(Context.CharTy.withConst());
6214   if (!Arg1Ty->isPointerType() ||
6215       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
6216     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6217         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6218         << 0                                      /* qualifier difference */
6219         << 3                                      /* parameter mismatch */
6220         << 2 << Arg1->getType() << ConstCharPtrTy;
6221 
6222   const QualType SizeTy = Context.getSizeType();
6223   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6224     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6225         << Arg2->getType() << SizeTy << 1 /* different class */
6226         << 0                              /* qualifier difference */
6227         << 3                              /* parameter mismatch */
6228         << 3 << Arg2->getType() << SizeTy;
6229 
6230   return false;
6231 }
6232 
6233 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6234 /// friends.  This is declared to take (...), so we have to check everything.
6235 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6236   if (checkArgCount(*this, TheCall, 2))
6237     return true;
6238 
6239   ExprResult OrigArg0 = TheCall->getArg(0);
6240   ExprResult OrigArg1 = TheCall->getArg(1);
6241 
6242   // Do standard promotions between the two arguments, returning their common
6243   // type.
6244   QualType Res = UsualArithmeticConversions(
6245       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6246   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6247     return true;
6248 
6249   // Make sure any conversions are pushed back into the call; this is
6250   // type safe since unordered compare builtins are declared as "_Bool
6251   // foo(...)".
6252   TheCall->setArg(0, OrigArg0.get());
6253   TheCall->setArg(1, OrigArg1.get());
6254 
6255   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6256     return false;
6257 
6258   // If the common type isn't a real floating type, then the arguments were
6259   // invalid for this operation.
6260   if (Res.isNull() || !Res->isRealFloatingType())
6261     return Diag(OrigArg0.get()->getBeginLoc(),
6262                 diag::err_typecheck_call_invalid_ordered_compare)
6263            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6264            << SourceRange(OrigArg0.get()->getBeginLoc(),
6265                           OrigArg1.get()->getEndLoc());
6266 
6267   return false;
6268 }
6269 
6270 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6271 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6272 /// to check everything. We expect the last argument to be a floating point
6273 /// value.
6274 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6275   if (checkArgCount(*this, TheCall, NumArgs))
6276     return true;
6277 
6278   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6279   // on all preceding parameters just being int.  Try all of those.
6280   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6281     Expr *Arg = TheCall->getArg(i);
6282 
6283     if (Arg->isTypeDependent())
6284       return false;
6285 
6286     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6287 
6288     if (Res.isInvalid())
6289       return true;
6290     TheCall->setArg(i, Res.get());
6291   }
6292 
6293   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6294 
6295   if (OrigArg->isTypeDependent())
6296     return false;
6297 
6298   // Usual Unary Conversions will convert half to float, which we want for
6299   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6300   // type how it is, but do normal L->Rvalue conversions.
6301   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6302     OrigArg = UsualUnaryConversions(OrigArg).get();
6303   else
6304     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6305   TheCall->setArg(NumArgs - 1, OrigArg);
6306 
6307   // This operation requires a non-_Complex floating-point number.
6308   if (!OrigArg->getType()->isRealFloatingType())
6309     return Diag(OrigArg->getBeginLoc(),
6310                 diag::err_typecheck_call_invalid_unary_fp)
6311            << OrigArg->getType() << OrigArg->getSourceRange();
6312 
6313   return false;
6314 }
6315 
6316 /// Perform semantic analysis for a call to __builtin_complex.
6317 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6318   if (checkArgCount(*this, TheCall, 2))
6319     return true;
6320 
6321   bool Dependent = false;
6322   for (unsigned I = 0; I != 2; ++I) {
6323     Expr *Arg = TheCall->getArg(I);
6324     QualType T = Arg->getType();
6325     if (T->isDependentType()) {
6326       Dependent = true;
6327       continue;
6328     }
6329 
6330     // Despite supporting _Complex int, GCC requires a real floating point type
6331     // for the operands of __builtin_complex.
6332     if (!T->isRealFloatingType()) {
6333       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6334              << Arg->getType() << Arg->getSourceRange();
6335     }
6336 
6337     ExprResult Converted = DefaultLvalueConversion(Arg);
6338     if (Converted.isInvalid())
6339       return true;
6340     TheCall->setArg(I, Converted.get());
6341   }
6342 
6343   if (Dependent) {
6344     TheCall->setType(Context.DependentTy);
6345     return false;
6346   }
6347 
6348   Expr *Real = TheCall->getArg(0);
6349   Expr *Imag = TheCall->getArg(1);
6350   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6351     return Diag(Real->getBeginLoc(),
6352                 diag::err_typecheck_call_different_arg_types)
6353            << Real->getType() << Imag->getType()
6354            << Real->getSourceRange() << Imag->getSourceRange();
6355   }
6356 
6357   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6358   // don't allow this builtin to form those types either.
6359   // FIXME: Should we allow these types?
6360   if (Real->getType()->isFloat16Type())
6361     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6362            << "_Float16";
6363   if (Real->getType()->isHalfType())
6364     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6365            << "half";
6366 
6367   TheCall->setType(Context.getComplexType(Real->getType()));
6368   return false;
6369 }
6370 
6371 // Customized Sema Checking for VSX builtins that have the following signature:
6372 // vector [...] builtinName(vector [...], vector [...], const int);
6373 // Which takes the same type of vectors (any legal vector type) for the first
6374 // two arguments and takes compile time constant for the third argument.
6375 // Example builtins are :
6376 // vector double vec_xxpermdi(vector double, vector double, int);
6377 // vector short vec_xxsldwi(vector short, vector short, int);
6378 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6379   unsigned ExpectedNumArgs = 3;
6380   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6381     return true;
6382 
6383   // Check the third argument is a compile time constant
6384   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6385     return Diag(TheCall->getBeginLoc(),
6386                 diag::err_vsx_builtin_nonconstant_argument)
6387            << 3 /* argument index */ << TheCall->getDirectCallee()
6388            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6389                           TheCall->getArg(2)->getEndLoc());
6390 
6391   QualType Arg1Ty = TheCall->getArg(0)->getType();
6392   QualType Arg2Ty = TheCall->getArg(1)->getType();
6393 
6394   // Check the type of argument 1 and argument 2 are vectors.
6395   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6396   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6397       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6398     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6399            << TheCall->getDirectCallee()
6400            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6401                           TheCall->getArg(1)->getEndLoc());
6402   }
6403 
6404   // Check the first two arguments are the same type.
6405   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6406     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6407            << TheCall->getDirectCallee()
6408            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6409                           TheCall->getArg(1)->getEndLoc());
6410   }
6411 
6412   // When default clang type checking is turned off and the customized type
6413   // checking is used, the returning type of the function must be explicitly
6414   // set. Otherwise it is _Bool by default.
6415   TheCall->setType(Arg1Ty);
6416 
6417   return false;
6418 }
6419 
6420 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6421 // This is declared to take (...), so we have to check everything.
6422 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6423   if (TheCall->getNumArgs() < 2)
6424     return ExprError(Diag(TheCall->getEndLoc(),
6425                           diag::err_typecheck_call_too_few_args_at_least)
6426                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6427                      << TheCall->getSourceRange());
6428 
6429   // Determine which of the following types of shufflevector we're checking:
6430   // 1) unary, vector mask: (lhs, mask)
6431   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6432   QualType resType = TheCall->getArg(0)->getType();
6433   unsigned numElements = 0;
6434 
6435   if (!TheCall->getArg(0)->isTypeDependent() &&
6436       !TheCall->getArg(1)->isTypeDependent()) {
6437     QualType LHSType = TheCall->getArg(0)->getType();
6438     QualType RHSType = TheCall->getArg(1)->getType();
6439 
6440     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6441       return ExprError(
6442           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6443           << TheCall->getDirectCallee()
6444           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6445                          TheCall->getArg(1)->getEndLoc()));
6446 
6447     numElements = LHSType->castAs<VectorType>()->getNumElements();
6448     unsigned numResElements = TheCall->getNumArgs() - 2;
6449 
6450     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6451     // with mask.  If so, verify that RHS is an integer vector type with the
6452     // same number of elts as lhs.
6453     if (TheCall->getNumArgs() == 2) {
6454       if (!RHSType->hasIntegerRepresentation() ||
6455           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6456         return ExprError(Diag(TheCall->getBeginLoc(),
6457                               diag::err_vec_builtin_incompatible_vector)
6458                          << TheCall->getDirectCallee()
6459                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6460                                         TheCall->getArg(1)->getEndLoc()));
6461     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6462       return ExprError(Diag(TheCall->getBeginLoc(),
6463                             diag::err_vec_builtin_incompatible_vector)
6464                        << TheCall->getDirectCallee()
6465                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6466                                       TheCall->getArg(1)->getEndLoc()));
6467     } else if (numElements != numResElements) {
6468       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6469       resType = Context.getVectorType(eltType, numResElements,
6470                                       VectorType::GenericVector);
6471     }
6472   }
6473 
6474   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6475     if (TheCall->getArg(i)->isTypeDependent() ||
6476         TheCall->getArg(i)->isValueDependent())
6477       continue;
6478 
6479     Optional<llvm::APSInt> Result;
6480     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6481       return ExprError(Diag(TheCall->getBeginLoc(),
6482                             diag::err_shufflevector_nonconstant_argument)
6483                        << TheCall->getArg(i)->getSourceRange());
6484 
6485     // Allow -1 which will be translated to undef in the IR.
6486     if (Result->isSigned() && Result->isAllOnesValue())
6487       continue;
6488 
6489     if (Result->getActiveBits() > 64 ||
6490         Result->getZExtValue() >= numElements * 2)
6491       return ExprError(Diag(TheCall->getBeginLoc(),
6492                             diag::err_shufflevector_argument_too_large)
6493                        << TheCall->getArg(i)->getSourceRange());
6494   }
6495 
6496   SmallVector<Expr*, 32> exprs;
6497 
6498   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6499     exprs.push_back(TheCall->getArg(i));
6500     TheCall->setArg(i, nullptr);
6501   }
6502 
6503   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6504                                          TheCall->getCallee()->getBeginLoc(),
6505                                          TheCall->getRParenLoc());
6506 }
6507 
6508 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6509 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6510                                        SourceLocation BuiltinLoc,
6511                                        SourceLocation RParenLoc) {
6512   ExprValueKind VK = VK_PRValue;
6513   ExprObjectKind OK = OK_Ordinary;
6514   QualType DstTy = TInfo->getType();
6515   QualType SrcTy = E->getType();
6516 
6517   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6518     return ExprError(Diag(BuiltinLoc,
6519                           diag::err_convertvector_non_vector)
6520                      << E->getSourceRange());
6521   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6522     return ExprError(Diag(BuiltinLoc,
6523                           diag::err_convertvector_non_vector_type));
6524 
6525   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6526     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6527     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6528     if (SrcElts != DstElts)
6529       return ExprError(Diag(BuiltinLoc,
6530                             diag::err_convertvector_incompatible_vector)
6531                        << E->getSourceRange());
6532   }
6533 
6534   return new (Context)
6535       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6536 }
6537 
6538 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6539 // This is declared to take (const void*, ...) and can take two
6540 // optional constant int args.
6541 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6542   unsigned NumArgs = TheCall->getNumArgs();
6543 
6544   if (NumArgs > 3)
6545     return Diag(TheCall->getEndLoc(),
6546                 diag::err_typecheck_call_too_many_args_at_most)
6547            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6548 
6549   // Argument 0 is checked for us and the remaining arguments must be
6550   // constant integers.
6551   for (unsigned i = 1; i != NumArgs; ++i)
6552     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6553       return true;
6554 
6555   return false;
6556 }
6557 
6558 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
6559 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
6560   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6561     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6562            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6563   if (checkArgCount(*this, TheCall, 1))
6564     return true;
6565   Expr *Arg = TheCall->getArg(0);
6566   if (Arg->isInstantiationDependent())
6567     return false;
6568 
6569   QualType ArgTy = Arg->getType();
6570   if (!ArgTy->hasFloatingRepresentation())
6571     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6572            << ArgTy;
6573   if (Arg->isLValue()) {
6574     ExprResult FirstArg = DefaultLvalueConversion(Arg);
6575     TheCall->setArg(0, FirstArg.get());
6576   }
6577   TheCall->setType(TheCall->getArg(0)->getType());
6578   return false;
6579 }
6580 
6581 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6582 // __assume does not evaluate its arguments, and should warn if its argument
6583 // has side effects.
6584 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6585   Expr *Arg = TheCall->getArg(0);
6586   if (Arg->isInstantiationDependent()) return false;
6587 
6588   if (Arg->HasSideEffects(Context))
6589     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6590         << Arg->getSourceRange()
6591         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6592 
6593   return false;
6594 }
6595 
6596 /// Handle __builtin_alloca_with_align. This is declared
6597 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6598 /// than 8.
6599 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6600   // The alignment must be a constant integer.
6601   Expr *Arg = TheCall->getArg(1);
6602 
6603   // We can't check the value of a dependent argument.
6604   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6605     if (const auto *UE =
6606             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6607       if (UE->getKind() == UETT_AlignOf ||
6608           UE->getKind() == UETT_PreferredAlignOf)
6609         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6610             << Arg->getSourceRange();
6611 
6612     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6613 
6614     if (!Result.isPowerOf2())
6615       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6616              << Arg->getSourceRange();
6617 
6618     if (Result < Context.getCharWidth())
6619       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6620              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6621 
6622     if (Result > std::numeric_limits<int32_t>::max())
6623       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6624              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6625   }
6626 
6627   return false;
6628 }
6629 
6630 /// Handle __builtin_assume_aligned. This is declared
6631 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6632 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6633   unsigned NumArgs = TheCall->getNumArgs();
6634 
6635   if (NumArgs > 3)
6636     return Diag(TheCall->getEndLoc(),
6637                 diag::err_typecheck_call_too_many_args_at_most)
6638            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6639 
6640   // The alignment must be a constant integer.
6641   Expr *Arg = TheCall->getArg(1);
6642 
6643   // We can't check the value of a dependent argument.
6644   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6645     llvm::APSInt Result;
6646     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6647       return true;
6648 
6649     if (!Result.isPowerOf2())
6650       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6651              << Arg->getSourceRange();
6652 
6653     if (Result > Sema::MaximumAlignment)
6654       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6655           << Arg->getSourceRange() << Sema::MaximumAlignment;
6656   }
6657 
6658   if (NumArgs > 2) {
6659     ExprResult Arg(TheCall->getArg(2));
6660     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6661       Context.getSizeType(), false);
6662     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6663     if (Arg.isInvalid()) return true;
6664     TheCall->setArg(2, Arg.get());
6665   }
6666 
6667   return false;
6668 }
6669 
6670 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6671   unsigned BuiltinID =
6672       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6673   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6674 
6675   unsigned NumArgs = TheCall->getNumArgs();
6676   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6677   if (NumArgs < NumRequiredArgs) {
6678     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6679            << 0 /* function call */ << NumRequiredArgs << NumArgs
6680            << TheCall->getSourceRange();
6681   }
6682   if (NumArgs >= NumRequiredArgs + 0x100) {
6683     return Diag(TheCall->getEndLoc(),
6684                 diag::err_typecheck_call_too_many_args_at_most)
6685            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6686            << TheCall->getSourceRange();
6687   }
6688   unsigned i = 0;
6689 
6690   // For formatting call, check buffer arg.
6691   if (!IsSizeCall) {
6692     ExprResult Arg(TheCall->getArg(i));
6693     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6694         Context, Context.VoidPtrTy, false);
6695     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6696     if (Arg.isInvalid())
6697       return true;
6698     TheCall->setArg(i, Arg.get());
6699     i++;
6700   }
6701 
6702   // Check string literal arg.
6703   unsigned FormatIdx = i;
6704   {
6705     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6706     if (Arg.isInvalid())
6707       return true;
6708     TheCall->setArg(i, Arg.get());
6709     i++;
6710   }
6711 
6712   // Make sure variadic args are scalar.
6713   unsigned FirstDataArg = i;
6714   while (i < NumArgs) {
6715     ExprResult Arg = DefaultVariadicArgumentPromotion(
6716         TheCall->getArg(i), VariadicFunction, nullptr);
6717     if (Arg.isInvalid())
6718       return true;
6719     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6720     if (ArgSize.getQuantity() >= 0x100) {
6721       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6722              << i << (int)ArgSize.getQuantity() << 0xff
6723              << TheCall->getSourceRange();
6724     }
6725     TheCall->setArg(i, Arg.get());
6726     i++;
6727   }
6728 
6729   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6730   // call to avoid duplicate diagnostics.
6731   if (!IsSizeCall) {
6732     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6733     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6734     bool Success = CheckFormatArguments(
6735         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6736         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6737         CheckedVarArgs);
6738     if (!Success)
6739       return true;
6740   }
6741 
6742   if (IsSizeCall) {
6743     TheCall->setType(Context.getSizeType());
6744   } else {
6745     TheCall->setType(Context.VoidPtrTy);
6746   }
6747   return false;
6748 }
6749 
6750 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6751 /// TheCall is a constant expression.
6752 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6753                                   llvm::APSInt &Result) {
6754   Expr *Arg = TheCall->getArg(ArgNum);
6755   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6756   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6757 
6758   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6759 
6760   Optional<llvm::APSInt> R;
6761   if (!(R = Arg->getIntegerConstantExpr(Context)))
6762     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6763            << FDecl->getDeclName() << Arg->getSourceRange();
6764   Result = *R;
6765   return false;
6766 }
6767 
6768 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6769 /// TheCall is a constant expression in the range [Low, High].
6770 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6771                                        int Low, int High, bool RangeIsError) {
6772   if (isConstantEvaluated())
6773     return false;
6774   llvm::APSInt Result;
6775 
6776   // We can't check the value of a dependent argument.
6777   Expr *Arg = TheCall->getArg(ArgNum);
6778   if (Arg->isTypeDependent() || Arg->isValueDependent())
6779     return false;
6780 
6781   // Check constant-ness first.
6782   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6783     return true;
6784 
6785   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6786     if (RangeIsError)
6787       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6788              << toString(Result, 10) << Low << High << Arg->getSourceRange();
6789     else
6790       // Defer the warning until we know if the code will be emitted so that
6791       // dead code can ignore this.
6792       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6793                           PDiag(diag::warn_argument_invalid_range)
6794                               << toString(Result, 10) << Low << High
6795                               << Arg->getSourceRange());
6796   }
6797 
6798   return false;
6799 }
6800 
6801 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6802 /// TheCall is a constant expression is a multiple of Num..
6803 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6804                                           unsigned Num) {
6805   llvm::APSInt Result;
6806 
6807   // We can't check the value of a dependent argument.
6808   Expr *Arg = TheCall->getArg(ArgNum);
6809   if (Arg->isTypeDependent() || Arg->isValueDependent())
6810     return false;
6811 
6812   // Check constant-ness first.
6813   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6814     return true;
6815 
6816   if (Result.getSExtValue() % Num != 0)
6817     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6818            << Num << Arg->getSourceRange();
6819 
6820   return false;
6821 }
6822 
6823 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6824 /// constant expression representing a power of 2.
6825 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6826   llvm::APSInt Result;
6827 
6828   // We can't check the value of a dependent argument.
6829   Expr *Arg = TheCall->getArg(ArgNum);
6830   if (Arg->isTypeDependent() || Arg->isValueDependent())
6831     return false;
6832 
6833   // Check constant-ness first.
6834   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6835     return true;
6836 
6837   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6838   // and only if x is a power of 2.
6839   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6840     return false;
6841 
6842   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6843          << Arg->getSourceRange();
6844 }
6845 
6846 static bool IsShiftedByte(llvm::APSInt Value) {
6847   if (Value.isNegative())
6848     return false;
6849 
6850   // Check if it's a shifted byte, by shifting it down
6851   while (true) {
6852     // If the value fits in the bottom byte, the check passes.
6853     if (Value < 0x100)
6854       return true;
6855 
6856     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6857     // fails.
6858     if ((Value & 0xFF) != 0)
6859       return false;
6860 
6861     // If the bottom 8 bits are all 0, but something above that is nonzero,
6862     // then shifting the value right by 8 bits won't affect whether it's a
6863     // shifted byte or not. So do that, and go round again.
6864     Value >>= 8;
6865   }
6866 }
6867 
6868 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6869 /// a constant expression representing an arbitrary byte value shifted left by
6870 /// a multiple of 8 bits.
6871 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6872                                              unsigned ArgBits) {
6873   llvm::APSInt Result;
6874 
6875   // We can't check the value of a dependent argument.
6876   Expr *Arg = TheCall->getArg(ArgNum);
6877   if (Arg->isTypeDependent() || Arg->isValueDependent())
6878     return false;
6879 
6880   // Check constant-ness first.
6881   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6882     return true;
6883 
6884   // Truncate to the given size.
6885   Result = Result.getLoBits(ArgBits);
6886   Result.setIsUnsigned(true);
6887 
6888   if (IsShiftedByte(Result))
6889     return false;
6890 
6891   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6892          << Arg->getSourceRange();
6893 }
6894 
6895 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6896 /// TheCall is a constant expression representing either a shifted byte value,
6897 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6898 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6899 /// Arm MVE intrinsics.
6900 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6901                                                    int ArgNum,
6902                                                    unsigned ArgBits) {
6903   llvm::APSInt Result;
6904 
6905   // We can't check the value of a dependent argument.
6906   Expr *Arg = TheCall->getArg(ArgNum);
6907   if (Arg->isTypeDependent() || Arg->isValueDependent())
6908     return false;
6909 
6910   // Check constant-ness first.
6911   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6912     return true;
6913 
6914   // Truncate to the given size.
6915   Result = Result.getLoBits(ArgBits);
6916   Result.setIsUnsigned(true);
6917 
6918   // Check to see if it's in either of the required forms.
6919   if (IsShiftedByte(Result) ||
6920       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6921     return false;
6922 
6923   return Diag(TheCall->getBeginLoc(),
6924               diag::err_argument_not_shifted_byte_or_xxff)
6925          << Arg->getSourceRange();
6926 }
6927 
6928 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6929 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6930   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6931     if (checkArgCount(*this, TheCall, 2))
6932       return true;
6933     Expr *Arg0 = TheCall->getArg(0);
6934     Expr *Arg1 = TheCall->getArg(1);
6935 
6936     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6937     if (FirstArg.isInvalid())
6938       return true;
6939     QualType FirstArgType = FirstArg.get()->getType();
6940     if (!FirstArgType->isAnyPointerType())
6941       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6942                << "first" << FirstArgType << Arg0->getSourceRange();
6943     TheCall->setArg(0, FirstArg.get());
6944 
6945     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6946     if (SecArg.isInvalid())
6947       return true;
6948     QualType SecArgType = SecArg.get()->getType();
6949     if (!SecArgType->isIntegerType())
6950       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6951                << "second" << SecArgType << Arg1->getSourceRange();
6952 
6953     // Derive the return type from the pointer argument.
6954     TheCall->setType(FirstArgType);
6955     return false;
6956   }
6957 
6958   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6959     if (checkArgCount(*this, TheCall, 2))
6960       return true;
6961 
6962     Expr *Arg0 = TheCall->getArg(0);
6963     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6964     if (FirstArg.isInvalid())
6965       return true;
6966     QualType FirstArgType = FirstArg.get()->getType();
6967     if (!FirstArgType->isAnyPointerType())
6968       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6969                << "first" << FirstArgType << Arg0->getSourceRange();
6970     TheCall->setArg(0, FirstArg.get());
6971 
6972     // Derive the return type from the pointer argument.
6973     TheCall->setType(FirstArgType);
6974 
6975     // Second arg must be an constant in range [0,15]
6976     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6977   }
6978 
6979   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6980     if (checkArgCount(*this, TheCall, 2))
6981       return true;
6982     Expr *Arg0 = TheCall->getArg(0);
6983     Expr *Arg1 = TheCall->getArg(1);
6984 
6985     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6986     if (FirstArg.isInvalid())
6987       return true;
6988     QualType FirstArgType = FirstArg.get()->getType();
6989     if (!FirstArgType->isAnyPointerType())
6990       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6991                << "first" << FirstArgType << Arg0->getSourceRange();
6992 
6993     QualType SecArgType = Arg1->getType();
6994     if (!SecArgType->isIntegerType())
6995       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6996                << "second" << SecArgType << Arg1->getSourceRange();
6997     TheCall->setType(Context.IntTy);
6998     return false;
6999   }
7000 
7001   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7002       BuiltinID == AArch64::BI__builtin_arm_stg) {
7003     if (checkArgCount(*this, TheCall, 1))
7004       return true;
7005     Expr *Arg0 = TheCall->getArg(0);
7006     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7007     if (FirstArg.isInvalid())
7008       return true;
7009 
7010     QualType FirstArgType = FirstArg.get()->getType();
7011     if (!FirstArgType->isAnyPointerType())
7012       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7013                << "first" << FirstArgType << Arg0->getSourceRange();
7014     TheCall->setArg(0, FirstArg.get());
7015 
7016     // Derive the return type from the pointer argument.
7017     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7018       TheCall->setType(FirstArgType);
7019     return false;
7020   }
7021 
7022   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7023     Expr *ArgA = TheCall->getArg(0);
7024     Expr *ArgB = TheCall->getArg(1);
7025 
7026     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7027     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7028 
7029     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7030       return true;
7031 
7032     QualType ArgTypeA = ArgExprA.get()->getType();
7033     QualType ArgTypeB = ArgExprB.get()->getType();
7034 
7035     auto isNull = [&] (Expr *E) -> bool {
7036       return E->isNullPointerConstant(
7037                         Context, Expr::NPC_ValueDependentIsNotNull); };
7038 
7039     // argument should be either a pointer or null
7040     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7041       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7042         << "first" << ArgTypeA << ArgA->getSourceRange();
7043 
7044     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7045       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7046         << "second" << ArgTypeB << ArgB->getSourceRange();
7047 
7048     // Ensure Pointee types are compatible
7049     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7050         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7051       QualType pointeeA = ArgTypeA->getPointeeType();
7052       QualType pointeeB = ArgTypeB->getPointeeType();
7053       if (!Context.typesAreCompatible(
7054              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7055              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7056         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7057           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7058           << ArgB->getSourceRange();
7059       }
7060     }
7061 
7062     // at least one argument should be pointer type
7063     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7064       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7065         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7066 
7067     if (isNull(ArgA)) // adopt type of the other pointer
7068       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7069 
7070     if (isNull(ArgB))
7071       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7072 
7073     TheCall->setArg(0, ArgExprA.get());
7074     TheCall->setArg(1, ArgExprB.get());
7075     TheCall->setType(Context.LongLongTy);
7076     return false;
7077   }
7078   assert(false && "Unhandled ARM MTE intrinsic");
7079   return true;
7080 }
7081 
7082 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7083 /// TheCall is an ARM/AArch64 special register string literal.
7084 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7085                                     int ArgNum, unsigned ExpectedFieldNum,
7086                                     bool AllowName) {
7087   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7088                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7089                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7090                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7091                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7092                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7093   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7094                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7095                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7096                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7097                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7098                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7099   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7100 
7101   // We can't check the value of a dependent argument.
7102   Expr *Arg = TheCall->getArg(ArgNum);
7103   if (Arg->isTypeDependent() || Arg->isValueDependent())
7104     return false;
7105 
7106   // Check if the argument is a string literal.
7107   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7108     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7109            << Arg->getSourceRange();
7110 
7111   // Check the type of special register given.
7112   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7113   SmallVector<StringRef, 6> Fields;
7114   Reg.split(Fields, ":");
7115 
7116   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7117     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7118            << Arg->getSourceRange();
7119 
7120   // If the string is the name of a register then we cannot check that it is
7121   // valid here but if the string is of one the forms described in ACLE then we
7122   // can check that the supplied fields are integers and within the valid
7123   // ranges.
7124   if (Fields.size() > 1) {
7125     bool FiveFields = Fields.size() == 5;
7126 
7127     bool ValidString = true;
7128     if (IsARMBuiltin) {
7129       ValidString &= Fields[0].startswith_insensitive("cp") ||
7130                      Fields[0].startswith_insensitive("p");
7131       if (ValidString)
7132         Fields[0] = Fields[0].drop_front(
7133             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7134 
7135       ValidString &= Fields[2].startswith_insensitive("c");
7136       if (ValidString)
7137         Fields[2] = Fields[2].drop_front(1);
7138 
7139       if (FiveFields) {
7140         ValidString &= Fields[3].startswith_insensitive("c");
7141         if (ValidString)
7142           Fields[3] = Fields[3].drop_front(1);
7143       }
7144     }
7145 
7146     SmallVector<int, 5> Ranges;
7147     if (FiveFields)
7148       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7149     else
7150       Ranges.append({15, 7, 15});
7151 
7152     for (unsigned i=0; i<Fields.size(); ++i) {
7153       int IntField;
7154       ValidString &= !Fields[i].getAsInteger(10, IntField);
7155       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7156     }
7157 
7158     if (!ValidString)
7159       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7160              << Arg->getSourceRange();
7161   } else if (IsAArch64Builtin && Fields.size() == 1) {
7162     // If the register name is one of those that appear in the condition below
7163     // and the special register builtin being used is one of the write builtins,
7164     // then we require that the argument provided for writing to the register
7165     // is an integer constant expression. This is because it will be lowered to
7166     // an MSR (immediate) instruction, so we need to know the immediate at
7167     // compile time.
7168     if (TheCall->getNumArgs() != 2)
7169       return false;
7170 
7171     std::string RegLower = Reg.lower();
7172     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7173         RegLower != "pan" && RegLower != "uao")
7174       return false;
7175 
7176     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7177   }
7178 
7179   return false;
7180 }
7181 
7182 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7183 /// Emit an error and return true on failure; return false on success.
7184 /// TypeStr is a string containing the type descriptor of the value returned by
7185 /// the builtin and the descriptors of the expected type of the arguments.
7186 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
7187 
7188   assert((TypeStr[0] != '\0') &&
7189          "Invalid types in PPC MMA builtin declaration");
7190 
7191   unsigned Mask = 0;
7192   unsigned ArgNum = 0;
7193 
7194   // The first type in TypeStr is the type of the value returned by the
7195   // builtin. So we first read that type and change the type of TheCall.
7196   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7197   TheCall->setType(type);
7198 
7199   while (*TypeStr != '\0') {
7200     Mask = 0;
7201     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7202     if (ArgNum >= TheCall->getNumArgs()) {
7203       ArgNum++;
7204       break;
7205     }
7206 
7207     Expr *Arg = TheCall->getArg(ArgNum);
7208     QualType ArgType = Arg->getType();
7209 
7210     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
7211         (!ExpectedType->isVoidPointerType() &&
7212            ArgType.getCanonicalType() != ExpectedType))
7213       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
7214              << ArgType << ExpectedType << 1 << 0 << 0;
7215 
7216     // If the value of the Mask is not 0, we have a constraint in the size of
7217     // the integer argument so here we ensure the argument is a constant that
7218     // is in the valid range.
7219     if (Mask != 0 &&
7220         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7221       return true;
7222 
7223     ArgNum++;
7224   }
7225 
7226   // In case we exited early from the previous loop, there are other types to
7227   // read from TypeStr. So we need to read them all to ensure we have the right
7228   // number of arguments in TheCall and if it is not the case, to display a
7229   // better error message.
7230   while (*TypeStr != '\0') {
7231     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7232     ArgNum++;
7233   }
7234   if (checkArgCount(*this, TheCall, ArgNum))
7235     return true;
7236 
7237   return false;
7238 }
7239 
7240 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7241 /// This checks that the target supports __builtin_longjmp and
7242 /// that val is a constant 1.
7243 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7244   if (!Context.getTargetInfo().hasSjLjLowering())
7245     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7246            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7247 
7248   Expr *Arg = TheCall->getArg(1);
7249   llvm::APSInt Result;
7250 
7251   // TODO: This is less than ideal. Overload this to take a value.
7252   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7253     return true;
7254 
7255   if (Result != 1)
7256     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7257            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7258 
7259   return false;
7260 }
7261 
7262 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7263 /// This checks that the target supports __builtin_setjmp.
7264 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7265   if (!Context.getTargetInfo().hasSjLjLowering())
7266     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7267            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7268   return false;
7269 }
7270 
7271 namespace {
7272 
7273 class UncoveredArgHandler {
7274   enum { Unknown = -1, AllCovered = -2 };
7275 
7276   signed FirstUncoveredArg = Unknown;
7277   SmallVector<const Expr *, 4> DiagnosticExprs;
7278 
7279 public:
7280   UncoveredArgHandler() = default;
7281 
7282   bool hasUncoveredArg() const {
7283     return (FirstUncoveredArg >= 0);
7284   }
7285 
7286   unsigned getUncoveredArg() const {
7287     assert(hasUncoveredArg() && "no uncovered argument");
7288     return FirstUncoveredArg;
7289   }
7290 
7291   void setAllCovered() {
7292     // A string has been found with all arguments covered, so clear out
7293     // the diagnostics.
7294     DiagnosticExprs.clear();
7295     FirstUncoveredArg = AllCovered;
7296   }
7297 
7298   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7299     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7300 
7301     // Don't update if a previous string covers all arguments.
7302     if (FirstUncoveredArg == AllCovered)
7303       return;
7304 
7305     // UncoveredArgHandler tracks the highest uncovered argument index
7306     // and with it all the strings that match this index.
7307     if (NewFirstUncoveredArg == FirstUncoveredArg)
7308       DiagnosticExprs.push_back(StrExpr);
7309     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7310       DiagnosticExprs.clear();
7311       DiagnosticExprs.push_back(StrExpr);
7312       FirstUncoveredArg = NewFirstUncoveredArg;
7313     }
7314   }
7315 
7316   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7317 };
7318 
7319 enum StringLiteralCheckType {
7320   SLCT_NotALiteral,
7321   SLCT_UncheckedLiteral,
7322   SLCT_CheckedLiteral
7323 };
7324 
7325 } // namespace
7326 
7327 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7328                                      BinaryOperatorKind BinOpKind,
7329                                      bool AddendIsRight) {
7330   unsigned BitWidth = Offset.getBitWidth();
7331   unsigned AddendBitWidth = Addend.getBitWidth();
7332   // There might be negative interim results.
7333   if (Addend.isUnsigned()) {
7334     Addend = Addend.zext(++AddendBitWidth);
7335     Addend.setIsSigned(true);
7336   }
7337   // Adjust the bit width of the APSInts.
7338   if (AddendBitWidth > BitWidth) {
7339     Offset = Offset.sext(AddendBitWidth);
7340     BitWidth = AddendBitWidth;
7341   } else if (BitWidth > AddendBitWidth) {
7342     Addend = Addend.sext(BitWidth);
7343   }
7344 
7345   bool Ov = false;
7346   llvm::APSInt ResOffset = Offset;
7347   if (BinOpKind == BO_Add)
7348     ResOffset = Offset.sadd_ov(Addend, Ov);
7349   else {
7350     assert(AddendIsRight && BinOpKind == BO_Sub &&
7351            "operator must be add or sub with addend on the right");
7352     ResOffset = Offset.ssub_ov(Addend, Ov);
7353   }
7354 
7355   // We add an offset to a pointer here so we should support an offset as big as
7356   // possible.
7357   if (Ov) {
7358     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7359            "index (intermediate) result too big");
7360     Offset = Offset.sext(2 * BitWidth);
7361     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7362     return;
7363   }
7364 
7365   Offset = ResOffset;
7366 }
7367 
7368 namespace {
7369 
7370 // This is a wrapper class around StringLiteral to support offsetted string
7371 // literals as format strings. It takes the offset into account when returning
7372 // the string and its length or the source locations to display notes correctly.
7373 class FormatStringLiteral {
7374   const StringLiteral *FExpr;
7375   int64_t Offset;
7376 
7377  public:
7378   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7379       : FExpr(fexpr), Offset(Offset) {}
7380 
7381   StringRef getString() const {
7382     return FExpr->getString().drop_front(Offset);
7383   }
7384 
7385   unsigned getByteLength() const {
7386     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7387   }
7388 
7389   unsigned getLength() const { return FExpr->getLength() - Offset; }
7390   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7391 
7392   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7393 
7394   QualType getType() const { return FExpr->getType(); }
7395 
7396   bool isAscii() const { return FExpr->isAscii(); }
7397   bool isWide() const { return FExpr->isWide(); }
7398   bool isUTF8() const { return FExpr->isUTF8(); }
7399   bool isUTF16() const { return FExpr->isUTF16(); }
7400   bool isUTF32() const { return FExpr->isUTF32(); }
7401   bool isPascal() const { return FExpr->isPascal(); }
7402 
7403   SourceLocation getLocationOfByte(
7404       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7405       const TargetInfo &Target, unsigned *StartToken = nullptr,
7406       unsigned *StartTokenByteOffset = nullptr) const {
7407     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7408                                     StartToken, StartTokenByteOffset);
7409   }
7410 
7411   SourceLocation getBeginLoc() const LLVM_READONLY {
7412     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7413   }
7414 
7415   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7416 };
7417 
7418 }  // namespace
7419 
7420 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7421                               const Expr *OrigFormatExpr,
7422                               ArrayRef<const Expr *> Args,
7423                               bool HasVAListArg, unsigned format_idx,
7424                               unsigned firstDataArg,
7425                               Sema::FormatStringType Type,
7426                               bool inFunctionCall,
7427                               Sema::VariadicCallType CallType,
7428                               llvm::SmallBitVector &CheckedVarArgs,
7429                               UncoveredArgHandler &UncoveredArg,
7430                               bool IgnoreStringsWithoutSpecifiers);
7431 
7432 // Determine if an expression is a string literal or constant string.
7433 // If this function returns false on the arguments to a function expecting a
7434 // format string, we will usually need to emit a warning.
7435 // True string literals are then checked by CheckFormatString.
7436 static StringLiteralCheckType
7437 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7438                       bool HasVAListArg, unsigned format_idx,
7439                       unsigned firstDataArg, Sema::FormatStringType Type,
7440                       Sema::VariadicCallType CallType, bool InFunctionCall,
7441                       llvm::SmallBitVector &CheckedVarArgs,
7442                       UncoveredArgHandler &UncoveredArg,
7443                       llvm::APSInt Offset,
7444                       bool IgnoreStringsWithoutSpecifiers = false) {
7445   if (S.isConstantEvaluated())
7446     return SLCT_NotALiteral;
7447  tryAgain:
7448   assert(Offset.isSigned() && "invalid offset");
7449 
7450   if (E->isTypeDependent() || E->isValueDependent())
7451     return SLCT_NotALiteral;
7452 
7453   E = E->IgnoreParenCasts();
7454 
7455   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7456     // Technically -Wformat-nonliteral does not warn about this case.
7457     // The behavior of printf and friends in this case is implementation
7458     // dependent.  Ideally if the format string cannot be null then
7459     // it should have a 'nonnull' attribute in the function prototype.
7460     return SLCT_UncheckedLiteral;
7461 
7462   switch (E->getStmtClass()) {
7463   case Stmt::BinaryConditionalOperatorClass:
7464   case Stmt::ConditionalOperatorClass: {
7465     // The expression is a literal if both sub-expressions were, and it was
7466     // completely checked only if both sub-expressions were checked.
7467     const AbstractConditionalOperator *C =
7468         cast<AbstractConditionalOperator>(E);
7469 
7470     // Determine whether it is necessary to check both sub-expressions, for
7471     // example, because the condition expression is a constant that can be
7472     // evaluated at compile time.
7473     bool CheckLeft = true, CheckRight = true;
7474 
7475     bool Cond;
7476     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7477                                                  S.isConstantEvaluated())) {
7478       if (Cond)
7479         CheckRight = false;
7480       else
7481         CheckLeft = false;
7482     }
7483 
7484     // We need to maintain the offsets for the right and the left hand side
7485     // separately to check if every possible indexed expression is a valid
7486     // string literal. They might have different offsets for different string
7487     // literals in the end.
7488     StringLiteralCheckType Left;
7489     if (!CheckLeft)
7490       Left = SLCT_UncheckedLiteral;
7491     else {
7492       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7493                                    HasVAListArg, format_idx, firstDataArg,
7494                                    Type, CallType, InFunctionCall,
7495                                    CheckedVarArgs, UncoveredArg, Offset,
7496                                    IgnoreStringsWithoutSpecifiers);
7497       if (Left == SLCT_NotALiteral || !CheckRight) {
7498         return Left;
7499       }
7500     }
7501 
7502     StringLiteralCheckType Right = checkFormatStringExpr(
7503         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7504         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7505         IgnoreStringsWithoutSpecifiers);
7506 
7507     return (CheckLeft && Left < Right) ? Left : Right;
7508   }
7509 
7510   case Stmt::ImplicitCastExprClass:
7511     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7512     goto tryAgain;
7513 
7514   case Stmt::OpaqueValueExprClass:
7515     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7516       E = src;
7517       goto tryAgain;
7518     }
7519     return SLCT_NotALiteral;
7520 
7521   case Stmt::PredefinedExprClass:
7522     // While __func__, etc., are technically not string literals, they
7523     // cannot contain format specifiers and thus are not a security
7524     // liability.
7525     return SLCT_UncheckedLiteral;
7526 
7527   case Stmt::DeclRefExprClass: {
7528     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7529 
7530     // As an exception, do not flag errors for variables binding to
7531     // const string literals.
7532     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7533       bool isConstant = false;
7534       QualType T = DR->getType();
7535 
7536       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7537         isConstant = AT->getElementType().isConstant(S.Context);
7538       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7539         isConstant = T.isConstant(S.Context) &&
7540                      PT->getPointeeType().isConstant(S.Context);
7541       } else if (T->isObjCObjectPointerType()) {
7542         // In ObjC, there is usually no "const ObjectPointer" type,
7543         // so don't check if the pointee type is constant.
7544         isConstant = T.isConstant(S.Context);
7545       }
7546 
7547       if (isConstant) {
7548         if (const Expr *Init = VD->getAnyInitializer()) {
7549           // Look through initializers like const char c[] = { "foo" }
7550           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7551             if (InitList->isStringLiteralInit())
7552               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7553           }
7554           return checkFormatStringExpr(S, Init, Args,
7555                                        HasVAListArg, format_idx,
7556                                        firstDataArg, Type, CallType,
7557                                        /*InFunctionCall*/ false, CheckedVarArgs,
7558                                        UncoveredArg, Offset);
7559         }
7560       }
7561 
7562       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7563       // special check to see if the format string is a function parameter
7564       // of the function calling the printf function.  If the function
7565       // has an attribute indicating it is a printf-like function, then we
7566       // should suppress warnings concerning non-literals being used in a call
7567       // to a vprintf function.  For example:
7568       //
7569       // void
7570       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7571       //      va_list ap;
7572       //      va_start(ap, fmt);
7573       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7574       //      ...
7575       // }
7576       if (HasVAListArg) {
7577         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7578           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7579             int PVIndex = PV->getFunctionScopeIndex() + 1;
7580             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7581               // adjust for implicit parameter
7582               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7583                 if (MD->isInstance())
7584                   ++PVIndex;
7585               // We also check if the formats are compatible.
7586               // We can't pass a 'scanf' string to a 'printf' function.
7587               if (PVIndex == PVFormat->getFormatIdx() &&
7588                   Type == S.GetFormatStringType(PVFormat))
7589                 return SLCT_UncheckedLiteral;
7590             }
7591           }
7592         }
7593       }
7594     }
7595 
7596     return SLCT_NotALiteral;
7597   }
7598 
7599   case Stmt::CallExprClass:
7600   case Stmt::CXXMemberCallExprClass: {
7601     const CallExpr *CE = cast<CallExpr>(E);
7602     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7603       bool IsFirst = true;
7604       StringLiteralCheckType CommonResult;
7605       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7606         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7607         StringLiteralCheckType Result = checkFormatStringExpr(
7608             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7609             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7610             IgnoreStringsWithoutSpecifiers);
7611         if (IsFirst) {
7612           CommonResult = Result;
7613           IsFirst = false;
7614         }
7615       }
7616       if (!IsFirst)
7617         return CommonResult;
7618 
7619       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7620         unsigned BuiltinID = FD->getBuiltinID();
7621         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7622             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7623           const Expr *Arg = CE->getArg(0);
7624           return checkFormatStringExpr(S, Arg, Args,
7625                                        HasVAListArg, format_idx,
7626                                        firstDataArg, Type, CallType,
7627                                        InFunctionCall, CheckedVarArgs,
7628                                        UncoveredArg, Offset,
7629                                        IgnoreStringsWithoutSpecifiers);
7630         }
7631       }
7632     }
7633 
7634     return SLCT_NotALiteral;
7635   }
7636   case Stmt::ObjCMessageExprClass: {
7637     const auto *ME = cast<ObjCMessageExpr>(E);
7638     if (const auto *MD = ME->getMethodDecl()) {
7639       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7640         // As a special case heuristic, if we're using the method -[NSBundle
7641         // localizedStringForKey:value:table:], ignore any key strings that lack
7642         // format specifiers. The idea is that if the key doesn't have any
7643         // format specifiers then its probably just a key to map to the
7644         // localized strings. If it does have format specifiers though, then its
7645         // likely that the text of the key is the format string in the
7646         // programmer's language, and should be checked.
7647         const ObjCInterfaceDecl *IFace;
7648         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7649             IFace->getIdentifier()->isStr("NSBundle") &&
7650             MD->getSelector().isKeywordSelector(
7651                 {"localizedStringForKey", "value", "table"})) {
7652           IgnoreStringsWithoutSpecifiers = true;
7653         }
7654 
7655         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7656         return checkFormatStringExpr(
7657             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7658             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7659             IgnoreStringsWithoutSpecifiers);
7660       }
7661     }
7662 
7663     return SLCT_NotALiteral;
7664   }
7665   case Stmt::ObjCStringLiteralClass:
7666   case Stmt::StringLiteralClass: {
7667     const StringLiteral *StrE = nullptr;
7668 
7669     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7670       StrE = ObjCFExpr->getString();
7671     else
7672       StrE = cast<StringLiteral>(E);
7673 
7674     if (StrE) {
7675       if (Offset.isNegative() || Offset > StrE->getLength()) {
7676         // TODO: It would be better to have an explicit warning for out of
7677         // bounds literals.
7678         return SLCT_NotALiteral;
7679       }
7680       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7681       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7682                         firstDataArg, Type, InFunctionCall, CallType,
7683                         CheckedVarArgs, UncoveredArg,
7684                         IgnoreStringsWithoutSpecifiers);
7685       return SLCT_CheckedLiteral;
7686     }
7687 
7688     return SLCT_NotALiteral;
7689   }
7690   case Stmt::BinaryOperatorClass: {
7691     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7692 
7693     // A string literal + an int offset is still a string literal.
7694     if (BinOp->isAdditiveOp()) {
7695       Expr::EvalResult LResult, RResult;
7696 
7697       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7698           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7699       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7700           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7701 
7702       if (LIsInt != RIsInt) {
7703         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7704 
7705         if (LIsInt) {
7706           if (BinOpKind == BO_Add) {
7707             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7708             E = BinOp->getRHS();
7709             goto tryAgain;
7710           }
7711         } else {
7712           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7713           E = BinOp->getLHS();
7714           goto tryAgain;
7715         }
7716       }
7717     }
7718 
7719     return SLCT_NotALiteral;
7720   }
7721   case Stmt::UnaryOperatorClass: {
7722     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7723     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7724     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7725       Expr::EvalResult IndexResult;
7726       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7727                                        Expr::SE_NoSideEffects,
7728                                        S.isConstantEvaluated())) {
7729         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7730                    /*RHS is int*/ true);
7731         E = ASE->getBase();
7732         goto tryAgain;
7733       }
7734     }
7735 
7736     return SLCT_NotALiteral;
7737   }
7738 
7739   default:
7740     return SLCT_NotALiteral;
7741   }
7742 }
7743 
7744 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7745   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7746       .Case("scanf", FST_Scanf)
7747       .Cases("printf", "printf0", FST_Printf)
7748       .Cases("NSString", "CFString", FST_NSString)
7749       .Case("strftime", FST_Strftime)
7750       .Case("strfmon", FST_Strfmon)
7751       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7752       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7753       .Case("os_trace", FST_OSLog)
7754       .Case("os_log", FST_OSLog)
7755       .Default(FST_Unknown);
7756 }
7757 
7758 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7759 /// functions) for correct use of format strings.
7760 /// Returns true if a format string has been fully checked.
7761 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7762                                 ArrayRef<const Expr *> Args,
7763                                 bool IsCXXMember,
7764                                 VariadicCallType CallType,
7765                                 SourceLocation Loc, SourceRange Range,
7766                                 llvm::SmallBitVector &CheckedVarArgs) {
7767   FormatStringInfo FSI;
7768   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7769     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7770                                 FSI.FirstDataArg, GetFormatStringType(Format),
7771                                 CallType, Loc, Range, CheckedVarArgs);
7772   return false;
7773 }
7774 
7775 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7776                                 bool HasVAListArg, unsigned format_idx,
7777                                 unsigned firstDataArg, FormatStringType Type,
7778                                 VariadicCallType CallType,
7779                                 SourceLocation Loc, SourceRange Range,
7780                                 llvm::SmallBitVector &CheckedVarArgs) {
7781   // CHECK: printf/scanf-like function is called with no format string.
7782   if (format_idx >= Args.size()) {
7783     Diag(Loc, diag::warn_missing_format_string) << Range;
7784     return false;
7785   }
7786 
7787   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7788 
7789   // CHECK: format string is not a string literal.
7790   //
7791   // Dynamically generated format strings are difficult to
7792   // automatically vet at compile time.  Requiring that format strings
7793   // are string literals: (1) permits the checking of format strings by
7794   // the compiler and thereby (2) can practically remove the source of
7795   // many format string exploits.
7796 
7797   // Format string can be either ObjC string (e.g. @"%d") or
7798   // C string (e.g. "%d")
7799   // ObjC string uses the same format specifiers as C string, so we can use
7800   // the same format string checking logic for both ObjC and C strings.
7801   UncoveredArgHandler UncoveredArg;
7802   StringLiteralCheckType CT =
7803       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7804                             format_idx, firstDataArg, Type, CallType,
7805                             /*IsFunctionCall*/ true, CheckedVarArgs,
7806                             UncoveredArg,
7807                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7808 
7809   // Generate a diagnostic where an uncovered argument is detected.
7810   if (UncoveredArg.hasUncoveredArg()) {
7811     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7812     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7813     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7814   }
7815 
7816   if (CT != SLCT_NotALiteral)
7817     // Literal format string found, check done!
7818     return CT == SLCT_CheckedLiteral;
7819 
7820   // Strftime is particular as it always uses a single 'time' argument,
7821   // so it is safe to pass a non-literal string.
7822   if (Type == FST_Strftime)
7823     return false;
7824 
7825   // Do not emit diag when the string param is a macro expansion and the
7826   // format is either NSString or CFString. This is a hack to prevent
7827   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7828   // which are usually used in place of NS and CF string literals.
7829   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7830   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7831     return false;
7832 
7833   // If there are no arguments specified, warn with -Wformat-security, otherwise
7834   // warn only with -Wformat-nonliteral.
7835   if (Args.size() == firstDataArg) {
7836     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7837       << OrigFormatExpr->getSourceRange();
7838     switch (Type) {
7839     default:
7840       break;
7841     case FST_Kprintf:
7842     case FST_FreeBSDKPrintf:
7843     case FST_Printf:
7844       Diag(FormatLoc, diag::note_format_security_fixit)
7845         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7846       break;
7847     case FST_NSString:
7848       Diag(FormatLoc, diag::note_format_security_fixit)
7849         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7850       break;
7851     }
7852   } else {
7853     Diag(FormatLoc, diag::warn_format_nonliteral)
7854       << OrigFormatExpr->getSourceRange();
7855   }
7856   return false;
7857 }
7858 
7859 namespace {
7860 
7861 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7862 protected:
7863   Sema &S;
7864   const FormatStringLiteral *FExpr;
7865   const Expr *OrigFormatExpr;
7866   const Sema::FormatStringType FSType;
7867   const unsigned FirstDataArg;
7868   const unsigned NumDataArgs;
7869   const char *Beg; // Start of format string.
7870   const bool HasVAListArg;
7871   ArrayRef<const Expr *> Args;
7872   unsigned FormatIdx;
7873   llvm::SmallBitVector CoveredArgs;
7874   bool usesPositionalArgs = false;
7875   bool atFirstArg = true;
7876   bool inFunctionCall;
7877   Sema::VariadicCallType CallType;
7878   llvm::SmallBitVector &CheckedVarArgs;
7879   UncoveredArgHandler &UncoveredArg;
7880 
7881 public:
7882   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7883                      const Expr *origFormatExpr,
7884                      const Sema::FormatStringType type, unsigned firstDataArg,
7885                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7886                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7887                      bool inFunctionCall, Sema::VariadicCallType callType,
7888                      llvm::SmallBitVector &CheckedVarArgs,
7889                      UncoveredArgHandler &UncoveredArg)
7890       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7891         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7892         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7893         inFunctionCall(inFunctionCall), CallType(callType),
7894         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7895     CoveredArgs.resize(numDataArgs);
7896     CoveredArgs.reset();
7897   }
7898 
7899   void DoneProcessing();
7900 
7901   void HandleIncompleteSpecifier(const char *startSpecifier,
7902                                  unsigned specifierLen) override;
7903 
7904   void HandleInvalidLengthModifier(
7905                            const analyze_format_string::FormatSpecifier &FS,
7906                            const analyze_format_string::ConversionSpecifier &CS,
7907                            const char *startSpecifier, unsigned specifierLen,
7908                            unsigned DiagID);
7909 
7910   void HandleNonStandardLengthModifier(
7911                     const analyze_format_string::FormatSpecifier &FS,
7912                     const char *startSpecifier, unsigned specifierLen);
7913 
7914   void HandleNonStandardConversionSpecifier(
7915                     const analyze_format_string::ConversionSpecifier &CS,
7916                     const char *startSpecifier, unsigned specifierLen);
7917 
7918   void HandlePosition(const char *startPos, unsigned posLen) override;
7919 
7920   void HandleInvalidPosition(const char *startSpecifier,
7921                              unsigned specifierLen,
7922                              analyze_format_string::PositionContext p) override;
7923 
7924   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7925 
7926   void HandleNullChar(const char *nullCharacter) override;
7927 
7928   template <typename Range>
7929   static void
7930   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7931                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7932                        bool IsStringLocation, Range StringRange,
7933                        ArrayRef<FixItHint> Fixit = None);
7934 
7935 protected:
7936   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7937                                         const char *startSpec,
7938                                         unsigned specifierLen,
7939                                         const char *csStart, unsigned csLen);
7940 
7941   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7942                                          const char *startSpec,
7943                                          unsigned specifierLen);
7944 
7945   SourceRange getFormatStringRange();
7946   CharSourceRange getSpecifierRange(const char *startSpecifier,
7947                                     unsigned specifierLen);
7948   SourceLocation getLocationOfByte(const char *x);
7949 
7950   const Expr *getDataArg(unsigned i) const;
7951 
7952   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7953                     const analyze_format_string::ConversionSpecifier &CS,
7954                     const char *startSpecifier, unsigned specifierLen,
7955                     unsigned argIndex);
7956 
7957   template <typename Range>
7958   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7959                             bool IsStringLocation, Range StringRange,
7960                             ArrayRef<FixItHint> Fixit = None);
7961 };
7962 
7963 } // namespace
7964 
7965 SourceRange CheckFormatHandler::getFormatStringRange() {
7966   return OrigFormatExpr->getSourceRange();
7967 }
7968 
7969 CharSourceRange CheckFormatHandler::
7970 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7971   SourceLocation Start = getLocationOfByte(startSpecifier);
7972   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7973 
7974   // Advance the end SourceLocation by one due to half-open ranges.
7975   End = End.getLocWithOffset(1);
7976 
7977   return CharSourceRange::getCharRange(Start, End);
7978 }
7979 
7980 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7981   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7982                                   S.getLangOpts(), S.Context.getTargetInfo());
7983 }
7984 
7985 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7986                                                    unsigned specifierLen){
7987   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7988                        getLocationOfByte(startSpecifier),
7989                        /*IsStringLocation*/true,
7990                        getSpecifierRange(startSpecifier, specifierLen));
7991 }
7992 
7993 void CheckFormatHandler::HandleInvalidLengthModifier(
7994     const analyze_format_string::FormatSpecifier &FS,
7995     const analyze_format_string::ConversionSpecifier &CS,
7996     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7997   using namespace analyze_format_string;
7998 
7999   const LengthModifier &LM = FS.getLengthModifier();
8000   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8001 
8002   // See if we know how to fix this length modifier.
8003   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8004   if (FixedLM) {
8005     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8006                          getLocationOfByte(LM.getStart()),
8007                          /*IsStringLocation*/true,
8008                          getSpecifierRange(startSpecifier, specifierLen));
8009 
8010     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8011       << FixedLM->toString()
8012       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8013 
8014   } else {
8015     FixItHint Hint;
8016     if (DiagID == diag::warn_format_nonsensical_length)
8017       Hint = FixItHint::CreateRemoval(LMRange);
8018 
8019     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8020                          getLocationOfByte(LM.getStart()),
8021                          /*IsStringLocation*/true,
8022                          getSpecifierRange(startSpecifier, specifierLen),
8023                          Hint);
8024   }
8025 }
8026 
8027 void CheckFormatHandler::HandleNonStandardLengthModifier(
8028     const analyze_format_string::FormatSpecifier &FS,
8029     const char *startSpecifier, unsigned specifierLen) {
8030   using namespace analyze_format_string;
8031 
8032   const LengthModifier &LM = FS.getLengthModifier();
8033   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8034 
8035   // See if we know how to fix this length modifier.
8036   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8037   if (FixedLM) {
8038     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8039                            << LM.toString() << 0,
8040                          getLocationOfByte(LM.getStart()),
8041                          /*IsStringLocation*/true,
8042                          getSpecifierRange(startSpecifier, specifierLen));
8043 
8044     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8045       << FixedLM->toString()
8046       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8047 
8048   } else {
8049     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8050                            << LM.toString() << 0,
8051                          getLocationOfByte(LM.getStart()),
8052                          /*IsStringLocation*/true,
8053                          getSpecifierRange(startSpecifier, specifierLen));
8054   }
8055 }
8056 
8057 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8058     const analyze_format_string::ConversionSpecifier &CS,
8059     const char *startSpecifier, unsigned specifierLen) {
8060   using namespace analyze_format_string;
8061 
8062   // See if we know how to fix this conversion specifier.
8063   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8064   if (FixedCS) {
8065     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8066                           << CS.toString() << /*conversion specifier*/1,
8067                          getLocationOfByte(CS.getStart()),
8068                          /*IsStringLocation*/true,
8069                          getSpecifierRange(startSpecifier, specifierLen));
8070 
8071     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8072     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8073       << FixedCS->toString()
8074       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8075   } else {
8076     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8077                           << CS.toString() << /*conversion specifier*/1,
8078                          getLocationOfByte(CS.getStart()),
8079                          /*IsStringLocation*/true,
8080                          getSpecifierRange(startSpecifier, specifierLen));
8081   }
8082 }
8083 
8084 void CheckFormatHandler::HandlePosition(const char *startPos,
8085                                         unsigned posLen) {
8086   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8087                                getLocationOfByte(startPos),
8088                                /*IsStringLocation*/true,
8089                                getSpecifierRange(startPos, posLen));
8090 }
8091 
8092 void
8093 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8094                                      analyze_format_string::PositionContext p) {
8095   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8096                          << (unsigned) p,
8097                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8098                        getSpecifierRange(startPos, posLen));
8099 }
8100 
8101 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8102                                             unsigned posLen) {
8103   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8104                                getLocationOfByte(startPos),
8105                                /*IsStringLocation*/true,
8106                                getSpecifierRange(startPos, posLen));
8107 }
8108 
8109 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8110   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8111     // The presence of a null character is likely an error.
8112     EmitFormatDiagnostic(
8113       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8114       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8115       getFormatStringRange());
8116   }
8117 }
8118 
8119 // Note that this may return NULL if there was an error parsing or building
8120 // one of the argument expressions.
8121 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8122   return Args[FirstDataArg + i];
8123 }
8124 
8125 void CheckFormatHandler::DoneProcessing() {
8126   // Does the number of data arguments exceed the number of
8127   // format conversions in the format string?
8128   if (!HasVAListArg) {
8129       // Find any arguments that weren't covered.
8130     CoveredArgs.flip();
8131     signed notCoveredArg = CoveredArgs.find_first();
8132     if (notCoveredArg >= 0) {
8133       assert((unsigned)notCoveredArg < NumDataArgs);
8134       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8135     } else {
8136       UncoveredArg.setAllCovered();
8137     }
8138   }
8139 }
8140 
8141 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8142                                    const Expr *ArgExpr) {
8143   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8144          "Invalid state");
8145 
8146   if (!ArgExpr)
8147     return;
8148 
8149   SourceLocation Loc = ArgExpr->getBeginLoc();
8150 
8151   if (S.getSourceManager().isInSystemMacro(Loc))
8152     return;
8153 
8154   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8155   for (auto E : DiagnosticExprs)
8156     PDiag << E->getSourceRange();
8157 
8158   CheckFormatHandler::EmitFormatDiagnostic(
8159                                   S, IsFunctionCall, DiagnosticExprs[0],
8160                                   PDiag, Loc, /*IsStringLocation*/false,
8161                                   DiagnosticExprs[0]->getSourceRange());
8162 }
8163 
8164 bool
8165 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8166                                                      SourceLocation Loc,
8167                                                      const char *startSpec,
8168                                                      unsigned specifierLen,
8169                                                      const char *csStart,
8170                                                      unsigned csLen) {
8171   bool keepGoing = true;
8172   if (argIndex < NumDataArgs) {
8173     // Consider the argument coverered, even though the specifier doesn't
8174     // make sense.
8175     CoveredArgs.set(argIndex);
8176   }
8177   else {
8178     // If argIndex exceeds the number of data arguments we
8179     // don't issue a warning because that is just a cascade of warnings (and
8180     // they may have intended '%%' anyway). We don't want to continue processing
8181     // the format string after this point, however, as we will like just get
8182     // gibberish when trying to match arguments.
8183     keepGoing = false;
8184   }
8185 
8186   StringRef Specifier(csStart, csLen);
8187 
8188   // If the specifier in non-printable, it could be the first byte of a UTF-8
8189   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8190   // hex value.
8191   std::string CodePointStr;
8192   if (!llvm::sys::locale::isPrint(*csStart)) {
8193     llvm::UTF32 CodePoint;
8194     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8195     const llvm::UTF8 *E =
8196         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8197     llvm::ConversionResult Result =
8198         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8199 
8200     if (Result != llvm::conversionOK) {
8201       unsigned char FirstChar = *csStart;
8202       CodePoint = (llvm::UTF32)FirstChar;
8203     }
8204 
8205     llvm::raw_string_ostream OS(CodePointStr);
8206     if (CodePoint < 256)
8207       OS << "\\x" << llvm::format("%02x", CodePoint);
8208     else if (CodePoint <= 0xFFFF)
8209       OS << "\\u" << llvm::format("%04x", CodePoint);
8210     else
8211       OS << "\\U" << llvm::format("%08x", CodePoint);
8212     OS.flush();
8213     Specifier = CodePointStr;
8214   }
8215 
8216   EmitFormatDiagnostic(
8217       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8218       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8219 
8220   return keepGoing;
8221 }
8222 
8223 void
8224 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8225                                                       const char *startSpec,
8226                                                       unsigned specifierLen) {
8227   EmitFormatDiagnostic(
8228     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8229     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8230 }
8231 
8232 bool
8233 CheckFormatHandler::CheckNumArgs(
8234   const analyze_format_string::FormatSpecifier &FS,
8235   const analyze_format_string::ConversionSpecifier &CS,
8236   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8237 
8238   if (argIndex >= NumDataArgs) {
8239     PartialDiagnostic PDiag = FS.usesPositionalArg()
8240       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8241            << (argIndex+1) << NumDataArgs)
8242       : S.PDiag(diag::warn_printf_insufficient_data_args);
8243     EmitFormatDiagnostic(
8244       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8245       getSpecifierRange(startSpecifier, specifierLen));
8246 
8247     // Since more arguments than conversion tokens are given, by extension
8248     // all arguments are covered, so mark this as so.
8249     UncoveredArg.setAllCovered();
8250     return false;
8251   }
8252   return true;
8253 }
8254 
8255 template<typename Range>
8256 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8257                                               SourceLocation Loc,
8258                                               bool IsStringLocation,
8259                                               Range StringRange,
8260                                               ArrayRef<FixItHint> FixIt) {
8261   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8262                        Loc, IsStringLocation, StringRange, FixIt);
8263 }
8264 
8265 /// If the format string is not within the function call, emit a note
8266 /// so that the function call and string are in diagnostic messages.
8267 ///
8268 /// \param InFunctionCall if true, the format string is within the function
8269 /// call and only one diagnostic message will be produced.  Otherwise, an
8270 /// extra note will be emitted pointing to location of the format string.
8271 ///
8272 /// \param ArgumentExpr the expression that is passed as the format string
8273 /// argument in the function call.  Used for getting locations when two
8274 /// diagnostics are emitted.
8275 ///
8276 /// \param PDiag the callee should already have provided any strings for the
8277 /// diagnostic message.  This function only adds locations and fixits
8278 /// to diagnostics.
8279 ///
8280 /// \param Loc primary location for diagnostic.  If two diagnostics are
8281 /// required, one will be at Loc and a new SourceLocation will be created for
8282 /// the other one.
8283 ///
8284 /// \param IsStringLocation if true, Loc points to the format string should be
8285 /// used for the note.  Otherwise, Loc points to the argument list and will
8286 /// be used with PDiag.
8287 ///
8288 /// \param StringRange some or all of the string to highlight.  This is
8289 /// templated so it can accept either a CharSourceRange or a SourceRange.
8290 ///
8291 /// \param FixIt optional fix it hint for the format string.
8292 template <typename Range>
8293 void CheckFormatHandler::EmitFormatDiagnostic(
8294     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8295     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8296     Range StringRange, ArrayRef<FixItHint> FixIt) {
8297   if (InFunctionCall) {
8298     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8299     D << StringRange;
8300     D << FixIt;
8301   } else {
8302     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8303       << ArgumentExpr->getSourceRange();
8304 
8305     const Sema::SemaDiagnosticBuilder &Note =
8306       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8307              diag::note_format_string_defined);
8308 
8309     Note << StringRange;
8310     Note << FixIt;
8311   }
8312 }
8313 
8314 //===--- CHECK: Printf format string checking ------------------------------===//
8315 
8316 namespace {
8317 
8318 class CheckPrintfHandler : public CheckFormatHandler {
8319 public:
8320   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8321                      const Expr *origFormatExpr,
8322                      const Sema::FormatStringType type, unsigned firstDataArg,
8323                      unsigned numDataArgs, bool isObjC, const char *beg,
8324                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8325                      unsigned formatIdx, bool inFunctionCall,
8326                      Sema::VariadicCallType CallType,
8327                      llvm::SmallBitVector &CheckedVarArgs,
8328                      UncoveredArgHandler &UncoveredArg)
8329       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8330                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8331                            inFunctionCall, CallType, CheckedVarArgs,
8332                            UncoveredArg) {}
8333 
8334   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8335 
8336   /// Returns true if '%@' specifiers are allowed in the format string.
8337   bool allowsObjCArg() const {
8338     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8339            FSType == Sema::FST_OSTrace;
8340   }
8341 
8342   bool HandleInvalidPrintfConversionSpecifier(
8343                                       const analyze_printf::PrintfSpecifier &FS,
8344                                       const char *startSpecifier,
8345                                       unsigned specifierLen) override;
8346 
8347   void handleInvalidMaskType(StringRef MaskType) override;
8348 
8349   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8350                              const char *startSpecifier,
8351                              unsigned specifierLen) override;
8352   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8353                        const char *StartSpecifier,
8354                        unsigned SpecifierLen,
8355                        const Expr *E);
8356 
8357   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8358                     const char *startSpecifier, unsigned specifierLen);
8359   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8360                            const analyze_printf::OptionalAmount &Amt,
8361                            unsigned type,
8362                            const char *startSpecifier, unsigned specifierLen);
8363   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8364                   const analyze_printf::OptionalFlag &flag,
8365                   const char *startSpecifier, unsigned specifierLen);
8366   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8367                          const analyze_printf::OptionalFlag &ignoredFlag,
8368                          const analyze_printf::OptionalFlag &flag,
8369                          const char *startSpecifier, unsigned specifierLen);
8370   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8371                            const Expr *E);
8372 
8373   void HandleEmptyObjCModifierFlag(const char *startFlag,
8374                                    unsigned flagLen) override;
8375 
8376   void HandleInvalidObjCModifierFlag(const char *startFlag,
8377                                             unsigned flagLen) override;
8378 
8379   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8380                                            const char *flagsEnd,
8381                                            const char *conversionPosition)
8382                                              override;
8383 };
8384 
8385 } // namespace
8386 
8387 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8388                                       const analyze_printf::PrintfSpecifier &FS,
8389                                       const char *startSpecifier,
8390                                       unsigned specifierLen) {
8391   const analyze_printf::PrintfConversionSpecifier &CS =
8392     FS.getConversionSpecifier();
8393 
8394   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8395                                           getLocationOfByte(CS.getStart()),
8396                                           startSpecifier, specifierLen,
8397                                           CS.getStart(), CS.getLength());
8398 }
8399 
8400 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8401   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8402 }
8403 
8404 bool CheckPrintfHandler::HandleAmount(
8405                                const analyze_format_string::OptionalAmount &Amt,
8406                                unsigned k, const char *startSpecifier,
8407                                unsigned specifierLen) {
8408   if (Amt.hasDataArgument()) {
8409     if (!HasVAListArg) {
8410       unsigned argIndex = Amt.getArgIndex();
8411       if (argIndex >= NumDataArgs) {
8412         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8413                                << k,
8414                              getLocationOfByte(Amt.getStart()),
8415                              /*IsStringLocation*/true,
8416                              getSpecifierRange(startSpecifier, specifierLen));
8417         // Don't do any more checking.  We will just emit
8418         // spurious errors.
8419         return false;
8420       }
8421 
8422       // Type check the data argument.  It should be an 'int'.
8423       // Although not in conformance with C99, we also allow the argument to be
8424       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8425       // doesn't emit a warning for that case.
8426       CoveredArgs.set(argIndex);
8427       const Expr *Arg = getDataArg(argIndex);
8428       if (!Arg)
8429         return false;
8430 
8431       QualType T = Arg->getType();
8432 
8433       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8434       assert(AT.isValid());
8435 
8436       if (!AT.matchesType(S.Context, T)) {
8437         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8438                                << k << AT.getRepresentativeTypeName(S.Context)
8439                                << T << Arg->getSourceRange(),
8440                              getLocationOfByte(Amt.getStart()),
8441                              /*IsStringLocation*/true,
8442                              getSpecifierRange(startSpecifier, specifierLen));
8443         // Don't do any more checking.  We will just emit
8444         // spurious errors.
8445         return false;
8446       }
8447     }
8448   }
8449   return true;
8450 }
8451 
8452 void CheckPrintfHandler::HandleInvalidAmount(
8453                                       const analyze_printf::PrintfSpecifier &FS,
8454                                       const analyze_printf::OptionalAmount &Amt,
8455                                       unsigned type,
8456                                       const char *startSpecifier,
8457                                       unsigned specifierLen) {
8458   const analyze_printf::PrintfConversionSpecifier &CS =
8459     FS.getConversionSpecifier();
8460 
8461   FixItHint fixit =
8462     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8463       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8464                                  Amt.getConstantLength()))
8465       : FixItHint();
8466 
8467   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8468                          << type << CS.toString(),
8469                        getLocationOfByte(Amt.getStart()),
8470                        /*IsStringLocation*/true,
8471                        getSpecifierRange(startSpecifier, specifierLen),
8472                        fixit);
8473 }
8474 
8475 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8476                                     const analyze_printf::OptionalFlag &flag,
8477                                     const char *startSpecifier,
8478                                     unsigned specifierLen) {
8479   // Warn about pointless flag with a fixit removal.
8480   const analyze_printf::PrintfConversionSpecifier &CS =
8481     FS.getConversionSpecifier();
8482   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8483                          << flag.toString() << CS.toString(),
8484                        getLocationOfByte(flag.getPosition()),
8485                        /*IsStringLocation*/true,
8486                        getSpecifierRange(startSpecifier, specifierLen),
8487                        FixItHint::CreateRemoval(
8488                          getSpecifierRange(flag.getPosition(), 1)));
8489 }
8490 
8491 void CheckPrintfHandler::HandleIgnoredFlag(
8492                                 const analyze_printf::PrintfSpecifier &FS,
8493                                 const analyze_printf::OptionalFlag &ignoredFlag,
8494                                 const analyze_printf::OptionalFlag &flag,
8495                                 const char *startSpecifier,
8496                                 unsigned specifierLen) {
8497   // Warn about ignored flag with a fixit removal.
8498   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8499                          << ignoredFlag.toString() << flag.toString(),
8500                        getLocationOfByte(ignoredFlag.getPosition()),
8501                        /*IsStringLocation*/true,
8502                        getSpecifierRange(startSpecifier, specifierLen),
8503                        FixItHint::CreateRemoval(
8504                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8505 }
8506 
8507 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8508                                                      unsigned flagLen) {
8509   // Warn about an empty flag.
8510   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8511                        getLocationOfByte(startFlag),
8512                        /*IsStringLocation*/true,
8513                        getSpecifierRange(startFlag, flagLen));
8514 }
8515 
8516 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8517                                                        unsigned flagLen) {
8518   // Warn about an invalid flag.
8519   auto Range = getSpecifierRange(startFlag, flagLen);
8520   StringRef flag(startFlag, flagLen);
8521   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8522                       getLocationOfByte(startFlag),
8523                       /*IsStringLocation*/true,
8524                       Range, FixItHint::CreateRemoval(Range));
8525 }
8526 
8527 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8528     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8529     // Warn about using '[...]' without a '@' conversion.
8530     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8531     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8532     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8533                          getLocationOfByte(conversionPosition),
8534                          /*IsStringLocation*/true,
8535                          Range, FixItHint::CreateRemoval(Range));
8536 }
8537 
8538 // Determines if the specified is a C++ class or struct containing
8539 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8540 // "c_str()").
8541 template<typename MemberKind>
8542 static llvm::SmallPtrSet<MemberKind*, 1>
8543 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8544   const RecordType *RT = Ty->getAs<RecordType>();
8545   llvm::SmallPtrSet<MemberKind*, 1> Results;
8546 
8547   if (!RT)
8548     return Results;
8549   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8550   if (!RD || !RD->getDefinition())
8551     return Results;
8552 
8553   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8554                  Sema::LookupMemberName);
8555   R.suppressDiagnostics();
8556 
8557   // We just need to include all members of the right kind turned up by the
8558   // filter, at this point.
8559   if (S.LookupQualifiedName(R, RT->getDecl()))
8560     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8561       NamedDecl *decl = (*I)->getUnderlyingDecl();
8562       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8563         Results.insert(FK);
8564     }
8565   return Results;
8566 }
8567 
8568 /// Check if we could call '.c_str()' on an object.
8569 ///
8570 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8571 /// allow the call, or if it would be ambiguous).
8572 bool Sema::hasCStrMethod(const Expr *E) {
8573   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8574 
8575   MethodSet Results =
8576       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8577   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8578        MI != ME; ++MI)
8579     if ((*MI)->getMinRequiredArguments() == 0)
8580       return true;
8581   return false;
8582 }
8583 
8584 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8585 // better diagnostic if so. AT is assumed to be valid.
8586 // Returns true when a c_str() conversion method is found.
8587 bool CheckPrintfHandler::checkForCStrMembers(
8588     const analyze_printf::ArgType &AT, const Expr *E) {
8589   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8590 
8591   MethodSet Results =
8592       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8593 
8594   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8595        MI != ME; ++MI) {
8596     const CXXMethodDecl *Method = *MI;
8597     if (Method->getMinRequiredArguments() == 0 &&
8598         AT.matchesType(S.Context, Method->getReturnType())) {
8599       // FIXME: Suggest parens if the expression needs them.
8600       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8601       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8602           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8603       return true;
8604     }
8605   }
8606 
8607   return false;
8608 }
8609 
8610 bool
8611 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8612                                             &FS,
8613                                           const char *startSpecifier,
8614                                           unsigned specifierLen) {
8615   using namespace analyze_format_string;
8616   using namespace analyze_printf;
8617 
8618   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8619 
8620   if (FS.consumesDataArgument()) {
8621     if (atFirstArg) {
8622         atFirstArg = false;
8623         usesPositionalArgs = FS.usesPositionalArg();
8624     }
8625     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8626       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8627                                         startSpecifier, specifierLen);
8628       return false;
8629     }
8630   }
8631 
8632   // First check if the field width, precision, and conversion specifier
8633   // have matching data arguments.
8634   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8635                     startSpecifier, specifierLen)) {
8636     return false;
8637   }
8638 
8639   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8640                     startSpecifier, specifierLen)) {
8641     return false;
8642   }
8643 
8644   if (!CS.consumesDataArgument()) {
8645     // FIXME: Technically specifying a precision or field width here
8646     // makes no sense.  Worth issuing a warning at some point.
8647     return true;
8648   }
8649 
8650   // Consume the argument.
8651   unsigned argIndex = FS.getArgIndex();
8652   if (argIndex < NumDataArgs) {
8653     // The check to see if the argIndex is valid will come later.
8654     // We set the bit here because we may exit early from this
8655     // function if we encounter some other error.
8656     CoveredArgs.set(argIndex);
8657   }
8658 
8659   // FreeBSD kernel extensions.
8660   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8661       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8662     // We need at least two arguments.
8663     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8664       return false;
8665 
8666     // Claim the second argument.
8667     CoveredArgs.set(argIndex + 1);
8668 
8669     // Type check the first argument (int for %b, pointer for %D)
8670     const Expr *Ex = getDataArg(argIndex);
8671     const analyze_printf::ArgType &AT =
8672       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8673         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8674     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8675       EmitFormatDiagnostic(
8676           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8677               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8678               << false << Ex->getSourceRange(),
8679           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8680           getSpecifierRange(startSpecifier, specifierLen));
8681 
8682     // Type check the second argument (char * for both %b and %D)
8683     Ex = getDataArg(argIndex + 1);
8684     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8685     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8686       EmitFormatDiagnostic(
8687           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8688               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8689               << false << Ex->getSourceRange(),
8690           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8691           getSpecifierRange(startSpecifier, specifierLen));
8692 
8693      return true;
8694   }
8695 
8696   // Check for using an Objective-C specific conversion specifier
8697   // in a non-ObjC literal.
8698   if (!allowsObjCArg() && CS.isObjCArg()) {
8699     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8700                                                   specifierLen);
8701   }
8702 
8703   // %P can only be used with os_log.
8704   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8705     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8706                                                   specifierLen);
8707   }
8708 
8709   // %n is not allowed with os_log.
8710   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8711     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8712                          getLocationOfByte(CS.getStart()),
8713                          /*IsStringLocation*/ false,
8714                          getSpecifierRange(startSpecifier, specifierLen));
8715 
8716     return true;
8717   }
8718 
8719   // Only scalars are allowed for os_trace.
8720   if (FSType == Sema::FST_OSTrace &&
8721       (CS.getKind() == ConversionSpecifier::PArg ||
8722        CS.getKind() == ConversionSpecifier::sArg ||
8723        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8724     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8725                                                   specifierLen);
8726   }
8727 
8728   // Check for use of public/private annotation outside of os_log().
8729   if (FSType != Sema::FST_OSLog) {
8730     if (FS.isPublic().isSet()) {
8731       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8732                                << "public",
8733                            getLocationOfByte(FS.isPublic().getPosition()),
8734                            /*IsStringLocation*/ false,
8735                            getSpecifierRange(startSpecifier, specifierLen));
8736     }
8737     if (FS.isPrivate().isSet()) {
8738       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8739                                << "private",
8740                            getLocationOfByte(FS.isPrivate().getPosition()),
8741                            /*IsStringLocation*/ false,
8742                            getSpecifierRange(startSpecifier, specifierLen));
8743     }
8744   }
8745 
8746   // Check for invalid use of field width
8747   if (!FS.hasValidFieldWidth()) {
8748     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8749         startSpecifier, specifierLen);
8750   }
8751 
8752   // Check for invalid use of precision
8753   if (!FS.hasValidPrecision()) {
8754     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8755         startSpecifier, specifierLen);
8756   }
8757 
8758   // Precision is mandatory for %P specifier.
8759   if (CS.getKind() == ConversionSpecifier::PArg &&
8760       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8761     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8762                          getLocationOfByte(startSpecifier),
8763                          /*IsStringLocation*/ false,
8764                          getSpecifierRange(startSpecifier, specifierLen));
8765   }
8766 
8767   // Check each flag does not conflict with any other component.
8768   if (!FS.hasValidThousandsGroupingPrefix())
8769     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8770   if (!FS.hasValidLeadingZeros())
8771     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8772   if (!FS.hasValidPlusPrefix())
8773     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8774   if (!FS.hasValidSpacePrefix())
8775     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8776   if (!FS.hasValidAlternativeForm())
8777     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8778   if (!FS.hasValidLeftJustified())
8779     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8780 
8781   // Check that flags are not ignored by another flag
8782   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8783     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8784         startSpecifier, specifierLen);
8785   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8786     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8787             startSpecifier, specifierLen);
8788 
8789   // Check the length modifier is valid with the given conversion specifier.
8790   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8791                                  S.getLangOpts()))
8792     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8793                                 diag::warn_format_nonsensical_length);
8794   else if (!FS.hasStandardLengthModifier())
8795     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8796   else if (!FS.hasStandardLengthConversionCombination())
8797     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8798                                 diag::warn_format_non_standard_conversion_spec);
8799 
8800   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8801     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8802 
8803   // The remaining checks depend on the data arguments.
8804   if (HasVAListArg)
8805     return true;
8806 
8807   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8808     return false;
8809 
8810   const Expr *Arg = getDataArg(argIndex);
8811   if (!Arg)
8812     return true;
8813 
8814   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8815 }
8816 
8817 static bool requiresParensToAddCast(const Expr *E) {
8818   // FIXME: We should have a general way to reason about operator
8819   // precedence and whether parens are actually needed here.
8820   // Take care of a few common cases where they aren't.
8821   const Expr *Inside = E->IgnoreImpCasts();
8822   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8823     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8824 
8825   switch (Inside->getStmtClass()) {
8826   case Stmt::ArraySubscriptExprClass:
8827   case Stmt::CallExprClass:
8828   case Stmt::CharacterLiteralClass:
8829   case Stmt::CXXBoolLiteralExprClass:
8830   case Stmt::DeclRefExprClass:
8831   case Stmt::FloatingLiteralClass:
8832   case Stmt::IntegerLiteralClass:
8833   case Stmt::MemberExprClass:
8834   case Stmt::ObjCArrayLiteralClass:
8835   case Stmt::ObjCBoolLiteralExprClass:
8836   case Stmt::ObjCBoxedExprClass:
8837   case Stmt::ObjCDictionaryLiteralClass:
8838   case Stmt::ObjCEncodeExprClass:
8839   case Stmt::ObjCIvarRefExprClass:
8840   case Stmt::ObjCMessageExprClass:
8841   case Stmt::ObjCPropertyRefExprClass:
8842   case Stmt::ObjCStringLiteralClass:
8843   case Stmt::ObjCSubscriptRefExprClass:
8844   case Stmt::ParenExprClass:
8845   case Stmt::StringLiteralClass:
8846   case Stmt::UnaryOperatorClass:
8847     return false;
8848   default:
8849     return true;
8850   }
8851 }
8852 
8853 static std::pair<QualType, StringRef>
8854 shouldNotPrintDirectly(const ASTContext &Context,
8855                        QualType IntendedTy,
8856                        const Expr *E) {
8857   // Use a 'while' to peel off layers of typedefs.
8858   QualType TyTy = IntendedTy;
8859   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8860     StringRef Name = UserTy->getDecl()->getName();
8861     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8862       .Case("CFIndex", Context.getNSIntegerType())
8863       .Case("NSInteger", Context.getNSIntegerType())
8864       .Case("NSUInteger", Context.getNSUIntegerType())
8865       .Case("SInt32", Context.IntTy)
8866       .Case("UInt32", Context.UnsignedIntTy)
8867       .Default(QualType());
8868 
8869     if (!CastTy.isNull())
8870       return std::make_pair(CastTy, Name);
8871 
8872     TyTy = UserTy->desugar();
8873   }
8874 
8875   // Strip parens if necessary.
8876   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8877     return shouldNotPrintDirectly(Context,
8878                                   PE->getSubExpr()->getType(),
8879                                   PE->getSubExpr());
8880 
8881   // If this is a conditional expression, then its result type is constructed
8882   // via usual arithmetic conversions and thus there might be no necessary
8883   // typedef sugar there.  Recurse to operands to check for NSInteger &
8884   // Co. usage condition.
8885   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8886     QualType TrueTy, FalseTy;
8887     StringRef TrueName, FalseName;
8888 
8889     std::tie(TrueTy, TrueName) =
8890       shouldNotPrintDirectly(Context,
8891                              CO->getTrueExpr()->getType(),
8892                              CO->getTrueExpr());
8893     std::tie(FalseTy, FalseName) =
8894       shouldNotPrintDirectly(Context,
8895                              CO->getFalseExpr()->getType(),
8896                              CO->getFalseExpr());
8897 
8898     if (TrueTy == FalseTy)
8899       return std::make_pair(TrueTy, TrueName);
8900     else if (TrueTy.isNull())
8901       return std::make_pair(FalseTy, FalseName);
8902     else if (FalseTy.isNull())
8903       return std::make_pair(TrueTy, TrueName);
8904   }
8905 
8906   return std::make_pair(QualType(), StringRef());
8907 }
8908 
8909 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8910 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8911 /// type do not count.
8912 static bool
8913 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8914   QualType From = ICE->getSubExpr()->getType();
8915   QualType To = ICE->getType();
8916   // It's an integer promotion if the destination type is the promoted
8917   // source type.
8918   if (ICE->getCastKind() == CK_IntegralCast &&
8919       From->isPromotableIntegerType() &&
8920       S.Context.getPromotedIntegerType(From) == To)
8921     return true;
8922   // Look through vector types, since we do default argument promotion for
8923   // those in OpenCL.
8924   if (const auto *VecTy = From->getAs<ExtVectorType>())
8925     From = VecTy->getElementType();
8926   if (const auto *VecTy = To->getAs<ExtVectorType>())
8927     To = VecTy->getElementType();
8928   // It's a floating promotion if the source type is a lower rank.
8929   return ICE->getCastKind() == CK_FloatingCast &&
8930          S.Context.getFloatingTypeOrder(From, To) < 0;
8931 }
8932 
8933 bool
8934 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8935                                     const char *StartSpecifier,
8936                                     unsigned SpecifierLen,
8937                                     const Expr *E) {
8938   using namespace analyze_format_string;
8939   using namespace analyze_printf;
8940 
8941   // Now type check the data expression that matches the
8942   // format specifier.
8943   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8944   if (!AT.isValid())
8945     return true;
8946 
8947   QualType ExprTy = E->getType();
8948   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8949     ExprTy = TET->getUnderlyingExpr()->getType();
8950   }
8951 
8952   // Diagnose attempts to print a boolean value as a character. Unlike other
8953   // -Wformat diagnostics, this is fine from a type perspective, but it still
8954   // doesn't make sense.
8955   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8956       E->isKnownToHaveBooleanValue()) {
8957     const CharSourceRange &CSR =
8958         getSpecifierRange(StartSpecifier, SpecifierLen);
8959     SmallString<4> FSString;
8960     llvm::raw_svector_ostream os(FSString);
8961     FS.toString(os);
8962     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8963                              << FSString,
8964                          E->getExprLoc(), false, CSR);
8965     return true;
8966   }
8967 
8968   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8969   if (Match == analyze_printf::ArgType::Match)
8970     return true;
8971 
8972   // Look through argument promotions for our error message's reported type.
8973   // This includes the integral and floating promotions, but excludes array
8974   // and function pointer decay (seeing that an argument intended to be a
8975   // string has type 'char [6]' is probably more confusing than 'char *') and
8976   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8977   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8978     if (isArithmeticArgumentPromotion(S, ICE)) {
8979       E = ICE->getSubExpr();
8980       ExprTy = E->getType();
8981 
8982       // Check if we didn't match because of an implicit cast from a 'char'
8983       // or 'short' to an 'int'.  This is done because printf is a varargs
8984       // function.
8985       if (ICE->getType() == S.Context.IntTy ||
8986           ICE->getType() == S.Context.UnsignedIntTy) {
8987         // All further checking is done on the subexpression
8988         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8989             AT.matchesType(S.Context, ExprTy);
8990         if (ImplicitMatch == analyze_printf::ArgType::Match)
8991           return true;
8992         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8993             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8994           Match = ImplicitMatch;
8995       }
8996     }
8997   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8998     // Special case for 'a', which has type 'int' in C.
8999     // Note, however, that we do /not/ want to treat multibyte constants like
9000     // 'MooV' as characters! This form is deprecated but still exists. In
9001     // addition, don't treat expressions as of type 'char' if one byte length
9002     // modifier is provided.
9003     if (ExprTy == S.Context.IntTy &&
9004         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9005       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9006         ExprTy = S.Context.CharTy;
9007   }
9008 
9009   // Look through enums to their underlying type.
9010   bool IsEnum = false;
9011   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9012     ExprTy = EnumTy->getDecl()->getIntegerType();
9013     IsEnum = true;
9014   }
9015 
9016   // %C in an Objective-C context prints a unichar, not a wchar_t.
9017   // If the argument is an integer of some kind, believe the %C and suggest
9018   // a cast instead of changing the conversion specifier.
9019   QualType IntendedTy = ExprTy;
9020   if (isObjCContext() &&
9021       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9022     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9023         !ExprTy->isCharType()) {
9024       // 'unichar' is defined as a typedef of unsigned short, but we should
9025       // prefer using the typedef if it is visible.
9026       IntendedTy = S.Context.UnsignedShortTy;
9027 
9028       // While we are here, check if the value is an IntegerLiteral that happens
9029       // to be within the valid range.
9030       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9031         const llvm::APInt &V = IL->getValue();
9032         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9033           return true;
9034       }
9035 
9036       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9037                           Sema::LookupOrdinaryName);
9038       if (S.LookupName(Result, S.getCurScope())) {
9039         NamedDecl *ND = Result.getFoundDecl();
9040         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9041           if (TD->getUnderlyingType() == IntendedTy)
9042             IntendedTy = S.Context.getTypedefType(TD);
9043       }
9044     }
9045   }
9046 
9047   // Special-case some of Darwin's platform-independence types by suggesting
9048   // casts to primitive types that are known to be large enough.
9049   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9050   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9051     QualType CastTy;
9052     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9053     if (!CastTy.isNull()) {
9054       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9055       // (long in ASTContext). Only complain to pedants.
9056       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9057           (AT.isSizeT() || AT.isPtrdiffT()) &&
9058           AT.matchesType(S.Context, CastTy))
9059         Match = ArgType::NoMatchPedantic;
9060       IntendedTy = CastTy;
9061       ShouldNotPrintDirectly = true;
9062     }
9063   }
9064 
9065   // We may be able to offer a FixItHint if it is a supported type.
9066   PrintfSpecifier fixedFS = FS;
9067   bool Success =
9068       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9069 
9070   if (Success) {
9071     // Get the fix string from the fixed format specifier
9072     SmallString<16> buf;
9073     llvm::raw_svector_ostream os(buf);
9074     fixedFS.toString(os);
9075 
9076     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9077 
9078     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9079       unsigned Diag;
9080       switch (Match) {
9081       case ArgType::Match: llvm_unreachable("expected non-matching");
9082       case ArgType::NoMatchPedantic:
9083         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9084         break;
9085       case ArgType::NoMatchTypeConfusion:
9086         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9087         break;
9088       case ArgType::NoMatch:
9089         Diag = diag::warn_format_conversion_argument_type_mismatch;
9090         break;
9091       }
9092 
9093       // In this case, the specifier is wrong and should be changed to match
9094       // the argument.
9095       EmitFormatDiagnostic(S.PDiag(Diag)
9096                                << AT.getRepresentativeTypeName(S.Context)
9097                                << IntendedTy << IsEnum << E->getSourceRange(),
9098                            E->getBeginLoc(),
9099                            /*IsStringLocation*/ false, SpecRange,
9100                            FixItHint::CreateReplacement(SpecRange, os.str()));
9101     } else {
9102       // The canonical type for formatting this value is different from the
9103       // actual type of the expression. (This occurs, for example, with Darwin's
9104       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9105       // should be printed as 'long' for 64-bit compatibility.)
9106       // Rather than emitting a normal format/argument mismatch, we want to
9107       // add a cast to the recommended type (and correct the format string
9108       // if necessary).
9109       SmallString<16> CastBuf;
9110       llvm::raw_svector_ostream CastFix(CastBuf);
9111       CastFix << "(";
9112       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9113       CastFix << ")";
9114 
9115       SmallVector<FixItHint,4> Hints;
9116       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9117         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9118 
9119       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9120         // If there's already a cast present, just replace it.
9121         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9122         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9123 
9124       } else if (!requiresParensToAddCast(E)) {
9125         // If the expression has high enough precedence,
9126         // just write the C-style cast.
9127         Hints.push_back(
9128             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9129       } else {
9130         // Otherwise, add parens around the expression as well as the cast.
9131         CastFix << "(";
9132         Hints.push_back(
9133             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9134 
9135         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9136         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9137       }
9138 
9139       if (ShouldNotPrintDirectly) {
9140         // The expression has a type that should not be printed directly.
9141         // We extract the name from the typedef because we don't want to show
9142         // the underlying type in the diagnostic.
9143         StringRef Name;
9144         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9145           Name = TypedefTy->getDecl()->getName();
9146         else
9147           Name = CastTyName;
9148         unsigned Diag = Match == ArgType::NoMatchPedantic
9149                             ? diag::warn_format_argument_needs_cast_pedantic
9150                             : diag::warn_format_argument_needs_cast;
9151         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9152                                            << E->getSourceRange(),
9153                              E->getBeginLoc(), /*IsStringLocation=*/false,
9154                              SpecRange, Hints);
9155       } else {
9156         // In this case, the expression could be printed using a different
9157         // specifier, but we've decided that the specifier is probably correct
9158         // and we should cast instead. Just use the normal warning message.
9159         EmitFormatDiagnostic(
9160             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9161                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9162                 << E->getSourceRange(),
9163             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9164       }
9165     }
9166   } else {
9167     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9168                                                    SpecifierLen);
9169     // Since the warning for passing non-POD types to variadic functions
9170     // was deferred until now, we emit a warning for non-POD
9171     // arguments here.
9172     switch (S.isValidVarArgType(ExprTy)) {
9173     case Sema::VAK_Valid:
9174     case Sema::VAK_ValidInCXX11: {
9175       unsigned Diag;
9176       switch (Match) {
9177       case ArgType::Match: llvm_unreachable("expected non-matching");
9178       case ArgType::NoMatchPedantic:
9179         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9180         break;
9181       case ArgType::NoMatchTypeConfusion:
9182         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9183         break;
9184       case ArgType::NoMatch:
9185         Diag = diag::warn_format_conversion_argument_type_mismatch;
9186         break;
9187       }
9188 
9189       EmitFormatDiagnostic(
9190           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9191                         << IsEnum << CSR << E->getSourceRange(),
9192           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9193       break;
9194     }
9195     case Sema::VAK_Undefined:
9196     case Sema::VAK_MSVCUndefined:
9197       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9198                                << S.getLangOpts().CPlusPlus11 << ExprTy
9199                                << CallType
9200                                << AT.getRepresentativeTypeName(S.Context) << CSR
9201                                << E->getSourceRange(),
9202                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9203       checkForCStrMembers(AT, E);
9204       break;
9205 
9206     case Sema::VAK_Invalid:
9207       if (ExprTy->isObjCObjectType())
9208         EmitFormatDiagnostic(
9209             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9210                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9211                 << AT.getRepresentativeTypeName(S.Context) << CSR
9212                 << E->getSourceRange(),
9213             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9214       else
9215         // FIXME: If this is an initializer list, suggest removing the braces
9216         // or inserting a cast to the target type.
9217         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9218             << isa<InitListExpr>(E) << ExprTy << CallType
9219             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9220       break;
9221     }
9222 
9223     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9224            "format string specifier index out of range");
9225     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9226   }
9227 
9228   return true;
9229 }
9230 
9231 //===--- CHECK: Scanf format string checking ------------------------------===//
9232 
9233 namespace {
9234 
9235 class CheckScanfHandler : public CheckFormatHandler {
9236 public:
9237   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9238                     const Expr *origFormatExpr, Sema::FormatStringType type,
9239                     unsigned firstDataArg, unsigned numDataArgs,
9240                     const char *beg, bool hasVAListArg,
9241                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9242                     bool inFunctionCall, Sema::VariadicCallType CallType,
9243                     llvm::SmallBitVector &CheckedVarArgs,
9244                     UncoveredArgHandler &UncoveredArg)
9245       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9246                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9247                            inFunctionCall, CallType, CheckedVarArgs,
9248                            UncoveredArg) {}
9249 
9250   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9251                             const char *startSpecifier,
9252                             unsigned specifierLen) override;
9253 
9254   bool HandleInvalidScanfConversionSpecifier(
9255           const analyze_scanf::ScanfSpecifier &FS,
9256           const char *startSpecifier,
9257           unsigned specifierLen) override;
9258 
9259   void HandleIncompleteScanList(const char *start, const char *end) override;
9260 };
9261 
9262 } // namespace
9263 
9264 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9265                                                  const char *end) {
9266   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9267                        getLocationOfByte(end), /*IsStringLocation*/true,
9268                        getSpecifierRange(start, end - start));
9269 }
9270 
9271 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9272                                         const analyze_scanf::ScanfSpecifier &FS,
9273                                         const char *startSpecifier,
9274                                         unsigned specifierLen) {
9275   const analyze_scanf::ScanfConversionSpecifier &CS =
9276     FS.getConversionSpecifier();
9277 
9278   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9279                                           getLocationOfByte(CS.getStart()),
9280                                           startSpecifier, specifierLen,
9281                                           CS.getStart(), CS.getLength());
9282 }
9283 
9284 bool CheckScanfHandler::HandleScanfSpecifier(
9285                                        const analyze_scanf::ScanfSpecifier &FS,
9286                                        const char *startSpecifier,
9287                                        unsigned specifierLen) {
9288   using namespace analyze_scanf;
9289   using namespace analyze_format_string;
9290 
9291   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9292 
9293   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9294   // be used to decide if we are using positional arguments consistently.
9295   if (FS.consumesDataArgument()) {
9296     if (atFirstArg) {
9297       atFirstArg = false;
9298       usesPositionalArgs = FS.usesPositionalArg();
9299     }
9300     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9301       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9302                                         startSpecifier, specifierLen);
9303       return false;
9304     }
9305   }
9306 
9307   // Check if the field with is non-zero.
9308   const OptionalAmount &Amt = FS.getFieldWidth();
9309   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9310     if (Amt.getConstantAmount() == 0) {
9311       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9312                                                    Amt.getConstantLength());
9313       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9314                            getLocationOfByte(Amt.getStart()),
9315                            /*IsStringLocation*/true, R,
9316                            FixItHint::CreateRemoval(R));
9317     }
9318   }
9319 
9320   if (!FS.consumesDataArgument()) {
9321     // FIXME: Technically specifying a precision or field width here
9322     // makes no sense.  Worth issuing a warning at some point.
9323     return true;
9324   }
9325 
9326   // Consume the argument.
9327   unsigned argIndex = FS.getArgIndex();
9328   if (argIndex < NumDataArgs) {
9329       // The check to see if the argIndex is valid will come later.
9330       // We set the bit here because we may exit early from this
9331       // function if we encounter some other error.
9332     CoveredArgs.set(argIndex);
9333   }
9334 
9335   // Check the length modifier is valid with the given conversion specifier.
9336   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9337                                  S.getLangOpts()))
9338     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9339                                 diag::warn_format_nonsensical_length);
9340   else if (!FS.hasStandardLengthModifier())
9341     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9342   else if (!FS.hasStandardLengthConversionCombination())
9343     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9344                                 diag::warn_format_non_standard_conversion_spec);
9345 
9346   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9347     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9348 
9349   // The remaining checks depend on the data arguments.
9350   if (HasVAListArg)
9351     return true;
9352 
9353   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9354     return false;
9355 
9356   // Check that the argument type matches the format specifier.
9357   const Expr *Ex = getDataArg(argIndex);
9358   if (!Ex)
9359     return true;
9360 
9361   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9362 
9363   if (!AT.isValid()) {
9364     return true;
9365   }
9366 
9367   analyze_format_string::ArgType::MatchKind Match =
9368       AT.matchesType(S.Context, Ex->getType());
9369   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9370   if (Match == analyze_format_string::ArgType::Match)
9371     return true;
9372 
9373   ScanfSpecifier fixedFS = FS;
9374   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9375                                  S.getLangOpts(), S.Context);
9376 
9377   unsigned Diag =
9378       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9379                : diag::warn_format_conversion_argument_type_mismatch;
9380 
9381   if (Success) {
9382     // Get the fix string from the fixed format specifier.
9383     SmallString<128> buf;
9384     llvm::raw_svector_ostream os(buf);
9385     fixedFS.toString(os);
9386 
9387     EmitFormatDiagnostic(
9388         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9389                       << Ex->getType() << false << Ex->getSourceRange(),
9390         Ex->getBeginLoc(),
9391         /*IsStringLocation*/ false,
9392         getSpecifierRange(startSpecifier, specifierLen),
9393         FixItHint::CreateReplacement(
9394             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9395   } else {
9396     EmitFormatDiagnostic(S.PDiag(Diag)
9397                              << AT.getRepresentativeTypeName(S.Context)
9398                              << Ex->getType() << false << Ex->getSourceRange(),
9399                          Ex->getBeginLoc(),
9400                          /*IsStringLocation*/ false,
9401                          getSpecifierRange(startSpecifier, specifierLen));
9402   }
9403 
9404   return true;
9405 }
9406 
9407 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9408                               const Expr *OrigFormatExpr,
9409                               ArrayRef<const Expr *> Args,
9410                               bool HasVAListArg, unsigned format_idx,
9411                               unsigned firstDataArg,
9412                               Sema::FormatStringType Type,
9413                               bool inFunctionCall,
9414                               Sema::VariadicCallType CallType,
9415                               llvm::SmallBitVector &CheckedVarArgs,
9416                               UncoveredArgHandler &UncoveredArg,
9417                               bool IgnoreStringsWithoutSpecifiers) {
9418   // CHECK: is the format string a wide literal?
9419   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9420     CheckFormatHandler::EmitFormatDiagnostic(
9421         S, inFunctionCall, Args[format_idx],
9422         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9423         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9424     return;
9425   }
9426 
9427   // Str - The format string.  NOTE: this is NOT null-terminated!
9428   StringRef StrRef = FExpr->getString();
9429   const char *Str = StrRef.data();
9430   // Account for cases where the string literal is truncated in a declaration.
9431   const ConstantArrayType *T =
9432     S.Context.getAsConstantArrayType(FExpr->getType());
9433   assert(T && "String literal not of constant array type!");
9434   size_t TypeSize = T->getSize().getZExtValue();
9435   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9436   const unsigned numDataArgs = Args.size() - firstDataArg;
9437 
9438   if (IgnoreStringsWithoutSpecifiers &&
9439       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9440           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9441     return;
9442 
9443   // Emit a warning if the string literal is truncated and does not contain an
9444   // embedded null character.
9445   if (TypeSize <= StrRef.size() &&
9446       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9447     CheckFormatHandler::EmitFormatDiagnostic(
9448         S, inFunctionCall, Args[format_idx],
9449         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9450         FExpr->getBeginLoc(),
9451         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9452     return;
9453   }
9454 
9455   // CHECK: empty format string?
9456   if (StrLen == 0 && numDataArgs > 0) {
9457     CheckFormatHandler::EmitFormatDiagnostic(
9458         S, inFunctionCall, Args[format_idx],
9459         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9460         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9461     return;
9462   }
9463 
9464   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9465       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9466       Type == Sema::FST_OSTrace) {
9467     CheckPrintfHandler H(
9468         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9469         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9470         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9471         CheckedVarArgs, UncoveredArg);
9472 
9473     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9474                                                   S.getLangOpts(),
9475                                                   S.Context.getTargetInfo(),
9476                                             Type == Sema::FST_FreeBSDKPrintf))
9477       H.DoneProcessing();
9478   } else if (Type == Sema::FST_Scanf) {
9479     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9480                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9481                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9482 
9483     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9484                                                  S.getLangOpts(),
9485                                                  S.Context.getTargetInfo()))
9486       H.DoneProcessing();
9487   } // TODO: handle other formats
9488 }
9489 
9490 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9491   // Str - The format string.  NOTE: this is NOT null-terminated!
9492   StringRef StrRef = FExpr->getString();
9493   const char *Str = StrRef.data();
9494   // Account for cases where the string literal is truncated in a declaration.
9495   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9496   assert(T && "String literal not of constant array type!");
9497   size_t TypeSize = T->getSize().getZExtValue();
9498   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9499   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9500                                                          getLangOpts(),
9501                                                          Context.getTargetInfo());
9502 }
9503 
9504 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9505 
9506 // Returns the related absolute value function that is larger, of 0 if one
9507 // does not exist.
9508 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9509   switch (AbsFunction) {
9510   default:
9511     return 0;
9512 
9513   case Builtin::BI__builtin_abs:
9514     return Builtin::BI__builtin_labs;
9515   case Builtin::BI__builtin_labs:
9516     return Builtin::BI__builtin_llabs;
9517   case Builtin::BI__builtin_llabs:
9518     return 0;
9519 
9520   case Builtin::BI__builtin_fabsf:
9521     return Builtin::BI__builtin_fabs;
9522   case Builtin::BI__builtin_fabs:
9523     return Builtin::BI__builtin_fabsl;
9524   case Builtin::BI__builtin_fabsl:
9525     return 0;
9526 
9527   case Builtin::BI__builtin_cabsf:
9528     return Builtin::BI__builtin_cabs;
9529   case Builtin::BI__builtin_cabs:
9530     return Builtin::BI__builtin_cabsl;
9531   case Builtin::BI__builtin_cabsl:
9532     return 0;
9533 
9534   case Builtin::BIabs:
9535     return Builtin::BIlabs;
9536   case Builtin::BIlabs:
9537     return Builtin::BIllabs;
9538   case Builtin::BIllabs:
9539     return 0;
9540 
9541   case Builtin::BIfabsf:
9542     return Builtin::BIfabs;
9543   case Builtin::BIfabs:
9544     return Builtin::BIfabsl;
9545   case Builtin::BIfabsl:
9546     return 0;
9547 
9548   case Builtin::BIcabsf:
9549    return Builtin::BIcabs;
9550   case Builtin::BIcabs:
9551     return Builtin::BIcabsl;
9552   case Builtin::BIcabsl:
9553     return 0;
9554   }
9555 }
9556 
9557 // Returns the argument type of the absolute value function.
9558 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9559                                              unsigned AbsType) {
9560   if (AbsType == 0)
9561     return QualType();
9562 
9563   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9564   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9565   if (Error != ASTContext::GE_None)
9566     return QualType();
9567 
9568   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9569   if (!FT)
9570     return QualType();
9571 
9572   if (FT->getNumParams() != 1)
9573     return QualType();
9574 
9575   return FT->getParamType(0);
9576 }
9577 
9578 // Returns the best absolute value function, or zero, based on type and
9579 // current absolute value function.
9580 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9581                                    unsigned AbsFunctionKind) {
9582   unsigned BestKind = 0;
9583   uint64_t ArgSize = Context.getTypeSize(ArgType);
9584   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9585        Kind = getLargerAbsoluteValueFunction(Kind)) {
9586     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9587     if (Context.getTypeSize(ParamType) >= ArgSize) {
9588       if (BestKind == 0)
9589         BestKind = Kind;
9590       else if (Context.hasSameType(ParamType, ArgType)) {
9591         BestKind = Kind;
9592         break;
9593       }
9594     }
9595   }
9596   return BestKind;
9597 }
9598 
9599 enum AbsoluteValueKind {
9600   AVK_Integer,
9601   AVK_Floating,
9602   AVK_Complex
9603 };
9604 
9605 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9606   if (T->isIntegralOrEnumerationType())
9607     return AVK_Integer;
9608   if (T->isRealFloatingType())
9609     return AVK_Floating;
9610   if (T->isAnyComplexType())
9611     return AVK_Complex;
9612 
9613   llvm_unreachable("Type not integer, floating, or complex");
9614 }
9615 
9616 // Changes the absolute value function to a different type.  Preserves whether
9617 // the function is a builtin.
9618 static unsigned changeAbsFunction(unsigned AbsKind,
9619                                   AbsoluteValueKind ValueKind) {
9620   switch (ValueKind) {
9621   case AVK_Integer:
9622     switch (AbsKind) {
9623     default:
9624       return 0;
9625     case Builtin::BI__builtin_fabsf:
9626     case Builtin::BI__builtin_fabs:
9627     case Builtin::BI__builtin_fabsl:
9628     case Builtin::BI__builtin_cabsf:
9629     case Builtin::BI__builtin_cabs:
9630     case Builtin::BI__builtin_cabsl:
9631       return Builtin::BI__builtin_abs;
9632     case Builtin::BIfabsf:
9633     case Builtin::BIfabs:
9634     case Builtin::BIfabsl:
9635     case Builtin::BIcabsf:
9636     case Builtin::BIcabs:
9637     case Builtin::BIcabsl:
9638       return Builtin::BIabs;
9639     }
9640   case AVK_Floating:
9641     switch (AbsKind) {
9642     default:
9643       return 0;
9644     case Builtin::BI__builtin_abs:
9645     case Builtin::BI__builtin_labs:
9646     case Builtin::BI__builtin_llabs:
9647     case Builtin::BI__builtin_cabsf:
9648     case Builtin::BI__builtin_cabs:
9649     case Builtin::BI__builtin_cabsl:
9650       return Builtin::BI__builtin_fabsf;
9651     case Builtin::BIabs:
9652     case Builtin::BIlabs:
9653     case Builtin::BIllabs:
9654     case Builtin::BIcabsf:
9655     case Builtin::BIcabs:
9656     case Builtin::BIcabsl:
9657       return Builtin::BIfabsf;
9658     }
9659   case AVK_Complex:
9660     switch (AbsKind) {
9661     default:
9662       return 0;
9663     case Builtin::BI__builtin_abs:
9664     case Builtin::BI__builtin_labs:
9665     case Builtin::BI__builtin_llabs:
9666     case Builtin::BI__builtin_fabsf:
9667     case Builtin::BI__builtin_fabs:
9668     case Builtin::BI__builtin_fabsl:
9669       return Builtin::BI__builtin_cabsf;
9670     case Builtin::BIabs:
9671     case Builtin::BIlabs:
9672     case Builtin::BIllabs:
9673     case Builtin::BIfabsf:
9674     case Builtin::BIfabs:
9675     case Builtin::BIfabsl:
9676       return Builtin::BIcabsf;
9677     }
9678   }
9679   llvm_unreachable("Unable to convert function");
9680 }
9681 
9682 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9683   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9684   if (!FnInfo)
9685     return 0;
9686 
9687   switch (FDecl->getBuiltinID()) {
9688   default:
9689     return 0;
9690   case Builtin::BI__builtin_abs:
9691   case Builtin::BI__builtin_fabs:
9692   case Builtin::BI__builtin_fabsf:
9693   case Builtin::BI__builtin_fabsl:
9694   case Builtin::BI__builtin_labs:
9695   case Builtin::BI__builtin_llabs:
9696   case Builtin::BI__builtin_cabs:
9697   case Builtin::BI__builtin_cabsf:
9698   case Builtin::BI__builtin_cabsl:
9699   case Builtin::BIabs:
9700   case Builtin::BIlabs:
9701   case Builtin::BIllabs:
9702   case Builtin::BIfabs:
9703   case Builtin::BIfabsf:
9704   case Builtin::BIfabsl:
9705   case Builtin::BIcabs:
9706   case Builtin::BIcabsf:
9707   case Builtin::BIcabsl:
9708     return FDecl->getBuiltinID();
9709   }
9710   llvm_unreachable("Unknown Builtin type");
9711 }
9712 
9713 // If the replacement is valid, emit a note with replacement function.
9714 // Additionally, suggest including the proper header if not already included.
9715 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9716                             unsigned AbsKind, QualType ArgType) {
9717   bool EmitHeaderHint = true;
9718   const char *HeaderName = nullptr;
9719   const char *FunctionName = nullptr;
9720   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9721     FunctionName = "std::abs";
9722     if (ArgType->isIntegralOrEnumerationType()) {
9723       HeaderName = "cstdlib";
9724     } else if (ArgType->isRealFloatingType()) {
9725       HeaderName = "cmath";
9726     } else {
9727       llvm_unreachable("Invalid Type");
9728     }
9729 
9730     // Lookup all std::abs
9731     if (NamespaceDecl *Std = S.getStdNamespace()) {
9732       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9733       R.suppressDiagnostics();
9734       S.LookupQualifiedName(R, Std);
9735 
9736       for (const auto *I : R) {
9737         const FunctionDecl *FDecl = nullptr;
9738         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9739           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9740         } else {
9741           FDecl = dyn_cast<FunctionDecl>(I);
9742         }
9743         if (!FDecl)
9744           continue;
9745 
9746         // Found std::abs(), check that they are the right ones.
9747         if (FDecl->getNumParams() != 1)
9748           continue;
9749 
9750         // Check that the parameter type can handle the argument.
9751         QualType ParamType = FDecl->getParamDecl(0)->getType();
9752         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9753             S.Context.getTypeSize(ArgType) <=
9754                 S.Context.getTypeSize(ParamType)) {
9755           // Found a function, don't need the header hint.
9756           EmitHeaderHint = false;
9757           break;
9758         }
9759       }
9760     }
9761   } else {
9762     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9763     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9764 
9765     if (HeaderName) {
9766       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9767       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9768       R.suppressDiagnostics();
9769       S.LookupName(R, S.getCurScope());
9770 
9771       if (R.isSingleResult()) {
9772         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9773         if (FD && FD->getBuiltinID() == AbsKind) {
9774           EmitHeaderHint = false;
9775         } else {
9776           return;
9777         }
9778       } else if (!R.empty()) {
9779         return;
9780       }
9781     }
9782   }
9783 
9784   S.Diag(Loc, diag::note_replace_abs_function)
9785       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9786 
9787   if (!HeaderName)
9788     return;
9789 
9790   if (!EmitHeaderHint)
9791     return;
9792 
9793   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9794                                                     << FunctionName;
9795 }
9796 
9797 template <std::size_t StrLen>
9798 static bool IsStdFunction(const FunctionDecl *FDecl,
9799                           const char (&Str)[StrLen]) {
9800   if (!FDecl)
9801     return false;
9802   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9803     return false;
9804   if (!FDecl->isInStdNamespace())
9805     return false;
9806 
9807   return true;
9808 }
9809 
9810 // Warn when using the wrong abs() function.
9811 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9812                                       const FunctionDecl *FDecl) {
9813   if (Call->getNumArgs() != 1)
9814     return;
9815 
9816   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9817   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9818   if (AbsKind == 0 && !IsStdAbs)
9819     return;
9820 
9821   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9822   QualType ParamType = Call->getArg(0)->getType();
9823 
9824   // Unsigned types cannot be negative.  Suggest removing the absolute value
9825   // function call.
9826   if (ArgType->isUnsignedIntegerType()) {
9827     const char *FunctionName =
9828         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9829     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9830     Diag(Call->getExprLoc(), diag::note_remove_abs)
9831         << FunctionName
9832         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9833     return;
9834   }
9835 
9836   // Taking the absolute value of a pointer is very suspicious, they probably
9837   // wanted to index into an array, dereference a pointer, call a function, etc.
9838   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9839     unsigned DiagType = 0;
9840     if (ArgType->isFunctionType())
9841       DiagType = 1;
9842     else if (ArgType->isArrayType())
9843       DiagType = 2;
9844 
9845     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9846     return;
9847   }
9848 
9849   // std::abs has overloads which prevent most of the absolute value problems
9850   // from occurring.
9851   if (IsStdAbs)
9852     return;
9853 
9854   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9855   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9856 
9857   // The argument and parameter are the same kind.  Check if they are the right
9858   // size.
9859   if (ArgValueKind == ParamValueKind) {
9860     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9861       return;
9862 
9863     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9864     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9865         << FDecl << ArgType << ParamType;
9866 
9867     if (NewAbsKind == 0)
9868       return;
9869 
9870     emitReplacement(*this, Call->getExprLoc(),
9871                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9872     return;
9873   }
9874 
9875   // ArgValueKind != ParamValueKind
9876   // The wrong type of absolute value function was used.  Attempt to find the
9877   // proper one.
9878   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9879   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9880   if (NewAbsKind == 0)
9881     return;
9882 
9883   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9884       << FDecl << ParamValueKind << ArgValueKind;
9885 
9886   emitReplacement(*this, Call->getExprLoc(),
9887                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9888 }
9889 
9890 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9891 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9892                                 const FunctionDecl *FDecl) {
9893   if (!Call || !FDecl) return;
9894 
9895   // Ignore template specializations and macros.
9896   if (inTemplateInstantiation()) return;
9897   if (Call->getExprLoc().isMacroID()) return;
9898 
9899   // Only care about the one template argument, two function parameter std::max
9900   if (Call->getNumArgs() != 2) return;
9901   if (!IsStdFunction(FDecl, "max")) return;
9902   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9903   if (!ArgList) return;
9904   if (ArgList->size() != 1) return;
9905 
9906   // Check that template type argument is unsigned integer.
9907   const auto& TA = ArgList->get(0);
9908   if (TA.getKind() != TemplateArgument::Type) return;
9909   QualType ArgType = TA.getAsType();
9910   if (!ArgType->isUnsignedIntegerType()) return;
9911 
9912   // See if either argument is a literal zero.
9913   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9914     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9915     if (!MTE) return false;
9916     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9917     if (!Num) return false;
9918     if (Num->getValue() != 0) return false;
9919     return true;
9920   };
9921 
9922   const Expr *FirstArg = Call->getArg(0);
9923   const Expr *SecondArg = Call->getArg(1);
9924   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9925   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9926 
9927   // Only warn when exactly one argument is zero.
9928   if (IsFirstArgZero == IsSecondArgZero) return;
9929 
9930   SourceRange FirstRange = FirstArg->getSourceRange();
9931   SourceRange SecondRange = SecondArg->getSourceRange();
9932 
9933   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9934 
9935   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9936       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9937 
9938   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9939   SourceRange RemovalRange;
9940   if (IsFirstArgZero) {
9941     RemovalRange = SourceRange(FirstRange.getBegin(),
9942                                SecondRange.getBegin().getLocWithOffset(-1));
9943   } else {
9944     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9945                                SecondRange.getEnd());
9946   }
9947 
9948   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9949         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9950         << FixItHint::CreateRemoval(RemovalRange);
9951 }
9952 
9953 //===--- CHECK: Standard memory functions ---------------------------------===//
9954 
9955 /// Takes the expression passed to the size_t parameter of functions
9956 /// such as memcmp, strncat, etc and warns if it's a comparison.
9957 ///
9958 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9959 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9960                                            IdentifierInfo *FnName,
9961                                            SourceLocation FnLoc,
9962                                            SourceLocation RParenLoc) {
9963   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9964   if (!Size)
9965     return false;
9966 
9967   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9968   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9969     return false;
9970 
9971   SourceRange SizeRange = Size->getSourceRange();
9972   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9973       << SizeRange << FnName;
9974   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9975       << FnName
9976       << FixItHint::CreateInsertion(
9977              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9978       << FixItHint::CreateRemoval(RParenLoc);
9979   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9980       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9981       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9982                                     ")");
9983 
9984   return true;
9985 }
9986 
9987 /// Determine whether the given type is or contains a dynamic class type
9988 /// (e.g., whether it has a vtable).
9989 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9990                                                      bool &IsContained) {
9991   // Look through array types while ignoring qualifiers.
9992   const Type *Ty = T->getBaseElementTypeUnsafe();
9993   IsContained = false;
9994 
9995   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9996   RD = RD ? RD->getDefinition() : nullptr;
9997   if (!RD || RD->isInvalidDecl())
9998     return nullptr;
9999 
10000   if (RD->isDynamicClass())
10001     return RD;
10002 
10003   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10004   // It's impossible for a class to transitively contain itself by value, so
10005   // infinite recursion is impossible.
10006   for (auto *FD : RD->fields()) {
10007     bool SubContained;
10008     if (const CXXRecordDecl *ContainedRD =
10009             getContainedDynamicClass(FD->getType(), SubContained)) {
10010       IsContained = true;
10011       return ContainedRD;
10012     }
10013   }
10014 
10015   return nullptr;
10016 }
10017 
10018 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10019   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10020     if (Unary->getKind() == UETT_SizeOf)
10021       return Unary;
10022   return nullptr;
10023 }
10024 
10025 /// If E is a sizeof expression, returns its argument expression,
10026 /// otherwise returns NULL.
10027 static const Expr *getSizeOfExprArg(const Expr *E) {
10028   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10029     if (!SizeOf->isArgumentType())
10030       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10031   return nullptr;
10032 }
10033 
10034 /// If E is a sizeof expression, returns its argument type.
10035 static QualType getSizeOfArgType(const Expr *E) {
10036   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10037     return SizeOf->getTypeOfArgument();
10038   return QualType();
10039 }
10040 
10041 namespace {
10042 
10043 struct SearchNonTrivialToInitializeField
10044     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10045   using Super =
10046       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10047 
10048   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10049 
10050   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10051                      SourceLocation SL) {
10052     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10053       asDerived().visitArray(PDIK, AT, SL);
10054       return;
10055     }
10056 
10057     Super::visitWithKind(PDIK, FT, SL);
10058   }
10059 
10060   void visitARCStrong(QualType FT, SourceLocation SL) {
10061     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10062   }
10063   void visitARCWeak(QualType FT, SourceLocation SL) {
10064     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10065   }
10066   void visitStruct(QualType FT, SourceLocation SL) {
10067     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10068       visit(FD->getType(), FD->getLocation());
10069   }
10070   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10071                   const ArrayType *AT, SourceLocation SL) {
10072     visit(getContext().getBaseElementType(AT), SL);
10073   }
10074   void visitTrivial(QualType FT, SourceLocation SL) {}
10075 
10076   static void diag(QualType RT, const Expr *E, Sema &S) {
10077     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10078   }
10079 
10080   ASTContext &getContext() { return S.getASTContext(); }
10081 
10082   const Expr *E;
10083   Sema &S;
10084 };
10085 
10086 struct SearchNonTrivialToCopyField
10087     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10088   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10089 
10090   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10091 
10092   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10093                      SourceLocation SL) {
10094     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10095       asDerived().visitArray(PCK, AT, SL);
10096       return;
10097     }
10098 
10099     Super::visitWithKind(PCK, FT, SL);
10100   }
10101 
10102   void visitARCStrong(QualType FT, SourceLocation SL) {
10103     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10104   }
10105   void visitARCWeak(QualType FT, SourceLocation SL) {
10106     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10107   }
10108   void visitStruct(QualType FT, SourceLocation SL) {
10109     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10110       visit(FD->getType(), FD->getLocation());
10111   }
10112   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10113                   SourceLocation SL) {
10114     visit(getContext().getBaseElementType(AT), SL);
10115   }
10116   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10117                 SourceLocation SL) {}
10118   void visitTrivial(QualType FT, SourceLocation SL) {}
10119   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10120 
10121   static void diag(QualType RT, const Expr *E, Sema &S) {
10122     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10123   }
10124 
10125   ASTContext &getContext() { return S.getASTContext(); }
10126 
10127   const Expr *E;
10128   Sema &S;
10129 };
10130 
10131 }
10132 
10133 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10134 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10135   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10136 
10137   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10138     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10139       return false;
10140 
10141     return doesExprLikelyComputeSize(BO->getLHS()) ||
10142            doesExprLikelyComputeSize(BO->getRHS());
10143   }
10144 
10145   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10146 }
10147 
10148 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10149 ///
10150 /// \code
10151 ///   #define MACRO 0
10152 ///   foo(MACRO);
10153 ///   foo(0);
10154 /// \endcode
10155 ///
10156 /// This should return true for the first call to foo, but not for the second
10157 /// (regardless of whether foo is a macro or function).
10158 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10159                                         SourceLocation CallLoc,
10160                                         SourceLocation ArgLoc) {
10161   if (!CallLoc.isMacroID())
10162     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10163 
10164   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10165          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10166 }
10167 
10168 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10169 /// last two arguments transposed.
10170 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10171   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10172     return;
10173 
10174   const Expr *SizeArg =
10175     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10176 
10177   auto isLiteralZero = [](const Expr *E) {
10178     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10179   };
10180 
10181   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10182   SourceLocation CallLoc = Call->getRParenLoc();
10183   SourceManager &SM = S.getSourceManager();
10184   if (isLiteralZero(SizeArg) &&
10185       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10186 
10187     SourceLocation DiagLoc = SizeArg->getExprLoc();
10188 
10189     // Some platforms #define bzero to __builtin_memset. See if this is the
10190     // case, and if so, emit a better diagnostic.
10191     if (BId == Builtin::BIbzero ||
10192         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10193                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10194       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10195       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10196     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10197       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10198       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10199     }
10200     return;
10201   }
10202 
10203   // If the second argument to a memset is a sizeof expression and the third
10204   // isn't, this is also likely an error. This should catch
10205   // 'memset(buf, sizeof(buf), 0xff)'.
10206   if (BId == Builtin::BImemset &&
10207       doesExprLikelyComputeSize(Call->getArg(1)) &&
10208       !doesExprLikelyComputeSize(Call->getArg(2))) {
10209     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10210     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10211     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10212     return;
10213   }
10214 }
10215 
10216 /// Check for dangerous or invalid arguments to memset().
10217 ///
10218 /// This issues warnings on known problematic, dangerous or unspecified
10219 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10220 /// function calls.
10221 ///
10222 /// \param Call The call expression to diagnose.
10223 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10224                                    unsigned BId,
10225                                    IdentifierInfo *FnName) {
10226   assert(BId != 0);
10227 
10228   // It is possible to have a non-standard definition of memset.  Validate
10229   // we have enough arguments, and if not, abort further checking.
10230   unsigned ExpectedNumArgs =
10231       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10232   if (Call->getNumArgs() < ExpectedNumArgs)
10233     return;
10234 
10235   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10236                       BId == Builtin::BIstrndup ? 1 : 2);
10237   unsigned LenArg =
10238       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10239   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10240 
10241   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10242                                      Call->getBeginLoc(), Call->getRParenLoc()))
10243     return;
10244 
10245   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10246   CheckMemaccessSize(*this, BId, Call);
10247 
10248   // We have special checking when the length is a sizeof expression.
10249   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10250   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10251   llvm::FoldingSetNodeID SizeOfArgID;
10252 
10253   // Although widely used, 'bzero' is not a standard function. Be more strict
10254   // with the argument types before allowing diagnostics and only allow the
10255   // form bzero(ptr, sizeof(...)).
10256   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10257   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10258     return;
10259 
10260   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10261     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10262     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10263 
10264     QualType DestTy = Dest->getType();
10265     QualType PointeeTy;
10266     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10267       PointeeTy = DestPtrTy->getPointeeType();
10268 
10269       // Never warn about void type pointers. This can be used to suppress
10270       // false positives.
10271       if (PointeeTy->isVoidType())
10272         continue;
10273 
10274       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10275       // actually comparing the expressions for equality. Because computing the
10276       // expression IDs can be expensive, we only do this if the diagnostic is
10277       // enabled.
10278       if (SizeOfArg &&
10279           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10280                            SizeOfArg->getExprLoc())) {
10281         // We only compute IDs for expressions if the warning is enabled, and
10282         // cache the sizeof arg's ID.
10283         if (SizeOfArgID == llvm::FoldingSetNodeID())
10284           SizeOfArg->Profile(SizeOfArgID, Context, true);
10285         llvm::FoldingSetNodeID DestID;
10286         Dest->Profile(DestID, Context, true);
10287         if (DestID == SizeOfArgID) {
10288           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10289           //       over sizeof(src) as well.
10290           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10291           StringRef ReadableName = FnName->getName();
10292 
10293           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10294             if (UnaryOp->getOpcode() == UO_AddrOf)
10295               ActionIdx = 1; // If its an address-of operator, just remove it.
10296           if (!PointeeTy->isIncompleteType() &&
10297               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10298             ActionIdx = 2; // If the pointee's size is sizeof(char),
10299                            // suggest an explicit length.
10300 
10301           // If the function is defined as a builtin macro, do not show macro
10302           // expansion.
10303           SourceLocation SL = SizeOfArg->getExprLoc();
10304           SourceRange DSR = Dest->getSourceRange();
10305           SourceRange SSR = SizeOfArg->getSourceRange();
10306           SourceManager &SM = getSourceManager();
10307 
10308           if (SM.isMacroArgExpansion(SL)) {
10309             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10310             SL = SM.getSpellingLoc(SL);
10311             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10312                              SM.getSpellingLoc(DSR.getEnd()));
10313             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10314                              SM.getSpellingLoc(SSR.getEnd()));
10315           }
10316 
10317           DiagRuntimeBehavior(SL, SizeOfArg,
10318                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10319                                 << ReadableName
10320                                 << PointeeTy
10321                                 << DestTy
10322                                 << DSR
10323                                 << SSR);
10324           DiagRuntimeBehavior(SL, SizeOfArg,
10325                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10326                                 << ActionIdx
10327                                 << SSR);
10328 
10329           break;
10330         }
10331       }
10332 
10333       // Also check for cases where the sizeof argument is the exact same
10334       // type as the memory argument, and where it points to a user-defined
10335       // record type.
10336       if (SizeOfArgTy != QualType()) {
10337         if (PointeeTy->isRecordType() &&
10338             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10339           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10340                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10341                                 << FnName << SizeOfArgTy << ArgIdx
10342                                 << PointeeTy << Dest->getSourceRange()
10343                                 << LenExpr->getSourceRange());
10344           break;
10345         }
10346       }
10347     } else if (DestTy->isArrayType()) {
10348       PointeeTy = DestTy;
10349     }
10350 
10351     if (PointeeTy == QualType())
10352       continue;
10353 
10354     // Always complain about dynamic classes.
10355     bool IsContained;
10356     if (const CXXRecordDecl *ContainedRD =
10357             getContainedDynamicClass(PointeeTy, IsContained)) {
10358 
10359       unsigned OperationType = 0;
10360       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10361       // "overwritten" if we're warning about the destination for any call
10362       // but memcmp; otherwise a verb appropriate to the call.
10363       if (ArgIdx != 0 || IsCmp) {
10364         if (BId == Builtin::BImemcpy)
10365           OperationType = 1;
10366         else if(BId == Builtin::BImemmove)
10367           OperationType = 2;
10368         else if (IsCmp)
10369           OperationType = 3;
10370       }
10371 
10372       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10373                           PDiag(diag::warn_dyn_class_memaccess)
10374                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10375                               << IsContained << ContainedRD << OperationType
10376                               << Call->getCallee()->getSourceRange());
10377     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10378              BId != Builtin::BImemset)
10379       DiagRuntimeBehavior(
10380         Dest->getExprLoc(), Dest,
10381         PDiag(diag::warn_arc_object_memaccess)
10382           << ArgIdx << FnName << PointeeTy
10383           << Call->getCallee()->getSourceRange());
10384     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10385       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10386           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10387         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10388                             PDiag(diag::warn_cstruct_memaccess)
10389                                 << ArgIdx << FnName << PointeeTy << 0);
10390         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10391       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10392                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10393         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10394                             PDiag(diag::warn_cstruct_memaccess)
10395                                 << ArgIdx << FnName << PointeeTy << 1);
10396         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10397       } else {
10398         continue;
10399       }
10400     } else
10401       continue;
10402 
10403     DiagRuntimeBehavior(
10404       Dest->getExprLoc(), Dest,
10405       PDiag(diag::note_bad_memaccess_silence)
10406         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10407     break;
10408   }
10409 }
10410 
10411 // A little helper routine: ignore addition and subtraction of integer literals.
10412 // This intentionally does not ignore all integer constant expressions because
10413 // we don't want to remove sizeof().
10414 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10415   Ex = Ex->IgnoreParenCasts();
10416 
10417   while (true) {
10418     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10419     if (!BO || !BO->isAdditiveOp())
10420       break;
10421 
10422     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10423     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10424 
10425     if (isa<IntegerLiteral>(RHS))
10426       Ex = LHS;
10427     else if (isa<IntegerLiteral>(LHS))
10428       Ex = RHS;
10429     else
10430       break;
10431   }
10432 
10433   return Ex;
10434 }
10435 
10436 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10437                                                       ASTContext &Context) {
10438   // Only handle constant-sized or VLAs, but not flexible members.
10439   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10440     // Only issue the FIXIT for arrays of size > 1.
10441     if (CAT->getSize().getSExtValue() <= 1)
10442       return false;
10443   } else if (!Ty->isVariableArrayType()) {
10444     return false;
10445   }
10446   return true;
10447 }
10448 
10449 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10450 // be the size of the source, instead of the destination.
10451 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10452                                     IdentifierInfo *FnName) {
10453 
10454   // Don't crash if the user has the wrong number of arguments
10455   unsigned NumArgs = Call->getNumArgs();
10456   if ((NumArgs != 3) && (NumArgs != 4))
10457     return;
10458 
10459   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10460   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10461   const Expr *CompareWithSrc = nullptr;
10462 
10463   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10464                                      Call->getBeginLoc(), Call->getRParenLoc()))
10465     return;
10466 
10467   // Look for 'strlcpy(dst, x, sizeof(x))'
10468   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10469     CompareWithSrc = Ex;
10470   else {
10471     // Look for 'strlcpy(dst, x, strlen(x))'
10472     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10473       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10474           SizeCall->getNumArgs() == 1)
10475         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10476     }
10477   }
10478 
10479   if (!CompareWithSrc)
10480     return;
10481 
10482   // Determine if the argument to sizeof/strlen is equal to the source
10483   // argument.  In principle there's all kinds of things you could do
10484   // here, for instance creating an == expression and evaluating it with
10485   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10486   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10487   if (!SrcArgDRE)
10488     return;
10489 
10490   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10491   if (!CompareWithSrcDRE ||
10492       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10493     return;
10494 
10495   const Expr *OriginalSizeArg = Call->getArg(2);
10496   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10497       << OriginalSizeArg->getSourceRange() << FnName;
10498 
10499   // Output a FIXIT hint if the destination is an array (rather than a
10500   // pointer to an array).  This could be enhanced to handle some
10501   // pointers if we know the actual size, like if DstArg is 'array+2'
10502   // we could say 'sizeof(array)-2'.
10503   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10504   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10505     return;
10506 
10507   SmallString<128> sizeString;
10508   llvm::raw_svector_ostream OS(sizeString);
10509   OS << "sizeof(";
10510   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10511   OS << ")";
10512 
10513   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10514       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10515                                       OS.str());
10516 }
10517 
10518 /// Check if two expressions refer to the same declaration.
10519 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10520   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10521     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10522       return D1->getDecl() == D2->getDecl();
10523   return false;
10524 }
10525 
10526 static const Expr *getStrlenExprArg(const Expr *E) {
10527   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10528     const FunctionDecl *FD = CE->getDirectCallee();
10529     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10530       return nullptr;
10531     return CE->getArg(0)->IgnoreParenCasts();
10532   }
10533   return nullptr;
10534 }
10535 
10536 // Warn on anti-patterns as the 'size' argument to strncat.
10537 // The correct size argument should look like following:
10538 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10539 void Sema::CheckStrncatArguments(const CallExpr *CE,
10540                                  IdentifierInfo *FnName) {
10541   // Don't crash if the user has the wrong number of arguments.
10542   if (CE->getNumArgs() < 3)
10543     return;
10544   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10545   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10546   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10547 
10548   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10549                                      CE->getRParenLoc()))
10550     return;
10551 
10552   // Identify common expressions, which are wrongly used as the size argument
10553   // to strncat and may lead to buffer overflows.
10554   unsigned PatternType = 0;
10555   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10556     // - sizeof(dst)
10557     if (referToTheSameDecl(SizeOfArg, DstArg))
10558       PatternType = 1;
10559     // - sizeof(src)
10560     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10561       PatternType = 2;
10562   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10563     if (BE->getOpcode() == BO_Sub) {
10564       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10565       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10566       // - sizeof(dst) - strlen(dst)
10567       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10568           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10569         PatternType = 1;
10570       // - sizeof(src) - (anything)
10571       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10572         PatternType = 2;
10573     }
10574   }
10575 
10576   if (PatternType == 0)
10577     return;
10578 
10579   // Generate the diagnostic.
10580   SourceLocation SL = LenArg->getBeginLoc();
10581   SourceRange SR = LenArg->getSourceRange();
10582   SourceManager &SM = getSourceManager();
10583 
10584   // If the function is defined as a builtin macro, do not show macro expansion.
10585   if (SM.isMacroArgExpansion(SL)) {
10586     SL = SM.getSpellingLoc(SL);
10587     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10588                      SM.getSpellingLoc(SR.getEnd()));
10589   }
10590 
10591   // Check if the destination is an array (rather than a pointer to an array).
10592   QualType DstTy = DstArg->getType();
10593   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10594                                                                     Context);
10595   if (!isKnownSizeArray) {
10596     if (PatternType == 1)
10597       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10598     else
10599       Diag(SL, diag::warn_strncat_src_size) << SR;
10600     return;
10601   }
10602 
10603   if (PatternType == 1)
10604     Diag(SL, diag::warn_strncat_large_size) << SR;
10605   else
10606     Diag(SL, diag::warn_strncat_src_size) << SR;
10607 
10608   SmallString<128> sizeString;
10609   llvm::raw_svector_ostream OS(sizeString);
10610   OS << "sizeof(";
10611   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10612   OS << ") - ";
10613   OS << "strlen(";
10614   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10615   OS << ") - 1";
10616 
10617   Diag(SL, diag::note_strncat_wrong_size)
10618     << FixItHint::CreateReplacement(SR, OS.str());
10619 }
10620 
10621 namespace {
10622 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10623                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10624   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10625     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10626         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10627     return;
10628   }
10629 }
10630 
10631 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10632                                  const UnaryOperator *UnaryExpr) {
10633   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10634     const Decl *D = Lvalue->getDecl();
10635     if (isa<VarDecl, FunctionDecl>(D))
10636       return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10637   }
10638 
10639   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10640     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10641                                       Lvalue->getMemberDecl());
10642 }
10643 
10644 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10645                             const UnaryOperator *UnaryExpr) {
10646   const auto *Lambda = dyn_cast<LambdaExpr>(
10647       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10648   if (!Lambda)
10649     return;
10650 
10651   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10652       << CalleeName << 2 /*object: lambda expression*/;
10653 }
10654 
10655 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10656                                   const DeclRefExpr *Lvalue) {
10657   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10658   if (Var == nullptr)
10659     return;
10660 
10661   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10662       << CalleeName << 0 /*object: */ << Var;
10663 }
10664 
10665 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10666                             const CastExpr *Cast) {
10667   SmallString<128> SizeString;
10668   llvm::raw_svector_ostream OS(SizeString);
10669 
10670   clang::CastKind Kind = Cast->getCastKind();
10671   if (Kind == clang::CK_BitCast &&
10672       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10673     return;
10674   if (Kind == clang::CK_IntegralToPointer &&
10675       !isa<IntegerLiteral>(
10676           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10677     return;
10678 
10679   switch (Cast->getCastKind()) {
10680   case clang::CK_BitCast:
10681   case clang::CK_IntegralToPointer:
10682   case clang::CK_FunctionToPointerDecay:
10683     OS << '\'';
10684     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10685     OS << '\'';
10686     break;
10687   default:
10688     return;
10689   }
10690 
10691   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10692       << CalleeName << 0 /*object: */ << OS.str();
10693 }
10694 } // namespace
10695 
10696 /// Alerts the user that they are attempting to free a non-malloc'd object.
10697 void Sema::CheckFreeArguments(const CallExpr *E) {
10698   const std::string CalleeName =
10699       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10700 
10701   { // Prefer something that doesn't involve a cast to make things simpler.
10702     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10703     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10704       switch (UnaryExpr->getOpcode()) {
10705       case UnaryOperator::Opcode::UO_AddrOf:
10706         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10707       case UnaryOperator::Opcode::UO_Plus:
10708         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10709       default:
10710         break;
10711       }
10712 
10713     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10714       if (Lvalue->getType()->isArrayType())
10715         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10716 
10717     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10718       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10719           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10720       return;
10721     }
10722 
10723     if (isa<BlockExpr>(Arg)) {
10724       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10725           << CalleeName << 1 /*object: block*/;
10726       return;
10727     }
10728   }
10729   // Maybe the cast was important, check after the other cases.
10730   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10731     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10732 }
10733 
10734 void
10735 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10736                          SourceLocation ReturnLoc,
10737                          bool isObjCMethod,
10738                          const AttrVec *Attrs,
10739                          const FunctionDecl *FD) {
10740   // Check if the return value is null but should not be.
10741   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10742        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10743       CheckNonNullExpr(*this, RetValExp))
10744     Diag(ReturnLoc, diag::warn_null_ret)
10745       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10746 
10747   // C++11 [basic.stc.dynamic.allocation]p4:
10748   //   If an allocation function declared with a non-throwing
10749   //   exception-specification fails to allocate storage, it shall return
10750   //   a null pointer. Any other allocation function that fails to allocate
10751   //   storage shall indicate failure only by throwing an exception [...]
10752   if (FD) {
10753     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10754     if (Op == OO_New || Op == OO_Array_New) {
10755       const FunctionProtoType *Proto
10756         = FD->getType()->castAs<FunctionProtoType>();
10757       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10758           CheckNonNullExpr(*this, RetValExp))
10759         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10760           << FD << getLangOpts().CPlusPlus11;
10761     }
10762   }
10763 
10764   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10765   // here prevent the user from using a PPC MMA type as trailing return type.
10766   if (Context.getTargetInfo().getTriple().isPPC64())
10767     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10768 }
10769 
10770 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10771 
10772 /// Check for comparisons of floating point operands using != and ==.
10773 /// Issue a warning if these are no self-comparisons, as they are not likely
10774 /// to do what the programmer intended.
10775 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10776   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10777   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10778 
10779   // Special case: check for x == x (which is OK).
10780   // Do not emit warnings for such cases.
10781   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10782     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10783       if (DRL->getDecl() == DRR->getDecl())
10784         return;
10785 
10786   // Special case: check for comparisons against literals that can be exactly
10787   //  represented by APFloat.  In such cases, do not emit a warning.  This
10788   //  is a heuristic: often comparison against such literals are used to
10789   //  detect if a value in a variable has not changed.  This clearly can
10790   //  lead to false negatives.
10791   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10792     if (FLL->isExact())
10793       return;
10794   } else
10795     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10796       if (FLR->isExact())
10797         return;
10798 
10799   // Check for comparisons with builtin types.
10800   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10801     if (CL->getBuiltinCallee())
10802       return;
10803 
10804   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10805     if (CR->getBuiltinCallee())
10806       return;
10807 
10808   // Emit the diagnostic.
10809   Diag(Loc, diag::warn_floatingpoint_eq)
10810     << LHS->getSourceRange() << RHS->getSourceRange();
10811 }
10812 
10813 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10814 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10815 
10816 namespace {
10817 
10818 /// Structure recording the 'active' range of an integer-valued
10819 /// expression.
10820 struct IntRange {
10821   /// The number of bits active in the int. Note that this includes exactly one
10822   /// sign bit if !NonNegative.
10823   unsigned Width;
10824 
10825   /// True if the int is known not to have negative values. If so, all leading
10826   /// bits before Width are known zero, otherwise they are known to be the
10827   /// same as the MSB within Width.
10828   bool NonNegative;
10829 
10830   IntRange(unsigned Width, bool NonNegative)
10831       : Width(Width), NonNegative(NonNegative) {}
10832 
10833   /// Number of bits excluding the sign bit.
10834   unsigned valueBits() const {
10835     return NonNegative ? Width : Width - 1;
10836   }
10837 
10838   /// Returns the range of the bool type.
10839   static IntRange forBoolType() {
10840     return IntRange(1, true);
10841   }
10842 
10843   /// Returns the range of an opaque value of the given integral type.
10844   static IntRange forValueOfType(ASTContext &C, QualType T) {
10845     return forValueOfCanonicalType(C,
10846                           T->getCanonicalTypeInternal().getTypePtr());
10847   }
10848 
10849   /// Returns the range of an opaque value of a canonical integral type.
10850   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10851     assert(T->isCanonicalUnqualified());
10852 
10853     if (const VectorType *VT = dyn_cast<VectorType>(T))
10854       T = VT->getElementType().getTypePtr();
10855     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10856       T = CT->getElementType().getTypePtr();
10857     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10858       T = AT->getValueType().getTypePtr();
10859 
10860     if (!C.getLangOpts().CPlusPlus) {
10861       // For enum types in C code, use the underlying datatype.
10862       if (const EnumType *ET = dyn_cast<EnumType>(T))
10863         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10864     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10865       // For enum types in C++, use the known bit width of the enumerators.
10866       EnumDecl *Enum = ET->getDecl();
10867       // In C++11, enums can have a fixed underlying type. Use this type to
10868       // compute the range.
10869       if (Enum->isFixed()) {
10870         return IntRange(C.getIntWidth(QualType(T, 0)),
10871                         !ET->isSignedIntegerOrEnumerationType());
10872       }
10873 
10874       unsigned NumPositive = Enum->getNumPositiveBits();
10875       unsigned NumNegative = Enum->getNumNegativeBits();
10876 
10877       if (NumNegative == 0)
10878         return IntRange(NumPositive, true/*NonNegative*/);
10879       else
10880         return IntRange(std::max(NumPositive + 1, NumNegative),
10881                         false/*NonNegative*/);
10882     }
10883 
10884     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10885       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10886 
10887     const BuiltinType *BT = cast<BuiltinType>(T);
10888     assert(BT->isInteger());
10889 
10890     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10891   }
10892 
10893   /// Returns the "target" range of a canonical integral type, i.e.
10894   /// the range of values expressible in the type.
10895   ///
10896   /// This matches forValueOfCanonicalType except that enums have the
10897   /// full range of their type, not the range of their enumerators.
10898   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10899     assert(T->isCanonicalUnqualified());
10900 
10901     if (const VectorType *VT = dyn_cast<VectorType>(T))
10902       T = VT->getElementType().getTypePtr();
10903     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10904       T = CT->getElementType().getTypePtr();
10905     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10906       T = AT->getValueType().getTypePtr();
10907     if (const EnumType *ET = dyn_cast<EnumType>(T))
10908       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10909 
10910     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10911       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10912 
10913     const BuiltinType *BT = cast<BuiltinType>(T);
10914     assert(BT->isInteger());
10915 
10916     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10917   }
10918 
10919   /// Returns the supremum of two ranges: i.e. their conservative merge.
10920   static IntRange join(IntRange L, IntRange R) {
10921     bool Unsigned = L.NonNegative && R.NonNegative;
10922     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10923                     L.NonNegative && R.NonNegative);
10924   }
10925 
10926   /// Return the range of a bitwise-AND of the two ranges.
10927   static IntRange bit_and(IntRange L, IntRange R) {
10928     unsigned Bits = std::max(L.Width, R.Width);
10929     bool NonNegative = false;
10930     if (L.NonNegative) {
10931       Bits = std::min(Bits, L.Width);
10932       NonNegative = true;
10933     }
10934     if (R.NonNegative) {
10935       Bits = std::min(Bits, R.Width);
10936       NonNegative = true;
10937     }
10938     return IntRange(Bits, NonNegative);
10939   }
10940 
10941   /// Return the range of a sum of the two ranges.
10942   static IntRange sum(IntRange L, IntRange R) {
10943     bool Unsigned = L.NonNegative && R.NonNegative;
10944     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10945                     Unsigned);
10946   }
10947 
10948   /// Return the range of a difference of the two ranges.
10949   static IntRange difference(IntRange L, IntRange R) {
10950     // We need a 1-bit-wider range if:
10951     //   1) LHS can be negative: least value can be reduced.
10952     //   2) RHS can be negative: greatest value can be increased.
10953     bool CanWiden = !L.NonNegative || !R.NonNegative;
10954     bool Unsigned = L.NonNegative && R.Width == 0;
10955     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10956                         !Unsigned,
10957                     Unsigned);
10958   }
10959 
10960   /// Return the range of a product of the two ranges.
10961   static IntRange product(IntRange L, IntRange R) {
10962     // If both LHS and RHS can be negative, we can form
10963     //   -2^L * -2^R = 2^(L + R)
10964     // which requires L + R + 1 value bits to represent.
10965     bool CanWiden = !L.NonNegative && !R.NonNegative;
10966     bool Unsigned = L.NonNegative && R.NonNegative;
10967     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10968                     Unsigned);
10969   }
10970 
10971   /// Return the range of a remainder operation between the two ranges.
10972   static IntRange rem(IntRange L, IntRange R) {
10973     // The result of a remainder can't be larger than the result of
10974     // either side. The sign of the result is the sign of the LHS.
10975     bool Unsigned = L.NonNegative;
10976     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10977                     Unsigned);
10978   }
10979 };
10980 
10981 } // namespace
10982 
10983 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10984                               unsigned MaxWidth) {
10985   if (value.isSigned() && value.isNegative())
10986     return IntRange(value.getMinSignedBits(), false);
10987 
10988   if (value.getBitWidth() > MaxWidth)
10989     value = value.trunc(MaxWidth);
10990 
10991   // isNonNegative() just checks the sign bit without considering
10992   // signedness.
10993   return IntRange(value.getActiveBits(), true);
10994 }
10995 
10996 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10997                               unsigned MaxWidth) {
10998   if (result.isInt())
10999     return GetValueRange(C, result.getInt(), MaxWidth);
11000 
11001   if (result.isVector()) {
11002     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11003     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11004       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11005       R = IntRange::join(R, El);
11006     }
11007     return R;
11008   }
11009 
11010   if (result.isComplexInt()) {
11011     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11012     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11013     return IntRange::join(R, I);
11014   }
11015 
11016   // This can happen with lossless casts to intptr_t of "based" lvalues.
11017   // Assume it might use arbitrary bits.
11018   // FIXME: The only reason we need to pass the type in here is to get
11019   // the sign right on this one case.  It would be nice if APValue
11020   // preserved this.
11021   assert(result.isLValue() || result.isAddrLabelDiff());
11022   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11023 }
11024 
11025 static QualType GetExprType(const Expr *E) {
11026   QualType Ty = E->getType();
11027   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11028     Ty = AtomicRHS->getValueType();
11029   return Ty;
11030 }
11031 
11032 /// Pseudo-evaluate the given integer expression, estimating the
11033 /// range of values it might take.
11034 ///
11035 /// \param MaxWidth The width to which the value will be truncated.
11036 /// \param Approximate If \c true, return a likely range for the result: in
11037 ///        particular, assume that aritmetic on narrower types doesn't leave
11038 ///        those types. If \c false, return a range including all possible
11039 ///        result values.
11040 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11041                              bool InConstantContext, bool Approximate) {
11042   E = E->IgnoreParens();
11043 
11044   // Try a full evaluation first.
11045   Expr::EvalResult result;
11046   if (E->EvaluateAsRValue(result, C, InConstantContext))
11047     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11048 
11049   // I think we only want to look through implicit casts here; if the
11050   // user has an explicit widening cast, we should treat the value as
11051   // being of the new, wider type.
11052   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11053     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11054       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11055                           Approximate);
11056 
11057     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11058 
11059     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11060                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11061 
11062     // Assume that non-integer casts can span the full range of the type.
11063     if (!isIntegerCast)
11064       return OutputTypeRange;
11065 
11066     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11067                                      std::min(MaxWidth, OutputTypeRange.Width),
11068                                      InConstantContext, Approximate);
11069 
11070     // Bail out if the subexpr's range is as wide as the cast type.
11071     if (SubRange.Width >= OutputTypeRange.Width)
11072       return OutputTypeRange;
11073 
11074     // Otherwise, we take the smaller width, and we're non-negative if
11075     // either the output type or the subexpr is.
11076     return IntRange(SubRange.Width,
11077                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11078   }
11079 
11080   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11081     // If we can fold the condition, just take that operand.
11082     bool CondResult;
11083     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11084       return GetExprRange(C,
11085                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11086                           MaxWidth, InConstantContext, Approximate);
11087 
11088     // Otherwise, conservatively merge.
11089     // GetExprRange requires an integer expression, but a throw expression
11090     // results in a void type.
11091     Expr *E = CO->getTrueExpr();
11092     IntRange L = E->getType()->isVoidType()
11093                      ? IntRange{0, true}
11094                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11095     E = CO->getFalseExpr();
11096     IntRange R = E->getType()->isVoidType()
11097                      ? IntRange{0, true}
11098                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11099     return IntRange::join(L, R);
11100   }
11101 
11102   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11103     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11104 
11105     switch (BO->getOpcode()) {
11106     case BO_Cmp:
11107       llvm_unreachable("builtin <=> should have class type");
11108 
11109     // Boolean-valued operations are single-bit and positive.
11110     case BO_LAnd:
11111     case BO_LOr:
11112     case BO_LT:
11113     case BO_GT:
11114     case BO_LE:
11115     case BO_GE:
11116     case BO_EQ:
11117     case BO_NE:
11118       return IntRange::forBoolType();
11119 
11120     // The type of the assignments is the type of the LHS, so the RHS
11121     // is not necessarily the same type.
11122     case BO_MulAssign:
11123     case BO_DivAssign:
11124     case BO_RemAssign:
11125     case BO_AddAssign:
11126     case BO_SubAssign:
11127     case BO_XorAssign:
11128     case BO_OrAssign:
11129       // TODO: bitfields?
11130       return IntRange::forValueOfType(C, GetExprType(E));
11131 
11132     // Simple assignments just pass through the RHS, which will have
11133     // been coerced to the LHS type.
11134     case BO_Assign:
11135       // TODO: bitfields?
11136       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11137                           Approximate);
11138 
11139     // Operations with opaque sources are black-listed.
11140     case BO_PtrMemD:
11141     case BO_PtrMemI:
11142       return IntRange::forValueOfType(C, GetExprType(E));
11143 
11144     // Bitwise-and uses the *infinum* of the two source ranges.
11145     case BO_And:
11146     case BO_AndAssign:
11147       Combine = IntRange::bit_and;
11148       break;
11149 
11150     // Left shift gets black-listed based on a judgement call.
11151     case BO_Shl:
11152       // ...except that we want to treat '1 << (blah)' as logically
11153       // positive.  It's an important idiom.
11154       if (IntegerLiteral *I
11155             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11156         if (I->getValue() == 1) {
11157           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11158           return IntRange(R.Width, /*NonNegative*/ true);
11159         }
11160       }
11161       LLVM_FALLTHROUGH;
11162 
11163     case BO_ShlAssign:
11164       return IntRange::forValueOfType(C, GetExprType(E));
11165 
11166     // Right shift by a constant can narrow its left argument.
11167     case BO_Shr:
11168     case BO_ShrAssign: {
11169       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11170                                 Approximate);
11171 
11172       // If the shift amount is a positive constant, drop the width by
11173       // that much.
11174       if (Optional<llvm::APSInt> shift =
11175               BO->getRHS()->getIntegerConstantExpr(C)) {
11176         if (shift->isNonNegative()) {
11177           unsigned zext = shift->getZExtValue();
11178           if (zext >= L.Width)
11179             L.Width = (L.NonNegative ? 0 : 1);
11180           else
11181             L.Width -= zext;
11182         }
11183       }
11184 
11185       return L;
11186     }
11187 
11188     // Comma acts as its right operand.
11189     case BO_Comma:
11190       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11191                           Approximate);
11192 
11193     case BO_Add:
11194       if (!Approximate)
11195         Combine = IntRange::sum;
11196       break;
11197 
11198     case BO_Sub:
11199       if (BO->getLHS()->getType()->isPointerType())
11200         return IntRange::forValueOfType(C, GetExprType(E));
11201       if (!Approximate)
11202         Combine = IntRange::difference;
11203       break;
11204 
11205     case BO_Mul:
11206       if (!Approximate)
11207         Combine = IntRange::product;
11208       break;
11209 
11210     // The width of a division result is mostly determined by the size
11211     // of the LHS.
11212     case BO_Div: {
11213       // Don't 'pre-truncate' the operands.
11214       unsigned opWidth = C.getIntWidth(GetExprType(E));
11215       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11216                                 Approximate);
11217 
11218       // If the divisor is constant, use that.
11219       if (Optional<llvm::APSInt> divisor =
11220               BO->getRHS()->getIntegerConstantExpr(C)) {
11221         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11222         if (log2 >= L.Width)
11223           L.Width = (L.NonNegative ? 0 : 1);
11224         else
11225           L.Width = std::min(L.Width - log2, MaxWidth);
11226         return L;
11227       }
11228 
11229       // Otherwise, just use the LHS's width.
11230       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11231       // could be -1.
11232       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11233                                 Approximate);
11234       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11235     }
11236 
11237     case BO_Rem:
11238       Combine = IntRange::rem;
11239       break;
11240 
11241     // The default behavior is okay for these.
11242     case BO_Xor:
11243     case BO_Or:
11244       break;
11245     }
11246 
11247     // Combine the two ranges, but limit the result to the type in which we
11248     // performed the computation.
11249     QualType T = GetExprType(E);
11250     unsigned opWidth = C.getIntWidth(T);
11251     IntRange L =
11252         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11253     IntRange R =
11254         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11255     IntRange C = Combine(L, R);
11256     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11257     C.Width = std::min(C.Width, MaxWidth);
11258     return C;
11259   }
11260 
11261   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11262     switch (UO->getOpcode()) {
11263     // Boolean-valued operations are white-listed.
11264     case UO_LNot:
11265       return IntRange::forBoolType();
11266 
11267     // Operations with opaque sources are black-listed.
11268     case UO_Deref:
11269     case UO_AddrOf: // should be impossible
11270       return IntRange::forValueOfType(C, GetExprType(E));
11271 
11272     default:
11273       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11274                           Approximate);
11275     }
11276   }
11277 
11278   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11279     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11280                         Approximate);
11281 
11282   if (const auto *BitField = E->getSourceBitField())
11283     return IntRange(BitField->getBitWidthValue(C),
11284                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11285 
11286   return IntRange::forValueOfType(C, GetExprType(E));
11287 }
11288 
11289 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11290                              bool InConstantContext, bool Approximate) {
11291   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11292                       Approximate);
11293 }
11294 
11295 /// Checks whether the given value, which currently has the given
11296 /// source semantics, has the same value when coerced through the
11297 /// target semantics.
11298 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11299                                  const llvm::fltSemantics &Src,
11300                                  const llvm::fltSemantics &Tgt) {
11301   llvm::APFloat truncated = value;
11302 
11303   bool ignored;
11304   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11305   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11306 
11307   return truncated.bitwiseIsEqual(value);
11308 }
11309 
11310 /// Checks whether the given value, which currently has the given
11311 /// source semantics, has the same value when coerced through the
11312 /// target semantics.
11313 ///
11314 /// The value might be a vector of floats (or a complex number).
11315 static bool IsSameFloatAfterCast(const APValue &value,
11316                                  const llvm::fltSemantics &Src,
11317                                  const llvm::fltSemantics &Tgt) {
11318   if (value.isFloat())
11319     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11320 
11321   if (value.isVector()) {
11322     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11323       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11324         return false;
11325     return true;
11326   }
11327 
11328   assert(value.isComplexFloat());
11329   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11330           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11331 }
11332 
11333 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11334                                        bool IsListInit = false);
11335 
11336 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11337   // Suppress cases where we are comparing against an enum constant.
11338   if (const DeclRefExpr *DR =
11339       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11340     if (isa<EnumConstantDecl>(DR->getDecl()))
11341       return true;
11342 
11343   // Suppress cases where the value is expanded from a macro, unless that macro
11344   // is how a language represents a boolean literal. This is the case in both C
11345   // and Objective-C.
11346   SourceLocation BeginLoc = E->getBeginLoc();
11347   if (BeginLoc.isMacroID()) {
11348     StringRef MacroName = Lexer::getImmediateMacroName(
11349         BeginLoc, S.getSourceManager(), S.getLangOpts());
11350     return MacroName != "YES" && MacroName != "NO" &&
11351            MacroName != "true" && MacroName != "false";
11352   }
11353 
11354   return false;
11355 }
11356 
11357 static bool isKnownToHaveUnsignedValue(Expr *E) {
11358   return E->getType()->isIntegerType() &&
11359          (!E->getType()->isSignedIntegerType() ||
11360           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11361 }
11362 
11363 namespace {
11364 /// The promoted range of values of a type. In general this has the
11365 /// following structure:
11366 ///
11367 ///     |-----------| . . . |-----------|
11368 ///     ^           ^       ^           ^
11369 ///    Min       HoleMin  HoleMax      Max
11370 ///
11371 /// ... where there is only a hole if a signed type is promoted to unsigned
11372 /// (in which case Min and Max are the smallest and largest representable
11373 /// values).
11374 struct PromotedRange {
11375   // Min, or HoleMax if there is a hole.
11376   llvm::APSInt PromotedMin;
11377   // Max, or HoleMin if there is a hole.
11378   llvm::APSInt PromotedMax;
11379 
11380   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11381     if (R.Width == 0)
11382       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11383     else if (R.Width >= BitWidth && !Unsigned) {
11384       // Promotion made the type *narrower*. This happens when promoting
11385       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11386       // Treat all values of 'signed int' as being in range for now.
11387       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11388       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11389     } else {
11390       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11391                         .extOrTrunc(BitWidth);
11392       PromotedMin.setIsUnsigned(Unsigned);
11393 
11394       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11395                         .extOrTrunc(BitWidth);
11396       PromotedMax.setIsUnsigned(Unsigned);
11397     }
11398   }
11399 
11400   // Determine whether this range is contiguous (has no hole).
11401   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11402 
11403   // Where a constant value is within the range.
11404   enum ComparisonResult {
11405     LT = 0x1,
11406     LE = 0x2,
11407     GT = 0x4,
11408     GE = 0x8,
11409     EQ = 0x10,
11410     NE = 0x20,
11411     InRangeFlag = 0x40,
11412 
11413     Less = LE | LT | NE,
11414     Min = LE | InRangeFlag,
11415     InRange = InRangeFlag,
11416     Max = GE | InRangeFlag,
11417     Greater = GE | GT | NE,
11418 
11419     OnlyValue = LE | GE | EQ | InRangeFlag,
11420     InHole = NE
11421   };
11422 
11423   ComparisonResult compare(const llvm::APSInt &Value) const {
11424     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11425            Value.isUnsigned() == PromotedMin.isUnsigned());
11426     if (!isContiguous()) {
11427       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11428       if (Value.isMinValue()) return Min;
11429       if (Value.isMaxValue()) return Max;
11430       if (Value >= PromotedMin) return InRange;
11431       if (Value <= PromotedMax) return InRange;
11432       return InHole;
11433     }
11434 
11435     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11436     case -1: return Less;
11437     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11438     case 1:
11439       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11440       case -1: return InRange;
11441       case 0: return Max;
11442       case 1: return Greater;
11443       }
11444     }
11445 
11446     llvm_unreachable("impossible compare result");
11447   }
11448 
11449   static llvm::Optional<StringRef>
11450   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11451     if (Op == BO_Cmp) {
11452       ComparisonResult LTFlag = LT, GTFlag = GT;
11453       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11454 
11455       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11456       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11457       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11458       return llvm::None;
11459     }
11460 
11461     ComparisonResult TrueFlag, FalseFlag;
11462     if (Op == BO_EQ) {
11463       TrueFlag = EQ;
11464       FalseFlag = NE;
11465     } else if (Op == BO_NE) {
11466       TrueFlag = NE;
11467       FalseFlag = EQ;
11468     } else {
11469       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11470         TrueFlag = LT;
11471         FalseFlag = GE;
11472       } else {
11473         TrueFlag = GT;
11474         FalseFlag = LE;
11475       }
11476       if (Op == BO_GE || Op == BO_LE)
11477         std::swap(TrueFlag, FalseFlag);
11478     }
11479     if (R & TrueFlag)
11480       return StringRef("true");
11481     if (R & FalseFlag)
11482       return StringRef("false");
11483     return llvm::None;
11484   }
11485 };
11486 }
11487 
11488 static bool HasEnumType(Expr *E) {
11489   // Strip off implicit integral promotions.
11490   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11491     if (ICE->getCastKind() != CK_IntegralCast &&
11492         ICE->getCastKind() != CK_NoOp)
11493       break;
11494     E = ICE->getSubExpr();
11495   }
11496 
11497   return E->getType()->isEnumeralType();
11498 }
11499 
11500 static int classifyConstantValue(Expr *Constant) {
11501   // The values of this enumeration are used in the diagnostics
11502   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11503   enum ConstantValueKind {
11504     Miscellaneous = 0,
11505     LiteralTrue,
11506     LiteralFalse
11507   };
11508   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11509     return BL->getValue() ? ConstantValueKind::LiteralTrue
11510                           : ConstantValueKind::LiteralFalse;
11511   return ConstantValueKind::Miscellaneous;
11512 }
11513 
11514 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11515                                         Expr *Constant, Expr *Other,
11516                                         const llvm::APSInt &Value,
11517                                         bool RhsConstant) {
11518   if (S.inTemplateInstantiation())
11519     return false;
11520 
11521   Expr *OriginalOther = Other;
11522 
11523   Constant = Constant->IgnoreParenImpCasts();
11524   Other = Other->IgnoreParenImpCasts();
11525 
11526   // Suppress warnings on tautological comparisons between values of the same
11527   // enumeration type. There are only two ways we could warn on this:
11528   //  - If the constant is outside the range of representable values of
11529   //    the enumeration. In such a case, we should warn about the cast
11530   //    to enumeration type, not about the comparison.
11531   //  - If the constant is the maximum / minimum in-range value. For an
11532   //    enumeratin type, such comparisons can be meaningful and useful.
11533   if (Constant->getType()->isEnumeralType() &&
11534       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11535     return false;
11536 
11537   IntRange OtherValueRange = GetExprRange(
11538       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11539 
11540   QualType OtherT = Other->getType();
11541   if (const auto *AT = OtherT->getAs<AtomicType>())
11542     OtherT = AT->getValueType();
11543   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11544 
11545   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11546   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11547   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11548                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11549                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11550 
11551   // Whether we're treating Other as being a bool because of the form of
11552   // expression despite it having another type (typically 'int' in C).
11553   bool OtherIsBooleanDespiteType =
11554       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11555   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11556     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11557 
11558   // Check if all values in the range of possible values of this expression
11559   // lead to the same comparison outcome.
11560   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11561                                         Value.isUnsigned());
11562   auto Cmp = OtherPromotedValueRange.compare(Value);
11563   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11564   if (!Result)
11565     return false;
11566 
11567   // Also consider the range determined by the type alone. This allows us to
11568   // classify the warning under the proper diagnostic group.
11569   bool TautologicalTypeCompare = false;
11570   {
11571     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11572                                          Value.isUnsigned());
11573     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11574     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11575                                                        RhsConstant)) {
11576       TautologicalTypeCompare = true;
11577       Cmp = TypeCmp;
11578       Result = TypeResult;
11579     }
11580   }
11581 
11582   // Don't warn if the non-constant operand actually always evaluates to the
11583   // same value.
11584   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11585     return false;
11586 
11587   // Suppress the diagnostic for an in-range comparison if the constant comes
11588   // from a macro or enumerator. We don't want to diagnose
11589   //
11590   //   some_long_value <= INT_MAX
11591   //
11592   // when sizeof(int) == sizeof(long).
11593   bool InRange = Cmp & PromotedRange::InRangeFlag;
11594   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11595     return false;
11596 
11597   // A comparison of an unsigned bit-field against 0 is really a type problem,
11598   // even though at the type level the bit-field might promote to 'signed int'.
11599   if (Other->refersToBitField() && InRange && Value == 0 &&
11600       Other->getType()->isUnsignedIntegerOrEnumerationType())
11601     TautologicalTypeCompare = true;
11602 
11603   // If this is a comparison to an enum constant, include that
11604   // constant in the diagnostic.
11605   const EnumConstantDecl *ED = nullptr;
11606   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11607     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11608 
11609   // Should be enough for uint128 (39 decimal digits)
11610   SmallString<64> PrettySourceValue;
11611   llvm::raw_svector_ostream OS(PrettySourceValue);
11612   if (ED) {
11613     OS << '\'' << *ED << "' (" << Value << ")";
11614   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11615                Constant->IgnoreParenImpCasts())) {
11616     OS << (BL->getValue() ? "YES" : "NO");
11617   } else {
11618     OS << Value;
11619   }
11620 
11621   if (!TautologicalTypeCompare) {
11622     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11623         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11624         << E->getOpcodeStr() << OS.str() << *Result
11625         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11626     return true;
11627   }
11628 
11629   if (IsObjCSignedCharBool) {
11630     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11631                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11632                               << OS.str() << *Result);
11633     return true;
11634   }
11635 
11636   // FIXME: We use a somewhat different formatting for the in-range cases and
11637   // cases involving boolean values for historical reasons. We should pick a
11638   // consistent way of presenting these diagnostics.
11639   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11640 
11641     S.DiagRuntimeBehavior(
11642         E->getOperatorLoc(), E,
11643         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11644                          : diag::warn_tautological_bool_compare)
11645             << OS.str() << classifyConstantValue(Constant) << OtherT
11646             << OtherIsBooleanDespiteType << *Result
11647             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11648   } else {
11649     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11650     unsigned Diag =
11651         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11652             ? (HasEnumType(OriginalOther)
11653                    ? diag::warn_unsigned_enum_always_true_comparison
11654                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11655                               : diag::warn_unsigned_always_true_comparison)
11656             : diag::warn_tautological_constant_compare;
11657 
11658     S.Diag(E->getOperatorLoc(), Diag)
11659         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11660         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11661   }
11662 
11663   return true;
11664 }
11665 
11666 /// Analyze the operands of the given comparison.  Implements the
11667 /// fallback case from AnalyzeComparison.
11668 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11669   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11670   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11671 }
11672 
11673 /// Implements -Wsign-compare.
11674 ///
11675 /// \param E the binary operator to check for warnings
11676 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11677   // The type the comparison is being performed in.
11678   QualType T = E->getLHS()->getType();
11679 
11680   // Only analyze comparison operators where both sides have been converted to
11681   // the same type.
11682   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11683     return AnalyzeImpConvsInComparison(S, E);
11684 
11685   // Don't analyze value-dependent comparisons directly.
11686   if (E->isValueDependent())
11687     return AnalyzeImpConvsInComparison(S, E);
11688 
11689   Expr *LHS = E->getLHS();
11690   Expr *RHS = E->getRHS();
11691 
11692   if (T->isIntegralType(S.Context)) {
11693     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11694     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11695 
11696     // We don't care about expressions whose result is a constant.
11697     if (RHSValue && LHSValue)
11698       return AnalyzeImpConvsInComparison(S, E);
11699 
11700     // We only care about expressions where just one side is literal
11701     if ((bool)RHSValue ^ (bool)LHSValue) {
11702       // Is the constant on the RHS or LHS?
11703       const bool RhsConstant = (bool)RHSValue;
11704       Expr *Const = RhsConstant ? RHS : LHS;
11705       Expr *Other = RhsConstant ? LHS : RHS;
11706       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11707 
11708       // Check whether an integer constant comparison results in a value
11709       // of 'true' or 'false'.
11710       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11711         return AnalyzeImpConvsInComparison(S, E);
11712     }
11713   }
11714 
11715   if (!T->hasUnsignedIntegerRepresentation()) {
11716     // We don't do anything special if this isn't an unsigned integral
11717     // comparison:  we're only interested in integral comparisons, and
11718     // signed comparisons only happen in cases we don't care to warn about.
11719     return AnalyzeImpConvsInComparison(S, E);
11720   }
11721 
11722   LHS = LHS->IgnoreParenImpCasts();
11723   RHS = RHS->IgnoreParenImpCasts();
11724 
11725   if (!S.getLangOpts().CPlusPlus) {
11726     // Avoid warning about comparison of integers with different signs when
11727     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11728     // the type of `E`.
11729     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11730       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11731     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11732       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11733   }
11734 
11735   // Check to see if one of the (unmodified) operands is of different
11736   // signedness.
11737   Expr *signedOperand, *unsignedOperand;
11738   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11739     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11740            "unsigned comparison between two signed integer expressions?");
11741     signedOperand = LHS;
11742     unsignedOperand = RHS;
11743   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11744     signedOperand = RHS;
11745     unsignedOperand = LHS;
11746   } else {
11747     return AnalyzeImpConvsInComparison(S, E);
11748   }
11749 
11750   // Otherwise, calculate the effective range of the signed operand.
11751   IntRange signedRange = GetExprRange(
11752       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11753 
11754   // Go ahead and analyze implicit conversions in the operands.  Note
11755   // that we skip the implicit conversions on both sides.
11756   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11757   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11758 
11759   // If the signed range is non-negative, -Wsign-compare won't fire.
11760   if (signedRange.NonNegative)
11761     return;
11762 
11763   // For (in)equality comparisons, if the unsigned operand is a
11764   // constant which cannot collide with a overflowed signed operand,
11765   // then reinterpreting the signed operand as unsigned will not
11766   // change the result of the comparison.
11767   if (E->isEqualityOp()) {
11768     unsigned comparisonWidth = S.Context.getIntWidth(T);
11769     IntRange unsignedRange =
11770         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11771                      /*Approximate*/ true);
11772 
11773     // We should never be unable to prove that the unsigned operand is
11774     // non-negative.
11775     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11776 
11777     if (unsignedRange.Width < comparisonWidth)
11778       return;
11779   }
11780 
11781   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11782                         S.PDiag(diag::warn_mixed_sign_comparison)
11783                             << LHS->getType() << RHS->getType()
11784                             << LHS->getSourceRange() << RHS->getSourceRange());
11785 }
11786 
11787 /// Analyzes an attempt to assign the given value to a bitfield.
11788 ///
11789 /// Returns true if there was something fishy about the attempt.
11790 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11791                                       SourceLocation InitLoc) {
11792   assert(Bitfield->isBitField());
11793   if (Bitfield->isInvalidDecl())
11794     return false;
11795 
11796   // White-list bool bitfields.
11797   QualType BitfieldType = Bitfield->getType();
11798   if (BitfieldType->isBooleanType())
11799      return false;
11800 
11801   if (BitfieldType->isEnumeralType()) {
11802     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
11803     // If the underlying enum type was not explicitly specified as an unsigned
11804     // type and the enum contain only positive values, MSVC++ will cause an
11805     // inconsistency by storing this as a signed type.
11806     if (S.getLangOpts().CPlusPlus11 &&
11807         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11808         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11809         BitfieldEnumDecl->getNumNegativeBits() == 0) {
11810       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11811           << BitfieldEnumDecl;
11812     }
11813   }
11814 
11815   if (Bitfield->getType()->isBooleanType())
11816     return false;
11817 
11818   // Ignore value- or type-dependent expressions.
11819   if (Bitfield->getBitWidth()->isValueDependent() ||
11820       Bitfield->getBitWidth()->isTypeDependent() ||
11821       Init->isValueDependent() ||
11822       Init->isTypeDependent())
11823     return false;
11824 
11825   Expr *OriginalInit = Init->IgnoreParenImpCasts();
11826   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
11827 
11828   Expr::EvalResult Result;
11829   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11830                                    Expr::SE_AllowSideEffects)) {
11831     // The RHS is not constant.  If the RHS has an enum type, make sure the
11832     // bitfield is wide enough to hold all the values of the enum without
11833     // truncation.
11834     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
11835       EnumDecl *ED = EnumTy->getDecl();
11836       bool SignedBitfield = BitfieldType->isSignedIntegerType();
11837 
11838       // Enum types are implicitly signed on Windows, so check if there are any
11839       // negative enumerators to see if the enum was intended to be signed or
11840       // not.
11841       bool SignedEnum = ED->getNumNegativeBits() > 0;
11842 
11843       // Check for surprising sign changes when assigning enum values to a
11844       // bitfield of different signedness.  If the bitfield is signed and we
11845       // have exactly the right number of bits to store this unsigned enum,
11846       // suggest changing the enum to an unsigned type. This typically happens
11847       // on Windows where unfixed enums always use an underlying type of 'int'.
11848       unsigned DiagID = 0;
11849       if (SignedEnum && !SignedBitfield) {
11850         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
11851       } else if (SignedBitfield && !SignedEnum &&
11852                  ED->getNumPositiveBits() == FieldWidth) {
11853         DiagID = diag::warn_signed_bitfield_enum_conversion;
11854       }
11855 
11856       if (DiagID) {
11857         S.Diag(InitLoc, DiagID) << Bitfield << ED;
11858         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11859         SourceRange TypeRange =
11860             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11861         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11862             << SignedEnum << TypeRange;
11863       }
11864 
11865       // Compute the required bitwidth. If the enum has negative values, we need
11866       // one more bit than the normal number of positive bits to represent the
11867       // sign bit.
11868       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11869                                                   ED->getNumNegativeBits())
11870                                        : ED->getNumPositiveBits();
11871 
11872       // Check the bitwidth.
11873       if (BitsNeeded > FieldWidth) {
11874         Expr *WidthExpr = Bitfield->getBitWidth();
11875         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11876             << Bitfield << ED;
11877         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11878             << BitsNeeded << ED << WidthExpr->getSourceRange();
11879       }
11880     }
11881 
11882     return false;
11883   }
11884 
11885   llvm::APSInt Value = Result.Val.getInt();
11886 
11887   unsigned OriginalWidth = Value.getBitWidth();
11888 
11889   if (!Value.isSigned() || Value.isNegative())
11890     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11891       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11892         OriginalWidth = Value.getMinSignedBits();
11893 
11894   if (OriginalWidth <= FieldWidth)
11895     return false;
11896 
11897   // Compute the value which the bitfield will contain.
11898   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11899   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11900 
11901   // Check whether the stored value is equal to the original value.
11902   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11903   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11904     return false;
11905 
11906   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11907   // therefore don't strictly fit into a signed bitfield of width 1.
11908   if (FieldWidth == 1 && Value == 1)
11909     return false;
11910 
11911   std::string PrettyValue = toString(Value, 10);
11912   std::string PrettyTrunc = toString(TruncatedValue, 10);
11913 
11914   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11915     << PrettyValue << PrettyTrunc << OriginalInit->getType()
11916     << Init->getSourceRange();
11917 
11918   return true;
11919 }
11920 
11921 /// Analyze the given simple or compound assignment for warning-worthy
11922 /// operations.
11923 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11924   // Just recurse on the LHS.
11925   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11926 
11927   // We want to recurse on the RHS as normal unless we're assigning to
11928   // a bitfield.
11929   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11930     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11931                                   E->getOperatorLoc())) {
11932       // Recurse, ignoring any implicit conversions on the RHS.
11933       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11934                                         E->getOperatorLoc());
11935     }
11936   }
11937 
11938   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11939 
11940   // Diagnose implicitly sequentially-consistent atomic assignment.
11941   if (E->getLHS()->getType()->isAtomicType())
11942     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11943 }
11944 
11945 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11946 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11947                             SourceLocation CContext, unsigned diag,
11948                             bool pruneControlFlow = false) {
11949   if (pruneControlFlow) {
11950     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11951                           S.PDiag(diag)
11952                               << SourceType << T << E->getSourceRange()
11953                               << SourceRange(CContext));
11954     return;
11955   }
11956   S.Diag(E->getExprLoc(), diag)
11957     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11958 }
11959 
11960 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11961 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11962                             SourceLocation CContext,
11963                             unsigned diag, bool pruneControlFlow = false) {
11964   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11965 }
11966 
11967 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11968   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11969       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11970 }
11971 
11972 static void adornObjCBoolConversionDiagWithTernaryFixit(
11973     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11974   Expr *Ignored = SourceExpr->IgnoreImplicit();
11975   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11976     Ignored = OVE->getSourceExpr();
11977   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11978                      isa<BinaryOperator>(Ignored) ||
11979                      isa<CXXOperatorCallExpr>(Ignored);
11980   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11981   if (NeedsParens)
11982     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11983             << FixItHint::CreateInsertion(EndLoc, ")");
11984   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11985 }
11986 
11987 /// Diagnose an implicit cast from a floating point value to an integer value.
11988 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11989                                     SourceLocation CContext) {
11990   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11991   const bool PruneWarnings = S.inTemplateInstantiation();
11992 
11993   Expr *InnerE = E->IgnoreParenImpCasts();
11994   // We also want to warn on, e.g., "int i = -1.234"
11995   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11996     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11997       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11998 
11999   const bool IsLiteral =
12000       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12001 
12002   llvm::APFloat Value(0.0);
12003   bool IsConstant =
12004     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12005   if (!IsConstant) {
12006     if (isObjCSignedCharBool(S, T)) {
12007       return adornObjCBoolConversionDiagWithTernaryFixit(
12008           S, E,
12009           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12010               << E->getType());
12011     }
12012 
12013     return DiagnoseImpCast(S, E, T, CContext,
12014                            diag::warn_impcast_float_integer, PruneWarnings);
12015   }
12016 
12017   bool isExact = false;
12018 
12019   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12020                             T->hasUnsignedIntegerRepresentation());
12021   llvm::APFloat::opStatus Result = Value.convertToInteger(
12022       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12023 
12024   // FIXME: Force the precision of the source value down so we don't print
12025   // digits which are usually useless (we don't really care here if we
12026   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12027   // would automatically print the shortest representation, but it's a bit
12028   // tricky to implement.
12029   SmallString<16> PrettySourceValue;
12030   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12031   precision = (precision * 59 + 195) / 196;
12032   Value.toString(PrettySourceValue, precision);
12033 
12034   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12035     return adornObjCBoolConversionDiagWithTernaryFixit(
12036         S, E,
12037         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12038             << PrettySourceValue);
12039   }
12040 
12041   if (Result == llvm::APFloat::opOK && isExact) {
12042     if (IsLiteral) return;
12043     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12044                            PruneWarnings);
12045   }
12046 
12047   // Conversion of a floating-point value to a non-bool integer where the
12048   // integral part cannot be represented by the integer type is undefined.
12049   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12050     return DiagnoseImpCast(
12051         S, E, T, CContext,
12052         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12053                   : diag::warn_impcast_float_to_integer_out_of_range,
12054         PruneWarnings);
12055 
12056   unsigned DiagID = 0;
12057   if (IsLiteral) {
12058     // Warn on floating point literal to integer.
12059     DiagID = diag::warn_impcast_literal_float_to_integer;
12060   } else if (IntegerValue == 0) {
12061     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12062       return DiagnoseImpCast(S, E, T, CContext,
12063                              diag::warn_impcast_float_integer, PruneWarnings);
12064     }
12065     // Warn on non-zero to zero conversion.
12066     DiagID = diag::warn_impcast_float_to_integer_zero;
12067   } else {
12068     if (IntegerValue.isUnsigned()) {
12069       if (!IntegerValue.isMaxValue()) {
12070         return DiagnoseImpCast(S, E, T, CContext,
12071                                diag::warn_impcast_float_integer, PruneWarnings);
12072       }
12073     } else {  // IntegerValue.isSigned()
12074       if (!IntegerValue.isMaxSignedValue() &&
12075           !IntegerValue.isMinSignedValue()) {
12076         return DiagnoseImpCast(S, E, T, CContext,
12077                                diag::warn_impcast_float_integer, PruneWarnings);
12078       }
12079     }
12080     // Warn on evaluatable floating point expression to integer conversion.
12081     DiagID = diag::warn_impcast_float_to_integer;
12082   }
12083 
12084   SmallString<16> PrettyTargetValue;
12085   if (IsBool)
12086     PrettyTargetValue = Value.isZero() ? "false" : "true";
12087   else
12088     IntegerValue.toString(PrettyTargetValue);
12089 
12090   if (PruneWarnings) {
12091     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12092                           S.PDiag(DiagID)
12093                               << E->getType() << T.getUnqualifiedType()
12094                               << PrettySourceValue << PrettyTargetValue
12095                               << E->getSourceRange() << SourceRange(CContext));
12096   } else {
12097     S.Diag(E->getExprLoc(), DiagID)
12098         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12099         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12100   }
12101 }
12102 
12103 /// Analyze the given compound assignment for the possible losing of
12104 /// floating-point precision.
12105 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12106   assert(isa<CompoundAssignOperator>(E) &&
12107          "Must be compound assignment operation");
12108   // Recurse on the LHS and RHS in here
12109   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12110   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12111 
12112   if (E->getLHS()->getType()->isAtomicType())
12113     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12114 
12115   // Now check the outermost expression
12116   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12117   const auto *RBT = cast<CompoundAssignOperator>(E)
12118                         ->getComputationResultType()
12119                         ->getAs<BuiltinType>();
12120 
12121   // The below checks assume source is floating point.
12122   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12123 
12124   // If source is floating point but target is an integer.
12125   if (ResultBT->isInteger())
12126     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12127                            E->getExprLoc(), diag::warn_impcast_float_integer);
12128 
12129   if (!ResultBT->isFloatingPoint())
12130     return;
12131 
12132   // If both source and target are floating points, warn about losing precision.
12133   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12134       QualType(ResultBT, 0), QualType(RBT, 0));
12135   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12136     // warn about dropping FP rank.
12137     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12138                     diag::warn_impcast_float_result_precision);
12139 }
12140 
12141 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12142                                       IntRange Range) {
12143   if (!Range.Width) return "0";
12144 
12145   llvm::APSInt ValueInRange = Value;
12146   ValueInRange.setIsSigned(!Range.NonNegative);
12147   ValueInRange = ValueInRange.trunc(Range.Width);
12148   return toString(ValueInRange, 10);
12149 }
12150 
12151 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12152   if (!isa<ImplicitCastExpr>(Ex))
12153     return false;
12154 
12155   Expr *InnerE = Ex->IgnoreParenImpCasts();
12156   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12157   const Type *Source =
12158     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12159   if (Target->isDependentType())
12160     return false;
12161 
12162   const BuiltinType *FloatCandidateBT =
12163     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12164   const Type *BoolCandidateType = ToBool ? Target : Source;
12165 
12166   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12167           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12168 }
12169 
12170 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12171                                              SourceLocation CC) {
12172   unsigned NumArgs = TheCall->getNumArgs();
12173   for (unsigned i = 0; i < NumArgs; ++i) {
12174     Expr *CurrA = TheCall->getArg(i);
12175     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12176       continue;
12177 
12178     bool IsSwapped = ((i > 0) &&
12179         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12180     IsSwapped |= ((i < (NumArgs - 1)) &&
12181         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12182     if (IsSwapped) {
12183       // Warn on this floating-point to bool conversion.
12184       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12185                       CurrA->getType(), CC,
12186                       diag::warn_impcast_floating_point_to_bool);
12187     }
12188   }
12189 }
12190 
12191 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12192                                    SourceLocation CC) {
12193   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12194                         E->getExprLoc()))
12195     return;
12196 
12197   // Don't warn on functions which have return type nullptr_t.
12198   if (isa<CallExpr>(E))
12199     return;
12200 
12201   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12202   const Expr::NullPointerConstantKind NullKind =
12203       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12204   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12205     return;
12206 
12207   // Return if target type is a safe conversion.
12208   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12209       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12210     return;
12211 
12212   SourceLocation Loc = E->getSourceRange().getBegin();
12213 
12214   // Venture through the macro stacks to get to the source of macro arguments.
12215   // The new location is a better location than the complete location that was
12216   // passed in.
12217   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12218   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12219 
12220   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12221   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12222     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12223         Loc, S.SourceMgr, S.getLangOpts());
12224     if (MacroName == "NULL")
12225       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12226   }
12227 
12228   // Only warn if the null and context location are in the same macro expansion.
12229   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12230     return;
12231 
12232   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12233       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12234       << FixItHint::CreateReplacement(Loc,
12235                                       S.getFixItZeroLiteralForType(T, Loc));
12236 }
12237 
12238 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12239                                   ObjCArrayLiteral *ArrayLiteral);
12240 
12241 static void
12242 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12243                            ObjCDictionaryLiteral *DictionaryLiteral);
12244 
12245 /// Check a single element within a collection literal against the
12246 /// target element type.
12247 static void checkObjCCollectionLiteralElement(Sema &S,
12248                                               QualType TargetElementType,
12249                                               Expr *Element,
12250                                               unsigned ElementKind) {
12251   // Skip a bitcast to 'id' or qualified 'id'.
12252   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12253     if (ICE->getCastKind() == CK_BitCast &&
12254         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12255       Element = ICE->getSubExpr();
12256   }
12257 
12258   QualType ElementType = Element->getType();
12259   ExprResult ElementResult(Element);
12260   if (ElementType->getAs<ObjCObjectPointerType>() &&
12261       S.CheckSingleAssignmentConstraints(TargetElementType,
12262                                          ElementResult,
12263                                          false, false)
12264         != Sema::Compatible) {
12265     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12266         << ElementType << ElementKind << TargetElementType
12267         << Element->getSourceRange();
12268   }
12269 
12270   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12271     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12272   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12273     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12274 }
12275 
12276 /// Check an Objective-C array literal being converted to the given
12277 /// target type.
12278 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12279                                   ObjCArrayLiteral *ArrayLiteral) {
12280   if (!S.NSArrayDecl)
12281     return;
12282 
12283   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12284   if (!TargetObjCPtr)
12285     return;
12286 
12287   if (TargetObjCPtr->isUnspecialized() ||
12288       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12289         != S.NSArrayDecl->getCanonicalDecl())
12290     return;
12291 
12292   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12293   if (TypeArgs.size() != 1)
12294     return;
12295 
12296   QualType TargetElementType = TypeArgs[0];
12297   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12298     checkObjCCollectionLiteralElement(S, TargetElementType,
12299                                       ArrayLiteral->getElement(I),
12300                                       0);
12301   }
12302 }
12303 
12304 /// Check an Objective-C dictionary literal being converted to the given
12305 /// target type.
12306 static void
12307 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12308                            ObjCDictionaryLiteral *DictionaryLiteral) {
12309   if (!S.NSDictionaryDecl)
12310     return;
12311 
12312   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12313   if (!TargetObjCPtr)
12314     return;
12315 
12316   if (TargetObjCPtr->isUnspecialized() ||
12317       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12318         != S.NSDictionaryDecl->getCanonicalDecl())
12319     return;
12320 
12321   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12322   if (TypeArgs.size() != 2)
12323     return;
12324 
12325   QualType TargetKeyType = TypeArgs[0];
12326   QualType TargetObjectType = TypeArgs[1];
12327   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12328     auto Element = DictionaryLiteral->getKeyValueElement(I);
12329     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12330     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12331   }
12332 }
12333 
12334 // Helper function to filter out cases for constant width constant conversion.
12335 // Don't warn on char array initialization or for non-decimal values.
12336 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12337                                           SourceLocation CC) {
12338   // If initializing from a constant, and the constant starts with '0',
12339   // then it is a binary, octal, or hexadecimal.  Allow these constants
12340   // to fill all the bits, even if there is a sign change.
12341   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12342     const char FirstLiteralCharacter =
12343         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12344     if (FirstLiteralCharacter == '0')
12345       return false;
12346   }
12347 
12348   // If the CC location points to a '{', and the type is char, then assume
12349   // assume it is an array initialization.
12350   if (CC.isValid() && T->isCharType()) {
12351     const char FirstContextCharacter =
12352         S.getSourceManager().getCharacterData(CC)[0];
12353     if (FirstContextCharacter == '{')
12354       return false;
12355   }
12356 
12357   return true;
12358 }
12359 
12360 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12361   const auto *IL = dyn_cast<IntegerLiteral>(E);
12362   if (!IL) {
12363     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12364       if (UO->getOpcode() == UO_Minus)
12365         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12366     }
12367   }
12368 
12369   return IL;
12370 }
12371 
12372 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12373   E = E->IgnoreParenImpCasts();
12374   SourceLocation ExprLoc = E->getExprLoc();
12375 
12376   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12377     BinaryOperator::Opcode Opc = BO->getOpcode();
12378     Expr::EvalResult Result;
12379     // Do not diagnose unsigned shifts.
12380     if (Opc == BO_Shl) {
12381       const auto *LHS = getIntegerLiteral(BO->getLHS());
12382       const auto *RHS = getIntegerLiteral(BO->getRHS());
12383       if (LHS && LHS->getValue() == 0)
12384         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12385       else if (!E->isValueDependent() && LHS && RHS &&
12386                RHS->getValue().isNonNegative() &&
12387                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12388         S.Diag(ExprLoc, diag::warn_left_shift_always)
12389             << (Result.Val.getInt() != 0);
12390       else if (E->getType()->isSignedIntegerType())
12391         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12392     }
12393   }
12394 
12395   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12396     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12397     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12398     if (!LHS || !RHS)
12399       return;
12400     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12401         (RHS->getValue() == 0 || RHS->getValue() == 1))
12402       // Do not diagnose common idioms.
12403       return;
12404     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12405       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12406   }
12407 }
12408 
12409 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12410                                     SourceLocation CC,
12411                                     bool *ICContext = nullptr,
12412                                     bool IsListInit = false) {
12413   if (E->isTypeDependent() || E->isValueDependent()) return;
12414 
12415   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12416   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12417   if (Source == Target) return;
12418   if (Target->isDependentType()) return;
12419 
12420   // If the conversion context location is invalid don't complain. We also
12421   // don't want to emit a warning if the issue occurs from the expansion of
12422   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12423   // delay this check as long as possible. Once we detect we are in that
12424   // scenario, we just return.
12425   if (CC.isInvalid())
12426     return;
12427 
12428   if (Source->isAtomicType())
12429     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12430 
12431   // Diagnose implicit casts to bool.
12432   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12433     if (isa<StringLiteral>(E))
12434       // Warn on string literal to bool.  Checks for string literals in logical
12435       // and expressions, for instance, assert(0 && "error here"), are
12436       // prevented by a check in AnalyzeImplicitConversions().
12437       return DiagnoseImpCast(S, E, T, CC,
12438                              diag::warn_impcast_string_literal_to_bool);
12439     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12440         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12441       // This covers the literal expressions that evaluate to Objective-C
12442       // objects.
12443       return DiagnoseImpCast(S, E, T, CC,
12444                              diag::warn_impcast_objective_c_literal_to_bool);
12445     }
12446     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12447       // Warn on pointer to bool conversion that is always true.
12448       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12449                                      SourceRange(CC));
12450     }
12451   }
12452 
12453   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12454   // is a typedef for signed char (macOS), then that constant value has to be 1
12455   // or 0.
12456   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12457     Expr::EvalResult Result;
12458     if (E->EvaluateAsInt(Result, S.getASTContext(),
12459                          Expr::SE_AllowSideEffects)) {
12460       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12461         adornObjCBoolConversionDiagWithTernaryFixit(
12462             S, E,
12463             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12464                 << toString(Result.Val.getInt(), 10));
12465       }
12466       return;
12467     }
12468   }
12469 
12470   // Check implicit casts from Objective-C collection literals to specialized
12471   // collection types, e.g., NSArray<NSString *> *.
12472   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12473     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12474   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12475     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12476 
12477   // Strip vector types.
12478   if (const auto *SourceVT = dyn_cast<VectorType>(Source)) {
12479     if (Target->isVLSTBuiltinType()) {
12480       auto SourceVectorKind = SourceVT->getVectorKind();
12481       if (SourceVectorKind == VectorType::SveFixedLengthDataVector ||
12482           SourceVectorKind == VectorType::SveFixedLengthPredicateVector ||
12483           (SourceVectorKind == VectorType::GenericVector &&
12484            S.Context.getTypeSize(Source) == S.getLangOpts().ArmSveVectorBits))
12485         return;
12486     }
12487 
12488     if (!isa<VectorType>(Target)) {
12489       if (S.SourceMgr.isInSystemMacro(CC))
12490         return;
12491       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12492     }
12493 
12494     // If the vector cast is cast between two vectors of the same size, it is
12495     // a bitcast, not a conversion.
12496     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12497       return;
12498 
12499     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12500     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12501   }
12502   if (auto VecTy = dyn_cast<VectorType>(Target))
12503     Target = VecTy->getElementType().getTypePtr();
12504 
12505   // Strip complex types.
12506   if (isa<ComplexType>(Source)) {
12507     if (!isa<ComplexType>(Target)) {
12508       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12509         return;
12510 
12511       return DiagnoseImpCast(S, E, T, CC,
12512                              S.getLangOpts().CPlusPlus
12513                                  ? diag::err_impcast_complex_scalar
12514                                  : diag::warn_impcast_complex_scalar);
12515     }
12516 
12517     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12518     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12519   }
12520 
12521   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12522   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12523 
12524   // If the source is floating point...
12525   if (SourceBT && SourceBT->isFloatingPoint()) {
12526     // ...and the target is floating point...
12527     if (TargetBT && TargetBT->isFloatingPoint()) {
12528       // ...then warn if we're dropping FP rank.
12529 
12530       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12531           QualType(SourceBT, 0), QualType(TargetBT, 0));
12532       if (Order > 0) {
12533         // Don't warn about float constants that are precisely
12534         // representable in the target type.
12535         Expr::EvalResult result;
12536         if (E->EvaluateAsRValue(result, S.Context)) {
12537           // Value might be a float, a float vector, or a float complex.
12538           if (IsSameFloatAfterCast(result.Val,
12539                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12540                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12541             return;
12542         }
12543 
12544         if (S.SourceMgr.isInSystemMacro(CC))
12545           return;
12546 
12547         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12548       }
12549       // ... or possibly if we're increasing rank, too
12550       else if (Order < 0) {
12551         if (S.SourceMgr.isInSystemMacro(CC))
12552           return;
12553 
12554         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12555       }
12556       return;
12557     }
12558 
12559     // If the target is integral, always warn.
12560     if (TargetBT && TargetBT->isInteger()) {
12561       if (S.SourceMgr.isInSystemMacro(CC))
12562         return;
12563 
12564       DiagnoseFloatingImpCast(S, E, T, CC);
12565     }
12566 
12567     // Detect the case where a call result is converted from floating-point to
12568     // to bool, and the final argument to the call is converted from bool, to
12569     // discover this typo:
12570     //
12571     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12572     //
12573     // FIXME: This is an incredibly special case; is there some more general
12574     // way to detect this class of misplaced-parentheses bug?
12575     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12576       // Check last argument of function call to see if it is an
12577       // implicit cast from a type matching the type the result
12578       // is being cast to.
12579       CallExpr *CEx = cast<CallExpr>(E);
12580       if (unsigned NumArgs = CEx->getNumArgs()) {
12581         Expr *LastA = CEx->getArg(NumArgs - 1);
12582         Expr *InnerE = LastA->IgnoreParenImpCasts();
12583         if (isa<ImplicitCastExpr>(LastA) &&
12584             InnerE->getType()->isBooleanType()) {
12585           // Warn on this floating-point to bool conversion
12586           DiagnoseImpCast(S, E, T, CC,
12587                           diag::warn_impcast_floating_point_to_bool);
12588         }
12589       }
12590     }
12591     return;
12592   }
12593 
12594   // Valid casts involving fixed point types should be accounted for here.
12595   if (Source->isFixedPointType()) {
12596     if (Target->isUnsaturatedFixedPointType()) {
12597       Expr::EvalResult Result;
12598       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12599                                   S.isConstantEvaluated())) {
12600         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12601         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12602         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12603         if (Value > MaxVal || Value < MinVal) {
12604           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12605                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12606                                     << Value.toString() << T
12607                                     << E->getSourceRange()
12608                                     << clang::SourceRange(CC));
12609           return;
12610         }
12611       }
12612     } else if (Target->isIntegerType()) {
12613       Expr::EvalResult Result;
12614       if (!S.isConstantEvaluated() &&
12615           E->EvaluateAsFixedPoint(Result, S.Context,
12616                                   Expr::SE_AllowSideEffects)) {
12617         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12618 
12619         bool Overflowed;
12620         llvm::APSInt IntResult = FXResult.convertToInt(
12621             S.Context.getIntWidth(T),
12622             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12623 
12624         if (Overflowed) {
12625           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12626                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12627                                     << FXResult.toString() << T
12628                                     << E->getSourceRange()
12629                                     << clang::SourceRange(CC));
12630           return;
12631         }
12632       }
12633     }
12634   } else if (Target->isUnsaturatedFixedPointType()) {
12635     if (Source->isIntegerType()) {
12636       Expr::EvalResult Result;
12637       if (!S.isConstantEvaluated() &&
12638           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12639         llvm::APSInt Value = Result.Val.getInt();
12640 
12641         bool Overflowed;
12642         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12643             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12644 
12645         if (Overflowed) {
12646           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12647                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12648                                     << toString(Value, /*Radix=*/10) << T
12649                                     << E->getSourceRange()
12650                                     << clang::SourceRange(CC));
12651           return;
12652         }
12653       }
12654     }
12655   }
12656 
12657   // If we are casting an integer type to a floating point type without
12658   // initialization-list syntax, we might lose accuracy if the floating
12659   // point type has a narrower significand than the integer type.
12660   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12661       TargetBT->isFloatingType() && !IsListInit) {
12662     // Determine the number of precision bits in the source integer type.
12663     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12664                                         /*Approximate*/ true);
12665     unsigned int SourcePrecision = SourceRange.Width;
12666 
12667     // Determine the number of precision bits in the
12668     // target floating point type.
12669     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12670         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12671 
12672     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12673         SourcePrecision > TargetPrecision) {
12674 
12675       if (Optional<llvm::APSInt> SourceInt =
12676               E->getIntegerConstantExpr(S.Context)) {
12677         // If the source integer is a constant, convert it to the target
12678         // floating point type. Issue a warning if the value changes
12679         // during the whole conversion.
12680         llvm::APFloat TargetFloatValue(
12681             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12682         llvm::APFloat::opStatus ConversionStatus =
12683             TargetFloatValue.convertFromAPInt(
12684                 *SourceInt, SourceBT->isSignedInteger(),
12685                 llvm::APFloat::rmNearestTiesToEven);
12686 
12687         if (ConversionStatus != llvm::APFloat::opOK) {
12688           SmallString<32> PrettySourceValue;
12689           SourceInt->toString(PrettySourceValue, 10);
12690           SmallString<32> PrettyTargetValue;
12691           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12692 
12693           S.DiagRuntimeBehavior(
12694               E->getExprLoc(), E,
12695               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12696                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12697                   << E->getSourceRange() << clang::SourceRange(CC));
12698         }
12699       } else {
12700         // Otherwise, the implicit conversion may lose precision.
12701         DiagnoseImpCast(S, E, T, CC,
12702                         diag::warn_impcast_integer_float_precision);
12703       }
12704     }
12705   }
12706 
12707   DiagnoseNullConversion(S, E, T, CC);
12708 
12709   S.DiscardMisalignedMemberAddress(Target, E);
12710 
12711   if (Target->isBooleanType())
12712     DiagnoseIntInBoolContext(S, E);
12713 
12714   if (!Source->isIntegerType() || !Target->isIntegerType())
12715     return;
12716 
12717   // TODO: remove this early return once the false positives for constant->bool
12718   // in templates, macros, etc, are reduced or removed.
12719   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12720     return;
12721 
12722   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12723       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12724     return adornObjCBoolConversionDiagWithTernaryFixit(
12725         S, E,
12726         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12727             << E->getType());
12728   }
12729 
12730   IntRange SourceTypeRange =
12731       IntRange::forTargetOfCanonicalType(S.Context, Source);
12732   IntRange LikelySourceRange =
12733       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12734   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12735 
12736   if (LikelySourceRange.Width > TargetRange.Width) {
12737     // If the source is a constant, use a default-on diagnostic.
12738     // TODO: this should happen for bitfield stores, too.
12739     Expr::EvalResult Result;
12740     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12741                          S.isConstantEvaluated())) {
12742       llvm::APSInt Value(32);
12743       Value = Result.Val.getInt();
12744 
12745       if (S.SourceMgr.isInSystemMacro(CC))
12746         return;
12747 
12748       std::string PrettySourceValue = toString(Value, 10);
12749       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12750 
12751       S.DiagRuntimeBehavior(
12752           E->getExprLoc(), E,
12753           S.PDiag(diag::warn_impcast_integer_precision_constant)
12754               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12755               << E->getSourceRange() << SourceRange(CC));
12756       return;
12757     }
12758 
12759     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12760     if (S.SourceMgr.isInSystemMacro(CC))
12761       return;
12762 
12763     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12764       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12765                              /* pruneControlFlow */ true);
12766     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12767   }
12768 
12769   if (TargetRange.Width > SourceTypeRange.Width) {
12770     if (auto *UO = dyn_cast<UnaryOperator>(E))
12771       if (UO->getOpcode() == UO_Minus)
12772         if (Source->isUnsignedIntegerType()) {
12773           if (Target->isUnsignedIntegerType())
12774             return DiagnoseImpCast(S, E, T, CC,
12775                                    diag::warn_impcast_high_order_zero_bits);
12776           if (Target->isSignedIntegerType())
12777             return DiagnoseImpCast(S, E, T, CC,
12778                                    diag::warn_impcast_nonnegative_result);
12779         }
12780   }
12781 
12782   if (TargetRange.Width == LikelySourceRange.Width &&
12783       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12784       Source->isSignedIntegerType()) {
12785     // Warn when doing a signed to signed conversion, warn if the positive
12786     // source value is exactly the width of the target type, which will
12787     // cause a negative value to be stored.
12788 
12789     Expr::EvalResult Result;
12790     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12791         !S.SourceMgr.isInSystemMacro(CC)) {
12792       llvm::APSInt Value = Result.Val.getInt();
12793       if (isSameWidthConstantConversion(S, E, T, CC)) {
12794         std::string PrettySourceValue = toString(Value, 10);
12795         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12796 
12797         S.DiagRuntimeBehavior(
12798             E->getExprLoc(), E,
12799             S.PDiag(diag::warn_impcast_integer_precision_constant)
12800                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12801                 << E->getSourceRange() << SourceRange(CC));
12802         return;
12803       }
12804     }
12805 
12806     // Fall through for non-constants to give a sign conversion warning.
12807   }
12808 
12809   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
12810       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12811        LikelySourceRange.Width == TargetRange.Width)) {
12812     if (S.SourceMgr.isInSystemMacro(CC))
12813       return;
12814 
12815     unsigned DiagID = diag::warn_impcast_integer_sign;
12816 
12817     // Traditionally, gcc has warned about this under -Wsign-compare.
12818     // We also want to warn about it in -Wconversion.
12819     // So if -Wconversion is off, use a completely identical diagnostic
12820     // in the sign-compare group.
12821     // The conditional-checking code will
12822     if (ICContext) {
12823       DiagID = diag::warn_impcast_integer_sign_conditional;
12824       *ICContext = true;
12825     }
12826 
12827     return DiagnoseImpCast(S, E, T, CC, DiagID);
12828   }
12829 
12830   // Diagnose conversions between different enumeration types.
12831   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12832   // type, to give us better diagnostics.
12833   QualType SourceType = E->getType();
12834   if (!S.getLangOpts().CPlusPlus) {
12835     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12836       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
12837         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
12838         SourceType = S.Context.getTypeDeclType(Enum);
12839         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
12840       }
12841   }
12842 
12843   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
12844     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
12845       if (SourceEnum->getDecl()->hasNameForLinkage() &&
12846           TargetEnum->getDecl()->hasNameForLinkage() &&
12847           SourceEnum != TargetEnum) {
12848         if (S.SourceMgr.isInSystemMacro(CC))
12849           return;
12850 
12851         return DiagnoseImpCast(S, E, SourceType, T, CC,
12852                                diag::warn_impcast_different_enum_types);
12853       }
12854 }
12855 
12856 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12857                                      SourceLocation CC, QualType T);
12858 
12859 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
12860                                     SourceLocation CC, bool &ICContext) {
12861   E = E->IgnoreParenImpCasts();
12862 
12863   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12864     return CheckConditionalOperator(S, CO, CC, T);
12865 
12866   AnalyzeImplicitConversions(S, E, CC);
12867   if (E->getType() != T)
12868     return CheckImplicitConversion(S, E, T, CC, &ICContext);
12869 }
12870 
12871 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12872                                      SourceLocation CC, QualType T) {
12873   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12874 
12875   Expr *TrueExpr = E->getTrueExpr();
12876   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12877     TrueExpr = BCO->getCommon();
12878 
12879   bool Suspicious = false;
12880   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12881   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12882 
12883   if (T->isBooleanType())
12884     DiagnoseIntInBoolContext(S, E);
12885 
12886   // If -Wconversion would have warned about either of the candidates
12887   // for a signedness conversion to the context type...
12888   if (!Suspicious) return;
12889 
12890   // ...but it's currently ignored...
12891   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12892     return;
12893 
12894   // ...then check whether it would have warned about either of the
12895   // candidates for a signedness conversion to the condition type.
12896   if (E->getType() == T) return;
12897 
12898   Suspicious = false;
12899   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
12900                           E->getType(), CC, &Suspicious);
12901   if (!Suspicious)
12902     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12903                             E->getType(), CC, &Suspicious);
12904 }
12905 
12906 /// Check conversion of given expression to boolean.
12907 /// Input argument E is a logical expression.
12908 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
12909   if (S.getLangOpts().Bool)
12910     return;
12911   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12912     return;
12913   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
12914 }
12915 
12916 namespace {
12917 struct AnalyzeImplicitConversionsWorkItem {
12918   Expr *E;
12919   SourceLocation CC;
12920   bool IsListInit;
12921 };
12922 }
12923 
12924 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12925 /// that should be visited are added to WorkList.
12926 static void AnalyzeImplicitConversions(
12927     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12928     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
12929   Expr *OrigE = Item.E;
12930   SourceLocation CC = Item.CC;
12931 
12932   QualType T = OrigE->getType();
12933   Expr *E = OrigE->IgnoreParenImpCasts();
12934 
12935   // Propagate whether we are in a C++ list initialization expression.
12936   // If so, we do not issue warnings for implicit int-float conversion
12937   // precision loss, because C++11 narrowing already handles it.
12938   bool IsListInit = Item.IsListInit ||
12939                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12940 
12941   if (E->isTypeDependent() || E->isValueDependent())
12942     return;
12943 
12944   Expr *SourceExpr = E;
12945   // Examine, but don't traverse into the source expression of an
12946   // OpaqueValueExpr, since it may have multiple parents and we don't want to
12947   // emit duplicate diagnostics. Its fine to examine the form or attempt to
12948   // evaluate it in the context of checking the specific conversion to T though.
12949   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12950     if (auto *Src = OVE->getSourceExpr())
12951       SourceExpr = Src;
12952 
12953   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12954     if (UO->getOpcode() == UO_Not &&
12955         UO->getSubExpr()->isKnownToHaveBooleanValue())
12956       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12957           << OrigE->getSourceRange() << T->isBooleanType()
12958           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12959 
12960   // For conditional operators, we analyze the arguments as if they
12961   // were being fed directly into the output.
12962   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
12963     CheckConditionalOperator(S, CO, CC, T);
12964     return;
12965   }
12966 
12967   // Check implicit argument conversions for function calls.
12968   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
12969     CheckImplicitArgumentConversions(S, Call, CC);
12970 
12971   // Go ahead and check any implicit conversions we might have skipped.
12972   // The non-canonical typecheck is just an optimization;
12973   // CheckImplicitConversion will filter out dead implicit conversions.
12974   if (SourceExpr->getType() != T)
12975     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
12976 
12977   // Now continue drilling into this expression.
12978 
12979   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12980     // The bound subexpressions in a PseudoObjectExpr are not reachable
12981     // as transitive children.
12982     // FIXME: Use a more uniform representation for this.
12983     for (auto *SE : POE->semantics())
12984       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12985         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
12986   }
12987 
12988   // Skip past explicit casts.
12989   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12990     E = CE->getSubExpr()->IgnoreParenImpCasts();
12991     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12992       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12993     WorkList.push_back({E, CC, IsListInit});
12994     return;
12995   }
12996 
12997   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12998     // Do a somewhat different check with comparison operators.
12999     if (BO->isComparisonOp())
13000       return AnalyzeComparison(S, BO);
13001 
13002     // And with simple assignments.
13003     if (BO->getOpcode() == BO_Assign)
13004       return AnalyzeAssignment(S, BO);
13005     // And with compound assignments.
13006     if (BO->isAssignmentOp())
13007       return AnalyzeCompoundAssignment(S, BO);
13008   }
13009 
13010   // These break the otherwise-useful invariant below.  Fortunately,
13011   // we don't really need to recurse into them, because any internal
13012   // expressions should have been analyzed already when they were
13013   // built into statements.
13014   if (isa<StmtExpr>(E)) return;
13015 
13016   // Don't descend into unevaluated contexts.
13017   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13018 
13019   // Now just recurse over the expression's children.
13020   CC = E->getExprLoc();
13021   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13022   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13023   for (Stmt *SubStmt : E->children()) {
13024     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13025     if (!ChildExpr)
13026       continue;
13027 
13028     if (IsLogicalAndOperator &&
13029         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13030       // Ignore checking string literals that are in logical and operators.
13031       // This is a common pattern for asserts.
13032       continue;
13033     WorkList.push_back({ChildExpr, CC, IsListInit});
13034   }
13035 
13036   if (BO && BO->isLogicalOp()) {
13037     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13038     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13039       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13040 
13041     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13042     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13043       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13044   }
13045 
13046   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13047     if (U->getOpcode() == UO_LNot) {
13048       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13049     } else if (U->getOpcode() != UO_AddrOf) {
13050       if (U->getSubExpr()->getType()->isAtomicType())
13051         S.Diag(U->getSubExpr()->getBeginLoc(),
13052                diag::warn_atomic_implicit_seq_cst);
13053     }
13054   }
13055 }
13056 
13057 /// AnalyzeImplicitConversions - Find and report any interesting
13058 /// implicit conversions in the given expression.  There are a couple
13059 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13060 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13061                                        bool IsListInit/*= false*/) {
13062   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13063   WorkList.push_back({OrigE, CC, IsListInit});
13064   while (!WorkList.empty())
13065     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13066 }
13067 
13068 /// Diagnose integer type and any valid implicit conversion to it.
13069 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13070   // Taking into account implicit conversions,
13071   // allow any integer.
13072   if (!E->getType()->isIntegerType()) {
13073     S.Diag(E->getBeginLoc(),
13074            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13075     return true;
13076   }
13077   // Potentially emit standard warnings for implicit conversions if enabled
13078   // using -Wconversion.
13079   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13080   return false;
13081 }
13082 
13083 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13084 // Returns true when emitting a warning about taking the address of a reference.
13085 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13086                               const PartialDiagnostic &PD) {
13087   E = E->IgnoreParenImpCasts();
13088 
13089   const FunctionDecl *FD = nullptr;
13090 
13091   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13092     if (!DRE->getDecl()->getType()->isReferenceType())
13093       return false;
13094   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13095     if (!M->getMemberDecl()->getType()->isReferenceType())
13096       return false;
13097   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13098     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13099       return false;
13100     FD = Call->getDirectCallee();
13101   } else {
13102     return false;
13103   }
13104 
13105   SemaRef.Diag(E->getExprLoc(), PD);
13106 
13107   // If possible, point to location of function.
13108   if (FD) {
13109     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13110   }
13111 
13112   return true;
13113 }
13114 
13115 // Returns true if the SourceLocation is expanded from any macro body.
13116 // Returns false if the SourceLocation is invalid, is from not in a macro
13117 // expansion, or is from expanded from a top-level macro argument.
13118 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13119   if (Loc.isInvalid())
13120     return false;
13121 
13122   while (Loc.isMacroID()) {
13123     if (SM.isMacroBodyExpansion(Loc))
13124       return true;
13125     Loc = SM.getImmediateMacroCallerLoc(Loc);
13126   }
13127 
13128   return false;
13129 }
13130 
13131 /// Diagnose pointers that are always non-null.
13132 /// \param E the expression containing the pointer
13133 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13134 /// compared to a null pointer
13135 /// \param IsEqual True when the comparison is equal to a null pointer
13136 /// \param Range Extra SourceRange to highlight in the diagnostic
13137 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13138                                         Expr::NullPointerConstantKind NullKind,
13139                                         bool IsEqual, SourceRange Range) {
13140   if (!E)
13141     return;
13142 
13143   // Don't warn inside macros.
13144   if (E->getExprLoc().isMacroID()) {
13145     const SourceManager &SM = getSourceManager();
13146     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13147         IsInAnyMacroBody(SM, Range.getBegin()))
13148       return;
13149   }
13150   E = E->IgnoreImpCasts();
13151 
13152   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13153 
13154   if (isa<CXXThisExpr>(E)) {
13155     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13156                                 : diag::warn_this_bool_conversion;
13157     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13158     return;
13159   }
13160 
13161   bool IsAddressOf = false;
13162 
13163   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13164     if (UO->getOpcode() != UO_AddrOf)
13165       return;
13166     IsAddressOf = true;
13167     E = UO->getSubExpr();
13168   }
13169 
13170   if (IsAddressOf) {
13171     unsigned DiagID = IsCompare
13172                           ? diag::warn_address_of_reference_null_compare
13173                           : diag::warn_address_of_reference_bool_conversion;
13174     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13175                                          << IsEqual;
13176     if (CheckForReference(*this, E, PD)) {
13177       return;
13178     }
13179   }
13180 
13181   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13182     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13183     std::string Str;
13184     llvm::raw_string_ostream S(Str);
13185     E->printPretty(S, nullptr, getPrintingPolicy());
13186     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13187                                 : diag::warn_cast_nonnull_to_bool;
13188     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13189       << E->getSourceRange() << Range << IsEqual;
13190     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13191   };
13192 
13193   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13194   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13195     if (auto *Callee = Call->getDirectCallee()) {
13196       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13197         ComplainAboutNonnullParamOrCall(A);
13198         return;
13199       }
13200     }
13201   }
13202 
13203   // Expect to find a single Decl.  Skip anything more complicated.
13204   ValueDecl *D = nullptr;
13205   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13206     D = R->getDecl();
13207   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13208     D = M->getMemberDecl();
13209   }
13210 
13211   // Weak Decls can be null.
13212   if (!D || D->isWeak())
13213     return;
13214 
13215   // Check for parameter decl with nonnull attribute
13216   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13217     if (getCurFunction() &&
13218         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13219       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13220         ComplainAboutNonnullParamOrCall(A);
13221         return;
13222       }
13223 
13224       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13225         // Skip function template not specialized yet.
13226         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13227           return;
13228         auto ParamIter = llvm::find(FD->parameters(), PV);
13229         assert(ParamIter != FD->param_end());
13230         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13231 
13232         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13233           if (!NonNull->args_size()) {
13234               ComplainAboutNonnullParamOrCall(NonNull);
13235               return;
13236           }
13237 
13238           for (const ParamIdx &ArgNo : NonNull->args()) {
13239             if (ArgNo.getASTIndex() == ParamNo) {
13240               ComplainAboutNonnullParamOrCall(NonNull);
13241               return;
13242             }
13243           }
13244         }
13245       }
13246     }
13247   }
13248 
13249   QualType T = D->getType();
13250   const bool IsArray = T->isArrayType();
13251   const bool IsFunction = T->isFunctionType();
13252 
13253   // Address of function is used to silence the function warning.
13254   if (IsAddressOf && IsFunction) {
13255     return;
13256   }
13257 
13258   // Found nothing.
13259   if (!IsAddressOf && !IsFunction && !IsArray)
13260     return;
13261 
13262   // Pretty print the expression for the diagnostic.
13263   std::string Str;
13264   llvm::raw_string_ostream S(Str);
13265   E->printPretty(S, nullptr, getPrintingPolicy());
13266 
13267   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13268                               : diag::warn_impcast_pointer_to_bool;
13269   enum {
13270     AddressOf,
13271     FunctionPointer,
13272     ArrayPointer
13273   } DiagType;
13274   if (IsAddressOf)
13275     DiagType = AddressOf;
13276   else if (IsFunction)
13277     DiagType = FunctionPointer;
13278   else if (IsArray)
13279     DiagType = ArrayPointer;
13280   else
13281     llvm_unreachable("Could not determine diagnostic.");
13282   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13283                                 << Range << IsEqual;
13284 
13285   if (!IsFunction)
13286     return;
13287 
13288   // Suggest '&' to silence the function warning.
13289   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13290       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13291 
13292   // Check to see if '()' fixit should be emitted.
13293   QualType ReturnType;
13294   UnresolvedSet<4> NonTemplateOverloads;
13295   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13296   if (ReturnType.isNull())
13297     return;
13298 
13299   if (IsCompare) {
13300     // There are two cases here.  If there is null constant, the only suggest
13301     // for a pointer return type.  If the null is 0, then suggest if the return
13302     // type is a pointer or an integer type.
13303     if (!ReturnType->isPointerType()) {
13304       if (NullKind == Expr::NPCK_ZeroExpression ||
13305           NullKind == Expr::NPCK_ZeroLiteral) {
13306         if (!ReturnType->isIntegerType())
13307           return;
13308       } else {
13309         return;
13310       }
13311     }
13312   } else { // !IsCompare
13313     // For function to bool, only suggest if the function pointer has bool
13314     // return type.
13315     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13316       return;
13317   }
13318   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13319       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13320 }
13321 
13322 /// Diagnoses "dangerous" implicit conversions within the given
13323 /// expression (which is a full expression).  Implements -Wconversion
13324 /// and -Wsign-compare.
13325 ///
13326 /// \param CC the "context" location of the implicit conversion, i.e.
13327 ///   the most location of the syntactic entity requiring the implicit
13328 ///   conversion
13329 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13330   // Don't diagnose in unevaluated contexts.
13331   if (isUnevaluatedContext())
13332     return;
13333 
13334   // Don't diagnose for value- or type-dependent expressions.
13335   if (E->isTypeDependent() || E->isValueDependent())
13336     return;
13337 
13338   // Check for array bounds violations in cases where the check isn't triggered
13339   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13340   // ArraySubscriptExpr is on the RHS of a variable initialization.
13341   CheckArrayAccess(E);
13342 
13343   // This is not the right CC for (e.g.) a variable initialization.
13344   AnalyzeImplicitConversions(*this, E, CC);
13345 }
13346 
13347 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13348 /// Input argument E is a logical expression.
13349 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13350   ::CheckBoolLikeConversion(*this, E, CC);
13351 }
13352 
13353 /// Diagnose when expression is an integer constant expression and its evaluation
13354 /// results in integer overflow
13355 void Sema::CheckForIntOverflow (Expr *E) {
13356   // Use a work list to deal with nested struct initializers.
13357   SmallVector<Expr *, 2> Exprs(1, E);
13358 
13359   do {
13360     Expr *OriginalE = Exprs.pop_back_val();
13361     Expr *E = OriginalE->IgnoreParenCasts();
13362 
13363     if (isa<BinaryOperator>(E)) {
13364       E->EvaluateForOverflow(Context);
13365       continue;
13366     }
13367 
13368     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13369       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13370     else if (isa<ObjCBoxedExpr>(OriginalE))
13371       E->EvaluateForOverflow(Context);
13372     else if (auto Call = dyn_cast<CallExpr>(E))
13373       Exprs.append(Call->arg_begin(), Call->arg_end());
13374     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13375       Exprs.append(Message->arg_begin(), Message->arg_end());
13376   } while (!Exprs.empty());
13377 }
13378 
13379 namespace {
13380 
13381 /// Visitor for expressions which looks for unsequenced operations on the
13382 /// same object.
13383 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13384   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13385 
13386   /// A tree of sequenced regions within an expression. Two regions are
13387   /// unsequenced if one is an ancestor or a descendent of the other. When we
13388   /// finish processing an expression with sequencing, such as a comma
13389   /// expression, we fold its tree nodes into its parent, since they are
13390   /// unsequenced with respect to nodes we will visit later.
13391   class SequenceTree {
13392     struct Value {
13393       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13394       unsigned Parent : 31;
13395       unsigned Merged : 1;
13396     };
13397     SmallVector<Value, 8> Values;
13398 
13399   public:
13400     /// A region within an expression which may be sequenced with respect
13401     /// to some other region.
13402     class Seq {
13403       friend class SequenceTree;
13404 
13405       unsigned Index;
13406 
13407       explicit Seq(unsigned N) : Index(N) {}
13408 
13409     public:
13410       Seq() : Index(0) {}
13411     };
13412 
13413     SequenceTree() { Values.push_back(Value(0)); }
13414     Seq root() const { return Seq(0); }
13415 
13416     /// Create a new sequence of operations, which is an unsequenced
13417     /// subset of \p Parent. This sequence of operations is sequenced with
13418     /// respect to other children of \p Parent.
13419     Seq allocate(Seq Parent) {
13420       Values.push_back(Value(Parent.Index));
13421       return Seq(Values.size() - 1);
13422     }
13423 
13424     /// Merge a sequence of operations into its parent.
13425     void merge(Seq S) {
13426       Values[S.Index].Merged = true;
13427     }
13428 
13429     /// Determine whether two operations are unsequenced. This operation
13430     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13431     /// should have been merged into its parent as appropriate.
13432     bool isUnsequenced(Seq Cur, Seq Old) {
13433       unsigned C = representative(Cur.Index);
13434       unsigned Target = representative(Old.Index);
13435       while (C >= Target) {
13436         if (C == Target)
13437           return true;
13438         C = Values[C].Parent;
13439       }
13440       return false;
13441     }
13442 
13443   private:
13444     /// Pick a representative for a sequence.
13445     unsigned representative(unsigned K) {
13446       if (Values[K].Merged)
13447         // Perform path compression as we go.
13448         return Values[K].Parent = representative(Values[K].Parent);
13449       return K;
13450     }
13451   };
13452 
13453   /// An object for which we can track unsequenced uses.
13454   using Object = const NamedDecl *;
13455 
13456   /// Different flavors of object usage which we track. We only track the
13457   /// least-sequenced usage of each kind.
13458   enum UsageKind {
13459     /// A read of an object. Multiple unsequenced reads are OK.
13460     UK_Use,
13461 
13462     /// A modification of an object which is sequenced before the value
13463     /// computation of the expression, such as ++n in C++.
13464     UK_ModAsValue,
13465 
13466     /// A modification of an object which is not sequenced before the value
13467     /// computation of the expression, such as n++.
13468     UK_ModAsSideEffect,
13469 
13470     UK_Count = UK_ModAsSideEffect + 1
13471   };
13472 
13473   /// Bundle together a sequencing region and the expression corresponding
13474   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13475   struct Usage {
13476     const Expr *UsageExpr;
13477     SequenceTree::Seq Seq;
13478 
13479     Usage() : UsageExpr(nullptr), Seq() {}
13480   };
13481 
13482   struct UsageInfo {
13483     Usage Uses[UK_Count];
13484 
13485     /// Have we issued a diagnostic for this object already?
13486     bool Diagnosed;
13487 
13488     UsageInfo() : Uses(), Diagnosed(false) {}
13489   };
13490   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13491 
13492   Sema &SemaRef;
13493 
13494   /// Sequenced regions within the expression.
13495   SequenceTree Tree;
13496 
13497   /// Declaration modifications and references which we have seen.
13498   UsageInfoMap UsageMap;
13499 
13500   /// The region we are currently within.
13501   SequenceTree::Seq Region;
13502 
13503   /// Filled in with declarations which were modified as a side-effect
13504   /// (that is, post-increment operations).
13505   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13506 
13507   /// Expressions to check later. We defer checking these to reduce
13508   /// stack usage.
13509   SmallVectorImpl<const Expr *> &WorkList;
13510 
13511   /// RAII object wrapping the visitation of a sequenced subexpression of an
13512   /// expression. At the end of this process, the side-effects of the evaluation
13513   /// become sequenced with respect to the value computation of the result, so
13514   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13515   /// UK_ModAsValue.
13516   struct SequencedSubexpression {
13517     SequencedSubexpression(SequenceChecker &Self)
13518       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13519       Self.ModAsSideEffect = &ModAsSideEffect;
13520     }
13521 
13522     ~SequencedSubexpression() {
13523       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13524         // Add a new usage with usage kind UK_ModAsValue, and then restore
13525         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13526         // the previous one was empty).
13527         UsageInfo &UI = Self.UsageMap[M.first];
13528         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13529         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13530         SideEffectUsage = M.second;
13531       }
13532       Self.ModAsSideEffect = OldModAsSideEffect;
13533     }
13534 
13535     SequenceChecker &Self;
13536     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13537     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13538   };
13539 
13540   /// RAII object wrapping the visitation of a subexpression which we might
13541   /// choose to evaluate as a constant. If any subexpression is evaluated and
13542   /// found to be non-constant, this allows us to suppress the evaluation of
13543   /// the outer expression.
13544   class EvaluationTracker {
13545   public:
13546     EvaluationTracker(SequenceChecker &Self)
13547         : Self(Self), Prev(Self.EvalTracker) {
13548       Self.EvalTracker = this;
13549     }
13550 
13551     ~EvaluationTracker() {
13552       Self.EvalTracker = Prev;
13553       if (Prev)
13554         Prev->EvalOK &= EvalOK;
13555     }
13556 
13557     bool evaluate(const Expr *E, bool &Result) {
13558       if (!EvalOK || E->isValueDependent())
13559         return false;
13560       EvalOK = E->EvaluateAsBooleanCondition(
13561           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13562       return EvalOK;
13563     }
13564 
13565   private:
13566     SequenceChecker &Self;
13567     EvaluationTracker *Prev;
13568     bool EvalOK = true;
13569   } *EvalTracker = nullptr;
13570 
13571   /// Find the object which is produced by the specified expression,
13572   /// if any.
13573   Object getObject(const Expr *E, bool Mod) const {
13574     E = E->IgnoreParenCasts();
13575     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13576       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13577         return getObject(UO->getSubExpr(), Mod);
13578     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13579       if (BO->getOpcode() == BO_Comma)
13580         return getObject(BO->getRHS(), Mod);
13581       if (Mod && BO->isAssignmentOp())
13582         return getObject(BO->getLHS(), Mod);
13583     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13584       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13585       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13586         return ME->getMemberDecl();
13587     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13588       // FIXME: If this is a reference, map through to its value.
13589       return DRE->getDecl();
13590     return nullptr;
13591   }
13592 
13593   /// Note that an object \p O was modified or used by an expression
13594   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13595   /// the object \p O as obtained via the \p UsageMap.
13596   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13597     // Get the old usage for the given object and usage kind.
13598     Usage &U = UI.Uses[UK];
13599     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13600       // If we have a modification as side effect and are in a sequenced
13601       // subexpression, save the old Usage so that we can restore it later
13602       // in SequencedSubexpression::~SequencedSubexpression.
13603       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13604         ModAsSideEffect->push_back(std::make_pair(O, U));
13605       // Then record the new usage with the current sequencing region.
13606       U.UsageExpr = UsageExpr;
13607       U.Seq = Region;
13608     }
13609   }
13610 
13611   /// Check whether a modification or use of an object \p O in an expression
13612   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13613   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13614   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13615   /// usage and false we are checking for a mod-use unsequenced usage.
13616   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13617                   UsageKind OtherKind, bool IsModMod) {
13618     if (UI.Diagnosed)
13619       return;
13620 
13621     const Usage &U = UI.Uses[OtherKind];
13622     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13623       return;
13624 
13625     const Expr *Mod = U.UsageExpr;
13626     const Expr *ModOrUse = UsageExpr;
13627     if (OtherKind == UK_Use)
13628       std::swap(Mod, ModOrUse);
13629 
13630     SemaRef.DiagRuntimeBehavior(
13631         Mod->getExprLoc(), {Mod, ModOrUse},
13632         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13633                                : diag::warn_unsequenced_mod_use)
13634             << O << SourceRange(ModOrUse->getExprLoc()));
13635     UI.Diagnosed = true;
13636   }
13637 
13638   // A note on note{Pre, Post}{Use, Mod}:
13639   //
13640   // (It helps to follow the algorithm with an expression such as
13641   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13642   //  operations before C++17 and both are well-defined in C++17).
13643   //
13644   // When visiting a node which uses/modify an object we first call notePreUse
13645   // or notePreMod before visiting its sub-expression(s). At this point the
13646   // children of the current node have not yet been visited and so the eventual
13647   // uses/modifications resulting from the children of the current node have not
13648   // been recorded yet.
13649   //
13650   // We then visit the children of the current node. After that notePostUse or
13651   // notePostMod is called. These will 1) detect an unsequenced modification
13652   // as side effect (as in "k++ + k") and 2) add a new usage with the
13653   // appropriate usage kind.
13654   //
13655   // We also have to be careful that some operation sequences modification as
13656   // side effect as well (for example: || or ,). To account for this we wrap
13657   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13658   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13659   // which record usages which are modifications as side effect, and then
13660   // downgrade them (or more accurately restore the previous usage which was a
13661   // modification as side effect) when exiting the scope of the sequenced
13662   // subexpression.
13663 
13664   void notePreUse(Object O, const Expr *UseExpr) {
13665     UsageInfo &UI = UsageMap[O];
13666     // Uses conflict with other modifications.
13667     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13668   }
13669 
13670   void notePostUse(Object O, const Expr *UseExpr) {
13671     UsageInfo &UI = UsageMap[O];
13672     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13673                /*IsModMod=*/false);
13674     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13675   }
13676 
13677   void notePreMod(Object O, const Expr *ModExpr) {
13678     UsageInfo &UI = UsageMap[O];
13679     // Modifications conflict with other modifications and with uses.
13680     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13681     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13682   }
13683 
13684   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13685     UsageInfo &UI = UsageMap[O];
13686     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13687                /*IsModMod=*/true);
13688     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13689   }
13690 
13691 public:
13692   SequenceChecker(Sema &S, const Expr *E,
13693                   SmallVectorImpl<const Expr *> &WorkList)
13694       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13695     Visit(E);
13696     // Silence a -Wunused-private-field since WorkList is now unused.
13697     // TODO: Evaluate if it can be used, and if not remove it.
13698     (void)this->WorkList;
13699   }
13700 
13701   void VisitStmt(const Stmt *S) {
13702     // Skip all statements which aren't expressions for now.
13703   }
13704 
13705   void VisitExpr(const Expr *E) {
13706     // By default, just recurse to evaluated subexpressions.
13707     Base::VisitStmt(E);
13708   }
13709 
13710   void VisitCastExpr(const CastExpr *E) {
13711     Object O = Object();
13712     if (E->getCastKind() == CK_LValueToRValue)
13713       O = getObject(E->getSubExpr(), false);
13714 
13715     if (O)
13716       notePreUse(O, E);
13717     VisitExpr(E);
13718     if (O)
13719       notePostUse(O, E);
13720   }
13721 
13722   void VisitSequencedExpressions(const Expr *SequencedBefore,
13723                                  const Expr *SequencedAfter) {
13724     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13725     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13726     SequenceTree::Seq OldRegion = Region;
13727 
13728     {
13729       SequencedSubexpression SeqBefore(*this);
13730       Region = BeforeRegion;
13731       Visit(SequencedBefore);
13732     }
13733 
13734     Region = AfterRegion;
13735     Visit(SequencedAfter);
13736 
13737     Region = OldRegion;
13738 
13739     Tree.merge(BeforeRegion);
13740     Tree.merge(AfterRegion);
13741   }
13742 
13743   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13744     // C++17 [expr.sub]p1:
13745     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13746     //   expression E1 is sequenced before the expression E2.
13747     if (SemaRef.getLangOpts().CPlusPlus17)
13748       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13749     else {
13750       Visit(ASE->getLHS());
13751       Visit(ASE->getRHS());
13752     }
13753   }
13754 
13755   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13756   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13757   void VisitBinPtrMem(const BinaryOperator *BO) {
13758     // C++17 [expr.mptr.oper]p4:
13759     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13760     //  the expression E1 is sequenced before the expression E2.
13761     if (SemaRef.getLangOpts().CPlusPlus17)
13762       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13763     else {
13764       Visit(BO->getLHS());
13765       Visit(BO->getRHS());
13766     }
13767   }
13768 
13769   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13770   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13771   void VisitBinShlShr(const BinaryOperator *BO) {
13772     // C++17 [expr.shift]p4:
13773     //  The expression E1 is sequenced before the expression E2.
13774     if (SemaRef.getLangOpts().CPlusPlus17)
13775       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13776     else {
13777       Visit(BO->getLHS());
13778       Visit(BO->getRHS());
13779     }
13780   }
13781 
13782   void VisitBinComma(const BinaryOperator *BO) {
13783     // C++11 [expr.comma]p1:
13784     //   Every value computation and side effect associated with the left
13785     //   expression is sequenced before every value computation and side
13786     //   effect associated with the right expression.
13787     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13788   }
13789 
13790   void VisitBinAssign(const BinaryOperator *BO) {
13791     SequenceTree::Seq RHSRegion;
13792     SequenceTree::Seq LHSRegion;
13793     if (SemaRef.getLangOpts().CPlusPlus17) {
13794       RHSRegion = Tree.allocate(Region);
13795       LHSRegion = Tree.allocate(Region);
13796     } else {
13797       RHSRegion = Region;
13798       LHSRegion = Region;
13799     }
13800     SequenceTree::Seq OldRegion = Region;
13801 
13802     // C++11 [expr.ass]p1:
13803     //  [...] the assignment is sequenced after the value computation
13804     //  of the right and left operands, [...]
13805     //
13806     // so check it before inspecting the operands and update the
13807     // map afterwards.
13808     Object O = getObject(BO->getLHS(), /*Mod=*/true);
13809     if (O)
13810       notePreMod(O, BO);
13811 
13812     if (SemaRef.getLangOpts().CPlusPlus17) {
13813       // C++17 [expr.ass]p1:
13814       //  [...] The right operand is sequenced before the left operand. [...]
13815       {
13816         SequencedSubexpression SeqBefore(*this);
13817         Region = RHSRegion;
13818         Visit(BO->getRHS());
13819       }
13820 
13821       Region = LHSRegion;
13822       Visit(BO->getLHS());
13823 
13824       if (O && isa<CompoundAssignOperator>(BO))
13825         notePostUse(O, BO);
13826 
13827     } else {
13828       // C++11 does not specify any sequencing between the LHS and RHS.
13829       Region = LHSRegion;
13830       Visit(BO->getLHS());
13831 
13832       if (O && isa<CompoundAssignOperator>(BO))
13833         notePostUse(O, BO);
13834 
13835       Region = RHSRegion;
13836       Visit(BO->getRHS());
13837     }
13838 
13839     // C++11 [expr.ass]p1:
13840     //  the assignment is sequenced [...] before the value computation of the
13841     //  assignment expression.
13842     // C11 6.5.16/3 has no such rule.
13843     Region = OldRegion;
13844     if (O)
13845       notePostMod(O, BO,
13846                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13847                                                   : UK_ModAsSideEffect);
13848     if (SemaRef.getLangOpts().CPlusPlus17) {
13849       Tree.merge(RHSRegion);
13850       Tree.merge(LHSRegion);
13851     }
13852   }
13853 
13854   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13855     VisitBinAssign(CAO);
13856   }
13857 
13858   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13859   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13860   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13861     Object O = getObject(UO->getSubExpr(), true);
13862     if (!O)
13863       return VisitExpr(UO);
13864 
13865     notePreMod(O, UO);
13866     Visit(UO->getSubExpr());
13867     // C++11 [expr.pre.incr]p1:
13868     //   the expression ++x is equivalent to x+=1
13869     notePostMod(O, UO,
13870                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13871                                                 : UK_ModAsSideEffect);
13872   }
13873 
13874   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13875   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13876   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13877     Object O = getObject(UO->getSubExpr(), true);
13878     if (!O)
13879       return VisitExpr(UO);
13880 
13881     notePreMod(O, UO);
13882     Visit(UO->getSubExpr());
13883     notePostMod(O, UO, UK_ModAsSideEffect);
13884   }
13885 
13886   void VisitBinLOr(const BinaryOperator *BO) {
13887     // C++11 [expr.log.or]p2:
13888     //  If the second expression is evaluated, every value computation and
13889     //  side effect associated with the first expression is sequenced before
13890     //  every value computation and side effect associated with the
13891     //  second expression.
13892     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13893     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13894     SequenceTree::Seq OldRegion = Region;
13895 
13896     EvaluationTracker Eval(*this);
13897     {
13898       SequencedSubexpression Sequenced(*this);
13899       Region = LHSRegion;
13900       Visit(BO->getLHS());
13901     }
13902 
13903     // C++11 [expr.log.or]p1:
13904     //  [...] the second operand is not evaluated if the first operand
13905     //  evaluates to true.
13906     bool EvalResult = false;
13907     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13908     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
13909     if (ShouldVisitRHS) {
13910       Region = RHSRegion;
13911       Visit(BO->getRHS());
13912     }
13913 
13914     Region = OldRegion;
13915     Tree.merge(LHSRegion);
13916     Tree.merge(RHSRegion);
13917   }
13918 
13919   void VisitBinLAnd(const BinaryOperator *BO) {
13920     // C++11 [expr.log.and]p2:
13921     //  If the second expression is evaluated, every value computation and
13922     //  side effect associated with the first expression is sequenced before
13923     //  every value computation and side effect associated with the
13924     //  second expression.
13925     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13926     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13927     SequenceTree::Seq OldRegion = Region;
13928 
13929     EvaluationTracker Eval(*this);
13930     {
13931       SequencedSubexpression Sequenced(*this);
13932       Region = LHSRegion;
13933       Visit(BO->getLHS());
13934     }
13935 
13936     // C++11 [expr.log.and]p1:
13937     //  [...] the second operand is not evaluated if the first operand is false.
13938     bool EvalResult = false;
13939     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13940     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
13941     if (ShouldVisitRHS) {
13942       Region = RHSRegion;
13943       Visit(BO->getRHS());
13944     }
13945 
13946     Region = OldRegion;
13947     Tree.merge(LHSRegion);
13948     Tree.merge(RHSRegion);
13949   }
13950 
13951   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13952     // C++11 [expr.cond]p1:
13953     //  [...] Every value computation and side effect associated with the first
13954     //  expression is sequenced before every value computation and side effect
13955     //  associated with the second or third expression.
13956     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13957 
13958     // No sequencing is specified between the true and false expression.
13959     // However since exactly one of both is going to be evaluated we can
13960     // consider them to be sequenced. This is needed to avoid warning on
13961     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13962     // both the true and false expressions because we can't evaluate x.
13963     // This will still allow us to detect an expression like (pre C++17)
13964     // "(x ? y += 1 : y += 2) = y".
13965     //
13966     // We don't wrap the visitation of the true and false expression with
13967     // SequencedSubexpression because we don't want to downgrade modifications
13968     // as side effect in the true and false expressions after the visition
13969     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13970     // not warn between the two "y++", but we should warn between the "y++"
13971     // and the "y".
13972     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13973     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13974     SequenceTree::Seq OldRegion = Region;
13975 
13976     EvaluationTracker Eval(*this);
13977     {
13978       SequencedSubexpression Sequenced(*this);
13979       Region = ConditionRegion;
13980       Visit(CO->getCond());
13981     }
13982 
13983     // C++11 [expr.cond]p1:
13984     // [...] The first expression is contextually converted to bool (Clause 4).
13985     // It is evaluated and if it is true, the result of the conditional
13986     // expression is the value of the second expression, otherwise that of the
13987     // third expression. Only one of the second and third expressions is
13988     // evaluated. [...]
13989     bool EvalResult = false;
13990     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13991     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
13992     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
13993     if (ShouldVisitTrueExpr) {
13994       Region = TrueRegion;
13995       Visit(CO->getTrueExpr());
13996     }
13997     if (ShouldVisitFalseExpr) {
13998       Region = FalseRegion;
13999       Visit(CO->getFalseExpr());
14000     }
14001 
14002     Region = OldRegion;
14003     Tree.merge(ConditionRegion);
14004     Tree.merge(TrueRegion);
14005     Tree.merge(FalseRegion);
14006   }
14007 
14008   void VisitCallExpr(const CallExpr *CE) {
14009     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14010 
14011     if (CE->isUnevaluatedBuiltinCall(Context))
14012       return;
14013 
14014     // C++11 [intro.execution]p15:
14015     //   When calling a function [...], every value computation and side effect
14016     //   associated with any argument expression, or with the postfix expression
14017     //   designating the called function, is sequenced before execution of every
14018     //   expression or statement in the body of the function [and thus before
14019     //   the value computation of its result].
14020     SequencedSubexpression Sequenced(*this);
14021     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14022       // C++17 [expr.call]p5
14023       //   The postfix-expression is sequenced before each expression in the
14024       //   expression-list and any default argument. [...]
14025       SequenceTree::Seq CalleeRegion;
14026       SequenceTree::Seq OtherRegion;
14027       if (SemaRef.getLangOpts().CPlusPlus17) {
14028         CalleeRegion = Tree.allocate(Region);
14029         OtherRegion = Tree.allocate(Region);
14030       } else {
14031         CalleeRegion = Region;
14032         OtherRegion = Region;
14033       }
14034       SequenceTree::Seq OldRegion = Region;
14035 
14036       // Visit the callee expression first.
14037       Region = CalleeRegion;
14038       if (SemaRef.getLangOpts().CPlusPlus17) {
14039         SequencedSubexpression Sequenced(*this);
14040         Visit(CE->getCallee());
14041       } else {
14042         Visit(CE->getCallee());
14043       }
14044 
14045       // Then visit the argument expressions.
14046       Region = OtherRegion;
14047       for (const Expr *Argument : CE->arguments())
14048         Visit(Argument);
14049 
14050       Region = OldRegion;
14051       if (SemaRef.getLangOpts().CPlusPlus17) {
14052         Tree.merge(CalleeRegion);
14053         Tree.merge(OtherRegion);
14054       }
14055     });
14056   }
14057 
14058   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14059     // C++17 [over.match.oper]p2:
14060     //   [...] the operator notation is first transformed to the equivalent
14061     //   function-call notation as summarized in Table 12 (where @ denotes one
14062     //   of the operators covered in the specified subclause). However, the
14063     //   operands are sequenced in the order prescribed for the built-in
14064     //   operator (Clause 8).
14065     //
14066     // From the above only overloaded binary operators and overloaded call
14067     // operators have sequencing rules in C++17 that we need to handle
14068     // separately.
14069     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14070         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14071       return VisitCallExpr(CXXOCE);
14072 
14073     enum {
14074       NoSequencing,
14075       LHSBeforeRHS,
14076       RHSBeforeLHS,
14077       LHSBeforeRest
14078     } SequencingKind;
14079     switch (CXXOCE->getOperator()) {
14080     case OO_Equal:
14081     case OO_PlusEqual:
14082     case OO_MinusEqual:
14083     case OO_StarEqual:
14084     case OO_SlashEqual:
14085     case OO_PercentEqual:
14086     case OO_CaretEqual:
14087     case OO_AmpEqual:
14088     case OO_PipeEqual:
14089     case OO_LessLessEqual:
14090     case OO_GreaterGreaterEqual:
14091       SequencingKind = RHSBeforeLHS;
14092       break;
14093 
14094     case OO_LessLess:
14095     case OO_GreaterGreater:
14096     case OO_AmpAmp:
14097     case OO_PipePipe:
14098     case OO_Comma:
14099     case OO_ArrowStar:
14100     case OO_Subscript:
14101       SequencingKind = LHSBeforeRHS;
14102       break;
14103 
14104     case OO_Call:
14105       SequencingKind = LHSBeforeRest;
14106       break;
14107 
14108     default:
14109       SequencingKind = NoSequencing;
14110       break;
14111     }
14112 
14113     if (SequencingKind == NoSequencing)
14114       return VisitCallExpr(CXXOCE);
14115 
14116     // This is a call, so all subexpressions are sequenced before the result.
14117     SequencedSubexpression Sequenced(*this);
14118 
14119     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14120       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14121              "Should only get there with C++17 and above!");
14122       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14123              "Should only get there with an overloaded binary operator"
14124              " or an overloaded call operator!");
14125 
14126       if (SequencingKind == LHSBeforeRest) {
14127         assert(CXXOCE->getOperator() == OO_Call &&
14128                "We should only have an overloaded call operator here!");
14129 
14130         // This is very similar to VisitCallExpr, except that we only have the
14131         // C++17 case. The postfix-expression is the first argument of the
14132         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14133         // are in the following arguments.
14134         //
14135         // Note that we intentionally do not visit the callee expression since
14136         // it is just a decayed reference to a function.
14137         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14138         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14139         SequenceTree::Seq OldRegion = Region;
14140 
14141         assert(CXXOCE->getNumArgs() >= 1 &&
14142                "An overloaded call operator must have at least one argument"
14143                " for the postfix-expression!");
14144         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14145         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14146                                           CXXOCE->getNumArgs() - 1);
14147 
14148         // Visit the postfix-expression first.
14149         {
14150           Region = PostfixExprRegion;
14151           SequencedSubexpression Sequenced(*this);
14152           Visit(PostfixExpr);
14153         }
14154 
14155         // Then visit the argument expressions.
14156         Region = ArgsRegion;
14157         for (const Expr *Arg : Args)
14158           Visit(Arg);
14159 
14160         Region = OldRegion;
14161         Tree.merge(PostfixExprRegion);
14162         Tree.merge(ArgsRegion);
14163       } else {
14164         assert(CXXOCE->getNumArgs() == 2 &&
14165                "Should only have two arguments here!");
14166         assert((SequencingKind == LHSBeforeRHS ||
14167                 SequencingKind == RHSBeforeLHS) &&
14168                "Unexpected sequencing kind!");
14169 
14170         // We do not visit the callee expression since it is just a decayed
14171         // reference to a function.
14172         const Expr *E1 = CXXOCE->getArg(0);
14173         const Expr *E2 = CXXOCE->getArg(1);
14174         if (SequencingKind == RHSBeforeLHS)
14175           std::swap(E1, E2);
14176 
14177         return VisitSequencedExpressions(E1, E2);
14178       }
14179     });
14180   }
14181 
14182   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14183     // This is a call, so all subexpressions are sequenced before the result.
14184     SequencedSubexpression Sequenced(*this);
14185 
14186     if (!CCE->isListInitialization())
14187       return VisitExpr(CCE);
14188 
14189     // In C++11, list initializations are sequenced.
14190     SmallVector<SequenceTree::Seq, 32> Elts;
14191     SequenceTree::Seq Parent = Region;
14192     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14193                                               E = CCE->arg_end();
14194          I != E; ++I) {
14195       Region = Tree.allocate(Parent);
14196       Elts.push_back(Region);
14197       Visit(*I);
14198     }
14199 
14200     // Forget that the initializers are sequenced.
14201     Region = Parent;
14202     for (unsigned I = 0; I < Elts.size(); ++I)
14203       Tree.merge(Elts[I]);
14204   }
14205 
14206   void VisitInitListExpr(const InitListExpr *ILE) {
14207     if (!SemaRef.getLangOpts().CPlusPlus11)
14208       return VisitExpr(ILE);
14209 
14210     // In C++11, list initializations are sequenced.
14211     SmallVector<SequenceTree::Seq, 32> Elts;
14212     SequenceTree::Seq Parent = Region;
14213     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14214       const Expr *E = ILE->getInit(I);
14215       if (!E)
14216         continue;
14217       Region = Tree.allocate(Parent);
14218       Elts.push_back(Region);
14219       Visit(E);
14220     }
14221 
14222     // Forget that the initializers are sequenced.
14223     Region = Parent;
14224     for (unsigned I = 0; I < Elts.size(); ++I)
14225       Tree.merge(Elts[I]);
14226   }
14227 };
14228 
14229 } // namespace
14230 
14231 void Sema::CheckUnsequencedOperations(const Expr *E) {
14232   SmallVector<const Expr *, 8> WorkList;
14233   WorkList.push_back(E);
14234   while (!WorkList.empty()) {
14235     const Expr *Item = WorkList.pop_back_val();
14236     SequenceChecker(*this, Item, WorkList);
14237   }
14238 }
14239 
14240 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14241                               bool IsConstexpr) {
14242   llvm::SaveAndRestore<bool> ConstantContext(
14243       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14244   CheckImplicitConversions(E, CheckLoc);
14245   if (!E->isInstantiationDependent())
14246     CheckUnsequencedOperations(E);
14247   if (!IsConstexpr && !E->isValueDependent())
14248     CheckForIntOverflow(E);
14249   DiagnoseMisalignedMembers();
14250 }
14251 
14252 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14253                                        FieldDecl *BitField,
14254                                        Expr *Init) {
14255   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14256 }
14257 
14258 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14259                                          SourceLocation Loc) {
14260   if (!PType->isVariablyModifiedType())
14261     return;
14262   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14263     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14264     return;
14265   }
14266   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14267     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14268     return;
14269   }
14270   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14271     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14272     return;
14273   }
14274 
14275   const ArrayType *AT = S.Context.getAsArrayType(PType);
14276   if (!AT)
14277     return;
14278 
14279   if (AT->getSizeModifier() != ArrayType::Star) {
14280     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14281     return;
14282   }
14283 
14284   S.Diag(Loc, diag::err_array_star_in_function_definition);
14285 }
14286 
14287 /// CheckParmsForFunctionDef - Check that the parameters of the given
14288 /// function are appropriate for the definition of a function. This
14289 /// takes care of any checks that cannot be performed on the
14290 /// declaration itself, e.g., that the types of each of the function
14291 /// parameters are complete.
14292 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14293                                     bool CheckParameterNames) {
14294   bool HasInvalidParm = false;
14295   for (ParmVarDecl *Param : Parameters) {
14296     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14297     // function declarator that is part of a function definition of
14298     // that function shall not have incomplete type.
14299     //
14300     // This is also C++ [dcl.fct]p6.
14301     if (!Param->isInvalidDecl() &&
14302         RequireCompleteType(Param->getLocation(), Param->getType(),
14303                             diag::err_typecheck_decl_incomplete_type)) {
14304       Param->setInvalidDecl();
14305       HasInvalidParm = true;
14306     }
14307 
14308     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14309     // declaration of each parameter shall include an identifier.
14310     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14311         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14312       // Diagnose this as an extension in C17 and earlier.
14313       if (!getLangOpts().C2x)
14314         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14315     }
14316 
14317     // C99 6.7.5.3p12:
14318     //   If the function declarator is not part of a definition of that
14319     //   function, parameters may have incomplete type and may use the [*]
14320     //   notation in their sequences of declarator specifiers to specify
14321     //   variable length array types.
14322     QualType PType = Param->getOriginalType();
14323     // FIXME: This diagnostic should point the '[*]' if source-location
14324     // information is added for it.
14325     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14326 
14327     // If the parameter is a c++ class type and it has to be destructed in the
14328     // callee function, declare the destructor so that it can be called by the
14329     // callee function. Do not perform any direct access check on the dtor here.
14330     if (!Param->isInvalidDecl()) {
14331       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14332         if (!ClassDecl->isInvalidDecl() &&
14333             !ClassDecl->hasIrrelevantDestructor() &&
14334             !ClassDecl->isDependentContext() &&
14335             ClassDecl->isParamDestroyedInCallee()) {
14336           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14337           MarkFunctionReferenced(Param->getLocation(), Destructor);
14338           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14339         }
14340       }
14341     }
14342 
14343     // Parameters with the pass_object_size attribute only need to be marked
14344     // constant at function definitions. Because we lack information about
14345     // whether we're on a declaration or definition when we're instantiating the
14346     // attribute, we need to check for constness here.
14347     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14348       if (!Param->getType().isConstQualified())
14349         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14350             << Attr->getSpelling() << 1;
14351 
14352     // Check for parameter names shadowing fields from the class.
14353     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14354       // The owning context for the parameter should be the function, but we
14355       // want to see if this function's declaration context is a record.
14356       DeclContext *DC = Param->getDeclContext();
14357       if (DC && DC->isFunctionOrMethod()) {
14358         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14359           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14360                                      RD, /*DeclIsField*/ false);
14361       }
14362     }
14363   }
14364 
14365   return HasInvalidParm;
14366 }
14367 
14368 Optional<std::pair<CharUnits, CharUnits>>
14369 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14370 
14371 /// Compute the alignment and offset of the base class object given the
14372 /// derived-to-base cast expression and the alignment and offset of the derived
14373 /// class object.
14374 static std::pair<CharUnits, CharUnits>
14375 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14376                                    CharUnits BaseAlignment, CharUnits Offset,
14377                                    ASTContext &Ctx) {
14378   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14379        ++PathI) {
14380     const CXXBaseSpecifier *Base = *PathI;
14381     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14382     if (Base->isVirtual()) {
14383       // The complete object may have a lower alignment than the non-virtual
14384       // alignment of the base, in which case the base may be misaligned. Choose
14385       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14386       // conservative lower bound of the complete object alignment.
14387       CharUnits NonVirtualAlignment =
14388           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14389       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14390       Offset = CharUnits::Zero();
14391     } else {
14392       const ASTRecordLayout &RL =
14393           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14394       Offset += RL.getBaseClassOffset(BaseDecl);
14395     }
14396     DerivedType = Base->getType();
14397   }
14398 
14399   return std::make_pair(BaseAlignment, Offset);
14400 }
14401 
14402 /// Compute the alignment and offset of a binary additive operator.
14403 static Optional<std::pair<CharUnits, CharUnits>>
14404 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14405                                      bool IsSub, ASTContext &Ctx) {
14406   QualType PointeeType = PtrE->getType()->getPointeeType();
14407 
14408   if (!PointeeType->isConstantSizeType())
14409     return llvm::None;
14410 
14411   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14412 
14413   if (!P)
14414     return llvm::None;
14415 
14416   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14417   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14418     CharUnits Offset = EltSize * IdxRes->getExtValue();
14419     if (IsSub)
14420       Offset = -Offset;
14421     return std::make_pair(P->first, P->second + Offset);
14422   }
14423 
14424   // If the integer expression isn't a constant expression, compute the lower
14425   // bound of the alignment using the alignment and offset of the pointer
14426   // expression and the element size.
14427   return std::make_pair(
14428       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14429       CharUnits::Zero());
14430 }
14431 
14432 /// This helper function takes an lvalue expression and returns the alignment of
14433 /// a VarDecl and a constant offset from the VarDecl.
14434 Optional<std::pair<CharUnits, CharUnits>>
14435 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14436   E = E->IgnoreParens();
14437   switch (E->getStmtClass()) {
14438   default:
14439     break;
14440   case Stmt::CStyleCastExprClass:
14441   case Stmt::CXXStaticCastExprClass:
14442   case Stmt::ImplicitCastExprClass: {
14443     auto *CE = cast<CastExpr>(E);
14444     const Expr *From = CE->getSubExpr();
14445     switch (CE->getCastKind()) {
14446     default:
14447       break;
14448     case CK_NoOp:
14449       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14450     case CK_UncheckedDerivedToBase:
14451     case CK_DerivedToBase: {
14452       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14453       if (!P)
14454         break;
14455       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14456                                                 P->second, Ctx);
14457     }
14458     }
14459     break;
14460   }
14461   case Stmt::ArraySubscriptExprClass: {
14462     auto *ASE = cast<ArraySubscriptExpr>(E);
14463     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14464                                                 false, Ctx);
14465   }
14466   case Stmt::DeclRefExprClass: {
14467     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14468       // FIXME: If VD is captured by copy or is an escaping __block variable,
14469       // use the alignment of VD's type.
14470       if (!VD->getType()->isReferenceType())
14471         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14472       if (VD->hasInit())
14473         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14474     }
14475     break;
14476   }
14477   case Stmt::MemberExprClass: {
14478     auto *ME = cast<MemberExpr>(E);
14479     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14480     if (!FD || FD->getType()->isReferenceType() ||
14481         FD->getParent()->isInvalidDecl())
14482       break;
14483     Optional<std::pair<CharUnits, CharUnits>> P;
14484     if (ME->isArrow())
14485       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14486     else
14487       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14488     if (!P)
14489       break;
14490     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14491     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14492     return std::make_pair(P->first,
14493                           P->second + CharUnits::fromQuantity(Offset));
14494   }
14495   case Stmt::UnaryOperatorClass: {
14496     auto *UO = cast<UnaryOperator>(E);
14497     switch (UO->getOpcode()) {
14498     default:
14499       break;
14500     case UO_Deref:
14501       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14502     }
14503     break;
14504   }
14505   case Stmt::BinaryOperatorClass: {
14506     auto *BO = cast<BinaryOperator>(E);
14507     auto Opcode = BO->getOpcode();
14508     switch (Opcode) {
14509     default:
14510       break;
14511     case BO_Comma:
14512       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14513     }
14514     break;
14515   }
14516   }
14517   return llvm::None;
14518 }
14519 
14520 /// This helper function takes a pointer expression and returns the alignment of
14521 /// a VarDecl and a constant offset from the VarDecl.
14522 Optional<std::pair<CharUnits, CharUnits>>
14523 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14524   E = E->IgnoreParens();
14525   switch (E->getStmtClass()) {
14526   default:
14527     break;
14528   case Stmt::CStyleCastExprClass:
14529   case Stmt::CXXStaticCastExprClass:
14530   case Stmt::ImplicitCastExprClass: {
14531     auto *CE = cast<CastExpr>(E);
14532     const Expr *From = CE->getSubExpr();
14533     switch (CE->getCastKind()) {
14534     default:
14535       break;
14536     case CK_NoOp:
14537       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14538     case CK_ArrayToPointerDecay:
14539       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14540     case CK_UncheckedDerivedToBase:
14541     case CK_DerivedToBase: {
14542       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14543       if (!P)
14544         break;
14545       return getDerivedToBaseAlignmentAndOffset(
14546           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14547     }
14548     }
14549     break;
14550   }
14551   case Stmt::CXXThisExprClass: {
14552     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14553     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14554     return std::make_pair(Alignment, CharUnits::Zero());
14555   }
14556   case Stmt::UnaryOperatorClass: {
14557     auto *UO = cast<UnaryOperator>(E);
14558     if (UO->getOpcode() == UO_AddrOf)
14559       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14560     break;
14561   }
14562   case Stmt::BinaryOperatorClass: {
14563     auto *BO = cast<BinaryOperator>(E);
14564     auto Opcode = BO->getOpcode();
14565     switch (Opcode) {
14566     default:
14567       break;
14568     case BO_Add:
14569     case BO_Sub: {
14570       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14571       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14572         std::swap(LHS, RHS);
14573       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14574                                                   Ctx);
14575     }
14576     case BO_Comma:
14577       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14578     }
14579     break;
14580   }
14581   }
14582   return llvm::None;
14583 }
14584 
14585 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14586   // See if we can compute the alignment of a VarDecl and an offset from it.
14587   Optional<std::pair<CharUnits, CharUnits>> P =
14588       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14589 
14590   if (P)
14591     return P->first.alignmentAtOffset(P->second);
14592 
14593   // If that failed, return the type's alignment.
14594   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14595 }
14596 
14597 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14598 /// pointer cast increases the alignment requirements.
14599 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14600   // This is actually a lot of work to potentially be doing on every
14601   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14602   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14603     return;
14604 
14605   // Ignore dependent types.
14606   if (T->isDependentType() || Op->getType()->isDependentType())
14607     return;
14608 
14609   // Require that the destination be a pointer type.
14610   const PointerType *DestPtr = T->getAs<PointerType>();
14611   if (!DestPtr) return;
14612 
14613   // If the destination has alignment 1, we're done.
14614   QualType DestPointee = DestPtr->getPointeeType();
14615   if (DestPointee->isIncompleteType()) return;
14616   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14617   if (DestAlign.isOne()) return;
14618 
14619   // Require that the source be a pointer type.
14620   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14621   if (!SrcPtr) return;
14622   QualType SrcPointee = SrcPtr->getPointeeType();
14623 
14624   // Explicitly allow casts from cv void*.  We already implicitly
14625   // allowed casts to cv void*, since they have alignment 1.
14626   // Also allow casts involving incomplete types, which implicitly
14627   // includes 'void'.
14628   if (SrcPointee->isIncompleteType()) return;
14629 
14630   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14631 
14632   if (SrcAlign >= DestAlign) return;
14633 
14634   Diag(TRange.getBegin(), diag::warn_cast_align)
14635     << Op->getType() << T
14636     << static_cast<unsigned>(SrcAlign.getQuantity())
14637     << static_cast<unsigned>(DestAlign.getQuantity())
14638     << TRange << Op->getSourceRange();
14639 }
14640 
14641 /// Check whether this array fits the idiom of a size-one tail padded
14642 /// array member of a struct.
14643 ///
14644 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14645 /// commonly used to emulate flexible arrays in C89 code.
14646 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14647                                     const NamedDecl *ND) {
14648   if (Size != 1 || !ND) return false;
14649 
14650   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14651   if (!FD) return false;
14652 
14653   // Don't consider sizes resulting from macro expansions or template argument
14654   // substitution to form C89 tail-padded arrays.
14655 
14656   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14657   while (TInfo) {
14658     TypeLoc TL = TInfo->getTypeLoc();
14659     // Look through typedefs.
14660     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14661       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14662       TInfo = TDL->getTypeSourceInfo();
14663       continue;
14664     }
14665     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14666       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14667       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14668         return false;
14669     }
14670     break;
14671   }
14672 
14673   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14674   if (!RD) return false;
14675   if (RD->isUnion()) return false;
14676   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14677     if (!CRD->isStandardLayout()) return false;
14678   }
14679 
14680   // See if this is the last field decl in the record.
14681   const Decl *D = FD;
14682   while ((D = D->getNextDeclInContext()))
14683     if (isa<FieldDecl>(D))
14684       return false;
14685   return true;
14686 }
14687 
14688 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14689                             const ArraySubscriptExpr *ASE,
14690                             bool AllowOnePastEnd, bool IndexNegated) {
14691   // Already diagnosed by the constant evaluator.
14692   if (isConstantEvaluated())
14693     return;
14694 
14695   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14696   if (IndexExpr->isValueDependent())
14697     return;
14698 
14699   const Type *EffectiveType =
14700       BaseExpr->getType()->getPointeeOrArrayElementType();
14701   BaseExpr = BaseExpr->IgnoreParenCasts();
14702   const ConstantArrayType *ArrayTy =
14703       Context.getAsConstantArrayType(BaseExpr->getType());
14704 
14705   const Type *BaseType =
14706       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14707   bool IsUnboundedArray = (BaseType == nullptr);
14708   if (EffectiveType->isDependentType() ||
14709       (!IsUnboundedArray && BaseType->isDependentType()))
14710     return;
14711 
14712   Expr::EvalResult Result;
14713   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14714     return;
14715 
14716   llvm::APSInt index = Result.Val.getInt();
14717   if (IndexNegated) {
14718     index.setIsUnsigned(false);
14719     index = -index;
14720   }
14721 
14722   const NamedDecl *ND = nullptr;
14723   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14724     ND = DRE->getDecl();
14725   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14726     ND = ME->getMemberDecl();
14727 
14728   if (IsUnboundedArray) {
14729     if (index.isUnsigned() || !index.isNegative()) {
14730       const auto &ASTC = getASTContext();
14731       unsigned AddrBits =
14732           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
14733               EffectiveType->getCanonicalTypeInternal()));
14734       if (index.getBitWidth() < AddrBits)
14735         index = index.zext(AddrBits);
14736       Optional<CharUnits> ElemCharUnits =
14737           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14738       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14739       // pointer) bounds-checking isn't meaningful.
14740       if (!ElemCharUnits)
14741         return;
14742       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14743       // If index has more active bits than address space, we already know
14744       // we have a bounds violation to warn about.  Otherwise, compute
14745       // address of (index + 1)th element, and warn about bounds violation
14746       // only if that address exceeds address space.
14747       if (index.getActiveBits() <= AddrBits) {
14748         bool Overflow;
14749         llvm::APInt Product(index);
14750         Product += 1;
14751         Product = Product.umul_ov(ElemBytes, Overflow);
14752         if (!Overflow && Product.getActiveBits() <= AddrBits)
14753           return;
14754       }
14755 
14756       // Need to compute max possible elements in address space, since that
14757       // is included in diag message.
14758       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
14759       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
14760       MaxElems += 1;
14761       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
14762       MaxElems = MaxElems.udiv(ElemBytes);
14763 
14764       unsigned DiagID =
14765           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
14766               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
14767 
14768       // Diag message shows element size in bits and in "bytes" (platform-
14769       // dependent CharUnits)
14770       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14771                           PDiag(DiagID)
14772                               << toString(index, 10, true) << AddrBits
14773                               << (unsigned)ASTC.toBits(*ElemCharUnits)
14774                               << toString(ElemBytes, 10, false)
14775                               << toString(MaxElems, 10, false)
14776                               << (unsigned)MaxElems.getLimitedValue(~0U)
14777                               << IndexExpr->getSourceRange());
14778 
14779       if (!ND) {
14780         // Try harder to find a NamedDecl to point at in the note.
14781         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14782           BaseExpr = ASE->getBase()->IgnoreParenCasts();
14783         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14784           ND = DRE->getDecl();
14785         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14786           ND = ME->getMemberDecl();
14787       }
14788 
14789       if (ND)
14790         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14791                             PDiag(diag::note_array_declared_here) << ND);
14792     }
14793     return;
14794   }
14795 
14796   if (index.isUnsigned() || !index.isNegative()) {
14797     // It is possible that the type of the base expression after
14798     // IgnoreParenCasts is incomplete, even though the type of the base
14799     // expression before IgnoreParenCasts is complete (see PR39746 for an
14800     // example). In this case we have no information about whether the array
14801     // access exceeds the array bounds. However we can still diagnose an array
14802     // access which precedes the array bounds.
14803     if (BaseType->isIncompleteType())
14804       return;
14805 
14806     llvm::APInt size = ArrayTy->getSize();
14807     if (!size.isStrictlyPositive())
14808       return;
14809 
14810     if (BaseType != EffectiveType) {
14811       // Make sure we're comparing apples to apples when comparing index to size
14812       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14813       uint64_t array_typesize = Context.getTypeSize(BaseType);
14814       // Handle ptrarith_typesize being zero, such as when casting to void*
14815       if (!ptrarith_typesize) ptrarith_typesize = 1;
14816       if (ptrarith_typesize != array_typesize) {
14817         // There's a cast to a different size type involved
14818         uint64_t ratio = array_typesize / ptrarith_typesize;
14819         // TODO: Be smarter about handling cases where array_typesize is not a
14820         // multiple of ptrarith_typesize
14821         if (ptrarith_typesize * ratio == array_typesize)
14822           size *= llvm::APInt(size.getBitWidth(), ratio);
14823       }
14824     }
14825 
14826     if (size.getBitWidth() > index.getBitWidth())
14827       index = index.zext(size.getBitWidth());
14828     else if (size.getBitWidth() < index.getBitWidth())
14829       size = size.zext(index.getBitWidth());
14830 
14831     // For array subscripting the index must be less than size, but for pointer
14832     // arithmetic also allow the index (offset) to be equal to size since
14833     // computing the next address after the end of the array is legal and
14834     // commonly done e.g. in C++ iterators and range-based for loops.
14835     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14836       return;
14837 
14838     // Also don't warn for arrays of size 1 which are members of some
14839     // structure. These are often used to approximate flexible arrays in C89
14840     // code.
14841     if (IsTailPaddedMemberArray(*this, size, ND))
14842       return;
14843 
14844     // Suppress the warning if the subscript expression (as identified by the
14845     // ']' location) and the index expression are both from macro expansions
14846     // within a system header.
14847     if (ASE) {
14848       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14849           ASE->getRBracketLoc());
14850       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14851         SourceLocation IndexLoc =
14852             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14853         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14854           return;
14855       }
14856     }
14857 
14858     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
14859                           : diag::warn_ptr_arith_exceeds_bounds;
14860 
14861     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14862                         PDiag(DiagID) << toString(index, 10, true)
14863                                       << toString(size, 10, true)
14864                                       << (unsigned)size.getLimitedValue(~0U)
14865                                       << IndexExpr->getSourceRange());
14866   } else {
14867     unsigned DiagID = diag::warn_array_index_precedes_bounds;
14868     if (!ASE) {
14869       DiagID = diag::warn_ptr_arith_precedes_bounds;
14870       if (index.isNegative()) index = -index;
14871     }
14872 
14873     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14874                         PDiag(DiagID) << toString(index, 10, true)
14875                                       << IndexExpr->getSourceRange());
14876   }
14877 
14878   if (!ND) {
14879     // Try harder to find a NamedDecl to point at in the note.
14880     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14881       BaseExpr = ASE->getBase()->IgnoreParenCasts();
14882     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14883       ND = DRE->getDecl();
14884     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14885       ND = ME->getMemberDecl();
14886   }
14887 
14888   if (ND)
14889     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14890                         PDiag(diag::note_array_declared_here) << ND);
14891 }
14892 
14893 void Sema::CheckArrayAccess(const Expr *expr) {
14894   int AllowOnePastEnd = 0;
14895   while (expr) {
14896     expr = expr->IgnoreParenImpCasts();
14897     switch (expr->getStmtClass()) {
14898       case Stmt::ArraySubscriptExprClass: {
14899         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
14900         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
14901                          AllowOnePastEnd > 0);
14902         expr = ASE->getBase();
14903         break;
14904       }
14905       case Stmt::MemberExprClass: {
14906         expr = cast<MemberExpr>(expr)->getBase();
14907         break;
14908       }
14909       case Stmt::OMPArraySectionExprClass: {
14910         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
14911         if (ASE->getLowerBound())
14912           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
14913                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
14914         return;
14915       }
14916       case Stmt::UnaryOperatorClass: {
14917         // Only unwrap the * and & unary operators
14918         const UnaryOperator *UO = cast<UnaryOperator>(expr);
14919         expr = UO->getSubExpr();
14920         switch (UO->getOpcode()) {
14921           case UO_AddrOf:
14922             AllowOnePastEnd++;
14923             break;
14924           case UO_Deref:
14925             AllowOnePastEnd--;
14926             break;
14927           default:
14928             return;
14929         }
14930         break;
14931       }
14932       case Stmt::ConditionalOperatorClass: {
14933         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
14934         if (const Expr *lhs = cond->getLHS())
14935           CheckArrayAccess(lhs);
14936         if (const Expr *rhs = cond->getRHS())
14937           CheckArrayAccess(rhs);
14938         return;
14939       }
14940       case Stmt::CXXOperatorCallExprClass: {
14941         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
14942         for (const auto *Arg : OCE->arguments())
14943           CheckArrayAccess(Arg);
14944         return;
14945       }
14946       default:
14947         return;
14948     }
14949   }
14950 }
14951 
14952 //===--- CHECK: Objective-C retain cycles ----------------------------------//
14953 
14954 namespace {
14955 
14956 struct RetainCycleOwner {
14957   VarDecl *Variable = nullptr;
14958   SourceRange Range;
14959   SourceLocation Loc;
14960   bool Indirect = false;
14961 
14962   RetainCycleOwner() = default;
14963 
14964   void setLocsFrom(Expr *e) {
14965     Loc = e->getExprLoc();
14966     Range = e->getSourceRange();
14967   }
14968 };
14969 
14970 } // namespace
14971 
14972 /// Consider whether capturing the given variable can possibly lead to
14973 /// a retain cycle.
14974 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
14975   // In ARC, it's captured strongly iff the variable has __strong
14976   // lifetime.  In MRR, it's captured strongly if the variable is
14977   // __block and has an appropriate type.
14978   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14979     return false;
14980 
14981   owner.Variable = var;
14982   if (ref)
14983     owner.setLocsFrom(ref);
14984   return true;
14985 }
14986 
14987 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
14988   while (true) {
14989     e = e->IgnoreParens();
14990     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
14991       switch (cast->getCastKind()) {
14992       case CK_BitCast:
14993       case CK_LValueBitCast:
14994       case CK_LValueToRValue:
14995       case CK_ARCReclaimReturnedObject:
14996         e = cast->getSubExpr();
14997         continue;
14998 
14999       default:
15000         return false;
15001       }
15002     }
15003 
15004     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15005       ObjCIvarDecl *ivar = ref->getDecl();
15006       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15007         return false;
15008 
15009       // Try to find a retain cycle in the base.
15010       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15011         return false;
15012 
15013       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15014       owner.Indirect = true;
15015       return true;
15016     }
15017 
15018     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15019       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15020       if (!var) return false;
15021       return considerVariable(var, ref, owner);
15022     }
15023 
15024     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15025       if (member->isArrow()) return false;
15026 
15027       // Don't count this as an indirect ownership.
15028       e = member->getBase();
15029       continue;
15030     }
15031 
15032     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15033       // Only pay attention to pseudo-objects on property references.
15034       ObjCPropertyRefExpr *pre
15035         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15036                                               ->IgnoreParens());
15037       if (!pre) return false;
15038       if (pre->isImplicitProperty()) return false;
15039       ObjCPropertyDecl *property = pre->getExplicitProperty();
15040       if (!property->isRetaining() &&
15041           !(property->getPropertyIvarDecl() &&
15042             property->getPropertyIvarDecl()->getType()
15043               .getObjCLifetime() == Qualifiers::OCL_Strong))
15044           return false;
15045 
15046       owner.Indirect = true;
15047       if (pre->isSuperReceiver()) {
15048         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15049         if (!owner.Variable)
15050           return false;
15051         owner.Loc = pre->getLocation();
15052         owner.Range = pre->getSourceRange();
15053         return true;
15054       }
15055       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15056                               ->getSourceExpr());
15057       continue;
15058     }
15059 
15060     // Array ivars?
15061 
15062     return false;
15063   }
15064 }
15065 
15066 namespace {
15067 
15068   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15069     ASTContext &Context;
15070     VarDecl *Variable;
15071     Expr *Capturer = nullptr;
15072     bool VarWillBeReased = false;
15073 
15074     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15075         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15076           Context(Context), Variable(variable) {}
15077 
15078     void VisitDeclRefExpr(DeclRefExpr *ref) {
15079       if (ref->getDecl() == Variable && !Capturer)
15080         Capturer = ref;
15081     }
15082 
15083     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15084       if (Capturer) return;
15085       Visit(ref->getBase());
15086       if (Capturer && ref->isFreeIvar())
15087         Capturer = ref;
15088     }
15089 
15090     void VisitBlockExpr(BlockExpr *block) {
15091       // Look inside nested blocks
15092       if (block->getBlockDecl()->capturesVariable(Variable))
15093         Visit(block->getBlockDecl()->getBody());
15094     }
15095 
15096     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15097       if (Capturer) return;
15098       if (OVE->getSourceExpr())
15099         Visit(OVE->getSourceExpr());
15100     }
15101 
15102     void VisitBinaryOperator(BinaryOperator *BinOp) {
15103       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15104         return;
15105       Expr *LHS = BinOp->getLHS();
15106       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15107         if (DRE->getDecl() != Variable)
15108           return;
15109         if (Expr *RHS = BinOp->getRHS()) {
15110           RHS = RHS->IgnoreParenCasts();
15111           Optional<llvm::APSInt> Value;
15112           VarWillBeReased =
15113               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15114                *Value == 0);
15115         }
15116       }
15117     }
15118   };
15119 
15120 } // namespace
15121 
15122 /// Check whether the given argument is a block which captures a
15123 /// variable.
15124 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15125   assert(owner.Variable && owner.Loc.isValid());
15126 
15127   e = e->IgnoreParenCasts();
15128 
15129   // Look through [^{...} copy] and Block_copy(^{...}).
15130   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15131     Selector Cmd = ME->getSelector();
15132     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15133       e = ME->getInstanceReceiver();
15134       if (!e)
15135         return nullptr;
15136       e = e->IgnoreParenCasts();
15137     }
15138   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15139     if (CE->getNumArgs() == 1) {
15140       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15141       if (Fn) {
15142         const IdentifierInfo *FnI = Fn->getIdentifier();
15143         if (FnI && FnI->isStr("_Block_copy")) {
15144           e = CE->getArg(0)->IgnoreParenCasts();
15145         }
15146       }
15147     }
15148   }
15149 
15150   BlockExpr *block = dyn_cast<BlockExpr>(e);
15151   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15152     return nullptr;
15153 
15154   FindCaptureVisitor visitor(S.Context, owner.Variable);
15155   visitor.Visit(block->getBlockDecl()->getBody());
15156   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15157 }
15158 
15159 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15160                                 RetainCycleOwner &owner) {
15161   assert(capturer);
15162   assert(owner.Variable && owner.Loc.isValid());
15163 
15164   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15165     << owner.Variable << capturer->getSourceRange();
15166   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15167     << owner.Indirect << owner.Range;
15168 }
15169 
15170 /// Check for a keyword selector that starts with the word 'add' or
15171 /// 'set'.
15172 static bool isSetterLikeSelector(Selector sel) {
15173   if (sel.isUnarySelector()) return false;
15174 
15175   StringRef str = sel.getNameForSlot(0);
15176   while (!str.empty() && str.front() == '_') str = str.substr(1);
15177   if (str.startswith("set"))
15178     str = str.substr(3);
15179   else if (str.startswith("add")) {
15180     // Specially allow 'addOperationWithBlock:'.
15181     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15182       return false;
15183     str = str.substr(3);
15184   }
15185   else
15186     return false;
15187 
15188   if (str.empty()) return true;
15189   return !isLowercase(str.front());
15190 }
15191 
15192 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15193                                                     ObjCMessageExpr *Message) {
15194   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15195                                                 Message->getReceiverInterface(),
15196                                                 NSAPI::ClassId_NSMutableArray);
15197   if (!IsMutableArray) {
15198     return None;
15199   }
15200 
15201   Selector Sel = Message->getSelector();
15202 
15203   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15204     S.NSAPIObj->getNSArrayMethodKind(Sel);
15205   if (!MKOpt) {
15206     return None;
15207   }
15208 
15209   NSAPI::NSArrayMethodKind MK = *MKOpt;
15210 
15211   switch (MK) {
15212     case NSAPI::NSMutableArr_addObject:
15213     case NSAPI::NSMutableArr_insertObjectAtIndex:
15214     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15215       return 0;
15216     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15217       return 1;
15218 
15219     default:
15220       return None;
15221   }
15222 
15223   return None;
15224 }
15225 
15226 static
15227 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15228                                                   ObjCMessageExpr *Message) {
15229   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15230                                             Message->getReceiverInterface(),
15231                                             NSAPI::ClassId_NSMutableDictionary);
15232   if (!IsMutableDictionary) {
15233     return None;
15234   }
15235 
15236   Selector Sel = Message->getSelector();
15237 
15238   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15239     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15240   if (!MKOpt) {
15241     return None;
15242   }
15243 
15244   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15245 
15246   switch (MK) {
15247     case NSAPI::NSMutableDict_setObjectForKey:
15248     case NSAPI::NSMutableDict_setValueForKey:
15249     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15250       return 0;
15251 
15252     default:
15253       return None;
15254   }
15255 
15256   return None;
15257 }
15258 
15259 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15260   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15261                                                 Message->getReceiverInterface(),
15262                                                 NSAPI::ClassId_NSMutableSet);
15263 
15264   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15265                                             Message->getReceiverInterface(),
15266                                             NSAPI::ClassId_NSMutableOrderedSet);
15267   if (!IsMutableSet && !IsMutableOrderedSet) {
15268     return None;
15269   }
15270 
15271   Selector Sel = Message->getSelector();
15272 
15273   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15274   if (!MKOpt) {
15275     return None;
15276   }
15277 
15278   NSAPI::NSSetMethodKind MK = *MKOpt;
15279 
15280   switch (MK) {
15281     case NSAPI::NSMutableSet_addObject:
15282     case NSAPI::NSOrderedSet_setObjectAtIndex:
15283     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15284     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15285       return 0;
15286     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15287       return 1;
15288   }
15289 
15290   return None;
15291 }
15292 
15293 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15294   if (!Message->isInstanceMessage()) {
15295     return;
15296   }
15297 
15298   Optional<int> ArgOpt;
15299 
15300   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15301       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15302       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15303     return;
15304   }
15305 
15306   int ArgIndex = *ArgOpt;
15307 
15308   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15309   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15310     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15311   }
15312 
15313   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15314     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15315       if (ArgRE->isObjCSelfExpr()) {
15316         Diag(Message->getSourceRange().getBegin(),
15317              diag::warn_objc_circular_container)
15318           << ArgRE->getDecl() << StringRef("'super'");
15319       }
15320     }
15321   } else {
15322     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15323 
15324     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15325       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15326     }
15327 
15328     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15329       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15330         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15331           ValueDecl *Decl = ReceiverRE->getDecl();
15332           Diag(Message->getSourceRange().getBegin(),
15333                diag::warn_objc_circular_container)
15334             << Decl << Decl;
15335           if (!ArgRE->isObjCSelfExpr()) {
15336             Diag(Decl->getLocation(),
15337                  diag::note_objc_circular_container_declared_here)
15338               << Decl;
15339           }
15340         }
15341       }
15342     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15343       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15344         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15345           ObjCIvarDecl *Decl = IvarRE->getDecl();
15346           Diag(Message->getSourceRange().getBegin(),
15347                diag::warn_objc_circular_container)
15348             << Decl << Decl;
15349           Diag(Decl->getLocation(),
15350                diag::note_objc_circular_container_declared_here)
15351             << Decl;
15352         }
15353       }
15354     }
15355   }
15356 }
15357 
15358 /// Check a message send to see if it's likely to cause a retain cycle.
15359 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15360   // Only check instance methods whose selector looks like a setter.
15361   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15362     return;
15363 
15364   // Try to find a variable that the receiver is strongly owned by.
15365   RetainCycleOwner owner;
15366   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15367     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15368       return;
15369   } else {
15370     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15371     owner.Variable = getCurMethodDecl()->getSelfDecl();
15372     owner.Loc = msg->getSuperLoc();
15373     owner.Range = msg->getSuperLoc();
15374   }
15375 
15376   // Check whether the receiver is captured by any of the arguments.
15377   const ObjCMethodDecl *MD = msg->getMethodDecl();
15378   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15379     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15380       // noescape blocks should not be retained by the method.
15381       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15382         continue;
15383       return diagnoseRetainCycle(*this, capturer, owner);
15384     }
15385   }
15386 }
15387 
15388 /// Check a property assign to see if it's likely to cause a retain cycle.
15389 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15390   RetainCycleOwner owner;
15391   if (!findRetainCycleOwner(*this, receiver, owner))
15392     return;
15393 
15394   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15395     diagnoseRetainCycle(*this, capturer, owner);
15396 }
15397 
15398 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15399   RetainCycleOwner Owner;
15400   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15401     return;
15402 
15403   // Because we don't have an expression for the variable, we have to set the
15404   // location explicitly here.
15405   Owner.Loc = Var->getLocation();
15406   Owner.Range = Var->getSourceRange();
15407 
15408   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15409     diagnoseRetainCycle(*this, Capturer, Owner);
15410 }
15411 
15412 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15413                                      Expr *RHS, bool isProperty) {
15414   // Check if RHS is an Objective-C object literal, which also can get
15415   // immediately zapped in a weak reference.  Note that we explicitly
15416   // allow ObjCStringLiterals, since those are designed to never really die.
15417   RHS = RHS->IgnoreParenImpCasts();
15418 
15419   // This enum needs to match with the 'select' in
15420   // warn_objc_arc_literal_assign (off-by-1).
15421   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15422   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15423     return false;
15424 
15425   S.Diag(Loc, diag::warn_arc_literal_assign)
15426     << (unsigned) Kind
15427     << (isProperty ? 0 : 1)
15428     << RHS->getSourceRange();
15429 
15430   return true;
15431 }
15432 
15433 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15434                                     Qualifiers::ObjCLifetime LT,
15435                                     Expr *RHS, bool isProperty) {
15436   // Strip off any implicit cast added to get to the one ARC-specific.
15437   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15438     if (cast->getCastKind() == CK_ARCConsumeObject) {
15439       S.Diag(Loc, diag::warn_arc_retained_assign)
15440         << (LT == Qualifiers::OCL_ExplicitNone)
15441         << (isProperty ? 0 : 1)
15442         << RHS->getSourceRange();
15443       return true;
15444     }
15445     RHS = cast->getSubExpr();
15446   }
15447 
15448   if (LT == Qualifiers::OCL_Weak &&
15449       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15450     return true;
15451 
15452   return false;
15453 }
15454 
15455 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15456                               QualType LHS, Expr *RHS) {
15457   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15458 
15459   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15460     return false;
15461 
15462   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15463     return true;
15464 
15465   return false;
15466 }
15467 
15468 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15469                               Expr *LHS, Expr *RHS) {
15470   QualType LHSType;
15471   // PropertyRef on LHS type need be directly obtained from
15472   // its declaration as it has a PseudoType.
15473   ObjCPropertyRefExpr *PRE
15474     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15475   if (PRE && !PRE->isImplicitProperty()) {
15476     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15477     if (PD)
15478       LHSType = PD->getType();
15479   }
15480 
15481   if (LHSType.isNull())
15482     LHSType = LHS->getType();
15483 
15484   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15485 
15486   if (LT == Qualifiers::OCL_Weak) {
15487     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15488       getCurFunction()->markSafeWeakUse(LHS);
15489   }
15490 
15491   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15492     return;
15493 
15494   // FIXME. Check for other life times.
15495   if (LT != Qualifiers::OCL_None)
15496     return;
15497 
15498   if (PRE) {
15499     if (PRE->isImplicitProperty())
15500       return;
15501     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15502     if (!PD)
15503       return;
15504 
15505     unsigned Attributes = PD->getPropertyAttributes();
15506     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15507       // when 'assign' attribute was not explicitly specified
15508       // by user, ignore it and rely on property type itself
15509       // for lifetime info.
15510       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15511       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15512           LHSType->isObjCRetainableType())
15513         return;
15514 
15515       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15516         if (cast->getCastKind() == CK_ARCConsumeObject) {
15517           Diag(Loc, diag::warn_arc_retained_property_assign)
15518           << RHS->getSourceRange();
15519           return;
15520         }
15521         RHS = cast->getSubExpr();
15522       }
15523     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15524       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15525         return;
15526     }
15527   }
15528 }
15529 
15530 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15531 
15532 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15533                                         SourceLocation StmtLoc,
15534                                         const NullStmt *Body) {
15535   // Do not warn if the body is a macro that expands to nothing, e.g:
15536   //
15537   // #define CALL(x)
15538   // if (condition)
15539   //   CALL(0);
15540   if (Body->hasLeadingEmptyMacro())
15541     return false;
15542 
15543   // Get line numbers of statement and body.
15544   bool StmtLineInvalid;
15545   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15546                                                       &StmtLineInvalid);
15547   if (StmtLineInvalid)
15548     return false;
15549 
15550   bool BodyLineInvalid;
15551   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15552                                                       &BodyLineInvalid);
15553   if (BodyLineInvalid)
15554     return false;
15555 
15556   // Warn if null statement and body are on the same line.
15557   if (StmtLine != BodyLine)
15558     return false;
15559 
15560   return true;
15561 }
15562 
15563 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15564                                  const Stmt *Body,
15565                                  unsigned DiagID) {
15566   // Since this is a syntactic check, don't emit diagnostic for template
15567   // instantiations, this just adds noise.
15568   if (CurrentInstantiationScope)
15569     return;
15570 
15571   // The body should be a null statement.
15572   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15573   if (!NBody)
15574     return;
15575 
15576   // Do the usual checks.
15577   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15578     return;
15579 
15580   Diag(NBody->getSemiLoc(), DiagID);
15581   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15582 }
15583 
15584 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15585                                  const Stmt *PossibleBody) {
15586   assert(!CurrentInstantiationScope); // Ensured by caller
15587 
15588   SourceLocation StmtLoc;
15589   const Stmt *Body;
15590   unsigned DiagID;
15591   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15592     StmtLoc = FS->getRParenLoc();
15593     Body = FS->getBody();
15594     DiagID = diag::warn_empty_for_body;
15595   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15596     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15597     Body = WS->getBody();
15598     DiagID = diag::warn_empty_while_body;
15599   } else
15600     return; // Neither `for' nor `while'.
15601 
15602   // The body should be a null statement.
15603   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15604   if (!NBody)
15605     return;
15606 
15607   // Skip expensive checks if diagnostic is disabled.
15608   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15609     return;
15610 
15611   // Do the usual checks.
15612   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15613     return;
15614 
15615   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15616   // noise level low, emit diagnostics only if for/while is followed by a
15617   // CompoundStmt, e.g.:
15618   //    for (int i = 0; i < n; i++);
15619   //    {
15620   //      a(i);
15621   //    }
15622   // or if for/while is followed by a statement with more indentation
15623   // than for/while itself:
15624   //    for (int i = 0; i < n; i++);
15625   //      a(i);
15626   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15627   if (!ProbableTypo) {
15628     bool BodyColInvalid;
15629     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15630         PossibleBody->getBeginLoc(), &BodyColInvalid);
15631     if (BodyColInvalid)
15632       return;
15633 
15634     bool StmtColInvalid;
15635     unsigned StmtCol =
15636         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15637     if (StmtColInvalid)
15638       return;
15639 
15640     if (BodyCol > StmtCol)
15641       ProbableTypo = true;
15642   }
15643 
15644   if (ProbableTypo) {
15645     Diag(NBody->getSemiLoc(), DiagID);
15646     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15647   }
15648 }
15649 
15650 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15651 
15652 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15653 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15654                              SourceLocation OpLoc) {
15655   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15656     return;
15657 
15658   if (inTemplateInstantiation())
15659     return;
15660 
15661   // Strip parens and casts away.
15662   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15663   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15664 
15665   // Check for a call expression
15666   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15667   if (!CE || CE->getNumArgs() != 1)
15668     return;
15669 
15670   // Check for a call to std::move
15671   if (!CE->isCallToStdMove())
15672     return;
15673 
15674   // Get argument from std::move
15675   RHSExpr = CE->getArg(0);
15676 
15677   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15678   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15679 
15680   // Two DeclRefExpr's, check that the decls are the same.
15681   if (LHSDeclRef && RHSDeclRef) {
15682     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15683       return;
15684     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15685         RHSDeclRef->getDecl()->getCanonicalDecl())
15686       return;
15687 
15688     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15689                                         << LHSExpr->getSourceRange()
15690                                         << RHSExpr->getSourceRange();
15691     return;
15692   }
15693 
15694   // Member variables require a different approach to check for self moves.
15695   // MemberExpr's are the same if every nested MemberExpr refers to the same
15696   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15697   // the base Expr's are CXXThisExpr's.
15698   const Expr *LHSBase = LHSExpr;
15699   const Expr *RHSBase = RHSExpr;
15700   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15701   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15702   if (!LHSME || !RHSME)
15703     return;
15704 
15705   while (LHSME && RHSME) {
15706     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15707         RHSME->getMemberDecl()->getCanonicalDecl())
15708       return;
15709 
15710     LHSBase = LHSME->getBase();
15711     RHSBase = RHSME->getBase();
15712     LHSME = dyn_cast<MemberExpr>(LHSBase);
15713     RHSME = dyn_cast<MemberExpr>(RHSBase);
15714   }
15715 
15716   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15717   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15718   if (LHSDeclRef && RHSDeclRef) {
15719     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15720       return;
15721     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15722         RHSDeclRef->getDecl()->getCanonicalDecl())
15723       return;
15724 
15725     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15726                                         << LHSExpr->getSourceRange()
15727                                         << RHSExpr->getSourceRange();
15728     return;
15729   }
15730 
15731   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15732     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15733                                         << LHSExpr->getSourceRange()
15734                                         << RHSExpr->getSourceRange();
15735 }
15736 
15737 //===--- Layout compatibility ----------------------------------------------//
15738 
15739 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15740 
15741 /// Check if two enumeration types are layout-compatible.
15742 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15743   // C++11 [dcl.enum] p8:
15744   // Two enumeration types are layout-compatible if they have the same
15745   // underlying type.
15746   return ED1->isComplete() && ED2->isComplete() &&
15747          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15748 }
15749 
15750 /// Check if two fields are layout-compatible.
15751 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15752                                FieldDecl *Field2) {
15753   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15754     return false;
15755 
15756   if (Field1->isBitField() != Field2->isBitField())
15757     return false;
15758 
15759   if (Field1->isBitField()) {
15760     // Make sure that the bit-fields are the same length.
15761     unsigned Bits1 = Field1->getBitWidthValue(C);
15762     unsigned Bits2 = Field2->getBitWidthValue(C);
15763 
15764     if (Bits1 != Bits2)
15765       return false;
15766   }
15767 
15768   return true;
15769 }
15770 
15771 /// Check if two standard-layout structs are layout-compatible.
15772 /// (C++11 [class.mem] p17)
15773 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15774                                      RecordDecl *RD2) {
15775   // If both records are C++ classes, check that base classes match.
15776   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15777     // If one of records is a CXXRecordDecl we are in C++ mode,
15778     // thus the other one is a CXXRecordDecl, too.
15779     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15780     // Check number of base classes.
15781     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15782       return false;
15783 
15784     // Check the base classes.
15785     for (CXXRecordDecl::base_class_const_iterator
15786                Base1 = D1CXX->bases_begin(),
15787            BaseEnd1 = D1CXX->bases_end(),
15788               Base2 = D2CXX->bases_begin();
15789          Base1 != BaseEnd1;
15790          ++Base1, ++Base2) {
15791       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
15792         return false;
15793     }
15794   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
15795     // If only RD2 is a C++ class, it should have zero base classes.
15796     if (D2CXX->getNumBases() > 0)
15797       return false;
15798   }
15799 
15800   // Check the fields.
15801   RecordDecl::field_iterator Field2 = RD2->field_begin(),
15802                              Field2End = RD2->field_end(),
15803                              Field1 = RD1->field_begin(),
15804                              Field1End = RD1->field_end();
15805   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
15806     if (!isLayoutCompatible(C, *Field1, *Field2))
15807       return false;
15808   }
15809   if (Field1 != Field1End || Field2 != Field2End)
15810     return false;
15811 
15812   return true;
15813 }
15814 
15815 /// Check if two standard-layout unions are layout-compatible.
15816 /// (C++11 [class.mem] p18)
15817 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
15818                                     RecordDecl *RD2) {
15819   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
15820   for (auto *Field2 : RD2->fields())
15821     UnmatchedFields.insert(Field2);
15822 
15823   for (auto *Field1 : RD1->fields()) {
15824     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
15825         I = UnmatchedFields.begin(),
15826         E = UnmatchedFields.end();
15827 
15828     for ( ; I != E; ++I) {
15829       if (isLayoutCompatible(C, Field1, *I)) {
15830         bool Result = UnmatchedFields.erase(*I);
15831         (void) Result;
15832         assert(Result);
15833         break;
15834       }
15835     }
15836     if (I == E)
15837       return false;
15838   }
15839 
15840   return UnmatchedFields.empty();
15841 }
15842 
15843 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
15844                                RecordDecl *RD2) {
15845   if (RD1->isUnion() != RD2->isUnion())
15846     return false;
15847 
15848   if (RD1->isUnion())
15849     return isLayoutCompatibleUnion(C, RD1, RD2);
15850   else
15851     return isLayoutCompatibleStruct(C, RD1, RD2);
15852 }
15853 
15854 /// Check if two types are layout-compatible in C++11 sense.
15855 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
15856   if (T1.isNull() || T2.isNull())
15857     return false;
15858 
15859   // C++11 [basic.types] p11:
15860   // If two types T1 and T2 are the same type, then T1 and T2 are
15861   // layout-compatible types.
15862   if (C.hasSameType(T1, T2))
15863     return true;
15864 
15865   T1 = T1.getCanonicalType().getUnqualifiedType();
15866   T2 = T2.getCanonicalType().getUnqualifiedType();
15867 
15868   const Type::TypeClass TC1 = T1->getTypeClass();
15869   const Type::TypeClass TC2 = T2->getTypeClass();
15870 
15871   if (TC1 != TC2)
15872     return false;
15873 
15874   if (TC1 == Type::Enum) {
15875     return isLayoutCompatible(C,
15876                               cast<EnumType>(T1)->getDecl(),
15877                               cast<EnumType>(T2)->getDecl());
15878   } else if (TC1 == Type::Record) {
15879     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15880       return false;
15881 
15882     return isLayoutCompatible(C,
15883                               cast<RecordType>(T1)->getDecl(),
15884                               cast<RecordType>(T2)->getDecl());
15885   }
15886 
15887   return false;
15888 }
15889 
15890 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15891 
15892 /// Given a type tag expression find the type tag itself.
15893 ///
15894 /// \param TypeExpr Type tag expression, as it appears in user's code.
15895 ///
15896 /// \param VD Declaration of an identifier that appears in a type tag.
15897 ///
15898 /// \param MagicValue Type tag magic value.
15899 ///
15900 /// \param isConstantEvaluated wether the evalaution should be performed in
15901 
15902 /// constant context.
15903 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15904                             const ValueDecl **VD, uint64_t *MagicValue,
15905                             bool isConstantEvaluated) {
15906   while(true) {
15907     if (!TypeExpr)
15908       return false;
15909 
15910     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15911 
15912     switch (TypeExpr->getStmtClass()) {
15913     case Stmt::UnaryOperatorClass: {
15914       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15915       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15916         TypeExpr = UO->getSubExpr();
15917         continue;
15918       }
15919       return false;
15920     }
15921 
15922     case Stmt::DeclRefExprClass: {
15923       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15924       *VD = DRE->getDecl();
15925       return true;
15926     }
15927 
15928     case Stmt::IntegerLiteralClass: {
15929       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15930       llvm::APInt MagicValueAPInt = IL->getValue();
15931       if (MagicValueAPInt.getActiveBits() <= 64) {
15932         *MagicValue = MagicValueAPInt.getZExtValue();
15933         return true;
15934       } else
15935         return false;
15936     }
15937 
15938     case Stmt::BinaryConditionalOperatorClass:
15939     case Stmt::ConditionalOperatorClass: {
15940       const AbstractConditionalOperator *ACO =
15941           cast<AbstractConditionalOperator>(TypeExpr);
15942       bool Result;
15943       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15944                                                      isConstantEvaluated)) {
15945         if (Result)
15946           TypeExpr = ACO->getTrueExpr();
15947         else
15948           TypeExpr = ACO->getFalseExpr();
15949         continue;
15950       }
15951       return false;
15952     }
15953 
15954     case Stmt::BinaryOperatorClass: {
15955       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15956       if (BO->getOpcode() == BO_Comma) {
15957         TypeExpr = BO->getRHS();
15958         continue;
15959       }
15960       return false;
15961     }
15962 
15963     default:
15964       return false;
15965     }
15966   }
15967 }
15968 
15969 /// Retrieve the C type corresponding to type tag TypeExpr.
15970 ///
15971 /// \param TypeExpr Expression that specifies a type tag.
15972 ///
15973 /// \param MagicValues Registered magic values.
15974 ///
15975 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15976 ///        kind.
15977 ///
15978 /// \param TypeInfo Information about the corresponding C type.
15979 ///
15980 /// \param isConstantEvaluated wether the evalaution should be performed in
15981 /// constant context.
15982 ///
15983 /// \returns true if the corresponding C type was found.
15984 static bool GetMatchingCType(
15985     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15986     const ASTContext &Ctx,
15987     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15988         *MagicValues,
15989     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15990     bool isConstantEvaluated) {
15991   FoundWrongKind = false;
15992 
15993   // Variable declaration that has type_tag_for_datatype attribute.
15994   const ValueDecl *VD = nullptr;
15995 
15996   uint64_t MagicValue;
15997 
15998   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15999     return false;
16000 
16001   if (VD) {
16002     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16003       if (I->getArgumentKind() != ArgumentKind) {
16004         FoundWrongKind = true;
16005         return false;
16006       }
16007       TypeInfo.Type = I->getMatchingCType();
16008       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16009       TypeInfo.MustBeNull = I->getMustBeNull();
16010       return true;
16011     }
16012     return false;
16013   }
16014 
16015   if (!MagicValues)
16016     return false;
16017 
16018   llvm::DenseMap<Sema::TypeTagMagicValue,
16019                  Sema::TypeTagData>::const_iterator I =
16020       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16021   if (I == MagicValues->end())
16022     return false;
16023 
16024   TypeInfo = I->second;
16025   return true;
16026 }
16027 
16028 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16029                                       uint64_t MagicValue, QualType Type,
16030                                       bool LayoutCompatible,
16031                                       bool MustBeNull) {
16032   if (!TypeTagForDatatypeMagicValues)
16033     TypeTagForDatatypeMagicValues.reset(
16034         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16035 
16036   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16037   (*TypeTagForDatatypeMagicValues)[Magic] =
16038       TypeTagData(Type, LayoutCompatible, MustBeNull);
16039 }
16040 
16041 static bool IsSameCharType(QualType T1, QualType T2) {
16042   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16043   if (!BT1)
16044     return false;
16045 
16046   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16047   if (!BT2)
16048     return false;
16049 
16050   BuiltinType::Kind T1Kind = BT1->getKind();
16051   BuiltinType::Kind T2Kind = BT2->getKind();
16052 
16053   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16054          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16055          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16056          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16057 }
16058 
16059 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16060                                     const ArrayRef<const Expr *> ExprArgs,
16061                                     SourceLocation CallSiteLoc) {
16062   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16063   bool IsPointerAttr = Attr->getIsPointer();
16064 
16065   // Retrieve the argument representing the 'type_tag'.
16066   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16067   if (TypeTagIdxAST >= ExprArgs.size()) {
16068     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16069         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16070     return;
16071   }
16072   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16073   bool FoundWrongKind;
16074   TypeTagData TypeInfo;
16075   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16076                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16077                         TypeInfo, isConstantEvaluated())) {
16078     if (FoundWrongKind)
16079       Diag(TypeTagExpr->getExprLoc(),
16080            diag::warn_type_tag_for_datatype_wrong_kind)
16081         << TypeTagExpr->getSourceRange();
16082     return;
16083   }
16084 
16085   // Retrieve the argument representing the 'arg_idx'.
16086   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16087   if (ArgumentIdxAST >= ExprArgs.size()) {
16088     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16089         << 1 << Attr->getArgumentIdx().getSourceIndex();
16090     return;
16091   }
16092   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16093   if (IsPointerAttr) {
16094     // Skip implicit cast of pointer to `void *' (as a function argument).
16095     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16096       if (ICE->getType()->isVoidPointerType() &&
16097           ICE->getCastKind() == CK_BitCast)
16098         ArgumentExpr = ICE->getSubExpr();
16099   }
16100   QualType ArgumentType = ArgumentExpr->getType();
16101 
16102   // Passing a `void*' pointer shouldn't trigger a warning.
16103   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16104     return;
16105 
16106   if (TypeInfo.MustBeNull) {
16107     // Type tag with matching void type requires a null pointer.
16108     if (!ArgumentExpr->isNullPointerConstant(Context,
16109                                              Expr::NPC_ValueDependentIsNotNull)) {
16110       Diag(ArgumentExpr->getExprLoc(),
16111            diag::warn_type_safety_null_pointer_required)
16112           << ArgumentKind->getName()
16113           << ArgumentExpr->getSourceRange()
16114           << TypeTagExpr->getSourceRange();
16115     }
16116     return;
16117   }
16118 
16119   QualType RequiredType = TypeInfo.Type;
16120   if (IsPointerAttr)
16121     RequiredType = Context.getPointerType(RequiredType);
16122 
16123   bool mismatch = false;
16124   if (!TypeInfo.LayoutCompatible) {
16125     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16126 
16127     // C++11 [basic.fundamental] p1:
16128     // Plain char, signed char, and unsigned char are three distinct types.
16129     //
16130     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16131     // char' depending on the current char signedness mode.
16132     if (mismatch)
16133       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16134                                            RequiredType->getPointeeType())) ||
16135           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16136         mismatch = false;
16137   } else
16138     if (IsPointerAttr)
16139       mismatch = !isLayoutCompatible(Context,
16140                                      ArgumentType->getPointeeType(),
16141                                      RequiredType->getPointeeType());
16142     else
16143       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16144 
16145   if (mismatch)
16146     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16147         << ArgumentType << ArgumentKind
16148         << TypeInfo.LayoutCompatible << RequiredType
16149         << ArgumentExpr->getSourceRange()
16150         << TypeTagExpr->getSourceRange();
16151 }
16152 
16153 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16154                                          CharUnits Alignment) {
16155   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16156 }
16157 
16158 void Sema::DiagnoseMisalignedMembers() {
16159   for (MisalignedMember &m : MisalignedMembers) {
16160     const NamedDecl *ND = m.RD;
16161     if (ND->getName().empty()) {
16162       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16163         ND = TD;
16164     }
16165     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16166         << m.MD << ND << m.E->getSourceRange();
16167   }
16168   MisalignedMembers.clear();
16169 }
16170 
16171 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16172   E = E->IgnoreParens();
16173   if (!T->isPointerType() && !T->isIntegerType())
16174     return;
16175   if (isa<UnaryOperator>(E) &&
16176       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16177     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16178     if (isa<MemberExpr>(Op)) {
16179       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16180       if (MA != MisalignedMembers.end() &&
16181           (T->isIntegerType() ||
16182            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16183                                    Context.getTypeAlignInChars(
16184                                        T->getPointeeType()) <= MA->Alignment))))
16185         MisalignedMembers.erase(MA);
16186     }
16187   }
16188 }
16189 
16190 void Sema::RefersToMemberWithReducedAlignment(
16191     Expr *E,
16192     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16193         Action) {
16194   const auto *ME = dyn_cast<MemberExpr>(E);
16195   if (!ME)
16196     return;
16197 
16198   // No need to check expressions with an __unaligned-qualified type.
16199   if (E->getType().getQualifiers().hasUnaligned())
16200     return;
16201 
16202   // For a chain of MemberExpr like "a.b.c.d" this list
16203   // will keep FieldDecl's like [d, c, b].
16204   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16205   const MemberExpr *TopME = nullptr;
16206   bool AnyIsPacked = false;
16207   do {
16208     QualType BaseType = ME->getBase()->getType();
16209     if (BaseType->isDependentType())
16210       return;
16211     if (ME->isArrow())
16212       BaseType = BaseType->getPointeeType();
16213     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16214     if (RD->isInvalidDecl())
16215       return;
16216 
16217     ValueDecl *MD = ME->getMemberDecl();
16218     auto *FD = dyn_cast<FieldDecl>(MD);
16219     // We do not care about non-data members.
16220     if (!FD || FD->isInvalidDecl())
16221       return;
16222 
16223     AnyIsPacked =
16224         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16225     ReverseMemberChain.push_back(FD);
16226 
16227     TopME = ME;
16228     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16229   } while (ME);
16230   assert(TopME && "We did not compute a topmost MemberExpr!");
16231 
16232   // Not the scope of this diagnostic.
16233   if (!AnyIsPacked)
16234     return;
16235 
16236   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16237   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16238   // TODO: The innermost base of the member expression may be too complicated.
16239   // For now, just disregard these cases. This is left for future
16240   // improvement.
16241   if (!DRE && !isa<CXXThisExpr>(TopBase))
16242       return;
16243 
16244   // Alignment expected by the whole expression.
16245   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16246 
16247   // No need to do anything else with this case.
16248   if (ExpectedAlignment.isOne())
16249     return;
16250 
16251   // Synthesize offset of the whole access.
16252   CharUnits Offset;
16253   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
16254        I++) {
16255     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
16256   }
16257 
16258   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16259   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16260       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16261 
16262   // The base expression of the innermost MemberExpr may give
16263   // stronger guarantees than the class containing the member.
16264   if (DRE && !TopME->isArrow()) {
16265     const ValueDecl *VD = DRE->getDecl();
16266     if (!VD->getType()->isReferenceType())
16267       CompleteObjectAlignment =
16268           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16269   }
16270 
16271   // Check if the synthesized offset fulfills the alignment.
16272   if (Offset % ExpectedAlignment != 0 ||
16273       // It may fulfill the offset it but the effective alignment may still be
16274       // lower than the expected expression alignment.
16275       CompleteObjectAlignment < ExpectedAlignment) {
16276     // If this happens, we want to determine a sensible culprit of this.
16277     // Intuitively, watching the chain of member expressions from right to
16278     // left, we start with the required alignment (as required by the field
16279     // type) but some packed attribute in that chain has reduced the alignment.
16280     // It may happen that another packed structure increases it again. But if
16281     // we are here such increase has not been enough. So pointing the first
16282     // FieldDecl that either is packed or else its RecordDecl is,
16283     // seems reasonable.
16284     FieldDecl *FD = nullptr;
16285     CharUnits Alignment;
16286     for (FieldDecl *FDI : ReverseMemberChain) {
16287       if (FDI->hasAttr<PackedAttr>() ||
16288           FDI->getParent()->hasAttr<PackedAttr>()) {
16289         FD = FDI;
16290         Alignment = std::min(
16291             Context.getTypeAlignInChars(FD->getType()),
16292             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16293         break;
16294       }
16295     }
16296     assert(FD && "We did not find a packed FieldDecl!");
16297     Action(E, FD->getParent(), FD, Alignment);
16298   }
16299 }
16300 
16301 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16302   using namespace std::placeholders;
16303 
16304   RefersToMemberWithReducedAlignment(
16305       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16306                      _2, _3, _4));
16307 }
16308 
16309 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16310                                             ExprResult CallResult) {
16311   if (checkArgCount(*this, TheCall, 1))
16312     return ExprError();
16313 
16314   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16315   if (MatrixArg.isInvalid())
16316     return MatrixArg;
16317   Expr *Matrix = MatrixArg.get();
16318 
16319   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16320   if (!MType) {
16321     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
16322     return ExprError();
16323   }
16324 
16325   // Create returned matrix type by swapping rows and columns of the argument
16326   // matrix type.
16327   QualType ResultType = Context.getConstantMatrixType(
16328       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16329 
16330   // Change the return type to the type of the returned matrix.
16331   TheCall->setType(ResultType);
16332 
16333   // Update call argument to use the possibly converted matrix argument.
16334   TheCall->setArg(0, Matrix);
16335   return CallResult;
16336 }
16337 
16338 // Get and verify the matrix dimensions.
16339 static llvm::Optional<unsigned>
16340 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16341   SourceLocation ErrorPos;
16342   Optional<llvm::APSInt> Value =
16343       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16344   if (!Value) {
16345     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16346         << Name;
16347     return {};
16348   }
16349   uint64_t Dim = Value->getZExtValue();
16350   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16351     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16352         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16353     return {};
16354   }
16355   return Dim;
16356 }
16357 
16358 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16359                                                   ExprResult CallResult) {
16360   if (!getLangOpts().MatrixTypes) {
16361     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16362     return ExprError();
16363   }
16364 
16365   if (checkArgCount(*this, TheCall, 4))
16366     return ExprError();
16367 
16368   unsigned PtrArgIdx = 0;
16369   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16370   Expr *RowsExpr = TheCall->getArg(1);
16371   Expr *ColumnsExpr = TheCall->getArg(2);
16372   Expr *StrideExpr = TheCall->getArg(3);
16373 
16374   bool ArgError = false;
16375 
16376   // Check pointer argument.
16377   {
16378     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16379     if (PtrConv.isInvalid())
16380       return PtrConv;
16381     PtrExpr = PtrConv.get();
16382     TheCall->setArg(0, PtrExpr);
16383     if (PtrExpr->isTypeDependent()) {
16384       TheCall->setType(Context.DependentTy);
16385       return TheCall;
16386     }
16387   }
16388 
16389   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16390   QualType ElementTy;
16391   if (!PtrTy) {
16392     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16393         << PtrArgIdx + 1;
16394     ArgError = true;
16395   } else {
16396     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16397 
16398     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16399       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16400           << PtrArgIdx + 1;
16401       ArgError = true;
16402     }
16403   }
16404 
16405   // Apply default Lvalue conversions and convert the expression to size_t.
16406   auto ApplyArgumentConversions = [this](Expr *E) {
16407     ExprResult Conv = DefaultLvalueConversion(E);
16408     if (Conv.isInvalid())
16409       return Conv;
16410 
16411     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16412   };
16413 
16414   // Apply conversion to row and column expressions.
16415   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16416   if (!RowsConv.isInvalid()) {
16417     RowsExpr = RowsConv.get();
16418     TheCall->setArg(1, RowsExpr);
16419   } else
16420     RowsExpr = nullptr;
16421 
16422   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16423   if (!ColumnsConv.isInvalid()) {
16424     ColumnsExpr = ColumnsConv.get();
16425     TheCall->setArg(2, ColumnsExpr);
16426   } else
16427     ColumnsExpr = nullptr;
16428 
16429   // If any any part of the result matrix type is still pending, just use
16430   // Context.DependentTy, until all parts are resolved.
16431   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16432       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16433     TheCall->setType(Context.DependentTy);
16434     return CallResult;
16435   }
16436 
16437   // Check row and column dimenions.
16438   llvm::Optional<unsigned> MaybeRows;
16439   if (RowsExpr)
16440     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16441 
16442   llvm::Optional<unsigned> MaybeColumns;
16443   if (ColumnsExpr)
16444     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16445 
16446   // Check stride argument.
16447   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16448   if (StrideConv.isInvalid())
16449     return ExprError();
16450   StrideExpr = StrideConv.get();
16451   TheCall->setArg(3, StrideExpr);
16452 
16453   if (MaybeRows) {
16454     if (Optional<llvm::APSInt> Value =
16455             StrideExpr->getIntegerConstantExpr(Context)) {
16456       uint64_t Stride = Value->getZExtValue();
16457       if (Stride < *MaybeRows) {
16458         Diag(StrideExpr->getBeginLoc(),
16459              diag::err_builtin_matrix_stride_too_small);
16460         ArgError = true;
16461       }
16462     }
16463   }
16464 
16465   if (ArgError || !MaybeRows || !MaybeColumns)
16466     return ExprError();
16467 
16468   TheCall->setType(
16469       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16470   return CallResult;
16471 }
16472 
16473 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16474                                                    ExprResult CallResult) {
16475   if (checkArgCount(*this, TheCall, 3))
16476     return ExprError();
16477 
16478   unsigned PtrArgIdx = 1;
16479   Expr *MatrixExpr = TheCall->getArg(0);
16480   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16481   Expr *StrideExpr = TheCall->getArg(2);
16482 
16483   bool ArgError = false;
16484 
16485   {
16486     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16487     if (MatrixConv.isInvalid())
16488       return MatrixConv;
16489     MatrixExpr = MatrixConv.get();
16490     TheCall->setArg(0, MatrixExpr);
16491   }
16492   if (MatrixExpr->isTypeDependent()) {
16493     TheCall->setType(Context.DependentTy);
16494     return TheCall;
16495   }
16496 
16497   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16498   if (!MatrixTy) {
16499     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16500     ArgError = true;
16501   }
16502 
16503   {
16504     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16505     if (PtrConv.isInvalid())
16506       return PtrConv;
16507     PtrExpr = PtrConv.get();
16508     TheCall->setArg(1, PtrExpr);
16509     if (PtrExpr->isTypeDependent()) {
16510       TheCall->setType(Context.DependentTy);
16511       return TheCall;
16512     }
16513   }
16514 
16515   // Check pointer argument.
16516   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16517   if (!PtrTy) {
16518     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16519         << PtrArgIdx + 1;
16520     ArgError = true;
16521   } else {
16522     QualType ElementTy = PtrTy->getPointeeType();
16523     if (ElementTy.isConstQualified()) {
16524       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16525       ArgError = true;
16526     }
16527     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16528     if (MatrixTy &&
16529         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16530       Diag(PtrExpr->getBeginLoc(),
16531            diag::err_builtin_matrix_pointer_arg_mismatch)
16532           << ElementTy << MatrixTy->getElementType();
16533       ArgError = true;
16534     }
16535   }
16536 
16537   // Apply default Lvalue conversions and convert the stride expression to
16538   // size_t.
16539   {
16540     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16541     if (StrideConv.isInvalid())
16542       return StrideConv;
16543 
16544     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16545     if (StrideConv.isInvalid())
16546       return StrideConv;
16547     StrideExpr = StrideConv.get();
16548     TheCall->setArg(2, StrideExpr);
16549   }
16550 
16551   // Check stride argument.
16552   if (MatrixTy) {
16553     if (Optional<llvm::APSInt> Value =
16554             StrideExpr->getIntegerConstantExpr(Context)) {
16555       uint64_t Stride = Value->getZExtValue();
16556       if (Stride < MatrixTy->getNumRows()) {
16557         Diag(StrideExpr->getBeginLoc(),
16558              diag::err_builtin_matrix_stride_too_small);
16559         ArgError = true;
16560       }
16561     }
16562   }
16563 
16564   if (ArgError)
16565     return ExprError();
16566 
16567   return CallResult;
16568 }
16569 
16570 /// \brief Enforce the bounds of a TCB
16571 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16572 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16573 /// and enforce_tcb_leaf attributes.
16574 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16575                                const FunctionDecl *Callee) {
16576   const FunctionDecl *Caller = getCurFunctionDecl();
16577 
16578   // Calls to builtins are not enforced.
16579   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16580       Callee->getBuiltinID() != 0)
16581     return;
16582 
16583   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16584   // all TCBs the callee is a part of.
16585   llvm::StringSet<> CalleeTCBs;
16586   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16587            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16588   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16589            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16590 
16591   // Go through the TCBs the caller is a part of and emit warnings if Caller
16592   // is in a TCB that the Callee is not.
16593   for_each(
16594       Caller->specific_attrs<EnforceTCBAttr>(),
16595       [&](const auto *A) {
16596         StringRef CallerTCB = A->getTCBName();
16597         if (CalleeTCBs.count(CallerTCB) == 0) {
16598           this->Diag(TheCall->getExprLoc(),
16599                      diag::warn_tcb_enforcement_violation) << Callee
16600                                                            << CallerTCB;
16601         }
16602       });
16603 }
16604