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 ScanfDiagnosticFormatHandler
412     : public analyze_format_string::FormatStringHandler {
413   // Accepts the argument index (relative to the first destination index) of the
414   // argument whose size we want.
415   using ComputeSizeFunction =
416       llvm::function_ref<Optional<llvm::APSInt>(unsigned)>;
417 
418   // Accepts the argument index (relative to the first destination index), the
419   // destination size, and the source size).
420   using DiagnoseFunction =
421       llvm::function_ref<void(unsigned, unsigned, unsigned)>;
422 
423   ComputeSizeFunction ComputeSizeArgument;
424   DiagnoseFunction Diagnose;
425 
426 public:
427   ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
428                                DiagnoseFunction Diagnose)
429       : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
430 
431   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
432                             const char *StartSpecifier,
433                             unsigned specifierLen) override {
434     if (!FS.consumesDataArgument())
435       return true;
436 
437     unsigned NulByte = 0;
438     switch ((FS.getConversionSpecifier().getKind())) {
439     default:
440       return true;
441     case analyze_format_string::ConversionSpecifier::sArg:
442     case analyze_format_string::ConversionSpecifier::ScanListArg:
443       NulByte = 1;
444       break;
445     case analyze_format_string::ConversionSpecifier::cArg:
446       break;
447     }
448 
449     auto OptionalFW = FS.getFieldWidth();
450     if (OptionalFW.getHowSpecified() !=
451         analyze_format_string::OptionalAmount::HowSpecified::Constant)
452       return true;
453 
454     unsigned SourceSize = OptionalFW.getConstantAmount() + NulByte;
455 
456     auto DestSizeAPS = ComputeSizeArgument(FS.getArgIndex());
457     if (!DestSizeAPS)
458       return true;
459 
460     unsigned DestSize = DestSizeAPS->getZExtValue();
461 
462     if (DestSize < SourceSize)
463       Diagnose(FS.getArgIndex(), DestSize, SourceSize);
464 
465     return true;
466   }
467 };
468 
469 class EstimateSizeFormatHandler
470     : public analyze_format_string::FormatStringHandler {
471   size_t Size;
472 
473 public:
474   EstimateSizeFormatHandler(StringRef Format)
475       : Size(std::min(Format.find(0), Format.size()) +
476              1 /* null byte always written by sprintf */) {}
477 
478   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
479                              const char *, unsigned SpecifierLen) override {
480 
481     const size_t FieldWidth = computeFieldWidth(FS);
482     const size_t Precision = computePrecision(FS);
483 
484     // The actual format.
485     switch (FS.getConversionSpecifier().getKind()) {
486     // Just a char.
487     case analyze_format_string::ConversionSpecifier::cArg:
488     case analyze_format_string::ConversionSpecifier::CArg:
489       Size += std::max(FieldWidth, (size_t)1);
490       break;
491     // Just an integer.
492     case analyze_format_string::ConversionSpecifier::dArg:
493     case analyze_format_string::ConversionSpecifier::DArg:
494     case analyze_format_string::ConversionSpecifier::iArg:
495     case analyze_format_string::ConversionSpecifier::oArg:
496     case analyze_format_string::ConversionSpecifier::OArg:
497     case analyze_format_string::ConversionSpecifier::uArg:
498     case analyze_format_string::ConversionSpecifier::UArg:
499     case analyze_format_string::ConversionSpecifier::xArg:
500     case analyze_format_string::ConversionSpecifier::XArg:
501       Size += std::max(FieldWidth, Precision);
502       break;
503 
504     // %g style conversion switches between %f or %e style dynamically.
505     // %f always takes less space, so default to it.
506     case analyze_format_string::ConversionSpecifier::gArg:
507     case analyze_format_string::ConversionSpecifier::GArg:
508 
509     // Floating point number in the form '[+]ddd.ddd'.
510     case analyze_format_string::ConversionSpecifier::fArg:
511     case analyze_format_string::ConversionSpecifier::FArg:
512       Size += std::max(FieldWidth, 1 /* integer part */ +
513                                        (Precision ? 1 + Precision
514                                                   : 0) /* period + decimal */);
515       break;
516 
517     // Floating point number in the form '[-]d.ddde[+-]dd'.
518     case analyze_format_string::ConversionSpecifier::eArg:
519     case analyze_format_string::ConversionSpecifier::EArg:
520       Size +=
521           std::max(FieldWidth,
522                    1 /* integer part */ +
523                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
524                        1 /* e or E letter */ + 2 /* exponent */);
525       break;
526 
527     // Floating point number in the form '[-]0xh.hhhhp±dd'.
528     case analyze_format_string::ConversionSpecifier::aArg:
529     case analyze_format_string::ConversionSpecifier::AArg:
530       Size +=
531           std::max(FieldWidth,
532                    2 /* 0x */ + 1 /* integer part */ +
533                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
534                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
535       break;
536 
537     // Just a string.
538     case analyze_format_string::ConversionSpecifier::sArg:
539     case analyze_format_string::ConversionSpecifier::SArg:
540       Size += FieldWidth;
541       break;
542 
543     // Just a pointer in the form '0xddd'.
544     case analyze_format_string::ConversionSpecifier::pArg:
545       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
546       break;
547 
548     // A plain percent.
549     case analyze_format_string::ConversionSpecifier::PercentArg:
550       Size += 1;
551       break;
552 
553     default:
554       break;
555     }
556 
557     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
558 
559     if (FS.hasAlternativeForm()) {
560       switch (FS.getConversionSpecifier().getKind()) {
561       default:
562         break;
563       // Force a leading '0'.
564       case analyze_format_string::ConversionSpecifier::oArg:
565         Size += 1;
566         break;
567       // Force a leading '0x'.
568       case analyze_format_string::ConversionSpecifier::xArg:
569       case analyze_format_string::ConversionSpecifier::XArg:
570         Size += 2;
571         break;
572       // Force a period '.' before decimal, even if precision is 0.
573       case analyze_format_string::ConversionSpecifier::aArg:
574       case analyze_format_string::ConversionSpecifier::AArg:
575       case analyze_format_string::ConversionSpecifier::eArg:
576       case analyze_format_string::ConversionSpecifier::EArg:
577       case analyze_format_string::ConversionSpecifier::fArg:
578       case analyze_format_string::ConversionSpecifier::FArg:
579       case analyze_format_string::ConversionSpecifier::gArg:
580       case analyze_format_string::ConversionSpecifier::GArg:
581         Size += (Precision ? 0 : 1);
582         break;
583       }
584     }
585     assert(SpecifierLen <= Size && "no underflow");
586     Size -= SpecifierLen;
587     return true;
588   }
589 
590   size_t getSizeLowerBound() const { return Size; }
591 
592 private:
593   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
594     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
595     size_t FieldWidth = 0;
596     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
597       FieldWidth = FW.getConstantAmount();
598     return FieldWidth;
599   }
600 
601   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
602     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
603     size_t Precision = 0;
604 
605     // See man 3 printf for default precision value based on the specifier.
606     switch (FW.getHowSpecified()) {
607     case analyze_format_string::OptionalAmount::NotSpecified:
608       switch (FS.getConversionSpecifier().getKind()) {
609       default:
610         break;
611       case analyze_format_string::ConversionSpecifier::dArg: // %d
612       case analyze_format_string::ConversionSpecifier::DArg: // %D
613       case analyze_format_string::ConversionSpecifier::iArg: // %i
614         Precision = 1;
615         break;
616       case analyze_format_string::ConversionSpecifier::oArg: // %d
617       case analyze_format_string::ConversionSpecifier::OArg: // %D
618       case analyze_format_string::ConversionSpecifier::uArg: // %d
619       case analyze_format_string::ConversionSpecifier::UArg: // %D
620       case analyze_format_string::ConversionSpecifier::xArg: // %d
621       case analyze_format_string::ConversionSpecifier::XArg: // %D
622         Precision = 1;
623         break;
624       case analyze_format_string::ConversionSpecifier::fArg: // %f
625       case analyze_format_string::ConversionSpecifier::FArg: // %F
626       case analyze_format_string::ConversionSpecifier::eArg: // %e
627       case analyze_format_string::ConversionSpecifier::EArg: // %E
628       case analyze_format_string::ConversionSpecifier::gArg: // %g
629       case analyze_format_string::ConversionSpecifier::GArg: // %G
630         Precision = 6;
631         break;
632       case analyze_format_string::ConversionSpecifier::pArg: // %d
633         Precision = 1;
634         break;
635       }
636       break;
637     case analyze_format_string::OptionalAmount::Constant:
638       Precision = FW.getConstantAmount();
639       break;
640     default:
641       break;
642     }
643     return Precision;
644   }
645 };
646 
647 } // namespace
648 
649 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
650                                                CallExpr *TheCall) {
651   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
652       isConstantEvaluated())
653     return;
654 
655   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
656   if (!BuiltinID)
657     return;
658 
659   const TargetInfo &TI = getASTContext().getTargetInfo();
660   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
661 
662   auto ComputeExplicitObjectSizeArgument =
663       [&](unsigned Index) -> Optional<llvm::APSInt> {
664     Expr::EvalResult Result;
665     Expr *SizeArg = TheCall->getArg(Index);
666     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
667       return llvm::None;
668     return Result.Val.getInt();
669   };
670 
671   auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
672     // If the parameter has a pass_object_size attribute, then we should use its
673     // (potentially) more strict checking mode. Otherwise, conservatively assume
674     // type 0.
675     int BOSType = 0;
676     // This check can fail for variadic functions.
677     if (Index < FD->getNumParams()) {
678       if (const auto *POS =
679               FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
680         BOSType = POS->getType();
681     }
682 
683     const Expr *ObjArg = TheCall->getArg(Index);
684     uint64_t Result;
685     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
686       return llvm::None;
687 
688     // Get the object size in the target's size_t width.
689     return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
690   };
691 
692   auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
693     Expr *ObjArg = TheCall->getArg(Index);
694     uint64_t Result;
695     if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
696       return llvm::None;
697     // Add 1 for null byte.
698     return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
699   };
700 
701   Optional<llvm::APSInt> SourceSize;
702   Optional<llvm::APSInt> DestinationSize;
703   unsigned DiagID = 0;
704   bool IsChkVariant = false;
705 
706   auto GetFunctionName = [&]() {
707     StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
708     // Skim off the details of whichever builtin was called to produce a better
709     // diagnostic, as it's unlikely that the user wrote the __builtin
710     // explicitly.
711     if (IsChkVariant) {
712       FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
713       FunctionName = FunctionName.drop_back(std::strlen("_chk"));
714     } else if (FunctionName.startswith("__builtin_")) {
715       FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
716     }
717     return FunctionName;
718   };
719 
720   switch (BuiltinID) {
721   default:
722     return;
723   case Builtin::BI__builtin_strcpy:
724   case Builtin::BIstrcpy: {
725     DiagID = diag::warn_fortify_strlen_overflow;
726     SourceSize = ComputeStrLenArgument(1);
727     DestinationSize = ComputeSizeArgument(0);
728     break;
729   }
730 
731   case Builtin::BI__builtin___strcpy_chk: {
732     DiagID = diag::warn_fortify_strlen_overflow;
733     SourceSize = ComputeStrLenArgument(1);
734     DestinationSize = ComputeExplicitObjectSizeArgument(2);
735     IsChkVariant = true;
736     break;
737   }
738 
739   case Builtin::BIscanf:
740   case Builtin::BIfscanf:
741   case Builtin::BIsscanf: {
742     unsigned FormatIndex = 1;
743     unsigned DataIndex = 2;
744     if (BuiltinID == Builtin::BIscanf) {
745       FormatIndex = 0;
746       DataIndex = 1;
747     }
748 
749     const auto *FormatExpr =
750         TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
751 
752     const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
753     if (!Format)
754       return;
755 
756     if (!Format->isAscii() && !Format->isUTF8())
757       return;
758 
759     auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
760                         unsigned SourceSize) {
761       DiagID = diag::warn_fortify_scanf_overflow;
762       unsigned Index = ArgIndex + DataIndex;
763       StringRef FunctionName = GetFunctionName();
764       DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
765                           PDiag(DiagID) << FunctionName << (Index + 1)
766                                         << DestSize << SourceSize);
767     };
768 
769     StringRef FormatStrRef = Format->getString();
770     auto ShiftedComputeSizeArgument = [&](unsigned Index) {
771       return ComputeSizeArgument(Index + DataIndex);
772     };
773     ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
774     const char *FormatBytes = FormatStrRef.data();
775     const ConstantArrayType *T =
776         Context.getAsConstantArrayType(Format->getType());
777     assert(T && "String literal not of constant array type!");
778     size_t TypeSize = T->getSize().getZExtValue();
779 
780     // In case there's a null byte somewhere.
781     size_t StrLen =
782         std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
783 
784     analyze_format_string::ParseScanfString(H, FormatBytes,
785                                             FormatBytes + StrLen, getLangOpts(),
786                                             Context.getTargetInfo());
787 
788     // Unlike the other cases, in this one we have already issued the diagnostic
789     // here, so no need to continue (because unlike the other cases, here the
790     // diagnostic refers to the argument number).
791     return;
792   }
793 
794   case Builtin::BIsprintf:
795   case Builtin::BI__builtin___sprintf_chk: {
796     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
797     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
798 
799     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
800 
801       if (!Format->isAscii() && !Format->isUTF8())
802         return;
803 
804       StringRef FormatStrRef = Format->getString();
805       EstimateSizeFormatHandler H(FormatStrRef);
806       const char *FormatBytes = FormatStrRef.data();
807       const ConstantArrayType *T =
808           Context.getAsConstantArrayType(Format->getType());
809       assert(T && "String literal not of constant array type!");
810       size_t TypeSize = T->getSize().getZExtValue();
811 
812       // In case there's a null byte somewhere.
813       size_t StrLen =
814           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
815       if (!analyze_format_string::ParsePrintfString(
816               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
817               Context.getTargetInfo(), false)) {
818         DiagID = diag::warn_fortify_source_format_overflow;
819         SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
820                          .extOrTrunc(SizeTypeWidth);
821         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
822           DestinationSize = ComputeExplicitObjectSizeArgument(2);
823           IsChkVariant = true;
824         } else {
825           DestinationSize = ComputeSizeArgument(0);
826         }
827         break;
828       }
829     }
830     return;
831   }
832   case Builtin::BI__builtin___memcpy_chk:
833   case Builtin::BI__builtin___memmove_chk:
834   case Builtin::BI__builtin___memset_chk:
835   case Builtin::BI__builtin___strlcat_chk:
836   case Builtin::BI__builtin___strlcpy_chk:
837   case Builtin::BI__builtin___strncat_chk:
838   case Builtin::BI__builtin___strncpy_chk:
839   case Builtin::BI__builtin___stpncpy_chk:
840   case Builtin::BI__builtin___memccpy_chk:
841   case Builtin::BI__builtin___mempcpy_chk: {
842     DiagID = diag::warn_builtin_chk_overflow;
843     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
844     DestinationSize =
845         ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
846     IsChkVariant = true;
847     break;
848   }
849 
850   case Builtin::BI__builtin___snprintf_chk:
851   case Builtin::BI__builtin___vsnprintf_chk: {
852     DiagID = diag::warn_builtin_chk_overflow;
853     SourceSize = ComputeExplicitObjectSizeArgument(1);
854     DestinationSize = ComputeExplicitObjectSizeArgument(3);
855     IsChkVariant = true;
856     break;
857   }
858 
859   case Builtin::BIstrncat:
860   case Builtin::BI__builtin_strncat:
861   case Builtin::BIstrncpy:
862   case Builtin::BI__builtin_strncpy:
863   case Builtin::BIstpncpy:
864   case Builtin::BI__builtin_stpncpy: {
865     // Whether these functions overflow depends on the runtime strlen of the
866     // string, not just the buffer size, so emitting the "always overflow"
867     // diagnostic isn't quite right. We should still diagnose passing a buffer
868     // size larger than the destination buffer though; this is a runtime abort
869     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
870     DiagID = diag::warn_fortify_source_size_mismatch;
871     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
872     DestinationSize = ComputeSizeArgument(0);
873     break;
874   }
875 
876   case Builtin::BImemcpy:
877   case Builtin::BI__builtin_memcpy:
878   case Builtin::BImemmove:
879   case Builtin::BI__builtin_memmove:
880   case Builtin::BImemset:
881   case Builtin::BI__builtin_memset:
882   case Builtin::BImempcpy:
883   case Builtin::BI__builtin_mempcpy: {
884     DiagID = diag::warn_fortify_source_overflow;
885     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
886     DestinationSize = ComputeSizeArgument(0);
887     break;
888   }
889   case Builtin::BIsnprintf:
890   case Builtin::BI__builtin_snprintf:
891   case Builtin::BIvsnprintf:
892   case Builtin::BI__builtin_vsnprintf: {
893     DiagID = diag::warn_fortify_source_size_mismatch;
894     SourceSize = ComputeExplicitObjectSizeArgument(1);
895     DestinationSize = ComputeSizeArgument(0);
896     break;
897   }
898   }
899 
900   if (!SourceSize || !DestinationSize ||
901       SourceSize.getValue().ule(DestinationSize.getValue()))
902     return;
903 
904   StringRef FunctionName = GetFunctionName();
905 
906   SmallString<16> DestinationStr;
907   SmallString<16> SourceStr;
908   DestinationSize->toString(DestinationStr, /*Radix=*/10);
909   SourceSize->toString(SourceStr, /*Radix=*/10);
910   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
911                       PDiag(DiagID)
912                           << FunctionName << DestinationStr << SourceStr);
913 }
914 
915 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
916                                      Scope::ScopeFlags NeededScopeFlags,
917                                      unsigned DiagID) {
918   // Scopes aren't available during instantiation. Fortunately, builtin
919   // functions cannot be template args so they cannot be formed through template
920   // instantiation. Therefore checking once during the parse is sufficient.
921   if (SemaRef.inTemplateInstantiation())
922     return false;
923 
924   Scope *S = SemaRef.getCurScope();
925   while (S && !S->isSEHExceptScope())
926     S = S->getParent();
927   if (!S || !(S->getFlags() & NeededScopeFlags)) {
928     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
929     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
930         << DRE->getDecl()->getIdentifier();
931     return true;
932   }
933 
934   return false;
935 }
936 
937 static inline bool isBlockPointer(Expr *Arg) {
938   return Arg->getType()->isBlockPointerType();
939 }
940 
941 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
942 /// void*, which is a requirement of device side enqueue.
943 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
944   const BlockPointerType *BPT =
945       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
946   ArrayRef<QualType> Params =
947       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
948   unsigned ArgCounter = 0;
949   bool IllegalParams = false;
950   // Iterate through the block parameters until either one is found that is not
951   // a local void*, or the block is valid.
952   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
953        I != E; ++I, ++ArgCounter) {
954     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
955         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
956             LangAS::opencl_local) {
957       // Get the location of the error. If a block literal has been passed
958       // (BlockExpr) then we can point straight to the offending argument,
959       // else we just point to the variable reference.
960       SourceLocation ErrorLoc;
961       if (isa<BlockExpr>(BlockArg)) {
962         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
963         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
964       } else if (isa<DeclRefExpr>(BlockArg)) {
965         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
966       }
967       S.Diag(ErrorLoc,
968              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
969       IllegalParams = true;
970     }
971   }
972 
973   return IllegalParams;
974 }
975 
976 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
977   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
978     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
979         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
980     return true;
981   }
982   return false;
983 }
984 
985 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
986   if (checkArgCount(S, TheCall, 2))
987     return true;
988 
989   if (checkOpenCLSubgroupExt(S, TheCall))
990     return true;
991 
992   // First argument is an ndrange_t type.
993   Expr *NDRangeArg = TheCall->getArg(0);
994   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
995     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
996         << TheCall->getDirectCallee() << "'ndrange_t'";
997     return true;
998   }
999 
1000   Expr *BlockArg = TheCall->getArg(1);
1001   if (!isBlockPointer(BlockArg)) {
1002     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1003         << TheCall->getDirectCallee() << "block";
1004     return true;
1005   }
1006   return checkOpenCLBlockArgs(S, BlockArg);
1007 }
1008 
1009 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
1010 /// get_kernel_work_group_size
1011 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
1012 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
1013   if (checkArgCount(S, TheCall, 1))
1014     return true;
1015 
1016   Expr *BlockArg = TheCall->getArg(0);
1017   if (!isBlockPointer(BlockArg)) {
1018     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1019         << TheCall->getDirectCallee() << "block";
1020     return true;
1021   }
1022   return checkOpenCLBlockArgs(S, BlockArg);
1023 }
1024 
1025 /// Diagnose integer type and any valid implicit conversion to it.
1026 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
1027                                       const QualType &IntType);
1028 
1029 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
1030                                             unsigned Start, unsigned End) {
1031   bool IllegalParams = false;
1032   for (unsigned I = Start; I <= End; ++I)
1033     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
1034                                               S.Context.getSizeType());
1035   return IllegalParams;
1036 }
1037 
1038 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
1039 /// 'local void*' parameter of passed block.
1040 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
1041                                            Expr *BlockArg,
1042                                            unsigned NumNonVarArgs) {
1043   const BlockPointerType *BPT =
1044       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
1045   unsigned NumBlockParams =
1046       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
1047   unsigned TotalNumArgs = TheCall->getNumArgs();
1048 
1049   // For each argument passed to the block, a corresponding uint needs to
1050   // be passed to describe the size of the local memory.
1051   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
1052     S.Diag(TheCall->getBeginLoc(),
1053            diag::err_opencl_enqueue_kernel_local_size_args);
1054     return true;
1055   }
1056 
1057   // Check that the sizes of the local memory are specified by integers.
1058   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
1059                                          TotalNumArgs - 1);
1060 }
1061 
1062 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
1063 /// overload formats specified in Table 6.13.17.1.
1064 /// int enqueue_kernel(queue_t queue,
1065 ///                    kernel_enqueue_flags_t flags,
1066 ///                    const ndrange_t ndrange,
1067 ///                    void (^block)(void))
1068 /// int enqueue_kernel(queue_t queue,
1069 ///                    kernel_enqueue_flags_t flags,
1070 ///                    const ndrange_t ndrange,
1071 ///                    uint num_events_in_wait_list,
1072 ///                    clk_event_t *event_wait_list,
1073 ///                    clk_event_t *event_ret,
1074 ///                    void (^block)(void))
1075 /// int enqueue_kernel(queue_t queue,
1076 ///                    kernel_enqueue_flags_t flags,
1077 ///                    const ndrange_t ndrange,
1078 ///                    void (^block)(local void*, ...),
1079 ///                    uint size0, ...)
1080 /// int enqueue_kernel(queue_t queue,
1081 ///                    kernel_enqueue_flags_t flags,
1082 ///                    const ndrange_t ndrange,
1083 ///                    uint num_events_in_wait_list,
1084 ///                    clk_event_t *event_wait_list,
1085 ///                    clk_event_t *event_ret,
1086 ///                    void (^block)(local void*, ...),
1087 ///                    uint size0, ...)
1088 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
1089   unsigned NumArgs = TheCall->getNumArgs();
1090 
1091   if (NumArgs < 4) {
1092     S.Diag(TheCall->getBeginLoc(),
1093            diag::err_typecheck_call_too_few_args_at_least)
1094         << 0 << 4 << NumArgs;
1095     return true;
1096   }
1097 
1098   Expr *Arg0 = TheCall->getArg(0);
1099   Expr *Arg1 = TheCall->getArg(1);
1100   Expr *Arg2 = TheCall->getArg(2);
1101   Expr *Arg3 = TheCall->getArg(3);
1102 
1103   // First argument always needs to be a queue_t type.
1104   if (!Arg0->getType()->isQueueT()) {
1105     S.Diag(TheCall->getArg(0)->getBeginLoc(),
1106            diag::err_opencl_builtin_expected_type)
1107         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
1108     return true;
1109   }
1110 
1111   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
1112   if (!Arg1->getType()->isIntegerType()) {
1113     S.Diag(TheCall->getArg(1)->getBeginLoc(),
1114            diag::err_opencl_builtin_expected_type)
1115         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
1116     return true;
1117   }
1118 
1119   // Third argument is always an ndrange_t type.
1120   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
1121     S.Diag(TheCall->getArg(2)->getBeginLoc(),
1122            diag::err_opencl_builtin_expected_type)
1123         << TheCall->getDirectCallee() << "'ndrange_t'";
1124     return true;
1125   }
1126 
1127   // With four arguments, there is only one form that the function could be
1128   // called in: no events and no variable arguments.
1129   if (NumArgs == 4) {
1130     // check that the last argument is the right block type.
1131     if (!isBlockPointer(Arg3)) {
1132       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1133           << TheCall->getDirectCallee() << "block";
1134       return true;
1135     }
1136     // we have a block type, check the prototype
1137     const BlockPointerType *BPT =
1138         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1139     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1140       S.Diag(Arg3->getBeginLoc(),
1141              diag::err_opencl_enqueue_kernel_blocks_no_args);
1142       return true;
1143     }
1144     return false;
1145   }
1146   // we can have block + varargs.
1147   if (isBlockPointer(Arg3))
1148     return (checkOpenCLBlockArgs(S, Arg3) ||
1149             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1150   // last two cases with either exactly 7 args or 7 args and varargs.
1151   if (NumArgs >= 7) {
1152     // check common block argument.
1153     Expr *Arg6 = TheCall->getArg(6);
1154     if (!isBlockPointer(Arg6)) {
1155       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1156           << TheCall->getDirectCallee() << "block";
1157       return true;
1158     }
1159     if (checkOpenCLBlockArgs(S, Arg6))
1160       return true;
1161 
1162     // Forth argument has to be any integer type.
1163     if (!Arg3->getType()->isIntegerType()) {
1164       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1165              diag::err_opencl_builtin_expected_type)
1166           << TheCall->getDirectCallee() << "integer";
1167       return true;
1168     }
1169     // check remaining common arguments.
1170     Expr *Arg4 = TheCall->getArg(4);
1171     Expr *Arg5 = TheCall->getArg(5);
1172 
1173     // Fifth argument is always passed as a pointer to clk_event_t.
1174     if (!Arg4->isNullPointerConstant(S.Context,
1175                                      Expr::NPC_ValueDependentIsNotNull) &&
1176         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1177       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1178              diag::err_opencl_builtin_expected_type)
1179           << TheCall->getDirectCallee()
1180           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1181       return true;
1182     }
1183 
1184     // Sixth argument is always passed as a pointer to clk_event_t.
1185     if (!Arg5->isNullPointerConstant(S.Context,
1186                                      Expr::NPC_ValueDependentIsNotNull) &&
1187         !(Arg5->getType()->isPointerType() &&
1188           Arg5->getType()->getPointeeType()->isClkEventT())) {
1189       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1190              diag::err_opencl_builtin_expected_type)
1191           << TheCall->getDirectCallee()
1192           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1193       return true;
1194     }
1195 
1196     if (NumArgs == 7)
1197       return false;
1198 
1199     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1200   }
1201 
1202   // None of the specific case has been detected, give generic error
1203   S.Diag(TheCall->getBeginLoc(),
1204          diag::err_opencl_enqueue_kernel_incorrect_args);
1205   return true;
1206 }
1207 
1208 /// Returns OpenCL access qual.
1209 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1210     return D->getAttr<OpenCLAccessAttr>();
1211 }
1212 
1213 /// Returns true if pipe element type is different from the pointer.
1214 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1215   const Expr *Arg0 = Call->getArg(0);
1216   // First argument type should always be pipe.
1217   if (!Arg0->getType()->isPipeType()) {
1218     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1219         << Call->getDirectCallee() << Arg0->getSourceRange();
1220     return true;
1221   }
1222   OpenCLAccessAttr *AccessQual =
1223       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1224   // Validates the access qualifier is compatible with the call.
1225   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1226   // read_only and write_only, and assumed to be read_only if no qualifier is
1227   // specified.
1228   switch (Call->getDirectCallee()->getBuiltinID()) {
1229   case Builtin::BIread_pipe:
1230   case Builtin::BIreserve_read_pipe:
1231   case Builtin::BIcommit_read_pipe:
1232   case Builtin::BIwork_group_reserve_read_pipe:
1233   case Builtin::BIsub_group_reserve_read_pipe:
1234   case Builtin::BIwork_group_commit_read_pipe:
1235   case Builtin::BIsub_group_commit_read_pipe:
1236     if (!(!AccessQual || AccessQual->isReadOnly())) {
1237       S.Diag(Arg0->getBeginLoc(),
1238              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1239           << "read_only" << Arg0->getSourceRange();
1240       return true;
1241     }
1242     break;
1243   case Builtin::BIwrite_pipe:
1244   case Builtin::BIreserve_write_pipe:
1245   case Builtin::BIcommit_write_pipe:
1246   case Builtin::BIwork_group_reserve_write_pipe:
1247   case Builtin::BIsub_group_reserve_write_pipe:
1248   case Builtin::BIwork_group_commit_write_pipe:
1249   case Builtin::BIsub_group_commit_write_pipe:
1250     if (!(AccessQual && AccessQual->isWriteOnly())) {
1251       S.Diag(Arg0->getBeginLoc(),
1252              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1253           << "write_only" << Arg0->getSourceRange();
1254       return true;
1255     }
1256     break;
1257   default:
1258     break;
1259   }
1260   return false;
1261 }
1262 
1263 /// Returns true if pipe element type is different from the pointer.
1264 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1265   const Expr *Arg0 = Call->getArg(0);
1266   const Expr *ArgIdx = Call->getArg(Idx);
1267   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1268   const QualType EltTy = PipeTy->getElementType();
1269   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1270   // The Idx argument should be a pointer and the type of the pointer and
1271   // the type of pipe element should also be the same.
1272   if (!ArgTy ||
1273       !S.Context.hasSameType(
1274           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1275     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1276         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1277         << ArgIdx->getType() << ArgIdx->getSourceRange();
1278     return true;
1279   }
1280   return false;
1281 }
1282 
1283 // Performs semantic analysis for the read/write_pipe call.
1284 // \param S Reference to the semantic analyzer.
1285 // \param Call A pointer to the builtin call.
1286 // \return True if a semantic error has been found, false otherwise.
1287 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1288   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1289   // functions have two forms.
1290   switch (Call->getNumArgs()) {
1291   case 2:
1292     if (checkOpenCLPipeArg(S, Call))
1293       return true;
1294     // The call with 2 arguments should be
1295     // read/write_pipe(pipe T, T*).
1296     // Check packet type T.
1297     if (checkOpenCLPipePacketType(S, Call, 1))
1298       return true;
1299     break;
1300 
1301   case 4: {
1302     if (checkOpenCLPipeArg(S, Call))
1303       return true;
1304     // The call with 4 arguments should be
1305     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1306     // Check reserve_id_t.
1307     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1308       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1309           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1310           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1311       return true;
1312     }
1313 
1314     // Check the index.
1315     const Expr *Arg2 = Call->getArg(2);
1316     if (!Arg2->getType()->isIntegerType() &&
1317         !Arg2->getType()->isUnsignedIntegerType()) {
1318       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1319           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1320           << Arg2->getType() << Arg2->getSourceRange();
1321       return true;
1322     }
1323 
1324     // Check packet type T.
1325     if (checkOpenCLPipePacketType(S, Call, 3))
1326       return true;
1327   } break;
1328   default:
1329     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1330         << Call->getDirectCallee() << Call->getSourceRange();
1331     return true;
1332   }
1333 
1334   return false;
1335 }
1336 
1337 // Performs a semantic analysis on the {work_group_/sub_group_
1338 //        /_}reserve_{read/write}_pipe
1339 // \param S Reference to the semantic analyzer.
1340 // \param Call The call to the builtin function to be analyzed.
1341 // \return True if a semantic error was found, false otherwise.
1342 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1343   if (checkArgCount(S, Call, 2))
1344     return true;
1345 
1346   if (checkOpenCLPipeArg(S, Call))
1347     return true;
1348 
1349   // Check the reserve size.
1350   if (!Call->getArg(1)->getType()->isIntegerType() &&
1351       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1352     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1353         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1354         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1355     return true;
1356   }
1357 
1358   // Since return type of reserve_read/write_pipe built-in function is
1359   // reserve_id_t, which is not defined in the builtin def file , we used int
1360   // as return type and need to override the return type of these functions.
1361   Call->setType(S.Context.OCLReserveIDTy);
1362 
1363   return false;
1364 }
1365 
1366 // Performs a semantic analysis on {work_group_/sub_group_
1367 //        /_}commit_{read/write}_pipe
1368 // \param S Reference to the semantic analyzer.
1369 // \param Call The call to the builtin function to be analyzed.
1370 // \return True if a semantic error was found, false otherwise.
1371 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1372   if (checkArgCount(S, Call, 2))
1373     return true;
1374 
1375   if (checkOpenCLPipeArg(S, Call))
1376     return true;
1377 
1378   // Check reserve_id_t.
1379   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1380     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1381         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1382         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1383     return true;
1384   }
1385 
1386   return false;
1387 }
1388 
1389 // Performs a semantic analysis on the call to built-in Pipe
1390 //        Query Functions.
1391 // \param S Reference to the semantic analyzer.
1392 // \param Call The call to the builtin function to be analyzed.
1393 // \return True if a semantic error was found, false otherwise.
1394 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1395   if (checkArgCount(S, Call, 1))
1396     return true;
1397 
1398   if (!Call->getArg(0)->getType()->isPipeType()) {
1399     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1400         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1401     return true;
1402   }
1403 
1404   return false;
1405 }
1406 
1407 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1408 // Performs semantic analysis for the to_global/local/private call.
1409 // \param S Reference to the semantic analyzer.
1410 // \param BuiltinID ID of the builtin function.
1411 // \param Call A pointer to the builtin call.
1412 // \return True if a semantic error has been found, false otherwise.
1413 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1414                                     CallExpr *Call) {
1415   if (checkArgCount(S, Call, 1))
1416     return true;
1417 
1418   auto RT = Call->getArg(0)->getType();
1419   if (!RT->isPointerType() || RT->getPointeeType()
1420       .getAddressSpace() == LangAS::opencl_constant) {
1421     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1422         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1423     return true;
1424   }
1425 
1426   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1427     S.Diag(Call->getArg(0)->getBeginLoc(),
1428            diag::warn_opencl_generic_address_space_arg)
1429         << Call->getDirectCallee()->getNameInfo().getAsString()
1430         << Call->getArg(0)->getSourceRange();
1431   }
1432 
1433   RT = RT->getPointeeType();
1434   auto Qual = RT.getQualifiers();
1435   switch (BuiltinID) {
1436   case Builtin::BIto_global:
1437     Qual.setAddressSpace(LangAS::opencl_global);
1438     break;
1439   case Builtin::BIto_local:
1440     Qual.setAddressSpace(LangAS::opencl_local);
1441     break;
1442   case Builtin::BIto_private:
1443     Qual.setAddressSpace(LangAS::opencl_private);
1444     break;
1445   default:
1446     llvm_unreachable("Invalid builtin function");
1447   }
1448   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1449       RT.getUnqualifiedType(), Qual)));
1450 
1451   return false;
1452 }
1453 
1454 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1455   if (checkArgCount(S, TheCall, 1))
1456     return ExprError();
1457 
1458   // Compute __builtin_launder's parameter type from the argument.
1459   // The parameter type is:
1460   //  * The type of the argument if it's not an array or function type,
1461   //  Otherwise,
1462   //  * The decayed argument type.
1463   QualType ParamTy = [&]() {
1464     QualType ArgTy = TheCall->getArg(0)->getType();
1465     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1466       return S.Context.getPointerType(Ty->getElementType());
1467     if (ArgTy->isFunctionType()) {
1468       return S.Context.getPointerType(ArgTy);
1469     }
1470     return ArgTy;
1471   }();
1472 
1473   TheCall->setType(ParamTy);
1474 
1475   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1476     if (!ParamTy->isPointerType())
1477       return 0;
1478     if (ParamTy->isFunctionPointerType())
1479       return 1;
1480     if (ParamTy->isVoidPointerType())
1481       return 2;
1482     return llvm::Optional<unsigned>{};
1483   }();
1484   if (DiagSelect.hasValue()) {
1485     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1486         << DiagSelect.getValue() << TheCall->getSourceRange();
1487     return ExprError();
1488   }
1489 
1490   // We either have an incomplete class type, or we have a class template
1491   // whose instantiation has not been forced. Example:
1492   //
1493   //   template <class T> struct Foo { T value; };
1494   //   Foo<int> *p = nullptr;
1495   //   auto *d = __builtin_launder(p);
1496   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1497                             diag::err_incomplete_type))
1498     return ExprError();
1499 
1500   assert(ParamTy->getPointeeType()->isObjectType() &&
1501          "Unhandled non-object pointer case");
1502 
1503   InitializedEntity Entity =
1504       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1505   ExprResult Arg =
1506       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1507   if (Arg.isInvalid())
1508     return ExprError();
1509   TheCall->setArg(0, Arg.get());
1510 
1511   return TheCall;
1512 }
1513 
1514 // Emit an error and return true if the current architecture is not in the list
1515 // of supported architectures.
1516 static bool
1517 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1518                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1519   llvm::Triple::ArchType CurArch =
1520       S.getASTContext().getTargetInfo().getTriple().getArch();
1521   if (llvm::is_contained(SupportedArchs, CurArch))
1522     return false;
1523   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1524       << TheCall->getSourceRange();
1525   return true;
1526 }
1527 
1528 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1529                                  SourceLocation CallSiteLoc);
1530 
1531 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1532                                       CallExpr *TheCall) {
1533   switch (TI.getTriple().getArch()) {
1534   default:
1535     // Some builtins don't require additional checking, so just consider these
1536     // acceptable.
1537     return false;
1538   case llvm::Triple::arm:
1539   case llvm::Triple::armeb:
1540   case llvm::Triple::thumb:
1541   case llvm::Triple::thumbeb:
1542     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1543   case llvm::Triple::aarch64:
1544   case llvm::Triple::aarch64_32:
1545   case llvm::Triple::aarch64_be:
1546     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1547   case llvm::Triple::bpfeb:
1548   case llvm::Triple::bpfel:
1549     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1550   case llvm::Triple::hexagon:
1551     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1552   case llvm::Triple::mips:
1553   case llvm::Triple::mipsel:
1554   case llvm::Triple::mips64:
1555   case llvm::Triple::mips64el:
1556     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1557   case llvm::Triple::systemz:
1558     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1559   case llvm::Triple::x86:
1560   case llvm::Triple::x86_64:
1561     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1562   case llvm::Triple::ppc:
1563   case llvm::Triple::ppcle:
1564   case llvm::Triple::ppc64:
1565   case llvm::Triple::ppc64le:
1566     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1567   case llvm::Triple::amdgcn:
1568     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1569   case llvm::Triple::riscv32:
1570   case llvm::Triple::riscv64:
1571     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1572   }
1573 }
1574 
1575 ExprResult
1576 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1577                                CallExpr *TheCall) {
1578   ExprResult TheCallResult(TheCall);
1579 
1580   // Find out if any arguments are required to be integer constant expressions.
1581   unsigned ICEArguments = 0;
1582   ASTContext::GetBuiltinTypeError Error;
1583   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1584   if (Error != ASTContext::GE_None)
1585     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1586 
1587   // If any arguments are required to be ICE's, check and diagnose.
1588   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1589     // Skip arguments not required to be ICE's.
1590     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1591 
1592     llvm::APSInt Result;
1593     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1594       return true;
1595     ICEArguments &= ~(1 << ArgNo);
1596   }
1597 
1598   switch (BuiltinID) {
1599   case Builtin::BI__builtin___CFStringMakeConstantString:
1600     assert(TheCall->getNumArgs() == 1 &&
1601            "Wrong # arguments to builtin CFStringMakeConstantString");
1602     if (CheckObjCString(TheCall->getArg(0)))
1603       return ExprError();
1604     break;
1605   case Builtin::BI__builtin_ms_va_start:
1606   case Builtin::BI__builtin_stdarg_start:
1607   case Builtin::BI__builtin_va_start:
1608     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1609       return ExprError();
1610     break;
1611   case Builtin::BI__va_start: {
1612     switch (Context.getTargetInfo().getTriple().getArch()) {
1613     case llvm::Triple::aarch64:
1614     case llvm::Triple::arm:
1615     case llvm::Triple::thumb:
1616       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1617         return ExprError();
1618       break;
1619     default:
1620       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1621         return ExprError();
1622       break;
1623     }
1624     break;
1625   }
1626 
1627   // The acquire, release, and no fence variants are ARM and AArch64 only.
1628   case Builtin::BI_interlockedbittestandset_acq:
1629   case Builtin::BI_interlockedbittestandset_rel:
1630   case Builtin::BI_interlockedbittestandset_nf:
1631   case Builtin::BI_interlockedbittestandreset_acq:
1632   case Builtin::BI_interlockedbittestandreset_rel:
1633   case Builtin::BI_interlockedbittestandreset_nf:
1634     if (CheckBuiltinTargetSupport(
1635             *this, BuiltinID, TheCall,
1636             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1637       return ExprError();
1638     break;
1639 
1640   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1641   case Builtin::BI_bittest64:
1642   case Builtin::BI_bittestandcomplement64:
1643   case Builtin::BI_bittestandreset64:
1644   case Builtin::BI_bittestandset64:
1645   case Builtin::BI_interlockedbittestandreset64:
1646   case Builtin::BI_interlockedbittestandset64:
1647     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1648                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1649                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1650       return ExprError();
1651     break;
1652 
1653   case Builtin::BI__builtin_isgreater:
1654   case Builtin::BI__builtin_isgreaterequal:
1655   case Builtin::BI__builtin_isless:
1656   case Builtin::BI__builtin_islessequal:
1657   case Builtin::BI__builtin_islessgreater:
1658   case Builtin::BI__builtin_isunordered:
1659     if (SemaBuiltinUnorderedCompare(TheCall))
1660       return ExprError();
1661     break;
1662   case Builtin::BI__builtin_fpclassify:
1663     if (SemaBuiltinFPClassification(TheCall, 6))
1664       return ExprError();
1665     break;
1666   case Builtin::BI__builtin_isfinite:
1667   case Builtin::BI__builtin_isinf:
1668   case Builtin::BI__builtin_isinf_sign:
1669   case Builtin::BI__builtin_isnan:
1670   case Builtin::BI__builtin_isnormal:
1671   case Builtin::BI__builtin_signbit:
1672   case Builtin::BI__builtin_signbitf:
1673   case Builtin::BI__builtin_signbitl:
1674     if (SemaBuiltinFPClassification(TheCall, 1))
1675       return ExprError();
1676     break;
1677   case Builtin::BI__builtin_shufflevector:
1678     return SemaBuiltinShuffleVector(TheCall);
1679     // TheCall will be freed by the smart pointer here, but that's fine, since
1680     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1681   case Builtin::BI__builtin_prefetch:
1682     if (SemaBuiltinPrefetch(TheCall))
1683       return ExprError();
1684     break;
1685   case Builtin::BI__builtin_alloca_with_align:
1686     if (SemaBuiltinAllocaWithAlign(TheCall))
1687       return ExprError();
1688     LLVM_FALLTHROUGH;
1689   case Builtin::BI__builtin_alloca:
1690     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1691         << TheCall->getDirectCallee();
1692     break;
1693   case Builtin::BI__arithmetic_fence:
1694     if (SemaBuiltinArithmeticFence(TheCall))
1695       return ExprError();
1696     break;
1697   case Builtin::BI__assume:
1698   case Builtin::BI__builtin_assume:
1699     if (SemaBuiltinAssume(TheCall))
1700       return ExprError();
1701     break;
1702   case Builtin::BI__builtin_assume_aligned:
1703     if (SemaBuiltinAssumeAligned(TheCall))
1704       return ExprError();
1705     break;
1706   case Builtin::BI__builtin_dynamic_object_size:
1707   case Builtin::BI__builtin_object_size:
1708     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1709       return ExprError();
1710     break;
1711   case Builtin::BI__builtin_longjmp:
1712     if (SemaBuiltinLongjmp(TheCall))
1713       return ExprError();
1714     break;
1715   case Builtin::BI__builtin_setjmp:
1716     if (SemaBuiltinSetjmp(TheCall))
1717       return ExprError();
1718     break;
1719   case Builtin::BI__builtin_classify_type:
1720     if (checkArgCount(*this, TheCall, 1)) return true;
1721     TheCall->setType(Context.IntTy);
1722     break;
1723   case Builtin::BI__builtin_complex:
1724     if (SemaBuiltinComplex(TheCall))
1725       return ExprError();
1726     break;
1727   case Builtin::BI__builtin_constant_p: {
1728     if (checkArgCount(*this, TheCall, 1)) return true;
1729     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1730     if (Arg.isInvalid()) return true;
1731     TheCall->setArg(0, Arg.get());
1732     TheCall->setType(Context.IntTy);
1733     break;
1734   }
1735   case Builtin::BI__builtin_launder:
1736     return SemaBuiltinLaunder(*this, TheCall);
1737   case Builtin::BI__sync_fetch_and_add:
1738   case Builtin::BI__sync_fetch_and_add_1:
1739   case Builtin::BI__sync_fetch_and_add_2:
1740   case Builtin::BI__sync_fetch_and_add_4:
1741   case Builtin::BI__sync_fetch_and_add_8:
1742   case Builtin::BI__sync_fetch_and_add_16:
1743   case Builtin::BI__sync_fetch_and_sub:
1744   case Builtin::BI__sync_fetch_and_sub_1:
1745   case Builtin::BI__sync_fetch_and_sub_2:
1746   case Builtin::BI__sync_fetch_and_sub_4:
1747   case Builtin::BI__sync_fetch_and_sub_8:
1748   case Builtin::BI__sync_fetch_and_sub_16:
1749   case Builtin::BI__sync_fetch_and_or:
1750   case Builtin::BI__sync_fetch_and_or_1:
1751   case Builtin::BI__sync_fetch_and_or_2:
1752   case Builtin::BI__sync_fetch_and_or_4:
1753   case Builtin::BI__sync_fetch_and_or_8:
1754   case Builtin::BI__sync_fetch_and_or_16:
1755   case Builtin::BI__sync_fetch_and_and:
1756   case Builtin::BI__sync_fetch_and_and_1:
1757   case Builtin::BI__sync_fetch_and_and_2:
1758   case Builtin::BI__sync_fetch_and_and_4:
1759   case Builtin::BI__sync_fetch_and_and_8:
1760   case Builtin::BI__sync_fetch_and_and_16:
1761   case Builtin::BI__sync_fetch_and_xor:
1762   case Builtin::BI__sync_fetch_and_xor_1:
1763   case Builtin::BI__sync_fetch_and_xor_2:
1764   case Builtin::BI__sync_fetch_and_xor_4:
1765   case Builtin::BI__sync_fetch_and_xor_8:
1766   case Builtin::BI__sync_fetch_and_xor_16:
1767   case Builtin::BI__sync_fetch_and_nand:
1768   case Builtin::BI__sync_fetch_and_nand_1:
1769   case Builtin::BI__sync_fetch_and_nand_2:
1770   case Builtin::BI__sync_fetch_and_nand_4:
1771   case Builtin::BI__sync_fetch_and_nand_8:
1772   case Builtin::BI__sync_fetch_and_nand_16:
1773   case Builtin::BI__sync_add_and_fetch:
1774   case Builtin::BI__sync_add_and_fetch_1:
1775   case Builtin::BI__sync_add_and_fetch_2:
1776   case Builtin::BI__sync_add_and_fetch_4:
1777   case Builtin::BI__sync_add_and_fetch_8:
1778   case Builtin::BI__sync_add_and_fetch_16:
1779   case Builtin::BI__sync_sub_and_fetch:
1780   case Builtin::BI__sync_sub_and_fetch_1:
1781   case Builtin::BI__sync_sub_and_fetch_2:
1782   case Builtin::BI__sync_sub_and_fetch_4:
1783   case Builtin::BI__sync_sub_and_fetch_8:
1784   case Builtin::BI__sync_sub_and_fetch_16:
1785   case Builtin::BI__sync_and_and_fetch:
1786   case Builtin::BI__sync_and_and_fetch_1:
1787   case Builtin::BI__sync_and_and_fetch_2:
1788   case Builtin::BI__sync_and_and_fetch_4:
1789   case Builtin::BI__sync_and_and_fetch_8:
1790   case Builtin::BI__sync_and_and_fetch_16:
1791   case Builtin::BI__sync_or_and_fetch:
1792   case Builtin::BI__sync_or_and_fetch_1:
1793   case Builtin::BI__sync_or_and_fetch_2:
1794   case Builtin::BI__sync_or_and_fetch_4:
1795   case Builtin::BI__sync_or_and_fetch_8:
1796   case Builtin::BI__sync_or_and_fetch_16:
1797   case Builtin::BI__sync_xor_and_fetch:
1798   case Builtin::BI__sync_xor_and_fetch_1:
1799   case Builtin::BI__sync_xor_and_fetch_2:
1800   case Builtin::BI__sync_xor_and_fetch_4:
1801   case Builtin::BI__sync_xor_and_fetch_8:
1802   case Builtin::BI__sync_xor_and_fetch_16:
1803   case Builtin::BI__sync_nand_and_fetch:
1804   case Builtin::BI__sync_nand_and_fetch_1:
1805   case Builtin::BI__sync_nand_and_fetch_2:
1806   case Builtin::BI__sync_nand_and_fetch_4:
1807   case Builtin::BI__sync_nand_and_fetch_8:
1808   case Builtin::BI__sync_nand_and_fetch_16:
1809   case Builtin::BI__sync_val_compare_and_swap:
1810   case Builtin::BI__sync_val_compare_and_swap_1:
1811   case Builtin::BI__sync_val_compare_and_swap_2:
1812   case Builtin::BI__sync_val_compare_and_swap_4:
1813   case Builtin::BI__sync_val_compare_and_swap_8:
1814   case Builtin::BI__sync_val_compare_and_swap_16:
1815   case Builtin::BI__sync_bool_compare_and_swap:
1816   case Builtin::BI__sync_bool_compare_and_swap_1:
1817   case Builtin::BI__sync_bool_compare_and_swap_2:
1818   case Builtin::BI__sync_bool_compare_and_swap_4:
1819   case Builtin::BI__sync_bool_compare_and_swap_8:
1820   case Builtin::BI__sync_bool_compare_and_swap_16:
1821   case Builtin::BI__sync_lock_test_and_set:
1822   case Builtin::BI__sync_lock_test_and_set_1:
1823   case Builtin::BI__sync_lock_test_and_set_2:
1824   case Builtin::BI__sync_lock_test_and_set_4:
1825   case Builtin::BI__sync_lock_test_and_set_8:
1826   case Builtin::BI__sync_lock_test_and_set_16:
1827   case Builtin::BI__sync_lock_release:
1828   case Builtin::BI__sync_lock_release_1:
1829   case Builtin::BI__sync_lock_release_2:
1830   case Builtin::BI__sync_lock_release_4:
1831   case Builtin::BI__sync_lock_release_8:
1832   case Builtin::BI__sync_lock_release_16:
1833   case Builtin::BI__sync_swap:
1834   case Builtin::BI__sync_swap_1:
1835   case Builtin::BI__sync_swap_2:
1836   case Builtin::BI__sync_swap_4:
1837   case Builtin::BI__sync_swap_8:
1838   case Builtin::BI__sync_swap_16:
1839     return SemaBuiltinAtomicOverloaded(TheCallResult);
1840   case Builtin::BI__sync_synchronize:
1841     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1842         << TheCall->getCallee()->getSourceRange();
1843     break;
1844   case Builtin::BI__builtin_nontemporal_load:
1845   case Builtin::BI__builtin_nontemporal_store:
1846     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1847   case Builtin::BI__builtin_memcpy_inline: {
1848     clang::Expr *SizeOp = TheCall->getArg(2);
1849     // We warn about copying to or from `nullptr` pointers when `size` is
1850     // greater than 0. When `size` is value dependent we cannot evaluate its
1851     // value so we bail out.
1852     if (SizeOp->isValueDependent())
1853       break;
1854     if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
1855       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1856       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1857     }
1858     break;
1859   }
1860 #define BUILTIN(ID, TYPE, ATTRS)
1861 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1862   case Builtin::BI##ID: \
1863     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1864 #include "clang/Basic/Builtins.def"
1865   case Builtin::BI__annotation:
1866     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1867       return ExprError();
1868     break;
1869   case Builtin::BI__builtin_annotation:
1870     if (SemaBuiltinAnnotation(*this, TheCall))
1871       return ExprError();
1872     break;
1873   case Builtin::BI__builtin_addressof:
1874     if (SemaBuiltinAddressof(*this, TheCall))
1875       return ExprError();
1876     break;
1877   case Builtin::BI__builtin_is_aligned:
1878   case Builtin::BI__builtin_align_up:
1879   case Builtin::BI__builtin_align_down:
1880     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1881       return ExprError();
1882     break;
1883   case Builtin::BI__builtin_add_overflow:
1884   case Builtin::BI__builtin_sub_overflow:
1885   case Builtin::BI__builtin_mul_overflow:
1886     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1887       return ExprError();
1888     break;
1889   case Builtin::BI__builtin_operator_new:
1890   case Builtin::BI__builtin_operator_delete: {
1891     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1892     ExprResult Res =
1893         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1894     if (Res.isInvalid())
1895       CorrectDelayedTyposInExpr(TheCallResult.get());
1896     return Res;
1897   }
1898   case Builtin::BI__builtin_dump_struct: {
1899     // We first want to ensure we are called with 2 arguments
1900     if (checkArgCount(*this, TheCall, 2))
1901       return ExprError();
1902     // Ensure that the first argument is of type 'struct XX *'
1903     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1904     const QualType PtrArgType = PtrArg->getType();
1905     if (!PtrArgType->isPointerType() ||
1906         !PtrArgType->getPointeeType()->isRecordType()) {
1907       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1908           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1909           << "structure pointer";
1910       return ExprError();
1911     }
1912 
1913     // Ensure that the second argument is of type 'FunctionType'
1914     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1915     const QualType FnPtrArgType = FnPtrArg->getType();
1916     if (!FnPtrArgType->isPointerType()) {
1917       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1918           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1919           << FnPtrArgType << "'int (*)(const char *, ...)'";
1920       return ExprError();
1921     }
1922 
1923     const auto *FuncType =
1924         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1925 
1926     if (!FuncType) {
1927       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1928           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1929           << FnPtrArgType << "'int (*)(const char *, ...)'";
1930       return ExprError();
1931     }
1932 
1933     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1934       if (!FT->getNumParams()) {
1935         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1936             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1937             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1938         return ExprError();
1939       }
1940       QualType PT = FT->getParamType(0);
1941       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1942           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1943           !PT->getPointeeType().isConstQualified()) {
1944         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1945             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1946             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1947         return ExprError();
1948       }
1949     }
1950 
1951     TheCall->setType(Context.IntTy);
1952     break;
1953   }
1954   case Builtin::BI__builtin_expect_with_probability: {
1955     // We first want to ensure we are called with 3 arguments
1956     if (checkArgCount(*this, TheCall, 3))
1957       return ExprError();
1958     // then check probability is constant float in range [0.0, 1.0]
1959     const Expr *ProbArg = TheCall->getArg(2);
1960     SmallVector<PartialDiagnosticAt, 8> Notes;
1961     Expr::EvalResult Eval;
1962     Eval.Diag = &Notes;
1963     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1964         !Eval.Val.isFloat()) {
1965       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1966           << ProbArg->getSourceRange();
1967       for (const PartialDiagnosticAt &PDiag : Notes)
1968         Diag(PDiag.first, PDiag.second);
1969       return ExprError();
1970     }
1971     llvm::APFloat Probability = Eval.Val.getFloat();
1972     bool LoseInfo = false;
1973     Probability.convert(llvm::APFloat::IEEEdouble(),
1974                         llvm::RoundingMode::Dynamic, &LoseInfo);
1975     if (!(Probability >= llvm::APFloat(0.0) &&
1976           Probability <= llvm::APFloat(1.0))) {
1977       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1978           << ProbArg->getSourceRange();
1979       return ExprError();
1980     }
1981     break;
1982   }
1983   case Builtin::BI__builtin_preserve_access_index:
1984     if (SemaBuiltinPreserveAI(*this, TheCall))
1985       return ExprError();
1986     break;
1987   case Builtin::BI__builtin_call_with_static_chain:
1988     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1989       return ExprError();
1990     break;
1991   case Builtin::BI__exception_code:
1992   case Builtin::BI_exception_code:
1993     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1994                                  diag::err_seh___except_block))
1995       return ExprError();
1996     break;
1997   case Builtin::BI__exception_info:
1998   case Builtin::BI_exception_info:
1999     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
2000                                  diag::err_seh___except_filter))
2001       return ExprError();
2002     break;
2003   case Builtin::BI__GetExceptionInfo:
2004     if (checkArgCount(*this, TheCall, 1))
2005       return ExprError();
2006 
2007     if (CheckCXXThrowOperand(
2008             TheCall->getBeginLoc(),
2009             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
2010             TheCall))
2011       return ExprError();
2012 
2013     TheCall->setType(Context.VoidPtrTy);
2014     break;
2015   // OpenCL v2.0, s6.13.16 - Pipe functions
2016   case Builtin::BIread_pipe:
2017   case Builtin::BIwrite_pipe:
2018     // Since those two functions are declared with var args, we need a semantic
2019     // check for the argument.
2020     if (SemaBuiltinRWPipe(*this, TheCall))
2021       return ExprError();
2022     break;
2023   case Builtin::BIreserve_read_pipe:
2024   case Builtin::BIreserve_write_pipe:
2025   case Builtin::BIwork_group_reserve_read_pipe:
2026   case Builtin::BIwork_group_reserve_write_pipe:
2027     if (SemaBuiltinReserveRWPipe(*this, TheCall))
2028       return ExprError();
2029     break;
2030   case Builtin::BIsub_group_reserve_read_pipe:
2031   case Builtin::BIsub_group_reserve_write_pipe:
2032     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2033         SemaBuiltinReserveRWPipe(*this, TheCall))
2034       return ExprError();
2035     break;
2036   case Builtin::BIcommit_read_pipe:
2037   case Builtin::BIcommit_write_pipe:
2038   case Builtin::BIwork_group_commit_read_pipe:
2039   case Builtin::BIwork_group_commit_write_pipe:
2040     if (SemaBuiltinCommitRWPipe(*this, TheCall))
2041       return ExprError();
2042     break;
2043   case Builtin::BIsub_group_commit_read_pipe:
2044   case Builtin::BIsub_group_commit_write_pipe:
2045     if (checkOpenCLSubgroupExt(*this, TheCall) ||
2046         SemaBuiltinCommitRWPipe(*this, TheCall))
2047       return ExprError();
2048     break;
2049   case Builtin::BIget_pipe_num_packets:
2050   case Builtin::BIget_pipe_max_packets:
2051     if (SemaBuiltinPipePackets(*this, TheCall))
2052       return ExprError();
2053     break;
2054   case Builtin::BIto_global:
2055   case Builtin::BIto_local:
2056   case Builtin::BIto_private:
2057     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
2058       return ExprError();
2059     break;
2060   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
2061   case Builtin::BIenqueue_kernel:
2062     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
2063       return ExprError();
2064     break;
2065   case Builtin::BIget_kernel_work_group_size:
2066   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
2067     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
2068       return ExprError();
2069     break;
2070   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
2071   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
2072     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
2073       return ExprError();
2074     break;
2075   case Builtin::BI__builtin_os_log_format:
2076     Cleanup.setExprNeedsCleanups(true);
2077     LLVM_FALLTHROUGH;
2078   case Builtin::BI__builtin_os_log_format_buffer_size:
2079     if (SemaBuiltinOSLogFormat(TheCall))
2080       return ExprError();
2081     break;
2082   case Builtin::BI__builtin_frame_address:
2083   case Builtin::BI__builtin_return_address: {
2084     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
2085       return ExprError();
2086 
2087     // -Wframe-address warning if non-zero passed to builtin
2088     // return/frame address.
2089     Expr::EvalResult Result;
2090     if (!TheCall->getArg(0)->isValueDependent() &&
2091         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
2092         Result.Val.getInt() != 0)
2093       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
2094           << ((BuiltinID == Builtin::BI__builtin_return_address)
2095                   ? "__builtin_return_address"
2096                   : "__builtin_frame_address")
2097           << TheCall->getSourceRange();
2098     break;
2099   }
2100 
2101   case Builtin::BI__builtin_elementwise_abs:
2102     if (SemaBuiltinElementwiseMathOneArg(TheCall))
2103       return ExprError();
2104     break;
2105   case Builtin::BI__builtin_elementwise_min:
2106   case Builtin::BI__builtin_elementwise_max:
2107     if (SemaBuiltinElementwiseMath(TheCall))
2108       return ExprError();
2109     break;
2110   case Builtin::BI__builtin_reduce_max:
2111   case Builtin::BI__builtin_reduce_min:
2112     if (SemaBuiltinReduceMath(TheCall))
2113       return ExprError();
2114     break;
2115   case Builtin::BI__builtin_matrix_transpose:
2116     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
2117 
2118   case Builtin::BI__builtin_matrix_column_major_load:
2119     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
2120 
2121   case Builtin::BI__builtin_matrix_column_major_store:
2122     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
2123 
2124   case Builtin::BI__builtin_get_device_side_mangled_name: {
2125     auto Check = [](CallExpr *TheCall) {
2126       if (TheCall->getNumArgs() != 1)
2127         return false;
2128       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2129       if (!DRE)
2130         return false;
2131       auto *D = DRE->getDecl();
2132       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2133         return false;
2134       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2135              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2136     };
2137     if (!Check(TheCall)) {
2138       Diag(TheCall->getBeginLoc(),
2139            diag::err_hip_invalid_args_builtin_mangled_name);
2140       return ExprError();
2141     }
2142   }
2143   }
2144 
2145   // Since the target specific builtins for each arch overlap, only check those
2146   // of the arch we are compiling for.
2147   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2148     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2149       assert(Context.getAuxTargetInfo() &&
2150              "Aux Target Builtin, but not an aux target?");
2151 
2152       if (CheckTSBuiltinFunctionCall(
2153               *Context.getAuxTargetInfo(),
2154               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2155         return ExprError();
2156     } else {
2157       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2158                                      TheCall))
2159         return ExprError();
2160     }
2161   }
2162 
2163   return TheCallResult;
2164 }
2165 
2166 // Get the valid immediate range for the specified NEON type code.
2167 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2168   NeonTypeFlags Type(t);
2169   int IsQuad = ForceQuad ? true : Type.isQuad();
2170   switch (Type.getEltType()) {
2171   case NeonTypeFlags::Int8:
2172   case NeonTypeFlags::Poly8:
2173     return shift ? 7 : (8 << IsQuad) - 1;
2174   case NeonTypeFlags::Int16:
2175   case NeonTypeFlags::Poly16:
2176     return shift ? 15 : (4 << IsQuad) - 1;
2177   case NeonTypeFlags::Int32:
2178     return shift ? 31 : (2 << IsQuad) - 1;
2179   case NeonTypeFlags::Int64:
2180   case NeonTypeFlags::Poly64:
2181     return shift ? 63 : (1 << IsQuad) - 1;
2182   case NeonTypeFlags::Poly128:
2183     return shift ? 127 : (1 << IsQuad) - 1;
2184   case NeonTypeFlags::Float16:
2185     assert(!shift && "cannot shift float types!");
2186     return (4 << IsQuad) - 1;
2187   case NeonTypeFlags::Float32:
2188     assert(!shift && "cannot shift float types!");
2189     return (2 << IsQuad) - 1;
2190   case NeonTypeFlags::Float64:
2191     assert(!shift && "cannot shift float types!");
2192     return (1 << IsQuad) - 1;
2193   case NeonTypeFlags::BFloat16:
2194     assert(!shift && "cannot shift float types!");
2195     return (4 << IsQuad) - 1;
2196   }
2197   llvm_unreachable("Invalid NeonTypeFlag!");
2198 }
2199 
2200 /// getNeonEltType - Return the QualType corresponding to the elements of
2201 /// the vector type specified by the NeonTypeFlags.  This is used to check
2202 /// the pointer arguments for Neon load/store intrinsics.
2203 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2204                                bool IsPolyUnsigned, bool IsInt64Long) {
2205   switch (Flags.getEltType()) {
2206   case NeonTypeFlags::Int8:
2207     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2208   case NeonTypeFlags::Int16:
2209     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2210   case NeonTypeFlags::Int32:
2211     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2212   case NeonTypeFlags::Int64:
2213     if (IsInt64Long)
2214       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2215     else
2216       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2217                                 : Context.LongLongTy;
2218   case NeonTypeFlags::Poly8:
2219     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2220   case NeonTypeFlags::Poly16:
2221     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2222   case NeonTypeFlags::Poly64:
2223     if (IsInt64Long)
2224       return Context.UnsignedLongTy;
2225     else
2226       return Context.UnsignedLongLongTy;
2227   case NeonTypeFlags::Poly128:
2228     break;
2229   case NeonTypeFlags::Float16:
2230     return Context.HalfTy;
2231   case NeonTypeFlags::Float32:
2232     return Context.FloatTy;
2233   case NeonTypeFlags::Float64:
2234     return Context.DoubleTy;
2235   case NeonTypeFlags::BFloat16:
2236     return Context.BFloat16Ty;
2237   }
2238   llvm_unreachable("Invalid NeonTypeFlag!");
2239 }
2240 
2241 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2242   // Range check SVE intrinsics that take immediate values.
2243   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2244 
2245   switch (BuiltinID) {
2246   default:
2247     return false;
2248 #define GET_SVE_IMMEDIATE_CHECK
2249 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2250 #undef GET_SVE_IMMEDIATE_CHECK
2251   }
2252 
2253   // Perform all the immediate checks for this builtin call.
2254   bool HasError = false;
2255   for (auto &I : ImmChecks) {
2256     int ArgNum, CheckTy, ElementSizeInBits;
2257     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2258 
2259     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2260 
2261     // Function that checks whether the operand (ArgNum) is an immediate
2262     // that is one of the predefined values.
2263     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2264                                    int ErrDiag) -> bool {
2265       // We can't check the value of a dependent argument.
2266       Expr *Arg = TheCall->getArg(ArgNum);
2267       if (Arg->isTypeDependent() || Arg->isValueDependent())
2268         return false;
2269 
2270       // Check constant-ness first.
2271       llvm::APSInt Imm;
2272       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2273         return true;
2274 
2275       if (!CheckImm(Imm.getSExtValue()))
2276         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2277       return false;
2278     };
2279 
2280     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2281     case SVETypeFlags::ImmCheck0_31:
2282       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2283         HasError = true;
2284       break;
2285     case SVETypeFlags::ImmCheck0_13:
2286       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2287         HasError = true;
2288       break;
2289     case SVETypeFlags::ImmCheck1_16:
2290       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2291         HasError = true;
2292       break;
2293     case SVETypeFlags::ImmCheck0_7:
2294       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2295         HasError = true;
2296       break;
2297     case SVETypeFlags::ImmCheckExtract:
2298       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2299                                       (2048 / ElementSizeInBits) - 1))
2300         HasError = true;
2301       break;
2302     case SVETypeFlags::ImmCheckShiftRight:
2303       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2304         HasError = true;
2305       break;
2306     case SVETypeFlags::ImmCheckShiftRightNarrow:
2307       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2308                                       ElementSizeInBits / 2))
2309         HasError = true;
2310       break;
2311     case SVETypeFlags::ImmCheckShiftLeft:
2312       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2313                                       ElementSizeInBits - 1))
2314         HasError = true;
2315       break;
2316     case SVETypeFlags::ImmCheckLaneIndex:
2317       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2318                                       (128 / (1 * ElementSizeInBits)) - 1))
2319         HasError = true;
2320       break;
2321     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2322       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2323                                       (128 / (2 * ElementSizeInBits)) - 1))
2324         HasError = true;
2325       break;
2326     case SVETypeFlags::ImmCheckLaneIndexDot:
2327       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2328                                       (128 / (4 * ElementSizeInBits)) - 1))
2329         HasError = true;
2330       break;
2331     case SVETypeFlags::ImmCheckComplexRot90_270:
2332       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2333                               diag::err_rotation_argument_to_cadd))
2334         HasError = true;
2335       break;
2336     case SVETypeFlags::ImmCheckComplexRotAll90:
2337       if (CheckImmediateInSet(
2338               [](int64_t V) {
2339                 return V == 0 || V == 90 || V == 180 || V == 270;
2340               },
2341               diag::err_rotation_argument_to_cmla))
2342         HasError = true;
2343       break;
2344     case SVETypeFlags::ImmCheck0_1:
2345       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2346         HasError = true;
2347       break;
2348     case SVETypeFlags::ImmCheck0_2:
2349       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2350         HasError = true;
2351       break;
2352     case SVETypeFlags::ImmCheck0_3:
2353       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2354         HasError = true;
2355       break;
2356     }
2357   }
2358 
2359   return HasError;
2360 }
2361 
2362 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2363                                         unsigned BuiltinID, CallExpr *TheCall) {
2364   llvm::APSInt Result;
2365   uint64_t mask = 0;
2366   unsigned TV = 0;
2367   int PtrArgNum = -1;
2368   bool HasConstPtr = false;
2369   switch (BuiltinID) {
2370 #define GET_NEON_OVERLOAD_CHECK
2371 #include "clang/Basic/arm_neon.inc"
2372 #include "clang/Basic/arm_fp16.inc"
2373 #undef GET_NEON_OVERLOAD_CHECK
2374   }
2375 
2376   // For NEON intrinsics which are overloaded on vector element type, validate
2377   // the immediate which specifies which variant to emit.
2378   unsigned ImmArg = TheCall->getNumArgs()-1;
2379   if (mask) {
2380     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2381       return true;
2382 
2383     TV = Result.getLimitedValue(64);
2384     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2385       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2386              << TheCall->getArg(ImmArg)->getSourceRange();
2387   }
2388 
2389   if (PtrArgNum >= 0) {
2390     // Check that pointer arguments have the specified type.
2391     Expr *Arg = TheCall->getArg(PtrArgNum);
2392     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2393       Arg = ICE->getSubExpr();
2394     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2395     QualType RHSTy = RHS.get()->getType();
2396 
2397     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2398     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2399                           Arch == llvm::Triple::aarch64_32 ||
2400                           Arch == llvm::Triple::aarch64_be;
2401     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2402     QualType EltTy =
2403         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2404     if (HasConstPtr)
2405       EltTy = EltTy.withConst();
2406     QualType LHSTy = Context.getPointerType(EltTy);
2407     AssignConvertType ConvTy;
2408     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2409     if (RHS.isInvalid())
2410       return true;
2411     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2412                                  RHS.get(), AA_Assigning))
2413       return true;
2414   }
2415 
2416   // For NEON intrinsics which take an immediate value as part of the
2417   // instruction, range check them here.
2418   unsigned i = 0, l = 0, u = 0;
2419   switch (BuiltinID) {
2420   default:
2421     return false;
2422   #define GET_NEON_IMMEDIATE_CHECK
2423   #include "clang/Basic/arm_neon.inc"
2424   #include "clang/Basic/arm_fp16.inc"
2425   #undef GET_NEON_IMMEDIATE_CHECK
2426   }
2427 
2428   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2429 }
2430 
2431 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2432   switch (BuiltinID) {
2433   default:
2434     return false;
2435   #include "clang/Basic/arm_mve_builtin_sema.inc"
2436   }
2437 }
2438 
2439 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2440                                        CallExpr *TheCall) {
2441   bool Err = false;
2442   switch (BuiltinID) {
2443   default:
2444     return false;
2445 #include "clang/Basic/arm_cde_builtin_sema.inc"
2446   }
2447 
2448   if (Err)
2449     return true;
2450 
2451   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2452 }
2453 
2454 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2455                                         const Expr *CoprocArg, bool WantCDE) {
2456   if (isConstantEvaluated())
2457     return false;
2458 
2459   // We can't check the value of a dependent argument.
2460   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2461     return false;
2462 
2463   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2464   int64_t CoprocNo = CoprocNoAP.getExtValue();
2465   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2466 
2467   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2468   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2469 
2470   if (IsCDECoproc != WantCDE)
2471     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2472            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2473 
2474   return false;
2475 }
2476 
2477 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2478                                         unsigned MaxWidth) {
2479   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2480           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2481           BuiltinID == ARM::BI__builtin_arm_strex ||
2482           BuiltinID == ARM::BI__builtin_arm_stlex ||
2483           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2484           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2485           BuiltinID == AArch64::BI__builtin_arm_strex ||
2486           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2487          "unexpected ARM builtin");
2488   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2489                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2490                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2491                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2492 
2493   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2494 
2495   // Ensure that we have the proper number of arguments.
2496   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2497     return true;
2498 
2499   // Inspect the pointer argument of the atomic builtin.  This should always be
2500   // a pointer type, whose element is an integral scalar or pointer type.
2501   // Because it is a pointer type, we don't have to worry about any implicit
2502   // casts here.
2503   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2504   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2505   if (PointerArgRes.isInvalid())
2506     return true;
2507   PointerArg = PointerArgRes.get();
2508 
2509   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2510   if (!pointerType) {
2511     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2512         << PointerArg->getType() << PointerArg->getSourceRange();
2513     return true;
2514   }
2515 
2516   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2517   // task is to insert the appropriate casts into the AST. First work out just
2518   // what the appropriate type is.
2519   QualType ValType = pointerType->getPointeeType();
2520   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2521   if (IsLdrex)
2522     AddrType.addConst();
2523 
2524   // Issue a warning if the cast is dodgy.
2525   CastKind CastNeeded = CK_NoOp;
2526   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2527     CastNeeded = CK_BitCast;
2528     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2529         << PointerArg->getType() << Context.getPointerType(AddrType)
2530         << AA_Passing << PointerArg->getSourceRange();
2531   }
2532 
2533   // Finally, do the cast and replace the argument with the corrected version.
2534   AddrType = Context.getPointerType(AddrType);
2535   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2536   if (PointerArgRes.isInvalid())
2537     return true;
2538   PointerArg = PointerArgRes.get();
2539 
2540   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2541 
2542   // In general, we allow ints, floats and pointers to be loaded and stored.
2543   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2544       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2545     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2546         << PointerArg->getType() << PointerArg->getSourceRange();
2547     return true;
2548   }
2549 
2550   // But ARM doesn't have instructions to deal with 128-bit versions.
2551   if (Context.getTypeSize(ValType) > MaxWidth) {
2552     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2553     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2554         << PointerArg->getType() << PointerArg->getSourceRange();
2555     return true;
2556   }
2557 
2558   switch (ValType.getObjCLifetime()) {
2559   case Qualifiers::OCL_None:
2560   case Qualifiers::OCL_ExplicitNone:
2561     // okay
2562     break;
2563 
2564   case Qualifiers::OCL_Weak:
2565   case Qualifiers::OCL_Strong:
2566   case Qualifiers::OCL_Autoreleasing:
2567     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2568         << ValType << PointerArg->getSourceRange();
2569     return true;
2570   }
2571 
2572   if (IsLdrex) {
2573     TheCall->setType(ValType);
2574     return false;
2575   }
2576 
2577   // Initialize the argument to be stored.
2578   ExprResult ValArg = TheCall->getArg(0);
2579   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2580       Context, ValType, /*consume*/ false);
2581   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2582   if (ValArg.isInvalid())
2583     return true;
2584   TheCall->setArg(0, ValArg.get());
2585 
2586   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2587   // but the custom checker bypasses all default analysis.
2588   TheCall->setType(Context.IntTy);
2589   return false;
2590 }
2591 
2592 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2593                                        CallExpr *TheCall) {
2594   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2595       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2596       BuiltinID == ARM::BI__builtin_arm_strex ||
2597       BuiltinID == ARM::BI__builtin_arm_stlex) {
2598     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2599   }
2600 
2601   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2602     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2603       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2604   }
2605 
2606   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2607       BuiltinID == ARM::BI__builtin_arm_wsr64)
2608     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2609 
2610   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2611       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2612       BuiltinID == ARM::BI__builtin_arm_wsr ||
2613       BuiltinID == ARM::BI__builtin_arm_wsrp)
2614     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2615 
2616   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2617     return true;
2618   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2619     return true;
2620   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2621     return true;
2622 
2623   // For intrinsics which take an immediate value as part of the instruction,
2624   // range check them here.
2625   // FIXME: VFP Intrinsics should error if VFP not present.
2626   switch (BuiltinID) {
2627   default: return false;
2628   case ARM::BI__builtin_arm_ssat:
2629     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2630   case ARM::BI__builtin_arm_usat:
2631     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2632   case ARM::BI__builtin_arm_ssat16:
2633     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2634   case ARM::BI__builtin_arm_usat16:
2635     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2636   case ARM::BI__builtin_arm_vcvtr_f:
2637   case ARM::BI__builtin_arm_vcvtr_d:
2638     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2639   case ARM::BI__builtin_arm_dmb:
2640   case ARM::BI__builtin_arm_dsb:
2641   case ARM::BI__builtin_arm_isb:
2642   case ARM::BI__builtin_arm_dbg:
2643     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2644   case ARM::BI__builtin_arm_cdp:
2645   case ARM::BI__builtin_arm_cdp2:
2646   case ARM::BI__builtin_arm_mcr:
2647   case ARM::BI__builtin_arm_mcr2:
2648   case ARM::BI__builtin_arm_mrc:
2649   case ARM::BI__builtin_arm_mrc2:
2650   case ARM::BI__builtin_arm_mcrr:
2651   case ARM::BI__builtin_arm_mcrr2:
2652   case ARM::BI__builtin_arm_mrrc:
2653   case ARM::BI__builtin_arm_mrrc2:
2654   case ARM::BI__builtin_arm_ldc:
2655   case ARM::BI__builtin_arm_ldcl:
2656   case ARM::BI__builtin_arm_ldc2:
2657   case ARM::BI__builtin_arm_ldc2l:
2658   case ARM::BI__builtin_arm_stc:
2659   case ARM::BI__builtin_arm_stcl:
2660   case ARM::BI__builtin_arm_stc2:
2661   case ARM::BI__builtin_arm_stc2l:
2662     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2663            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2664                                         /*WantCDE*/ false);
2665   }
2666 }
2667 
2668 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2669                                            unsigned BuiltinID,
2670                                            CallExpr *TheCall) {
2671   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2672       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2673       BuiltinID == AArch64::BI__builtin_arm_strex ||
2674       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2675     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2676   }
2677 
2678   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2679     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2680       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2681       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2682       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2683   }
2684 
2685   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2686       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2687     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2688 
2689   // Memory Tagging Extensions (MTE) Intrinsics
2690   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2691       BuiltinID == AArch64::BI__builtin_arm_addg ||
2692       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2693       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2694       BuiltinID == AArch64::BI__builtin_arm_stg ||
2695       BuiltinID == AArch64::BI__builtin_arm_subp) {
2696     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2697   }
2698 
2699   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2700       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2701       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2702       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2703     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2704 
2705   // Only check the valid encoding range. Any constant in this range would be
2706   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2707   // an exception for incorrect registers. This matches MSVC behavior.
2708   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2709       BuiltinID == AArch64::BI_WriteStatusReg)
2710     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2711 
2712   if (BuiltinID == AArch64::BI__getReg)
2713     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2714 
2715   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2716     return true;
2717 
2718   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2719     return true;
2720 
2721   // For intrinsics which take an immediate value as part of the instruction,
2722   // range check them here.
2723   unsigned i = 0, l = 0, u = 0;
2724   switch (BuiltinID) {
2725   default: return false;
2726   case AArch64::BI__builtin_arm_dmb:
2727   case AArch64::BI__builtin_arm_dsb:
2728   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2729   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2730   }
2731 
2732   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2733 }
2734 
2735 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2736   if (Arg->getType()->getAsPlaceholderType())
2737     return false;
2738 
2739   // The first argument needs to be a record field access.
2740   // If it is an array element access, we delay decision
2741   // to BPF backend to check whether the access is a
2742   // field access or not.
2743   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2744           isa<MemberExpr>(Arg->IgnoreParens()) ||
2745           isa<ArraySubscriptExpr>(Arg->IgnoreParens()));
2746 }
2747 
2748 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2749                             QualType VectorTy, QualType EltTy) {
2750   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2751   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2752     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2753         << Call->getSourceRange() << VectorEltTy << EltTy;
2754     return false;
2755   }
2756   return true;
2757 }
2758 
2759 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2760   QualType ArgType = Arg->getType();
2761   if (ArgType->getAsPlaceholderType())
2762     return false;
2763 
2764   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2765   // format:
2766   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2767   //   2. <type> var;
2768   //      __builtin_preserve_type_info(var, flag);
2769   if (!isa<DeclRefExpr>(Arg->IgnoreParens()) &&
2770       !isa<UnaryOperator>(Arg->IgnoreParens()))
2771     return false;
2772 
2773   // Typedef type.
2774   if (ArgType->getAs<TypedefType>())
2775     return true;
2776 
2777   // Record type or Enum type.
2778   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2779   if (const auto *RT = Ty->getAs<RecordType>()) {
2780     if (!RT->getDecl()->getDeclName().isEmpty())
2781       return true;
2782   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2783     if (!ET->getDecl()->getDeclName().isEmpty())
2784       return true;
2785   }
2786 
2787   return false;
2788 }
2789 
2790 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2791   QualType ArgType = Arg->getType();
2792   if (ArgType->getAsPlaceholderType())
2793     return false;
2794 
2795   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2796   // format:
2797   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2798   //                                 flag);
2799   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2800   if (!UO)
2801     return false;
2802 
2803   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2804   if (!CE)
2805     return false;
2806   if (CE->getCastKind() != CK_IntegralToPointer &&
2807       CE->getCastKind() != CK_NullToPointer)
2808     return false;
2809 
2810   // The integer must be from an EnumConstantDecl.
2811   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2812   if (!DR)
2813     return false;
2814 
2815   const EnumConstantDecl *Enumerator =
2816       dyn_cast<EnumConstantDecl>(DR->getDecl());
2817   if (!Enumerator)
2818     return false;
2819 
2820   // The type must be EnumType.
2821   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2822   const auto *ET = Ty->getAs<EnumType>();
2823   if (!ET)
2824     return false;
2825 
2826   // The enum value must be supported.
2827   return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
2828 }
2829 
2830 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2831                                        CallExpr *TheCall) {
2832   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2833           BuiltinID == BPF::BI__builtin_btf_type_id ||
2834           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2835           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2836          "unexpected BPF builtin");
2837 
2838   if (checkArgCount(*this, TheCall, 2))
2839     return true;
2840 
2841   // The second argument needs to be a constant int
2842   Expr *Arg = TheCall->getArg(1);
2843   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2844   diag::kind kind;
2845   if (!Value) {
2846     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2847       kind = diag::err_preserve_field_info_not_const;
2848     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2849       kind = diag::err_btf_type_id_not_const;
2850     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2851       kind = diag::err_preserve_type_info_not_const;
2852     else
2853       kind = diag::err_preserve_enum_value_not_const;
2854     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2855     return true;
2856   }
2857 
2858   // The first argument
2859   Arg = TheCall->getArg(0);
2860   bool InvalidArg = false;
2861   bool ReturnUnsignedInt = true;
2862   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2863     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2864       InvalidArg = true;
2865       kind = diag::err_preserve_field_info_not_field;
2866     }
2867   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2868     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2869       InvalidArg = true;
2870       kind = diag::err_preserve_type_info_invalid;
2871     }
2872   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2873     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2874       InvalidArg = true;
2875       kind = diag::err_preserve_enum_value_invalid;
2876     }
2877     ReturnUnsignedInt = false;
2878   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2879     ReturnUnsignedInt = false;
2880   }
2881 
2882   if (InvalidArg) {
2883     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2884     return true;
2885   }
2886 
2887   if (ReturnUnsignedInt)
2888     TheCall->setType(Context.UnsignedIntTy);
2889   else
2890     TheCall->setType(Context.UnsignedLongTy);
2891   return false;
2892 }
2893 
2894 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2895   struct ArgInfo {
2896     uint8_t OpNum;
2897     bool IsSigned;
2898     uint8_t BitWidth;
2899     uint8_t Align;
2900   };
2901   struct BuiltinInfo {
2902     unsigned BuiltinID;
2903     ArgInfo Infos[2];
2904   };
2905 
2906   static BuiltinInfo Infos[] = {
2907     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2908     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2909     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2910     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2911     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2912     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2913     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2914     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2915     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2916     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2917     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2918 
2919     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2922     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2923     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2924     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2925     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2927     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2928     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2929     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2930 
2931     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2934     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2935     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2939     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2940     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2941     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2942     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2943     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2944     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2945     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2946     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2947     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2948     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2949     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2950     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2951     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2952     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2953     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2954     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2955     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2956     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2957     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2958     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2959     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2960     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2961     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2962     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2963     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2964     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2965     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2966     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2967     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2968     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2969     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2970     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2971     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2972     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2973     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2974     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2975     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2976     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2977     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2978     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2979     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2980     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2981     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2982     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2983                                                       {{ 1, false, 6,  0 }} },
2984     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2985     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2986     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2987     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2988     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2989     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2990     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2991                                                       {{ 1, false, 5,  0 }} },
2992     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2993     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2994     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2995     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2996     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2997     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2998                                                        { 2, false, 5,  0 }} },
2999     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
3000                                                        { 2, false, 6,  0 }} },
3001     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
3002                                                        { 3, false, 5,  0 }} },
3003     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
3004                                                        { 3, false, 6,  0 }} },
3005     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
3006     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
3007     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
3008     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
3009     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
3010     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
3011     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
3012     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
3013     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
3014     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
3015     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
3016     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
3017     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
3018     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
3019     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
3020     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
3021                                                       {{ 2, false, 4,  0 },
3022                                                        { 3, false, 5,  0 }} },
3023     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
3024                                                       {{ 2, false, 4,  0 },
3025                                                        { 3, false, 5,  0 }} },
3026     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
3027                                                       {{ 2, false, 4,  0 },
3028                                                        { 3, false, 5,  0 }} },
3029     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
3030                                                       {{ 2, false, 4,  0 },
3031                                                        { 3, false, 5,  0 }} },
3032     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
3033     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
3034     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
3035     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
3036     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
3037     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
3038     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
3039     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
3040     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
3041     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
3042     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
3043                                                        { 2, false, 5,  0 }} },
3044     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
3045                                                        { 2, false, 6,  0 }} },
3046     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
3047     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
3048     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
3049     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
3050     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
3051     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
3052     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
3053     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
3054     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
3055                                                       {{ 1, false, 4,  0 }} },
3056     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
3057     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
3058                                                       {{ 1, false, 4,  0 }} },
3059     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
3060     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
3061     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
3062     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
3063     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
3064     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
3065     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
3066     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
3067     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
3068     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
3069     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
3070     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
3071     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
3072     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
3073     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
3074     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
3075     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
3076     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
3077     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
3078     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
3079                                                       {{ 3, false, 1,  0 }} },
3080     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
3081     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
3082     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
3083     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
3084                                                       {{ 3, false, 1,  0 }} },
3085     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
3086     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
3087     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
3088     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
3089                                                       {{ 3, false, 1,  0 }} },
3090   };
3091 
3092   // Use a dynamically initialized static to sort the table exactly once on
3093   // first run.
3094   static const bool SortOnce =
3095       (llvm::sort(Infos,
3096                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
3097                    return LHS.BuiltinID < RHS.BuiltinID;
3098                  }),
3099        true);
3100   (void)SortOnce;
3101 
3102   const BuiltinInfo *F = llvm::partition_point(
3103       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
3104   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
3105     return false;
3106 
3107   bool Error = false;
3108 
3109   for (const ArgInfo &A : F->Infos) {
3110     // Ignore empty ArgInfo elements.
3111     if (A.BitWidth == 0)
3112       continue;
3113 
3114     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
3115     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
3116     if (!A.Align) {
3117       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3118     } else {
3119       unsigned M = 1 << A.Align;
3120       Min *= M;
3121       Max *= M;
3122       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3123       Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3124     }
3125   }
3126   return Error;
3127 }
3128 
3129 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3130                                            CallExpr *TheCall) {
3131   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3132 }
3133 
3134 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3135                                         unsigned BuiltinID, CallExpr *TheCall) {
3136   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3137          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3138 }
3139 
3140 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3141                                CallExpr *TheCall) {
3142 
3143   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3144       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3145     if (!TI.hasFeature("dsp"))
3146       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3147   }
3148 
3149   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3150       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3151     if (!TI.hasFeature("dspr2"))
3152       return Diag(TheCall->getBeginLoc(),
3153                   diag::err_mips_builtin_requires_dspr2);
3154   }
3155 
3156   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3157       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3158     if (!TI.hasFeature("msa"))
3159       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3160   }
3161 
3162   return false;
3163 }
3164 
3165 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3166 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3167 // ordering for DSP is unspecified. MSA is ordered by the data format used
3168 // by the underlying instruction i.e., df/m, df/n and then by size.
3169 //
3170 // FIXME: The size tests here should instead be tablegen'd along with the
3171 //        definitions from include/clang/Basic/BuiltinsMips.def.
3172 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3173 //        be too.
3174 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3175   unsigned i = 0, l = 0, u = 0, m = 0;
3176   switch (BuiltinID) {
3177   default: return false;
3178   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3179   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3180   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3181   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3182   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3183   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3184   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3185   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3186   // df/m field.
3187   // These intrinsics take an unsigned 3 bit immediate.
3188   case Mips::BI__builtin_msa_bclri_b:
3189   case Mips::BI__builtin_msa_bnegi_b:
3190   case Mips::BI__builtin_msa_bseti_b:
3191   case Mips::BI__builtin_msa_sat_s_b:
3192   case Mips::BI__builtin_msa_sat_u_b:
3193   case Mips::BI__builtin_msa_slli_b:
3194   case Mips::BI__builtin_msa_srai_b:
3195   case Mips::BI__builtin_msa_srari_b:
3196   case Mips::BI__builtin_msa_srli_b:
3197   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3198   case Mips::BI__builtin_msa_binsli_b:
3199   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3200   // These intrinsics take an unsigned 4 bit immediate.
3201   case Mips::BI__builtin_msa_bclri_h:
3202   case Mips::BI__builtin_msa_bnegi_h:
3203   case Mips::BI__builtin_msa_bseti_h:
3204   case Mips::BI__builtin_msa_sat_s_h:
3205   case Mips::BI__builtin_msa_sat_u_h:
3206   case Mips::BI__builtin_msa_slli_h:
3207   case Mips::BI__builtin_msa_srai_h:
3208   case Mips::BI__builtin_msa_srari_h:
3209   case Mips::BI__builtin_msa_srli_h:
3210   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3211   case Mips::BI__builtin_msa_binsli_h:
3212   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3213   // These intrinsics take an unsigned 5 bit immediate.
3214   // The first block of intrinsics actually have an unsigned 5 bit field,
3215   // not a df/n field.
3216   case Mips::BI__builtin_msa_cfcmsa:
3217   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3218   case Mips::BI__builtin_msa_clei_u_b:
3219   case Mips::BI__builtin_msa_clei_u_h:
3220   case Mips::BI__builtin_msa_clei_u_w:
3221   case Mips::BI__builtin_msa_clei_u_d:
3222   case Mips::BI__builtin_msa_clti_u_b:
3223   case Mips::BI__builtin_msa_clti_u_h:
3224   case Mips::BI__builtin_msa_clti_u_w:
3225   case Mips::BI__builtin_msa_clti_u_d:
3226   case Mips::BI__builtin_msa_maxi_u_b:
3227   case Mips::BI__builtin_msa_maxi_u_h:
3228   case Mips::BI__builtin_msa_maxi_u_w:
3229   case Mips::BI__builtin_msa_maxi_u_d:
3230   case Mips::BI__builtin_msa_mini_u_b:
3231   case Mips::BI__builtin_msa_mini_u_h:
3232   case Mips::BI__builtin_msa_mini_u_w:
3233   case Mips::BI__builtin_msa_mini_u_d:
3234   case Mips::BI__builtin_msa_addvi_b:
3235   case Mips::BI__builtin_msa_addvi_h:
3236   case Mips::BI__builtin_msa_addvi_w:
3237   case Mips::BI__builtin_msa_addvi_d:
3238   case Mips::BI__builtin_msa_bclri_w:
3239   case Mips::BI__builtin_msa_bnegi_w:
3240   case Mips::BI__builtin_msa_bseti_w:
3241   case Mips::BI__builtin_msa_sat_s_w:
3242   case Mips::BI__builtin_msa_sat_u_w:
3243   case Mips::BI__builtin_msa_slli_w:
3244   case Mips::BI__builtin_msa_srai_w:
3245   case Mips::BI__builtin_msa_srari_w:
3246   case Mips::BI__builtin_msa_srli_w:
3247   case Mips::BI__builtin_msa_srlri_w:
3248   case Mips::BI__builtin_msa_subvi_b:
3249   case Mips::BI__builtin_msa_subvi_h:
3250   case Mips::BI__builtin_msa_subvi_w:
3251   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3252   case Mips::BI__builtin_msa_binsli_w:
3253   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3254   // These intrinsics take an unsigned 6 bit immediate.
3255   case Mips::BI__builtin_msa_bclri_d:
3256   case Mips::BI__builtin_msa_bnegi_d:
3257   case Mips::BI__builtin_msa_bseti_d:
3258   case Mips::BI__builtin_msa_sat_s_d:
3259   case Mips::BI__builtin_msa_sat_u_d:
3260   case Mips::BI__builtin_msa_slli_d:
3261   case Mips::BI__builtin_msa_srai_d:
3262   case Mips::BI__builtin_msa_srari_d:
3263   case Mips::BI__builtin_msa_srli_d:
3264   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3265   case Mips::BI__builtin_msa_binsli_d:
3266   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3267   // These intrinsics take a signed 5 bit immediate.
3268   case Mips::BI__builtin_msa_ceqi_b:
3269   case Mips::BI__builtin_msa_ceqi_h:
3270   case Mips::BI__builtin_msa_ceqi_w:
3271   case Mips::BI__builtin_msa_ceqi_d:
3272   case Mips::BI__builtin_msa_clti_s_b:
3273   case Mips::BI__builtin_msa_clti_s_h:
3274   case Mips::BI__builtin_msa_clti_s_w:
3275   case Mips::BI__builtin_msa_clti_s_d:
3276   case Mips::BI__builtin_msa_clei_s_b:
3277   case Mips::BI__builtin_msa_clei_s_h:
3278   case Mips::BI__builtin_msa_clei_s_w:
3279   case Mips::BI__builtin_msa_clei_s_d:
3280   case Mips::BI__builtin_msa_maxi_s_b:
3281   case Mips::BI__builtin_msa_maxi_s_h:
3282   case Mips::BI__builtin_msa_maxi_s_w:
3283   case Mips::BI__builtin_msa_maxi_s_d:
3284   case Mips::BI__builtin_msa_mini_s_b:
3285   case Mips::BI__builtin_msa_mini_s_h:
3286   case Mips::BI__builtin_msa_mini_s_w:
3287   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3288   // These intrinsics take an unsigned 8 bit immediate.
3289   case Mips::BI__builtin_msa_andi_b:
3290   case Mips::BI__builtin_msa_nori_b:
3291   case Mips::BI__builtin_msa_ori_b:
3292   case Mips::BI__builtin_msa_shf_b:
3293   case Mips::BI__builtin_msa_shf_h:
3294   case Mips::BI__builtin_msa_shf_w:
3295   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3296   case Mips::BI__builtin_msa_bseli_b:
3297   case Mips::BI__builtin_msa_bmnzi_b:
3298   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3299   // df/n format
3300   // These intrinsics take an unsigned 4 bit immediate.
3301   case Mips::BI__builtin_msa_copy_s_b:
3302   case Mips::BI__builtin_msa_copy_u_b:
3303   case Mips::BI__builtin_msa_insve_b:
3304   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3305   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3306   // These intrinsics take an unsigned 3 bit immediate.
3307   case Mips::BI__builtin_msa_copy_s_h:
3308   case Mips::BI__builtin_msa_copy_u_h:
3309   case Mips::BI__builtin_msa_insve_h:
3310   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3311   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3312   // These intrinsics take an unsigned 2 bit immediate.
3313   case Mips::BI__builtin_msa_copy_s_w:
3314   case Mips::BI__builtin_msa_copy_u_w:
3315   case Mips::BI__builtin_msa_insve_w:
3316   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3317   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3318   // These intrinsics take an unsigned 1 bit immediate.
3319   case Mips::BI__builtin_msa_copy_s_d:
3320   case Mips::BI__builtin_msa_copy_u_d:
3321   case Mips::BI__builtin_msa_insve_d:
3322   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3323   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3324   // Memory offsets and immediate loads.
3325   // These intrinsics take a signed 10 bit immediate.
3326   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3327   case Mips::BI__builtin_msa_ldi_h:
3328   case Mips::BI__builtin_msa_ldi_w:
3329   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3330   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3331   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3332   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3333   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3334   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3335   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3336   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3337   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3338   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3339   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3340   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3341   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3342   }
3343 
3344   if (!m)
3345     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3346 
3347   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3348          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3349 }
3350 
3351 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3352 /// advancing the pointer over the consumed characters. The decoded type is
3353 /// returned. If the decoded type represents a constant integer with a
3354 /// constraint on its value then Mask is set to that value. The type descriptors
3355 /// used in Str are specific to PPC MMA builtins and are documented in the file
3356 /// defining the PPC builtins.
3357 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3358                                         unsigned &Mask) {
3359   bool RequireICE = false;
3360   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3361   switch (*Str++) {
3362   case 'V':
3363     return Context.getVectorType(Context.UnsignedCharTy, 16,
3364                                  VectorType::VectorKind::AltiVecVector);
3365   case 'i': {
3366     char *End;
3367     unsigned size = strtoul(Str, &End, 10);
3368     assert(End != Str && "Missing constant parameter constraint");
3369     Str = End;
3370     Mask = size;
3371     return Context.IntTy;
3372   }
3373   case 'W': {
3374     char *End;
3375     unsigned size = strtoul(Str, &End, 10);
3376     assert(End != Str && "Missing PowerPC MMA type size");
3377     Str = End;
3378     QualType Type;
3379     switch (size) {
3380   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3381     case size: Type = Context.Id##Ty; break;
3382   #include "clang/Basic/PPCTypes.def"
3383     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3384     }
3385     bool CheckVectorArgs = false;
3386     while (!CheckVectorArgs) {
3387       switch (*Str++) {
3388       case '*':
3389         Type = Context.getPointerType(Type);
3390         break;
3391       case 'C':
3392         Type = Type.withConst();
3393         break;
3394       default:
3395         CheckVectorArgs = true;
3396         --Str;
3397         break;
3398       }
3399     }
3400     return Type;
3401   }
3402   default:
3403     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3404   }
3405 }
3406 
3407 static bool isPPC_64Builtin(unsigned BuiltinID) {
3408   // These builtins only work on PPC 64bit targets.
3409   switch (BuiltinID) {
3410   case PPC::BI__builtin_divde:
3411   case PPC::BI__builtin_divdeu:
3412   case PPC::BI__builtin_bpermd:
3413   case PPC::BI__builtin_ppc_ldarx:
3414   case PPC::BI__builtin_ppc_stdcx:
3415   case PPC::BI__builtin_ppc_tdw:
3416   case PPC::BI__builtin_ppc_trapd:
3417   case PPC::BI__builtin_ppc_cmpeqb:
3418   case PPC::BI__builtin_ppc_setb:
3419   case PPC::BI__builtin_ppc_mulhd:
3420   case PPC::BI__builtin_ppc_mulhdu:
3421   case PPC::BI__builtin_ppc_maddhd:
3422   case PPC::BI__builtin_ppc_maddhdu:
3423   case PPC::BI__builtin_ppc_maddld:
3424   case PPC::BI__builtin_ppc_load8r:
3425   case PPC::BI__builtin_ppc_store8r:
3426   case PPC::BI__builtin_ppc_insert_exp:
3427   case PPC::BI__builtin_ppc_extract_sig:
3428   case PPC::BI__builtin_ppc_addex:
3429   case PPC::BI__builtin_darn:
3430   case PPC::BI__builtin_darn_raw:
3431   case PPC::BI__builtin_ppc_compare_and_swaplp:
3432   case PPC::BI__builtin_ppc_fetch_and_addlp:
3433   case PPC::BI__builtin_ppc_fetch_and_andlp:
3434   case PPC::BI__builtin_ppc_fetch_and_orlp:
3435   case PPC::BI__builtin_ppc_fetch_and_swaplp:
3436     return true;
3437   }
3438   return false;
3439 }
3440 
3441 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3442                              StringRef FeatureToCheck, unsigned DiagID,
3443                              StringRef DiagArg = "") {
3444   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3445     return false;
3446 
3447   if (DiagArg.empty())
3448     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3449   else
3450     S.Diag(TheCall->getBeginLoc(), DiagID)
3451         << DiagArg << TheCall->getSourceRange();
3452 
3453   return true;
3454 }
3455 
3456 /// Returns true if the argument consists of one contiguous run of 1s with any
3457 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3458 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3459 /// since all 1s are not contiguous.
3460 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3461   llvm::APSInt Result;
3462   // We can't check the value of a dependent argument.
3463   Expr *Arg = TheCall->getArg(ArgNum);
3464   if (Arg->isTypeDependent() || Arg->isValueDependent())
3465     return false;
3466 
3467   // Check constant-ness first.
3468   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3469     return true;
3470 
3471   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3472   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3473     return false;
3474 
3475   return Diag(TheCall->getBeginLoc(),
3476               diag::err_argument_not_contiguous_bit_field)
3477          << ArgNum << Arg->getSourceRange();
3478 }
3479 
3480 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3481                                        CallExpr *TheCall) {
3482   unsigned i = 0, l = 0, u = 0;
3483   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3484   llvm::APSInt Result;
3485 
3486   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3487     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3488            << TheCall->getSourceRange();
3489 
3490   switch (BuiltinID) {
3491   default: return false;
3492   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3493   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3494     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3495            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3496   case PPC::BI__builtin_altivec_dss:
3497     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3498   case PPC::BI__builtin_tbegin:
3499   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3500   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3501   case PPC::BI__builtin_tabortwc:
3502   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3503   case PPC::BI__builtin_tabortwci:
3504   case PPC::BI__builtin_tabortdci:
3505     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3506            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3507   // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
3508   // __builtin_(un)pack_longdouble are available only if long double uses IBM
3509   // extended double representation.
3510   case PPC::BI__builtin_unpack_longdouble:
3511     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1))
3512       return true;
3513     LLVM_FALLTHROUGH;
3514   case PPC::BI__builtin_pack_longdouble:
3515     if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
3516       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
3517              << "ibmlongdouble";
3518     return false;
3519   case PPC::BI__builtin_altivec_dst:
3520   case PPC::BI__builtin_altivec_dstt:
3521   case PPC::BI__builtin_altivec_dstst:
3522   case PPC::BI__builtin_altivec_dststt:
3523     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3524   case PPC::BI__builtin_vsx_xxpermdi:
3525   case PPC::BI__builtin_vsx_xxsldwi:
3526     return SemaBuiltinVSX(TheCall);
3527   case PPC::BI__builtin_divwe:
3528   case PPC::BI__builtin_divweu:
3529   case PPC::BI__builtin_divde:
3530   case PPC::BI__builtin_divdeu:
3531     return SemaFeatureCheck(*this, TheCall, "extdiv",
3532                             diag::err_ppc_builtin_only_on_arch, "7");
3533   case PPC::BI__builtin_bpermd:
3534     return SemaFeatureCheck(*this, TheCall, "bpermd",
3535                             diag::err_ppc_builtin_only_on_arch, "7");
3536   case PPC::BI__builtin_unpack_vector_int128:
3537     return SemaFeatureCheck(*this, TheCall, "vsx",
3538                             diag::err_ppc_builtin_only_on_arch, "7") ||
3539            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3540   case PPC::BI__builtin_pack_vector_int128:
3541     return SemaFeatureCheck(*this, TheCall, "vsx",
3542                             diag::err_ppc_builtin_only_on_arch, "7");
3543   case PPC::BI__builtin_altivec_vgnb:
3544      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3545   case PPC::BI__builtin_altivec_vec_replace_elt:
3546   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3547     QualType VecTy = TheCall->getArg(0)->getType();
3548     QualType EltTy = TheCall->getArg(1)->getType();
3549     unsigned Width = Context.getIntWidth(EltTy);
3550     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3551            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3552   }
3553   case PPC::BI__builtin_vsx_xxeval:
3554      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3555   case PPC::BI__builtin_altivec_vsldbi:
3556      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3557   case PPC::BI__builtin_altivec_vsrdbi:
3558      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3559   case PPC::BI__builtin_vsx_xxpermx:
3560      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3561   case PPC::BI__builtin_ppc_tw:
3562   case PPC::BI__builtin_ppc_tdw:
3563     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3564   case PPC::BI__builtin_ppc_cmpeqb:
3565   case PPC::BI__builtin_ppc_setb:
3566   case PPC::BI__builtin_ppc_maddhd:
3567   case PPC::BI__builtin_ppc_maddhdu:
3568   case PPC::BI__builtin_ppc_maddld:
3569     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3570                             diag::err_ppc_builtin_only_on_arch, "9");
3571   case PPC::BI__builtin_ppc_cmprb:
3572     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3573                             diag::err_ppc_builtin_only_on_arch, "9") ||
3574            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3575   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3576   // be a constant that represents a contiguous bit field.
3577   case PPC::BI__builtin_ppc_rlwnm:
3578     return SemaValueIsRunOfOnes(TheCall, 2);
3579   case PPC::BI__builtin_ppc_rlwimi:
3580   case PPC::BI__builtin_ppc_rldimi:
3581     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3582            SemaValueIsRunOfOnes(TheCall, 3);
3583   case PPC::BI__builtin_ppc_extract_exp:
3584   case PPC::BI__builtin_ppc_extract_sig:
3585   case PPC::BI__builtin_ppc_insert_exp:
3586     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3587                             diag::err_ppc_builtin_only_on_arch, "9");
3588   case PPC::BI__builtin_ppc_addex: {
3589     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3590                          diag::err_ppc_builtin_only_on_arch, "9") ||
3591         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3592       return true;
3593     // Output warning for reserved values 1 to 3.
3594     int ArgValue =
3595         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3596     if (ArgValue != 0)
3597       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3598           << ArgValue;
3599     return false;
3600   }
3601   case PPC::BI__builtin_ppc_mtfsb0:
3602   case PPC::BI__builtin_ppc_mtfsb1:
3603     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3604   case PPC::BI__builtin_ppc_mtfsf:
3605     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3606   case PPC::BI__builtin_ppc_mtfsfi:
3607     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3608            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3609   case PPC::BI__builtin_ppc_alignx:
3610     return SemaBuiltinConstantArgPower2(TheCall, 0);
3611   case PPC::BI__builtin_ppc_rdlam:
3612     return SemaValueIsRunOfOnes(TheCall, 2);
3613   case PPC::BI__builtin_ppc_icbt:
3614   case PPC::BI__builtin_ppc_sthcx:
3615   case PPC::BI__builtin_ppc_stbcx:
3616   case PPC::BI__builtin_ppc_lharx:
3617   case PPC::BI__builtin_ppc_lbarx:
3618     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3619                             diag::err_ppc_builtin_only_on_arch, "8");
3620   case PPC::BI__builtin_vsx_ldrmb:
3621   case PPC::BI__builtin_vsx_strmb:
3622     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3623                             diag::err_ppc_builtin_only_on_arch, "8") ||
3624            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3625   case PPC::BI__builtin_altivec_vcntmbb:
3626   case PPC::BI__builtin_altivec_vcntmbh:
3627   case PPC::BI__builtin_altivec_vcntmbw:
3628   case PPC::BI__builtin_altivec_vcntmbd:
3629     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3630   case PPC::BI__builtin_darn:
3631   case PPC::BI__builtin_darn_raw:
3632   case PPC::BI__builtin_darn_32:
3633     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3634                             diag::err_ppc_builtin_only_on_arch, "9");
3635   case PPC::BI__builtin_vsx_xxgenpcvbm:
3636   case PPC::BI__builtin_vsx_xxgenpcvhm:
3637   case PPC::BI__builtin_vsx_xxgenpcvwm:
3638   case PPC::BI__builtin_vsx_xxgenpcvdm:
3639     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3640   case PPC::BI__builtin_ppc_compare_exp_uo:
3641   case PPC::BI__builtin_ppc_compare_exp_lt:
3642   case PPC::BI__builtin_ppc_compare_exp_gt:
3643   case PPC::BI__builtin_ppc_compare_exp_eq:
3644     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3645                             diag::err_ppc_builtin_only_on_arch, "9") ||
3646            SemaFeatureCheck(*this, TheCall, "vsx",
3647                             diag::err_ppc_builtin_requires_vsx);
3648   case PPC::BI__builtin_ppc_test_data_class: {
3649     // Check if the first argument of the __builtin_ppc_test_data_class call is
3650     // valid. The argument must be either a 'float' or a 'double'.
3651     QualType ArgType = TheCall->getArg(0)->getType();
3652     if (ArgType != QualType(Context.FloatTy) &&
3653         ArgType != QualType(Context.DoubleTy))
3654       return Diag(TheCall->getBeginLoc(),
3655                   diag::err_ppc_invalid_test_data_class_type);
3656     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3657                             diag::err_ppc_builtin_only_on_arch, "9") ||
3658            SemaFeatureCheck(*this, TheCall, "vsx",
3659                             diag::err_ppc_builtin_requires_vsx) ||
3660            SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
3661   }
3662   case PPC::BI__builtin_ppc_load8r:
3663   case PPC::BI__builtin_ppc_store8r:
3664     return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
3665                             diag::err_ppc_builtin_only_on_arch, "7");
3666 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc)                                 \
3667   case PPC::BI__builtin_##Name:                                                \
3668     return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
3669 #include "clang/Basic/BuiltinsPPC.def"
3670   }
3671   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3672 }
3673 
3674 // Check if the given type is a non-pointer PPC MMA type. This function is used
3675 // in Sema to prevent invalid uses of restricted PPC MMA types.
3676 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3677   if (Type->isPointerType() || Type->isArrayType())
3678     return false;
3679 
3680   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3681 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3682   if (false
3683 #include "clang/Basic/PPCTypes.def"
3684      ) {
3685     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3686     return true;
3687   }
3688   return false;
3689 }
3690 
3691 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3692                                           CallExpr *TheCall) {
3693   // position of memory order and scope arguments in the builtin
3694   unsigned OrderIndex, ScopeIndex;
3695   switch (BuiltinID) {
3696   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3697   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3698   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3699   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3700     OrderIndex = 2;
3701     ScopeIndex = 3;
3702     break;
3703   case AMDGPU::BI__builtin_amdgcn_fence:
3704     OrderIndex = 0;
3705     ScopeIndex = 1;
3706     break;
3707   default:
3708     return false;
3709   }
3710 
3711   ExprResult Arg = TheCall->getArg(OrderIndex);
3712   auto ArgExpr = Arg.get();
3713   Expr::EvalResult ArgResult;
3714 
3715   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3716     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3717            << ArgExpr->getType();
3718   auto Ord = ArgResult.Val.getInt().getZExtValue();
3719 
3720   // Check validity of memory ordering as per C11 / C++11's memody model.
3721   // Only fence needs check. Atomic dec/inc allow all memory orders.
3722   if (!llvm::isValidAtomicOrderingCABI(Ord))
3723     return Diag(ArgExpr->getBeginLoc(),
3724                 diag::warn_atomic_op_has_invalid_memory_order)
3725            << ArgExpr->getSourceRange();
3726   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3727   case llvm::AtomicOrderingCABI::relaxed:
3728   case llvm::AtomicOrderingCABI::consume:
3729     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3730       return Diag(ArgExpr->getBeginLoc(),
3731                   diag::warn_atomic_op_has_invalid_memory_order)
3732              << ArgExpr->getSourceRange();
3733     break;
3734   case llvm::AtomicOrderingCABI::acquire:
3735   case llvm::AtomicOrderingCABI::release:
3736   case llvm::AtomicOrderingCABI::acq_rel:
3737   case llvm::AtomicOrderingCABI::seq_cst:
3738     break;
3739   }
3740 
3741   Arg = TheCall->getArg(ScopeIndex);
3742   ArgExpr = Arg.get();
3743   Expr::EvalResult ArgResult1;
3744   // Check that sync scope is a constant literal
3745   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3746     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3747            << ArgExpr->getType();
3748 
3749   return false;
3750 }
3751 
3752 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3753   llvm::APSInt Result;
3754 
3755   // We can't check the value of a dependent argument.
3756   Expr *Arg = TheCall->getArg(ArgNum);
3757   if (Arg->isTypeDependent() || Arg->isValueDependent())
3758     return false;
3759 
3760   // Check constant-ness first.
3761   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3762     return true;
3763 
3764   int64_t Val = Result.getSExtValue();
3765   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3766     return false;
3767 
3768   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3769          << Arg->getSourceRange();
3770 }
3771 
3772 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3773                                          unsigned BuiltinID,
3774                                          CallExpr *TheCall) {
3775   // CodeGenFunction can also detect this, but this gives a better error
3776   // message.
3777   bool FeatureMissing = false;
3778   SmallVector<StringRef> ReqFeatures;
3779   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3780   Features.split(ReqFeatures, ',');
3781 
3782   // Check if each required feature is included
3783   for (StringRef F : ReqFeatures) {
3784     if (TI.hasFeature(F))
3785       continue;
3786 
3787     // If the feature is 64bit, alter the string so it will print better in
3788     // the diagnostic.
3789     if (F == "64bit")
3790       F = "RV64";
3791 
3792     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3793     F.consume_front("experimental-");
3794     std::string FeatureStr = F.str();
3795     FeatureStr[0] = std::toupper(FeatureStr[0]);
3796 
3797     // Error message
3798     FeatureMissing = true;
3799     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3800         << TheCall->getSourceRange() << StringRef(FeatureStr);
3801   }
3802 
3803   if (FeatureMissing)
3804     return true;
3805 
3806   switch (BuiltinID) {
3807   case RISCVVector::BI__builtin_rvv_vsetvli:
3808     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3809            CheckRISCVLMUL(TheCall, 2);
3810   case RISCVVector::BI__builtin_rvv_vsetvlimax:
3811     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3812            CheckRISCVLMUL(TheCall, 1);
3813   }
3814 
3815   return false;
3816 }
3817 
3818 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3819                                            CallExpr *TheCall) {
3820   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3821     Expr *Arg = TheCall->getArg(0);
3822     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3823       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3824         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3825                << Arg->getSourceRange();
3826   }
3827 
3828   // For intrinsics which take an immediate value as part of the instruction,
3829   // range check them here.
3830   unsigned i = 0, l = 0, u = 0;
3831   switch (BuiltinID) {
3832   default: return false;
3833   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3834   case SystemZ::BI__builtin_s390_verimb:
3835   case SystemZ::BI__builtin_s390_verimh:
3836   case SystemZ::BI__builtin_s390_verimf:
3837   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3838   case SystemZ::BI__builtin_s390_vfaeb:
3839   case SystemZ::BI__builtin_s390_vfaeh:
3840   case SystemZ::BI__builtin_s390_vfaef:
3841   case SystemZ::BI__builtin_s390_vfaebs:
3842   case SystemZ::BI__builtin_s390_vfaehs:
3843   case SystemZ::BI__builtin_s390_vfaefs:
3844   case SystemZ::BI__builtin_s390_vfaezb:
3845   case SystemZ::BI__builtin_s390_vfaezh:
3846   case SystemZ::BI__builtin_s390_vfaezf:
3847   case SystemZ::BI__builtin_s390_vfaezbs:
3848   case SystemZ::BI__builtin_s390_vfaezhs:
3849   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3850   case SystemZ::BI__builtin_s390_vfisb:
3851   case SystemZ::BI__builtin_s390_vfidb:
3852     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3853            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3854   case SystemZ::BI__builtin_s390_vftcisb:
3855   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3856   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3857   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3858   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3859   case SystemZ::BI__builtin_s390_vstrcb:
3860   case SystemZ::BI__builtin_s390_vstrch:
3861   case SystemZ::BI__builtin_s390_vstrcf:
3862   case SystemZ::BI__builtin_s390_vstrczb:
3863   case SystemZ::BI__builtin_s390_vstrczh:
3864   case SystemZ::BI__builtin_s390_vstrczf:
3865   case SystemZ::BI__builtin_s390_vstrcbs:
3866   case SystemZ::BI__builtin_s390_vstrchs:
3867   case SystemZ::BI__builtin_s390_vstrcfs:
3868   case SystemZ::BI__builtin_s390_vstrczbs:
3869   case SystemZ::BI__builtin_s390_vstrczhs:
3870   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3871   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3872   case SystemZ::BI__builtin_s390_vfminsb:
3873   case SystemZ::BI__builtin_s390_vfmaxsb:
3874   case SystemZ::BI__builtin_s390_vfmindb:
3875   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3876   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3877   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3878   case SystemZ::BI__builtin_s390_vclfnhs:
3879   case SystemZ::BI__builtin_s390_vclfnls:
3880   case SystemZ::BI__builtin_s390_vcfn:
3881   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
3882   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
3883   }
3884   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3885 }
3886 
3887 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3888 /// This checks that the target supports __builtin_cpu_supports and
3889 /// that the string argument is constant and valid.
3890 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3891                                    CallExpr *TheCall) {
3892   Expr *Arg = TheCall->getArg(0);
3893 
3894   // Check if the argument is a string literal.
3895   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3896     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3897            << Arg->getSourceRange();
3898 
3899   // Check the contents of the string.
3900   StringRef Feature =
3901       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3902   if (!TI.validateCpuSupports(Feature))
3903     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3904            << Arg->getSourceRange();
3905   return false;
3906 }
3907 
3908 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3909 /// This checks that the target supports __builtin_cpu_is and
3910 /// that the string argument is constant and valid.
3911 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3912   Expr *Arg = TheCall->getArg(0);
3913 
3914   // Check if the argument is a string literal.
3915   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3916     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3917            << Arg->getSourceRange();
3918 
3919   // Check the contents of the string.
3920   StringRef Feature =
3921       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3922   if (!TI.validateCpuIs(Feature))
3923     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3924            << Arg->getSourceRange();
3925   return false;
3926 }
3927 
3928 // Check if the rounding mode is legal.
3929 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3930   // Indicates if this instruction has rounding control or just SAE.
3931   bool HasRC = false;
3932 
3933   unsigned ArgNum = 0;
3934   switch (BuiltinID) {
3935   default:
3936     return false;
3937   case X86::BI__builtin_ia32_vcvttsd2si32:
3938   case X86::BI__builtin_ia32_vcvttsd2si64:
3939   case X86::BI__builtin_ia32_vcvttsd2usi32:
3940   case X86::BI__builtin_ia32_vcvttsd2usi64:
3941   case X86::BI__builtin_ia32_vcvttss2si32:
3942   case X86::BI__builtin_ia32_vcvttss2si64:
3943   case X86::BI__builtin_ia32_vcvttss2usi32:
3944   case X86::BI__builtin_ia32_vcvttss2usi64:
3945   case X86::BI__builtin_ia32_vcvttsh2si32:
3946   case X86::BI__builtin_ia32_vcvttsh2si64:
3947   case X86::BI__builtin_ia32_vcvttsh2usi32:
3948   case X86::BI__builtin_ia32_vcvttsh2usi64:
3949     ArgNum = 1;
3950     break;
3951   case X86::BI__builtin_ia32_maxpd512:
3952   case X86::BI__builtin_ia32_maxps512:
3953   case X86::BI__builtin_ia32_minpd512:
3954   case X86::BI__builtin_ia32_minps512:
3955   case X86::BI__builtin_ia32_maxph512:
3956   case X86::BI__builtin_ia32_minph512:
3957     ArgNum = 2;
3958     break;
3959   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
3960   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
3961   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3962   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3963   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3964   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3965   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3966   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3967   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3968   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3969   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3970   case X86::BI__builtin_ia32_vcvttph2w512_mask:
3971   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
3972   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
3973   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
3974   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
3975   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
3976   case X86::BI__builtin_ia32_exp2pd_mask:
3977   case X86::BI__builtin_ia32_exp2ps_mask:
3978   case X86::BI__builtin_ia32_getexppd512_mask:
3979   case X86::BI__builtin_ia32_getexpps512_mask:
3980   case X86::BI__builtin_ia32_getexpph512_mask:
3981   case X86::BI__builtin_ia32_rcp28pd_mask:
3982   case X86::BI__builtin_ia32_rcp28ps_mask:
3983   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3984   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3985   case X86::BI__builtin_ia32_vcomisd:
3986   case X86::BI__builtin_ia32_vcomiss:
3987   case X86::BI__builtin_ia32_vcomish:
3988   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3989     ArgNum = 3;
3990     break;
3991   case X86::BI__builtin_ia32_cmppd512_mask:
3992   case X86::BI__builtin_ia32_cmpps512_mask:
3993   case X86::BI__builtin_ia32_cmpsd_mask:
3994   case X86::BI__builtin_ia32_cmpss_mask:
3995   case X86::BI__builtin_ia32_cmpsh_mask:
3996   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
3997   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
3998   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3999   case X86::BI__builtin_ia32_getexpsd128_round_mask:
4000   case X86::BI__builtin_ia32_getexpss128_round_mask:
4001   case X86::BI__builtin_ia32_getexpsh128_round_mask:
4002   case X86::BI__builtin_ia32_getmantpd512_mask:
4003   case X86::BI__builtin_ia32_getmantps512_mask:
4004   case X86::BI__builtin_ia32_getmantph512_mask:
4005   case X86::BI__builtin_ia32_maxsd_round_mask:
4006   case X86::BI__builtin_ia32_maxss_round_mask:
4007   case X86::BI__builtin_ia32_maxsh_round_mask:
4008   case X86::BI__builtin_ia32_minsd_round_mask:
4009   case X86::BI__builtin_ia32_minss_round_mask:
4010   case X86::BI__builtin_ia32_minsh_round_mask:
4011   case X86::BI__builtin_ia32_rcp28sd_round_mask:
4012   case X86::BI__builtin_ia32_rcp28ss_round_mask:
4013   case X86::BI__builtin_ia32_reducepd512_mask:
4014   case X86::BI__builtin_ia32_reduceps512_mask:
4015   case X86::BI__builtin_ia32_reduceph512_mask:
4016   case X86::BI__builtin_ia32_rndscalepd_mask:
4017   case X86::BI__builtin_ia32_rndscaleps_mask:
4018   case X86::BI__builtin_ia32_rndscaleph_mask:
4019   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
4020   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
4021     ArgNum = 4;
4022     break;
4023   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4024   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4025   case X86::BI__builtin_ia32_fixupimmps512_mask:
4026   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4027   case X86::BI__builtin_ia32_fixupimmsd_mask:
4028   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4029   case X86::BI__builtin_ia32_fixupimmss_mask:
4030   case X86::BI__builtin_ia32_fixupimmss_maskz:
4031   case X86::BI__builtin_ia32_getmantsd_round_mask:
4032   case X86::BI__builtin_ia32_getmantss_round_mask:
4033   case X86::BI__builtin_ia32_getmantsh_round_mask:
4034   case X86::BI__builtin_ia32_rangepd512_mask:
4035   case X86::BI__builtin_ia32_rangeps512_mask:
4036   case X86::BI__builtin_ia32_rangesd128_round_mask:
4037   case X86::BI__builtin_ia32_rangess128_round_mask:
4038   case X86::BI__builtin_ia32_reducesd_mask:
4039   case X86::BI__builtin_ia32_reducess_mask:
4040   case X86::BI__builtin_ia32_reducesh_mask:
4041   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4042   case X86::BI__builtin_ia32_rndscaless_round_mask:
4043   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4044     ArgNum = 5;
4045     break;
4046   case X86::BI__builtin_ia32_vcvtsd2si64:
4047   case X86::BI__builtin_ia32_vcvtsd2si32:
4048   case X86::BI__builtin_ia32_vcvtsd2usi32:
4049   case X86::BI__builtin_ia32_vcvtsd2usi64:
4050   case X86::BI__builtin_ia32_vcvtss2si32:
4051   case X86::BI__builtin_ia32_vcvtss2si64:
4052   case X86::BI__builtin_ia32_vcvtss2usi32:
4053   case X86::BI__builtin_ia32_vcvtss2usi64:
4054   case X86::BI__builtin_ia32_vcvtsh2si32:
4055   case X86::BI__builtin_ia32_vcvtsh2si64:
4056   case X86::BI__builtin_ia32_vcvtsh2usi32:
4057   case X86::BI__builtin_ia32_vcvtsh2usi64:
4058   case X86::BI__builtin_ia32_sqrtpd512:
4059   case X86::BI__builtin_ia32_sqrtps512:
4060   case X86::BI__builtin_ia32_sqrtph512:
4061     ArgNum = 1;
4062     HasRC = true;
4063     break;
4064   case X86::BI__builtin_ia32_addph512:
4065   case X86::BI__builtin_ia32_divph512:
4066   case X86::BI__builtin_ia32_mulph512:
4067   case X86::BI__builtin_ia32_subph512:
4068   case X86::BI__builtin_ia32_addpd512:
4069   case X86::BI__builtin_ia32_addps512:
4070   case X86::BI__builtin_ia32_divpd512:
4071   case X86::BI__builtin_ia32_divps512:
4072   case X86::BI__builtin_ia32_mulpd512:
4073   case X86::BI__builtin_ia32_mulps512:
4074   case X86::BI__builtin_ia32_subpd512:
4075   case X86::BI__builtin_ia32_subps512:
4076   case X86::BI__builtin_ia32_cvtsi2sd64:
4077   case X86::BI__builtin_ia32_cvtsi2ss32:
4078   case X86::BI__builtin_ia32_cvtsi2ss64:
4079   case X86::BI__builtin_ia32_cvtusi2sd64:
4080   case X86::BI__builtin_ia32_cvtusi2ss32:
4081   case X86::BI__builtin_ia32_cvtusi2ss64:
4082   case X86::BI__builtin_ia32_vcvtusi2sh:
4083   case X86::BI__builtin_ia32_vcvtusi642sh:
4084   case X86::BI__builtin_ia32_vcvtsi2sh:
4085   case X86::BI__builtin_ia32_vcvtsi642sh:
4086     ArgNum = 2;
4087     HasRC = true;
4088     break;
4089   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4090   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4091   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4092   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4093   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4094   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4095   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4096   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4097   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4098   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4099   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4100   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4101   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4102   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4103   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4104   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4105   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4106   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4107   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4108   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4109   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4110   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4111   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4112   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4113   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4114   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4115   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4116   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4117   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4118     ArgNum = 3;
4119     HasRC = true;
4120     break;
4121   case X86::BI__builtin_ia32_addsh_round_mask:
4122   case X86::BI__builtin_ia32_addss_round_mask:
4123   case X86::BI__builtin_ia32_addsd_round_mask:
4124   case X86::BI__builtin_ia32_divsh_round_mask:
4125   case X86::BI__builtin_ia32_divss_round_mask:
4126   case X86::BI__builtin_ia32_divsd_round_mask:
4127   case X86::BI__builtin_ia32_mulsh_round_mask:
4128   case X86::BI__builtin_ia32_mulss_round_mask:
4129   case X86::BI__builtin_ia32_mulsd_round_mask:
4130   case X86::BI__builtin_ia32_subsh_round_mask:
4131   case X86::BI__builtin_ia32_subss_round_mask:
4132   case X86::BI__builtin_ia32_subsd_round_mask:
4133   case X86::BI__builtin_ia32_scalefph512_mask:
4134   case X86::BI__builtin_ia32_scalefpd512_mask:
4135   case X86::BI__builtin_ia32_scalefps512_mask:
4136   case X86::BI__builtin_ia32_scalefsd_round_mask:
4137   case X86::BI__builtin_ia32_scalefss_round_mask:
4138   case X86::BI__builtin_ia32_scalefsh_round_mask:
4139   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4140   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4141   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4142   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4143   case X86::BI__builtin_ia32_sqrtss_round_mask:
4144   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4145   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4146   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4147   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4148   case X86::BI__builtin_ia32_vfmaddss3_mask:
4149   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4150   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4151   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4152   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4153   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4154   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4155   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4156   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4157   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4158   case X86::BI__builtin_ia32_vfmaddps512_mask:
4159   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4160   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4161   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4162   case X86::BI__builtin_ia32_vfmaddph512_mask:
4163   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4164   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4165   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4166   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4167   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4168   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4169   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4170   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4171   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4172   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4173   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4174   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4175   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4176   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4177   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4178   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4179   case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
4180   case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
4181   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4182   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4183   case X86::BI__builtin_ia32_vfmaddcph512_mask3:
4184   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4185   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
4186   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
4187   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4188   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4189   case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
4190   case X86::BI__builtin_ia32_vfmulcsh_mask:
4191   case X86::BI__builtin_ia32_vfmulcph512_mask:
4192   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4193   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4194     ArgNum = 4;
4195     HasRC = true;
4196     break;
4197   }
4198 
4199   llvm::APSInt Result;
4200 
4201   // We can't check the value of a dependent argument.
4202   Expr *Arg = TheCall->getArg(ArgNum);
4203   if (Arg->isTypeDependent() || Arg->isValueDependent())
4204     return false;
4205 
4206   // Check constant-ness first.
4207   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4208     return true;
4209 
4210   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4211   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4212   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4213   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4214   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4215       Result == 8/*ROUND_NO_EXC*/ ||
4216       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4217       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4218     return false;
4219 
4220   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4221          << Arg->getSourceRange();
4222 }
4223 
4224 // Check if the gather/scatter scale is legal.
4225 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4226                                              CallExpr *TheCall) {
4227   unsigned ArgNum = 0;
4228   switch (BuiltinID) {
4229   default:
4230     return false;
4231   case X86::BI__builtin_ia32_gatherpfdpd:
4232   case X86::BI__builtin_ia32_gatherpfdps:
4233   case X86::BI__builtin_ia32_gatherpfqpd:
4234   case X86::BI__builtin_ia32_gatherpfqps:
4235   case X86::BI__builtin_ia32_scatterpfdpd:
4236   case X86::BI__builtin_ia32_scatterpfdps:
4237   case X86::BI__builtin_ia32_scatterpfqpd:
4238   case X86::BI__builtin_ia32_scatterpfqps:
4239     ArgNum = 3;
4240     break;
4241   case X86::BI__builtin_ia32_gatherd_pd:
4242   case X86::BI__builtin_ia32_gatherd_pd256:
4243   case X86::BI__builtin_ia32_gatherq_pd:
4244   case X86::BI__builtin_ia32_gatherq_pd256:
4245   case X86::BI__builtin_ia32_gatherd_ps:
4246   case X86::BI__builtin_ia32_gatherd_ps256:
4247   case X86::BI__builtin_ia32_gatherq_ps:
4248   case X86::BI__builtin_ia32_gatherq_ps256:
4249   case X86::BI__builtin_ia32_gatherd_q:
4250   case X86::BI__builtin_ia32_gatherd_q256:
4251   case X86::BI__builtin_ia32_gatherq_q:
4252   case X86::BI__builtin_ia32_gatherq_q256:
4253   case X86::BI__builtin_ia32_gatherd_d:
4254   case X86::BI__builtin_ia32_gatherd_d256:
4255   case X86::BI__builtin_ia32_gatherq_d:
4256   case X86::BI__builtin_ia32_gatherq_d256:
4257   case X86::BI__builtin_ia32_gather3div2df:
4258   case X86::BI__builtin_ia32_gather3div2di:
4259   case X86::BI__builtin_ia32_gather3div4df:
4260   case X86::BI__builtin_ia32_gather3div4di:
4261   case X86::BI__builtin_ia32_gather3div4sf:
4262   case X86::BI__builtin_ia32_gather3div4si:
4263   case X86::BI__builtin_ia32_gather3div8sf:
4264   case X86::BI__builtin_ia32_gather3div8si:
4265   case X86::BI__builtin_ia32_gather3siv2df:
4266   case X86::BI__builtin_ia32_gather3siv2di:
4267   case X86::BI__builtin_ia32_gather3siv4df:
4268   case X86::BI__builtin_ia32_gather3siv4di:
4269   case X86::BI__builtin_ia32_gather3siv4sf:
4270   case X86::BI__builtin_ia32_gather3siv4si:
4271   case X86::BI__builtin_ia32_gather3siv8sf:
4272   case X86::BI__builtin_ia32_gather3siv8si:
4273   case X86::BI__builtin_ia32_gathersiv8df:
4274   case X86::BI__builtin_ia32_gathersiv16sf:
4275   case X86::BI__builtin_ia32_gatherdiv8df:
4276   case X86::BI__builtin_ia32_gatherdiv16sf:
4277   case X86::BI__builtin_ia32_gathersiv8di:
4278   case X86::BI__builtin_ia32_gathersiv16si:
4279   case X86::BI__builtin_ia32_gatherdiv8di:
4280   case X86::BI__builtin_ia32_gatherdiv16si:
4281   case X86::BI__builtin_ia32_scatterdiv2df:
4282   case X86::BI__builtin_ia32_scatterdiv2di:
4283   case X86::BI__builtin_ia32_scatterdiv4df:
4284   case X86::BI__builtin_ia32_scatterdiv4di:
4285   case X86::BI__builtin_ia32_scatterdiv4sf:
4286   case X86::BI__builtin_ia32_scatterdiv4si:
4287   case X86::BI__builtin_ia32_scatterdiv8sf:
4288   case X86::BI__builtin_ia32_scatterdiv8si:
4289   case X86::BI__builtin_ia32_scattersiv2df:
4290   case X86::BI__builtin_ia32_scattersiv2di:
4291   case X86::BI__builtin_ia32_scattersiv4df:
4292   case X86::BI__builtin_ia32_scattersiv4di:
4293   case X86::BI__builtin_ia32_scattersiv4sf:
4294   case X86::BI__builtin_ia32_scattersiv4si:
4295   case X86::BI__builtin_ia32_scattersiv8sf:
4296   case X86::BI__builtin_ia32_scattersiv8si:
4297   case X86::BI__builtin_ia32_scattersiv8df:
4298   case X86::BI__builtin_ia32_scattersiv16sf:
4299   case X86::BI__builtin_ia32_scatterdiv8df:
4300   case X86::BI__builtin_ia32_scatterdiv16sf:
4301   case X86::BI__builtin_ia32_scattersiv8di:
4302   case X86::BI__builtin_ia32_scattersiv16si:
4303   case X86::BI__builtin_ia32_scatterdiv8di:
4304   case X86::BI__builtin_ia32_scatterdiv16si:
4305     ArgNum = 4;
4306     break;
4307   }
4308 
4309   llvm::APSInt Result;
4310 
4311   // We can't check the value of a dependent argument.
4312   Expr *Arg = TheCall->getArg(ArgNum);
4313   if (Arg->isTypeDependent() || Arg->isValueDependent())
4314     return false;
4315 
4316   // Check constant-ness first.
4317   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4318     return true;
4319 
4320   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4321     return false;
4322 
4323   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4324          << Arg->getSourceRange();
4325 }
4326 
4327 enum { TileRegLow = 0, TileRegHigh = 7 };
4328 
4329 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4330                                              ArrayRef<int> ArgNums) {
4331   for (int ArgNum : ArgNums) {
4332     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4333       return true;
4334   }
4335   return false;
4336 }
4337 
4338 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4339                                         ArrayRef<int> ArgNums) {
4340   // Because the max number of tile register is TileRegHigh + 1, so here we use
4341   // each bit to represent the usage of them in bitset.
4342   std::bitset<TileRegHigh + 1> ArgValues;
4343   for (int ArgNum : ArgNums) {
4344     Expr *Arg = TheCall->getArg(ArgNum);
4345     if (Arg->isTypeDependent() || Arg->isValueDependent())
4346       continue;
4347 
4348     llvm::APSInt Result;
4349     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4350       return true;
4351     int ArgExtValue = Result.getExtValue();
4352     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4353            "Incorrect tile register num.");
4354     if (ArgValues.test(ArgExtValue))
4355       return Diag(TheCall->getBeginLoc(),
4356                   diag::err_x86_builtin_tile_arg_duplicate)
4357              << TheCall->getArg(ArgNum)->getSourceRange();
4358     ArgValues.set(ArgExtValue);
4359   }
4360   return false;
4361 }
4362 
4363 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4364                                                 ArrayRef<int> ArgNums) {
4365   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4366          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4367 }
4368 
4369 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4370   switch (BuiltinID) {
4371   default:
4372     return false;
4373   case X86::BI__builtin_ia32_tileloadd64:
4374   case X86::BI__builtin_ia32_tileloaddt164:
4375   case X86::BI__builtin_ia32_tilestored64:
4376   case X86::BI__builtin_ia32_tilezero:
4377     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4378   case X86::BI__builtin_ia32_tdpbssd:
4379   case X86::BI__builtin_ia32_tdpbsud:
4380   case X86::BI__builtin_ia32_tdpbusd:
4381   case X86::BI__builtin_ia32_tdpbuud:
4382   case X86::BI__builtin_ia32_tdpbf16ps:
4383     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4384   }
4385 }
4386 static bool isX86_32Builtin(unsigned BuiltinID) {
4387   // These builtins only work on x86-32 targets.
4388   switch (BuiltinID) {
4389   case X86::BI__builtin_ia32_readeflags_u32:
4390   case X86::BI__builtin_ia32_writeeflags_u32:
4391     return true;
4392   }
4393 
4394   return false;
4395 }
4396 
4397 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4398                                        CallExpr *TheCall) {
4399   if (BuiltinID == X86::BI__builtin_cpu_supports)
4400     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4401 
4402   if (BuiltinID == X86::BI__builtin_cpu_is)
4403     return SemaBuiltinCpuIs(*this, TI, TheCall);
4404 
4405   // Check for 32-bit only builtins on a 64-bit target.
4406   const llvm::Triple &TT = TI.getTriple();
4407   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4408     return Diag(TheCall->getCallee()->getBeginLoc(),
4409                 diag::err_32_bit_builtin_64_bit_tgt);
4410 
4411   // If the intrinsic has rounding or SAE make sure its valid.
4412   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4413     return true;
4414 
4415   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4416   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4417     return true;
4418 
4419   // If the intrinsic has a tile arguments, make sure they are valid.
4420   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4421     return true;
4422 
4423   // For intrinsics which take an immediate value as part of the instruction,
4424   // range check them here.
4425   int i = 0, l = 0, u = 0;
4426   switch (BuiltinID) {
4427   default:
4428     return false;
4429   case X86::BI__builtin_ia32_vec_ext_v2si:
4430   case X86::BI__builtin_ia32_vec_ext_v2di:
4431   case X86::BI__builtin_ia32_vextractf128_pd256:
4432   case X86::BI__builtin_ia32_vextractf128_ps256:
4433   case X86::BI__builtin_ia32_vextractf128_si256:
4434   case X86::BI__builtin_ia32_extract128i256:
4435   case X86::BI__builtin_ia32_extractf64x4_mask:
4436   case X86::BI__builtin_ia32_extracti64x4_mask:
4437   case X86::BI__builtin_ia32_extractf32x8_mask:
4438   case X86::BI__builtin_ia32_extracti32x8_mask:
4439   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4440   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4441   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4442   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4443     i = 1; l = 0; u = 1;
4444     break;
4445   case X86::BI__builtin_ia32_vec_set_v2di:
4446   case X86::BI__builtin_ia32_vinsertf128_pd256:
4447   case X86::BI__builtin_ia32_vinsertf128_ps256:
4448   case X86::BI__builtin_ia32_vinsertf128_si256:
4449   case X86::BI__builtin_ia32_insert128i256:
4450   case X86::BI__builtin_ia32_insertf32x8:
4451   case X86::BI__builtin_ia32_inserti32x8:
4452   case X86::BI__builtin_ia32_insertf64x4:
4453   case X86::BI__builtin_ia32_inserti64x4:
4454   case X86::BI__builtin_ia32_insertf64x2_256:
4455   case X86::BI__builtin_ia32_inserti64x2_256:
4456   case X86::BI__builtin_ia32_insertf32x4_256:
4457   case X86::BI__builtin_ia32_inserti32x4_256:
4458     i = 2; l = 0; u = 1;
4459     break;
4460   case X86::BI__builtin_ia32_vpermilpd:
4461   case X86::BI__builtin_ia32_vec_ext_v4hi:
4462   case X86::BI__builtin_ia32_vec_ext_v4si:
4463   case X86::BI__builtin_ia32_vec_ext_v4sf:
4464   case X86::BI__builtin_ia32_vec_ext_v4di:
4465   case X86::BI__builtin_ia32_extractf32x4_mask:
4466   case X86::BI__builtin_ia32_extracti32x4_mask:
4467   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4468   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4469     i = 1; l = 0; u = 3;
4470     break;
4471   case X86::BI_mm_prefetch:
4472   case X86::BI__builtin_ia32_vec_ext_v8hi:
4473   case X86::BI__builtin_ia32_vec_ext_v8si:
4474     i = 1; l = 0; u = 7;
4475     break;
4476   case X86::BI__builtin_ia32_sha1rnds4:
4477   case X86::BI__builtin_ia32_blendpd:
4478   case X86::BI__builtin_ia32_shufpd:
4479   case X86::BI__builtin_ia32_vec_set_v4hi:
4480   case X86::BI__builtin_ia32_vec_set_v4si:
4481   case X86::BI__builtin_ia32_vec_set_v4di:
4482   case X86::BI__builtin_ia32_shuf_f32x4_256:
4483   case X86::BI__builtin_ia32_shuf_f64x2_256:
4484   case X86::BI__builtin_ia32_shuf_i32x4_256:
4485   case X86::BI__builtin_ia32_shuf_i64x2_256:
4486   case X86::BI__builtin_ia32_insertf64x2_512:
4487   case X86::BI__builtin_ia32_inserti64x2_512:
4488   case X86::BI__builtin_ia32_insertf32x4:
4489   case X86::BI__builtin_ia32_inserti32x4:
4490     i = 2; l = 0; u = 3;
4491     break;
4492   case X86::BI__builtin_ia32_vpermil2pd:
4493   case X86::BI__builtin_ia32_vpermil2pd256:
4494   case X86::BI__builtin_ia32_vpermil2ps:
4495   case X86::BI__builtin_ia32_vpermil2ps256:
4496     i = 3; l = 0; u = 3;
4497     break;
4498   case X86::BI__builtin_ia32_cmpb128_mask:
4499   case X86::BI__builtin_ia32_cmpw128_mask:
4500   case X86::BI__builtin_ia32_cmpd128_mask:
4501   case X86::BI__builtin_ia32_cmpq128_mask:
4502   case X86::BI__builtin_ia32_cmpb256_mask:
4503   case X86::BI__builtin_ia32_cmpw256_mask:
4504   case X86::BI__builtin_ia32_cmpd256_mask:
4505   case X86::BI__builtin_ia32_cmpq256_mask:
4506   case X86::BI__builtin_ia32_cmpb512_mask:
4507   case X86::BI__builtin_ia32_cmpw512_mask:
4508   case X86::BI__builtin_ia32_cmpd512_mask:
4509   case X86::BI__builtin_ia32_cmpq512_mask:
4510   case X86::BI__builtin_ia32_ucmpb128_mask:
4511   case X86::BI__builtin_ia32_ucmpw128_mask:
4512   case X86::BI__builtin_ia32_ucmpd128_mask:
4513   case X86::BI__builtin_ia32_ucmpq128_mask:
4514   case X86::BI__builtin_ia32_ucmpb256_mask:
4515   case X86::BI__builtin_ia32_ucmpw256_mask:
4516   case X86::BI__builtin_ia32_ucmpd256_mask:
4517   case X86::BI__builtin_ia32_ucmpq256_mask:
4518   case X86::BI__builtin_ia32_ucmpb512_mask:
4519   case X86::BI__builtin_ia32_ucmpw512_mask:
4520   case X86::BI__builtin_ia32_ucmpd512_mask:
4521   case X86::BI__builtin_ia32_ucmpq512_mask:
4522   case X86::BI__builtin_ia32_vpcomub:
4523   case X86::BI__builtin_ia32_vpcomuw:
4524   case X86::BI__builtin_ia32_vpcomud:
4525   case X86::BI__builtin_ia32_vpcomuq:
4526   case X86::BI__builtin_ia32_vpcomb:
4527   case X86::BI__builtin_ia32_vpcomw:
4528   case X86::BI__builtin_ia32_vpcomd:
4529   case X86::BI__builtin_ia32_vpcomq:
4530   case X86::BI__builtin_ia32_vec_set_v8hi:
4531   case X86::BI__builtin_ia32_vec_set_v8si:
4532     i = 2; l = 0; u = 7;
4533     break;
4534   case X86::BI__builtin_ia32_vpermilpd256:
4535   case X86::BI__builtin_ia32_roundps:
4536   case X86::BI__builtin_ia32_roundpd:
4537   case X86::BI__builtin_ia32_roundps256:
4538   case X86::BI__builtin_ia32_roundpd256:
4539   case X86::BI__builtin_ia32_getmantpd128_mask:
4540   case X86::BI__builtin_ia32_getmantpd256_mask:
4541   case X86::BI__builtin_ia32_getmantps128_mask:
4542   case X86::BI__builtin_ia32_getmantps256_mask:
4543   case X86::BI__builtin_ia32_getmantpd512_mask:
4544   case X86::BI__builtin_ia32_getmantps512_mask:
4545   case X86::BI__builtin_ia32_getmantph128_mask:
4546   case X86::BI__builtin_ia32_getmantph256_mask:
4547   case X86::BI__builtin_ia32_getmantph512_mask:
4548   case X86::BI__builtin_ia32_vec_ext_v16qi:
4549   case X86::BI__builtin_ia32_vec_ext_v16hi:
4550     i = 1; l = 0; u = 15;
4551     break;
4552   case X86::BI__builtin_ia32_pblendd128:
4553   case X86::BI__builtin_ia32_blendps:
4554   case X86::BI__builtin_ia32_blendpd256:
4555   case X86::BI__builtin_ia32_shufpd256:
4556   case X86::BI__builtin_ia32_roundss:
4557   case X86::BI__builtin_ia32_roundsd:
4558   case X86::BI__builtin_ia32_rangepd128_mask:
4559   case X86::BI__builtin_ia32_rangepd256_mask:
4560   case X86::BI__builtin_ia32_rangepd512_mask:
4561   case X86::BI__builtin_ia32_rangeps128_mask:
4562   case X86::BI__builtin_ia32_rangeps256_mask:
4563   case X86::BI__builtin_ia32_rangeps512_mask:
4564   case X86::BI__builtin_ia32_getmantsd_round_mask:
4565   case X86::BI__builtin_ia32_getmantss_round_mask:
4566   case X86::BI__builtin_ia32_getmantsh_round_mask:
4567   case X86::BI__builtin_ia32_vec_set_v16qi:
4568   case X86::BI__builtin_ia32_vec_set_v16hi:
4569     i = 2; l = 0; u = 15;
4570     break;
4571   case X86::BI__builtin_ia32_vec_ext_v32qi:
4572     i = 1; l = 0; u = 31;
4573     break;
4574   case X86::BI__builtin_ia32_cmpps:
4575   case X86::BI__builtin_ia32_cmpss:
4576   case X86::BI__builtin_ia32_cmppd:
4577   case X86::BI__builtin_ia32_cmpsd:
4578   case X86::BI__builtin_ia32_cmpps256:
4579   case X86::BI__builtin_ia32_cmppd256:
4580   case X86::BI__builtin_ia32_cmpps128_mask:
4581   case X86::BI__builtin_ia32_cmppd128_mask:
4582   case X86::BI__builtin_ia32_cmpps256_mask:
4583   case X86::BI__builtin_ia32_cmppd256_mask:
4584   case X86::BI__builtin_ia32_cmpps512_mask:
4585   case X86::BI__builtin_ia32_cmppd512_mask:
4586   case X86::BI__builtin_ia32_cmpsd_mask:
4587   case X86::BI__builtin_ia32_cmpss_mask:
4588   case X86::BI__builtin_ia32_vec_set_v32qi:
4589     i = 2; l = 0; u = 31;
4590     break;
4591   case X86::BI__builtin_ia32_permdf256:
4592   case X86::BI__builtin_ia32_permdi256:
4593   case X86::BI__builtin_ia32_permdf512:
4594   case X86::BI__builtin_ia32_permdi512:
4595   case X86::BI__builtin_ia32_vpermilps:
4596   case X86::BI__builtin_ia32_vpermilps256:
4597   case X86::BI__builtin_ia32_vpermilpd512:
4598   case X86::BI__builtin_ia32_vpermilps512:
4599   case X86::BI__builtin_ia32_pshufd:
4600   case X86::BI__builtin_ia32_pshufd256:
4601   case X86::BI__builtin_ia32_pshufd512:
4602   case X86::BI__builtin_ia32_pshufhw:
4603   case X86::BI__builtin_ia32_pshufhw256:
4604   case X86::BI__builtin_ia32_pshufhw512:
4605   case X86::BI__builtin_ia32_pshuflw:
4606   case X86::BI__builtin_ia32_pshuflw256:
4607   case X86::BI__builtin_ia32_pshuflw512:
4608   case X86::BI__builtin_ia32_vcvtps2ph:
4609   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4610   case X86::BI__builtin_ia32_vcvtps2ph256:
4611   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4612   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4613   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4614   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4615   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4616   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4617   case X86::BI__builtin_ia32_rndscaleps_mask:
4618   case X86::BI__builtin_ia32_rndscalepd_mask:
4619   case X86::BI__builtin_ia32_rndscaleph_mask:
4620   case X86::BI__builtin_ia32_reducepd128_mask:
4621   case X86::BI__builtin_ia32_reducepd256_mask:
4622   case X86::BI__builtin_ia32_reducepd512_mask:
4623   case X86::BI__builtin_ia32_reduceps128_mask:
4624   case X86::BI__builtin_ia32_reduceps256_mask:
4625   case X86::BI__builtin_ia32_reduceps512_mask:
4626   case X86::BI__builtin_ia32_reduceph128_mask:
4627   case X86::BI__builtin_ia32_reduceph256_mask:
4628   case X86::BI__builtin_ia32_reduceph512_mask:
4629   case X86::BI__builtin_ia32_prold512:
4630   case X86::BI__builtin_ia32_prolq512:
4631   case X86::BI__builtin_ia32_prold128:
4632   case X86::BI__builtin_ia32_prold256:
4633   case X86::BI__builtin_ia32_prolq128:
4634   case X86::BI__builtin_ia32_prolq256:
4635   case X86::BI__builtin_ia32_prord512:
4636   case X86::BI__builtin_ia32_prorq512:
4637   case X86::BI__builtin_ia32_prord128:
4638   case X86::BI__builtin_ia32_prord256:
4639   case X86::BI__builtin_ia32_prorq128:
4640   case X86::BI__builtin_ia32_prorq256:
4641   case X86::BI__builtin_ia32_fpclasspd128_mask:
4642   case X86::BI__builtin_ia32_fpclasspd256_mask:
4643   case X86::BI__builtin_ia32_fpclassps128_mask:
4644   case X86::BI__builtin_ia32_fpclassps256_mask:
4645   case X86::BI__builtin_ia32_fpclassps512_mask:
4646   case X86::BI__builtin_ia32_fpclasspd512_mask:
4647   case X86::BI__builtin_ia32_fpclassph128_mask:
4648   case X86::BI__builtin_ia32_fpclassph256_mask:
4649   case X86::BI__builtin_ia32_fpclassph512_mask:
4650   case X86::BI__builtin_ia32_fpclasssd_mask:
4651   case X86::BI__builtin_ia32_fpclassss_mask:
4652   case X86::BI__builtin_ia32_fpclasssh_mask:
4653   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4654   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4655   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4656   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4657   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4658   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4659   case X86::BI__builtin_ia32_kshiftliqi:
4660   case X86::BI__builtin_ia32_kshiftlihi:
4661   case X86::BI__builtin_ia32_kshiftlisi:
4662   case X86::BI__builtin_ia32_kshiftlidi:
4663   case X86::BI__builtin_ia32_kshiftriqi:
4664   case X86::BI__builtin_ia32_kshiftrihi:
4665   case X86::BI__builtin_ia32_kshiftrisi:
4666   case X86::BI__builtin_ia32_kshiftridi:
4667     i = 1; l = 0; u = 255;
4668     break;
4669   case X86::BI__builtin_ia32_vperm2f128_pd256:
4670   case X86::BI__builtin_ia32_vperm2f128_ps256:
4671   case X86::BI__builtin_ia32_vperm2f128_si256:
4672   case X86::BI__builtin_ia32_permti256:
4673   case X86::BI__builtin_ia32_pblendw128:
4674   case X86::BI__builtin_ia32_pblendw256:
4675   case X86::BI__builtin_ia32_blendps256:
4676   case X86::BI__builtin_ia32_pblendd256:
4677   case X86::BI__builtin_ia32_palignr128:
4678   case X86::BI__builtin_ia32_palignr256:
4679   case X86::BI__builtin_ia32_palignr512:
4680   case X86::BI__builtin_ia32_alignq512:
4681   case X86::BI__builtin_ia32_alignd512:
4682   case X86::BI__builtin_ia32_alignd128:
4683   case X86::BI__builtin_ia32_alignd256:
4684   case X86::BI__builtin_ia32_alignq128:
4685   case X86::BI__builtin_ia32_alignq256:
4686   case X86::BI__builtin_ia32_vcomisd:
4687   case X86::BI__builtin_ia32_vcomiss:
4688   case X86::BI__builtin_ia32_shuf_f32x4:
4689   case X86::BI__builtin_ia32_shuf_f64x2:
4690   case X86::BI__builtin_ia32_shuf_i32x4:
4691   case X86::BI__builtin_ia32_shuf_i64x2:
4692   case X86::BI__builtin_ia32_shufpd512:
4693   case X86::BI__builtin_ia32_shufps:
4694   case X86::BI__builtin_ia32_shufps256:
4695   case X86::BI__builtin_ia32_shufps512:
4696   case X86::BI__builtin_ia32_dbpsadbw128:
4697   case X86::BI__builtin_ia32_dbpsadbw256:
4698   case X86::BI__builtin_ia32_dbpsadbw512:
4699   case X86::BI__builtin_ia32_vpshldd128:
4700   case X86::BI__builtin_ia32_vpshldd256:
4701   case X86::BI__builtin_ia32_vpshldd512:
4702   case X86::BI__builtin_ia32_vpshldq128:
4703   case X86::BI__builtin_ia32_vpshldq256:
4704   case X86::BI__builtin_ia32_vpshldq512:
4705   case X86::BI__builtin_ia32_vpshldw128:
4706   case X86::BI__builtin_ia32_vpshldw256:
4707   case X86::BI__builtin_ia32_vpshldw512:
4708   case X86::BI__builtin_ia32_vpshrdd128:
4709   case X86::BI__builtin_ia32_vpshrdd256:
4710   case X86::BI__builtin_ia32_vpshrdd512:
4711   case X86::BI__builtin_ia32_vpshrdq128:
4712   case X86::BI__builtin_ia32_vpshrdq256:
4713   case X86::BI__builtin_ia32_vpshrdq512:
4714   case X86::BI__builtin_ia32_vpshrdw128:
4715   case X86::BI__builtin_ia32_vpshrdw256:
4716   case X86::BI__builtin_ia32_vpshrdw512:
4717     i = 2; l = 0; u = 255;
4718     break;
4719   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4720   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4721   case X86::BI__builtin_ia32_fixupimmps512_mask:
4722   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4723   case X86::BI__builtin_ia32_fixupimmsd_mask:
4724   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4725   case X86::BI__builtin_ia32_fixupimmss_mask:
4726   case X86::BI__builtin_ia32_fixupimmss_maskz:
4727   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4728   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4729   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4730   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4731   case X86::BI__builtin_ia32_fixupimmps128_mask:
4732   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4733   case X86::BI__builtin_ia32_fixupimmps256_mask:
4734   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4735   case X86::BI__builtin_ia32_pternlogd512_mask:
4736   case X86::BI__builtin_ia32_pternlogd512_maskz:
4737   case X86::BI__builtin_ia32_pternlogq512_mask:
4738   case X86::BI__builtin_ia32_pternlogq512_maskz:
4739   case X86::BI__builtin_ia32_pternlogd128_mask:
4740   case X86::BI__builtin_ia32_pternlogd128_maskz:
4741   case X86::BI__builtin_ia32_pternlogd256_mask:
4742   case X86::BI__builtin_ia32_pternlogd256_maskz:
4743   case X86::BI__builtin_ia32_pternlogq128_mask:
4744   case X86::BI__builtin_ia32_pternlogq128_maskz:
4745   case X86::BI__builtin_ia32_pternlogq256_mask:
4746   case X86::BI__builtin_ia32_pternlogq256_maskz:
4747     i = 3; l = 0; u = 255;
4748     break;
4749   case X86::BI__builtin_ia32_gatherpfdpd:
4750   case X86::BI__builtin_ia32_gatherpfdps:
4751   case X86::BI__builtin_ia32_gatherpfqpd:
4752   case X86::BI__builtin_ia32_gatherpfqps:
4753   case X86::BI__builtin_ia32_scatterpfdpd:
4754   case X86::BI__builtin_ia32_scatterpfdps:
4755   case X86::BI__builtin_ia32_scatterpfqpd:
4756   case X86::BI__builtin_ia32_scatterpfqps:
4757     i = 4; l = 2; u = 3;
4758     break;
4759   case X86::BI__builtin_ia32_reducesd_mask:
4760   case X86::BI__builtin_ia32_reducess_mask:
4761   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4762   case X86::BI__builtin_ia32_rndscaless_round_mask:
4763   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4764   case X86::BI__builtin_ia32_reducesh_mask:
4765     i = 4; l = 0; u = 255;
4766     break;
4767   }
4768 
4769   // Note that we don't force a hard error on the range check here, allowing
4770   // template-generated or macro-generated dead code to potentially have out-of-
4771   // range values. These need to code generate, but don't need to necessarily
4772   // make any sense. We use a warning that defaults to an error.
4773   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4774 }
4775 
4776 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4777 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4778 /// Returns true when the format fits the function and the FormatStringInfo has
4779 /// been populated.
4780 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4781                                FormatStringInfo *FSI) {
4782   FSI->HasVAListArg = Format->getFirstArg() == 0;
4783   FSI->FormatIdx = Format->getFormatIdx() - 1;
4784   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4785 
4786   // The way the format attribute works in GCC, the implicit this argument
4787   // of member functions is counted. However, it doesn't appear in our own
4788   // lists, so decrement format_idx in that case.
4789   if (IsCXXMember) {
4790     if(FSI->FormatIdx == 0)
4791       return false;
4792     --FSI->FormatIdx;
4793     if (FSI->FirstDataArg != 0)
4794       --FSI->FirstDataArg;
4795   }
4796   return true;
4797 }
4798 
4799 /// Checks if a the given expression evaluates to null.
4800 ///
4801 /// Returns true if the value evaluates to null.
4802 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4803   // If the expression has non-null type, it doesn't evaluate to null.
4804   if (auto nullability
4805         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4806     if (*nullability == NullabilityKind::NonNull)
4807       return false;
4808   }
4809 
4810   // As a special case, transparent unions initialized with zero are
4811   // considered null for the purposes of the nonnull attribute.
4812   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4813     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4814       if (const CompoundLiteralExpr *CLE =
4815           dyn_cast<CompoundLiteralExpr>(Expr))
4816         if (const InitListExpr *ILE =
4817             dyn_cast<InitListExpr>(CLE->getInitializer()))
4818           Expr = ILE->getInit(0);
4819   }
4820 
4821   bool Result;
4822   return (!Expr->isValueDependent() &&
4823           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4824           !Result);
4825 }
4826 
4827 static void CheckNonNullArgument(Sema &S,
4828                                  const Expr *ArgExpr,
4829                                  SourceLocation CallSiteLoc) {
4830   if (CheckNonNullExpr(S, ArgExpr))
4831     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4832                           S.PDiag(diag::warn_null_arg)
4833                               << ArgExpr->getSourceRange());
4834 }
4835 
4836 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4837   FormatStringInfo FSI;
4838   if ((GetFormatStringType(Format) == FST_NSString) &&
4839       getFormatStringInfo(Format, false, &FSI)) {
4840     Idx = FSI.FormatIdx;
4841     return true;
4842   }
4843   return false;
4844 }
4845 
4846 /// Diagnose use of %s directive in an NSString which is being passed
4847 /// as formatting string to formatting method.
4848 static void
4849 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4850                                         const NamedDecl *FDecl,
4851                                         Expr **Args,
4852                                         unsigned NumArgs) {
4853   unsigned Idx = 0;
4854   bool Format = false;
4855   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4856   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4857     Idx = 2;
4858     Format = true;
4859   }
4860   else
4861     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4862       if (S.GetFormatNSStringIdx(I, Idx)) {
4863         Format = true;
4864         break;
4865       }
4866     }
4867   if (!Format || NumArgs <= Idx)
4868     return;
4869   const Expr *FormatExpr = Args[Idx];
4870   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4871     FormatExpr = CSCE->getSubExpr();
4872   const StringLiteral *FormatString;
4873   if (const ObjCStringLiteral *OSL =
4874       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4875     FormatString = OSL->getString();
4876   else
4877     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4878   if (!FormatString)
4879     return;
4880   if (S.FormatStringHasSArg(FormatString)) {
4881     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4882       << "%s" << 1 << 1;
4883     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4884       << FDecl->getDeclName();
4885   }
4886 }
4887 
4888 /// Determine whether the given type has a non-null nullability annotation.
4889 static bool isNonNullType(ASTContext &ctx, QualType type) {
4890   if (auto nullability = type->getNullability(ctx))
4891     return *nullability == NullabilityKind::NonNull;
4892 
4893   return false;
4894 }
4895 
4896 static void CheckNonNullArguments(Sema &S,
4897                                   const NamedDecl *FDecl,
4898                                   const FunctionProtoType *Proto,
4899                                   ArrayRef<const Expr *> Args,
4900                                   SourceLocation CallSiteLoc) {
4901   assert((FDecl || Proto) && "Need a function declaration or prototype");
4902 
4903   // Already checked by by constant evaluator.
4904   if (S.isConstantEvaluated())
4905     return;
4906   // Check the attributes attached to the method/function itself.
4907   llvm::SmallBitVector NonNullArgs;
4908   if (FDecl) {
4909     // Handle the nonnull attribute on the function/method declaration itself.
4910     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4911       if (!NonNull->args_size()) {
4912         // Easy case: all pointer arguments are nonnull.
4913         for (const auto *Arg : Args)
4914           if (S.isValidPointerAttrType(Arg->getType()))
4915             CheckNonNullArgument(S, Arg, CallSiteLoc);
4916         return;
4917       }
4918 
4919       for (const ParamIdx &Idx : NonNull->args()) {
4920         unsigned IdxAST = Idx.getASTIndex();
4921         if (IdxAST >= Args.size())
4922           continue;
4923         if (NonNullArgs.empty())
4924           NonNullArgs.resize(Args.size());
4925         NonNullArgs.set(IdxAST);
4926       }
4927     }
4928   }
4929 
4930   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4931     // Handle the nonnull attribute on the parameters of the
4932     // function/method.
4933     ArrayRef<ParmVarDecl*> parms;
4934     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4935       parms = FD->parameters();
4936     else
4937       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4938 
4939     unsigned ParamIndex = 0;
4940     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4941          I != E; ++I, ++ParamIndex) {
4942       const ParmVarDecl *PVD = *I;
4943       if (PVD->hasAttr<NonNullAttr>() ||
4944           isNonNullType(S.Context, PVD->getType())) {
4945         if (NonNullArgs.empty())
4946           NonNullArgs.resize(Args.size());
4947 
4948         NonNullArgs.set(ParamIndex);
4949       }
4950     }
4951   } else {
4952     // If we have a non-function, non-method declaration but no
4953     // function prototype, try to dig out the function prototype.
4954     if (!Proto) {
4955       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4956         QualType type = VD->getType().getNonReferenceType();
4957         if (auto pointerType = type->getAs<PointerType>())
4958           type = pointerType->getPointeeType();
4959         else if (auto blockType = type->getAs<BlockPointerType>())
4960           type = blockType->getPointeeType();
4961         // FIXME: data member pointers?
4962 
4963         // Dig out the function prototype, if there is one.
4964         Proto = type->getAs<FunctionProtoType>();
4965       }
4966     }
4967 
4968     // Fill in non-null argument information from the nullability
4969     // information on the parameter types (if we have them).
4970     if (Proto) {
4971       unsigned Index = 0;
4972       for (auto paramType : Proto->getParamTypes()) {
4973         if (isNonNullType(S.Context, paramType)) {
4974           if (NonNullArgs.empty())
4975             NonNullArgs.resize(Args.size());
4976 
4977           NonNullArgs.set(Index);
4978         }
4979 
4980         ++Index;
4981       }
4982     }
4983   }
4984 
4985   // Check for non-null arguments.
4986   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4987        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4988     if (NonNullArgs[ArgIndex])
4989       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4990   }
4991 }
4992 
4993 /// Warn if a pointer or reference argument passed to a function points to an
4994 /// object that is less aligned than the parameter. This can happen when
4995 /// creating a typedef with a lower alignment than the original type and then
4996 /// calling functions defined in terms of the original type.
4997 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4998                              StringRef ParamName, QualType ArgTy,
4999                              QualType ParamTy) {
5000 
5001   // If a function accepts a pointer or reference type
5002   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
5003     return;
5004 
5005   // If the parameter is a pointer type, get the pointee type for the
5006   // argument too. If the parameter is a reference type, don't try to get
5007   // the pointee type for the argument.
5008   if (ParamTy->isPointerType())
5009     ArgTy = ArgTy->getPointeeType();
5010 
5011   // Remove reference or pointer
5012   ParamTy = ParamTy->getPointeeType();
5013 
5014   // Find expected alignment, and the actual alignment of the passed object.
5015   // getTypeAlignInChars requires complete types
5016   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
5017       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
5018       ArgTy->isUndeducedType())
5019     return;
5020 
5021   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
5022   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
5023 
5024   // If the argument is less aligned than the parameter, there is a
5025   // potential alignment issue.
5026   if (ArgAlign < ParamAlign)
5027     Diag(Loc, diag::warn_param_mismatched_alignment)
5028         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
5029         << ParamName << (FDecl != nullptr) << FDecl;
5030 }
5031 
5032 /// Handles the checks for format strings, non-POD arguments to vararg
5033 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
5034 /// attributes.
5035 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
5036                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
5037                      bool IsMemberFunction, SourceLocation Loc,
5038                      SourceRange Range, VariadicCallType CallType) {
5039   // FIXME: We should check as much as we can in the template definition.
5040   if (CurContext->isDependentContext())
5041     return;
5042 
5043   // Printf and scanf checking.
5044   llvm::SmallBitVector CheckedVarArgs;
5045   if (FDecl) {
5046     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
5047       // Only create vector if there are format attributes.
5048       CheckedVarArgs.resize(Args.size());
5049 
5050       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
5051                            CheckedVarArgs);
5052     }
5053   }
5054 
5055   // Refuse POD arguments that weren't caught by the format string
5056   // checks above.
5057   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
5058   if (CallType != VariadicDoesNotApply &&
5059       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
5060     unsigned NumParams = Proto ? Proto->getNumParams()
5061                        : FDecl && isa<FunctionDecl>(FDecl)
5062                            ? cast<FunctionDecl>(FDecl)->getNumParams()
5063                        : FDecl && isa<ObjCMethodDecl>(FDecl)
5064                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
5065                        : 0;
5066 
5067     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
5068       // Args[ArgIdx] can be null in malformed code.
5069       if (const Expr *Arg = Args[ArgIdx]) {
5070         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
5071           checkVariadicArgument(Arg, CallType);
5072       }
5073     }
5074   }
5075 
5076   if (FDecl || Proto) {
5077     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
5078 
5079     // Type safety checking.
5080     if (FDecl) {
5081       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
5082         CheckArgumentWithTypeTag(I, Args, Loc);
5083     }
5084   }
5085 
5086   // Check that passed arguments match the alignment of original arguments.
5087   // Try to get the missing prototype from the declaration.
5088   if (!Proto && FDecl) {
5089     const auto *FT = FDecl->getFunctionType();
5090     if (isa_and_nonnull<FunctionProtoType>(FT))
5091       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5092   }
5093   if (Proto) {
5094     // For variadic functions, we may have more args than parameters.
5095     // For some K&R functions, we may have less args than parameters.
5096     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5097     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5098       // Args[ArgIdx] can be null in malformed code.
5099       if (const Expr *Arg = Args[ArgIdx]) {
5100         if (Arg->containsErrors())
5101           continue;
5102 
5103         QualType ParamTy = Proto->getParamType(ArgIdx);
5104         QualType ArgTy = Arg->getType();
5105         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5106                           ArgTy, ParamTy);
5107       }
5108     }
5109   }
5110 
5111   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5112     auto *AA = FDecl->getAttr<AllocAlignAttr>();
5113     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5114     if (!Arg->isValueDependent()) {
5115       Expr::EvalResult Align;
5116       if (Arg->EvaluateAsInt(Align, Context)) {
5117         const llvm::APSInt &I = Align.Val.getInt();
5118         if (!I.isPowerOf2())
5119           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5120               << Arg->getSourceRange();
5121 
5122         if (I > Sema::MaximumAlignment)
5123           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5124               << Arg->getSourceRange() << Sema::MaximumAlignment;
5125       }
5126     }
5127   }
5128 
5129   if (FD)
5130     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5131 }
5132 
5133 /// CheckConstructorCall - Check a constructor call for correctness and safety
5134 /// properties not enforced by the C type system.
5135 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5136                                 ArrayRef<const Expr *> Args,
5137                                 const FunctionProtoType *Proto,
5138                                 SourceLocation Loc) {
5139   VariadicCallType CallType =
5140       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5141 
5142   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5143   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5144                     Context.getPointerType(Ctor->getThisObjectType()));
5145 
5146   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5147             Loc, SourceRange(), CallType);
5148 }
5149 
5150 /// CheckFunctionCall - Check a direct function call for various correctness
5151 /// and safety properties not strictly enforced by the C type system.
5152 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5153                              const FunctionProtoType *Proto) {
5154   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5155                               isa<CXXMethodDecl>(FDecl);
5156   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5157                           IsMemberOperatorCall;
5158   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5159                                                   TheCall->getCallee());
5160   Expr** Args = TheCall->getArgs();
5161   unsigned NumArgs = TheCall->getNumArgs();
5162 
5163   Expr *ImplicitThis = nullptr;
5164   if (IsMemberOperatorCall) {
5165     // If this is a call to a member operator, hide the first argument
5166     // from checkCall.
5167     // FIXME: Our choice of AST representation here is less than ideal.
5168     ImplicitThis = Args[0];
5169     ++Args;
5170     --NumArgs;
5171   } else if (IsMemberFunction)
5172     ImplicitThis =
5173         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5174 
5175   if (ImplicitThis) {
5176     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5177     // used.
5178     QualType ThisType = ImplicitThis->getType();
5179     if (!ThisType->isPointerType()) {
5180       assert(!ThisType->isReferenceType());
5181       ThisType = Context.getPointerType(ThisType);
5182     }
5183 
5184     QualType ThisTypeFromDecl =
5185         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5186 
5187     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5188                       ThisTypeFromDecl);
5189   }
5190 
5191   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5192             IsMemberFunction, TheCall->getRParenLoc(),
5193             TheCall->getCallee()->getSourceRange(), CallType);
5194 
5195   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5196   // None of the checks below are needed for functions that don't have
5197   // simple names (e.g., C++ conversion functions).
5198   if (!FnInfo)
5199     return false;
5200 
5201   CheckTCBEnforcement(TheCall, FDecl);
5202 
5203   CheckAbsoluteValueFunction(TheCall, FDecl);
5204   CheckMaxUnsignedZero(TheCall, FDecl);
5205 
5206   if (getLangOpts().ObjC)
5207     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5208 
5209   unsigned CMId = FDecl->getMemoryFunctionKind();
5210 
5211   // Handle memory setting and copying functions.
5212   switch (CMId) {
5213   case 0:
5214     return false;
5215   case Builtin::BIstrlcpy: // fallthrough
5216   case Builtin::BIstrlcat:
5217     CheckStrlcpycatArguments(TheCall, FnInfo);
5218     break;
5219   case Builtin::BIstrncat:
5220     CheckStrncatArguments(TheCall, FnInfo);
5221     break;
5222   case Builtin::BIfree:
5223     CheckFreeArguments(TheCall);
5224     break;
5225   default:
5226     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5227   }
5228 
5229   return false;
5230 }
5231 
5232 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5233                                ArrayRef<const Expr *> Args) {
5234   VariadicCallType CallType =
5235       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5236 
5237   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5238             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5239             CallType);
5240 
5241   return false;
5242 }
5243 
5244 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5245                             const FunctionProtoType *Proto) {
5246   QualType Ty;
5247   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5248     Ty = V->getType().getNonReferenceType();
5249   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5250     Ty = F->getType().getNonReferenceType();
5251   else
5252     return false;
5253 
5254   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5255       !Ty->isFunctionProtoType())
5256     return false;
5257 
5258   VariadicCallType CallType;
5259   if (!Proto || !Proto->isVariadic()) {
5260     CallType = VariadicDoesNotApply;
5261   } else if (Ty->isBlockPointerType()) {
5262     CallType = VariadicBlock;
5263   } else { // Ty->isFunctionPointerType()
5264     CallType = VariadicFunction;
5265   }
5266 
5267   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5268             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5269             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5270             TheCall->getCallee()->getSourceRange(), CallType);
5271 
5272   return false;
5273 }
5274 
5275 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5276 /// such as function pointers returned from functions.
5277 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5278   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5279                                                   TheCall->getCallee());
5280   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5281             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5282             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5283             TheCall->getCallee()->getSourceRange(), CallType);
5284 
5285   return false;
5286 }
5287 
5288 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5289   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5290     return false;
5291 
5292   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5293   switch (Op) {
5294   case AtomicExpr::AO__c11_atomic_init:
5295   case AtomicExpr::AO__opencl_atomic_init:
5296     llvm_unreachable("There is no ordering argument for an init");
5297 
5298   case AtomicExpr::AO__c11_atomic_load:
5299   case AtomicExpr::AO__opencl_atomic_load:
5300   case AtomicExpr::AO__hip_atomic_load:
5301   case AtomicExpr::AO__atomic_load_n:
5302   case AtomicExpr::AO__atomic_load:
5303     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5304            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5305 
5306   case AtomicExpr::AO__c11_atomic_store:
5307   case AtomicExpr::AO__opencl_atomic_store:
5308   case AtomicExpr::AO__hip_atomic_store:
5309   case AtomicExpr::AO__atomic_store:
5310   case AtomicExpr::AO__atomic_store_n:
5311     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5312            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5313            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5314 
5315   default:
5316     return true;
5317   }
5318 }
5319 
5320 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5321                                          AtomicExpr::AtomicOp Op) {
5322   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5323   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5324   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5325   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5326                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5327                          Op);
5328 }
5329 
5330 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5331                                  SourceLocation RParenLoc, MultiExprArg Args,
5332                                  AtomicExpr::AtomicOp Op,
5333                                  AtomicArgumentOrder ArgOrder) {
5334   // All the non-OpenCL operations take one of the following forms.
5335   // The OpenCL operations take the __c11 forms with one extra argument for
5336   // synchronization scope.
5337   enum {
5338     // C    __c11_atomic_init(A *, C)
5339     Init,
5340 
5341     // C    __c11_atomic_load(A *, int)
5342     Load,
5343 
5344     // void __atomic_load(A *, CP, int)
5345     LoadCopy,
5346 
5347     // void __atomic_store(A *, CP, int)
5348     Copy,
5349 
5350     // C    __c11_atomic_add(A *, M, int)
5351     Arithmetic,
5352 
5353     // C    __atomic_exchange_n(A *, CP, int)
5354     Xchg,
5355 
5356     // void __atomic_exchange(A *, C *, CP, int)
5357     GNUXchg,
5358 
5359     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5360     C11CmpXchg,
5361 
5362     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5363     GNUCmpXchg
5364   } Form = Init;
5365 
5366   const unsigned NumForm = GNUCmpXchg + 1;
5367   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5368   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5369   // where:
5370   //   C is an appropriate type,
5371   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5372   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5373   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5374   //   the int parameters are for orderings.
5375 
5376   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5377       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5378       "need to update code for modified forms");
5379   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5380                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5381                         AtomicExpr::AO__atomic_load,
5382                 "need to update code for modified C11 atomics");
5383   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5384                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5385   bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load &&
5386                Op <= AtomicExpr::AO__hip_atomic_fetch_max;
5387   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5388                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5389                IsOpenCL;
5390   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5391              Op == AtomicExpr::AO__atomic_store_n ||
5392              Op == AtomicExpr::AO__atomic_exchange_n ||
5393              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5394   bool IsAddSub = false;
5395 
5396   switch (Op) {
5397   case AtomicExpr::AO__c11_atomic_init:
5398   case AtomicExpr::AO__opencl_atomic_init:
5399     Form = Init;
5400     break;
5401 
5402   case AtomicExpr::AO__c11_atomic_load:
5403   case AtomicExpr::AO__opencl_atomic_load:
5404   case AtomicExpr::AO__hip_atomic_load:
5405   case AtomicExpr::AO__atomic_load_n:
5406     Form = Load;
5407     break;
5408 
5409   case AtomicExpr::AO__atomic_load:
5410     Form = LoadCopy;
5411     break;
5412 
5413   case AtomicExpr::AO__c11_atomic_store:
5414   case AtomicExpr::AO__opencl_atomic_store:
5415   case AtomicExpr::AO__hip_atomic_store:
5416   case AtomicExpr::AO__atomic_store:
5417   case AtomicExpr::AO__atomic_store_n:
5418     Form = Copy;
5419     break;
5420   case AtomicExpr::AO__hip_atomic_fetch_add:
5421   case AtomicExpr::AO__hip_atomic_fetch_min:
5422   case AtomicExpr::AO__hip_atomic_fetch_max:
5423   case AtomicExpr::AO__c11_atomic_fetch_add:
5424   case AtomicExpr::AO__c11_atomic_fetch_sub:
5425   case AtomicExpr::AO__opencl_atomic_fetch_add:
5426   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5427   case AtomicExpr::AO__atomic_fetch_add:
5428   case AtomicExpr::AO__atomic_fetch_sub:
5429   case AtomicExpr::AO__atomic_add_fetch:
5430   case AtomicExpr::AO__atomic_sub_fetch:
5431     IsAddSub = true;
5432     Form = Arithmetic;
5433     break;
5434   case AtomicExpr::AO__c11_atomic_fetch_and:
5435   case AtomicExpr::AO__c11_atomic_fetch_or:
5436   case AtomicExpr::AO__c11_atomic_fetch_xor:
5437   case AtomicExpr::AO__hip_atomic_fetch_and:
5438   case AtomicExpr::AO__hip_atomic_fetch_or:
5439   case AtomicExpr::AO__hip_atomic_fetch_xor:
5440   case AtomicExpr::AO__c11_atomic_fetch_nand:
5441   case AtomicExpr::AO__opencl_atomic_fetch_and:
5442   case AtomicExpr::AO__opencl_atomic_fetch_or:
5443   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5444   case AtomicExpr::AO__atomic_fetch_and:
5445   case AtomicExpr::AO__atomic_fetch_or:
5446   case AtomicExpr::AO__atomic_fetch_xor:
5447   case AtomicExpr::AO__atomic_fetch_nand:
5448   case AtomicExpr::AO__atomic_and_fetch:
5449   case AtomicExpr::AO__atomic_or_fetch:
5450   case AtomicExpr::AO__atomic_xor_fetch:
5451   case AtomicExpr::AO__atomic_nand_fetch:
5452     Form = Arithmetic;
5453     break;
5454   case AtomicExpr::AO__c11_atomic_fetch_min:
5455   case AtomicExpr::AO__c11_atomic_fetch_max:
5456   case AtomicExpr::AO__opencl_atomic_fetch_min:
5457   case AtomicExpr::AO__opencl_atomic_fetch_max:
5458   case AtomicExpr::AO__atomic_min_fetch:
5459   case AtomicExpr::AO__atomic_max_fetch:
5460   case AtomicExpr::AO__atomic_fetch_min:
5461   case AtomicExpr::AO__atomic_fetch_max:
5462     Form = Arithmetic;
5463     break;
5464 
5465   case AtomicExpr::AO__c11_atomic_exchange:
5466   case AtomicExpr::AO__hip_atomic_exchange:
5467   case AtomicExpr::AO__opencl_atomic_exchange:
5468   case AtomicExpr::AO__atomic_exchange_n:
5469     Form = Xchg;
5470     break;
5471 
5472   case AtomicExpr::AO__atomic_exchange:
5473     Form = GNUXchg;
5474     break;
5475 
5476   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5477   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5478   case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5479   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5480   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5481   case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5482     Form = C11CmpXchg;
5483     break;
5484 
5485   case AtomicExpr::AO__atomic_compare_exchange:
5486   case AtomicExpr::AO__atomic_compare_exchange_n:
5487     Form = GNUCmpXchg;
5488     break;
5489   }
5490 
5491   unsigned AdjustedNumArgs = NumArgs[Form];
5492   if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init)
5493     ++AdjustedNumArgs;
5494   // Check we have the right number of arguments.
5495   if (Args.size() < AdjustedNumArgs) {
5496     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5497         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5498         << ExprRange;
5499     return ExprError();
5500   } else if (Args.size() > AdjustedNumArgs) {
5501     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5502          diag::err_typecheck_call_too_many_args)
5503         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5504         << ExprRange;
5505     return ExprError();
5506   }
5507 
5508   // Inspect the first argument of the atomic operation.
5509   Expr *Ptr = Args[0];
5510   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5511   if (ConvertedPtr.isInvalid())
5512     return ExprError();
5513 
5514   Ptr = ConvertedPtr.get();
5515   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5516   if (!pointerType) {
5517     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5518         << Ptr->getType() << Ptr->getSourceRange();
5519     return ExprError();
5520   }
5521 
5522   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5523   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5524   QualType ValType = AtomTy; // 'C'
5525   if (IsC11) {
5526     if (!AtomTy->isAtomicType()) {
5527       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5528           << Ptr->getType() << Ptr->getSourceRange();
5529       return ExprError();
5530     }
5531     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5532         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5533       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5534           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5535           << Ptr->getSourceRange();
5536       return ExprError();
5537     }
5538     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5539   } else if (Form != Load && Form != LoadCopy) {
5540     if (ValType.isConstQualified()) {
5541       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5542           << Ptr->getType() << Ptr->getSourceRange();
5543       return ExprError();
5544     }
5545   }
5546 
5547   // For an arithmetic operation, the implied arithmetic must be well-formed.
5548   if (Form == Arithmetic) {
5549     // GCC does not enforce these rules for GNU atomics, but we do, because if
5550     // we didn't it would be very confusing. FIXME:  For whom? How so?
5551     auto IsAllowedValueType = [&](QualType ValType) {
5552       if (ValType->isIntegerType())
5553         return true;
5554       if (ValType->isPointerType())
5555         return true;
5556       if (!ValType->isFloatingType())
5557         return false;
5558       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5559       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5560           &Context.getTargetInfo().getLongDoubleFormat() ==
5561               &llvm::APFloat::x87DoubleExtended())
5562         return false;
5563       return true;
5564     };
5565     if (IsAddSub && !IsAllowedValueType(ValType)) {
5566       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5567           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5568       return ExprError();
5569     }
5570     if (!IsAddSub && !ValType->isIntegerType()) {
5571       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5572           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5573       return ExprError();
5574     }
5575     if (IsC11 && ValType->isPointerType() &&
5576         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5577                             diag::err_incomplete_type)) {
5578       return ExprError();
5579     }
5580   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5581     // For __atomic_*_n operations, the value type must be a scalar integral or
5582     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5583     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5584         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5585     return ExprError();
5586   }
5587 
5588   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5589       !AtomTy->isScalarType()) {
5590     // For GNU atomics, require a trivially-copyable type. This is not part of
5591     // the GNU atomics specification, but we enforce it, because if we didn't it
5592     // would be very confusing. FIXME:  For whom? How so?
5593     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5594         << Ptr->getType() << Ptr->getSourceRange();
5595     return ExprError();
5596   }
5597 
5598   switch (ValType.getObjCLifetime()) {
5599   case Qualifiers::OCL_None:
5600   case Qualifiers::OCL_ExplicitNone:
5601     // okay
5602     break;
5603 
5604   case Qualifiers::OCL_Weak:
5605   case Qualifiers::OCL_Strong:
5606   case Qualifiers::OCL_Autoreleasing:
5607     // FIXME: Can this happen? By this point, ValType should be known
5608     // to be trivially copyable.
5609     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5610         << ValType << Ptr->getSourceRange();
5611     return ExprError();
5612   }
5613 
5614   // All atomic operations have an overload which takes a pointer to a volatile
5615   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5616   // into the result or the other operands. Similarly atomic_load takes a
5617   // pointer to a const 'A'.
5618   ValType.removeLocalVolatile();
5619   ValType.removeLocalConst();
5620   QualType ResultType = ValType;
5621   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5622       Form == Init)
5623     ResultType = Context.VoidTy;
5624   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5625     ResultType = Context.BoolTy;
5626 
5627   // The type of a parameter passed 'by value'. In the GNU atomics, such
5628   // arguments are actually passed as pointers.
5629   QualType ByValType = ValType; // 'CP'
5630   bool IsPassedByAddress = false;
5631   if (!IsC11 && !IsHIP && !IsN) {
5632     ByValType = Ptr->getType();
5633     IsPassedByAddress = true;
5634   }
5635 
5636   SmallVector<Expr *, 5> APIOrderedArgs;
5637   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5638     APIOrderedArgs.push_back(Args[0]);
5639     switch (Form) {
5640     case Init:
5641     case Load:
5642       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5643       break;
5644     case LoadCopy:
5645     case Copy:
5646     case Arithmetic:
5647     case Xchg:
5648       APIOrderedArgs.push_back(Args[2]); // Val1
5649       APIOrderedArgs.push_back(Args[1]); // Order
5650       break;
5651     case GNUXchg:
5652       APIOrderedArgs.push_back(Args[2]); // Val1
5653       APIOrderedArgs.push_back(Args[3]); // Val2
5654       APIOrderedArgs.push_back(Args[1]); // Order
5655       break;
5656     case C11CmpXchg:
5657       APIOrderedArgs.push_back(Args[2]); // Val1
5658       APIOrderedArgs.push_back(Args[4]); // Val2
5659       APIOrderedArgs.push_back(Args[1]); // Order
5660       APIOrderedArgs.push_back(Args[3]); // OrderFail
5661       break;
5662     case GNUCmpXchg:
5663       APIOrderedArgs.push_back(Args[2]); // Val1
5664       APIOrderedArgs.push_back(Args[4]); // Val2
5665       APIOrderedArgs.push_back(Args[5]); // Weak
5666       APIOrderedArgs.push_back(Args[1]); // Order
5667       APIOrderedArgs.push_back(Args[3]); // OrderFail
5668       break;
5669     }
5670   } else
5671     APIOrderedArgs.append(Args.begin(), Args.end());
5672 
5673   // The first argument's non-CV pointer type is used to deduce the type of
5674   // subsequent arguments, except for:
5675   //  - weak flag (always converted to bool)
5676   //  - memory order (always converted to int)
5677   //  - scope  (always converted to int)
5678   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5679     QualType Ty;
5680     if (i < NumVals[Form] + 1) {
5681       switch (i) {
5682       case 0:
5683         // The first argument is always a pointer. It has a fixed type.
5684         // It is always dereferenced, a nullptr is undefined.
5685         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5686         // Nothing else to do: we already know all we want about this pointer.
5687         continue;
5688       case 1:
5689         // The second argument is the non-atomic operand. For arithmetic, this
5690         // is always passed by value, and for a compare_exchange it is always
5691         // passed by address. For the rest, GNU uses by-address and C11 uses
5692         // by-value.
5693         assert(Form != Load);
5694         if (Form == Arithmetic && ValType->isPointerType())
5695           Ty = Context.getPointerDiffType();
5696         else if (Form == Init || Form == Arithmetic)
5697           Ty = ValType;
5698         else if (Form == Copy || Form == Xchg) {
5699           if (IsPassedByAddress) {
5700             // The value pointer is always dereferenced, a nullptr is undefined.
5701             CheckNonNullArgument(*this, APIOrderedArgs[i],
5702                                  ExprRange.getBegin());
5703           }
5704           Ty = ByValType;
5705         } else {
5706           Expr *ValArg = APIOrderedArgs[i];
5707           // The value pointer is always dereferenced, a nullptr is undefined.
5708           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5709           LangAS AS = LangAS::Default;
5710           // Keep address space of non-atomic pointer type.
5711           if (const PointerType *PtrTy =
5712                   ValArg->getType()->getAs<PointerType>()) {
5713             AS = PtrTy->getPointeeType().getAddressSpace();
5714           }
5715           Ty = Context.getPointerType(
5716               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5717         }
5718         break;
5719       case 2:
5720         // The third argument to compare_exchange / GNU exchange is the desired
5721         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5722         if (IsPassedByAddress)
5723           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5724         Ty = ByValType;
5725         break;
5726       case 3:
5727         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5728         Ty = Context.BoolTy;
5729         break;
5730       }
5731     } else {
5732       // The order(s) and scope are always converted to int.
5733       Ty = Context.IntTy;
5734     }
5735 
5736     InitializedEntity Entity =
5737         InitializedEntity::InitializeParameter(Context, Ty, false);
5738     ExprResult Arg = APIOrderedArgs[i];
5739     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5740     if (Arg.isInvalid())
5741       return true;
5742     APIOrderedArgs[i] = Arg.get();
5743   }
5744 
5745   // Permute the arguments into a 'consistent' order.
5746   SmallVector<Expr*, 5> SubExprs;
5747   SubExprs.push_back(Ptr);
5748   switch (Form) {
5749   case Init:
5750     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5751     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5752     break;
5753   case Load:
5754     SubExprs.push_back(APIOrderedArgs[1]); // Order
5755     break;
5756   case LoadCopy:
5757   case Copy:
5758   case Arithmetic:
5759   case Xchg:
5760     SubExprs.push_back(APIOrderedArgs[2]); // Order
5761     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5762     break;
5763   case GNUXchg:
5764     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5765     SubExprs.push_back(APIOrderedArgs[3]); // Order
5766     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5767     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5768     break;
5769   case C11CmpXchg:
5770     SubExprs.push_back(APIOrderedArgs[3]); // Order
5771     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5772     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5773     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5774     break;
5775   case GNUCmpXchg:
5776     SubExprs.push_back(APIOrderedArgs[4]); // Order
5777     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5778     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5779     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5780     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5781     break;
5782   }
5783 
5784   if (SubExprs.size() >= 2 && Form != Init) {
5785     if (Optional<llvm::APSInt> Result =
5786             SubExprs[1]->getIntegerConstantExpr(Context))
5787       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5788         Diag(SubExprs[1]->getBeginLoc(),
5789              diag::warn_atomic_op_has_invalid_memory_order)
5790             << SubExprs[1]->getSourceRange();
5791   }
5792 
5793   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5794     auto *Scope = Args[Args.size() - 1];
5795     if (Optional<llvm::APSInt> Result =
5796             Scope->getIntegerConstantExpr(Context)) {
5797       if (!ScopeModel->isValid(Result->getZExtValue()))
5798         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5799             << Scope->getSourceRange();
5800     }
5801     SubExprs.push_back(Scope);
5802   }
5803 
5804   AtomicExpr *AE = new (Context)
5805       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5806 
5807   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5808        Op == AtomicExpr::AO__c11_atomic_store ||
5809        Op == AtomicExpr::AO__opencl_atomic_load ||
5810        Op == AtomicExpr::AO__hip_atomic_load ||
5811        Op == AtomicExpr::AO__opencl_atomic_store ||
5812        Op == AtomicExpr::AO__hip_atomic_store) &&
5813       Context.AtomicUsesUnsupportedLibcall(AE))
5814     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5815         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5816              Op == AtomicExpr::AO__opencl_atomic_load ||
5817              Op == AtomicExpr::AO__hip_atomic_load)
5818                 ? 0
5819                 : 1);
5820 
5821   if (ValType->isExtIntType()) {
5822     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5823     return ExprError();
5824   }
5825 
5826   return AE;
5827 }
5828 
5829 /// checkBuiltinArgument - Given a call to a builtin function, perform
5830 /// normal type-checking on the given argument, updating the call in
5831 /// place.  This is useful when a builtin function requires custom
5832 /// type-checking for some of its arguments but not necessarily all of
5833 /// them.
5834 ///
5835 /// Returns true on error.
5836 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5837   FunctionDecl *Fn = E->getDirectCallee();
5838   assert(Fn && "builtin call without direct callee!");
5839 
5840   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5841   InitializedEntity Entity =
5842     InitializedEntity::InitializeParameter(S.Context, Param);
5843 
5844   ExprResult Arg = E->getArg(0);
5845   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5846   if (Arg.isInvalid())
5847     return true;
5848 
5849   E->setArg(ArgIndex, Arg.get());
5850   return false;
5851 }
5852 
5853 /// We have a call to a function like __sync_fetch_and_add, which is an
5854 /// overloaded function based on the pointer type of its first argument.
5855 /// The main BuildCallExpr routines have already promoted the types of
5856 /// arguments because all of these calls are prototyped as void(...).
5857 ///
5858 /// This function goes through and does final semantic checking for these
5859 /// builtins, as well as generating any warnings.
5860 ExprResult
5861 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5862   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5863   Expr *Callee = TheCall->getCallee();
5864   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5865   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5866 
5867   // Ensure that we have at least one argument to do type inference from.
5868   if (TheCall->getNumArgs() < 1) {
5869     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5870         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5871     return ExprError();
5872   }
5873 
5874   // Inspect the first argument of the atomic builtin.  This should always be
5875   // a pointer type, whose element is an integral scalar or pointer type.
5876   // Because it is a pointer type, we don't have to worry about any implicit
5877   // casts here.
5878   // FIXME: We don't allow floating point scalars as input.
5879   Expr *FirstArg = TheCall->getArg(0);
5880   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5881   if (FirstArgResult.isInvalid())
5882     return ExprError();
5883   FirstArg = FirstArgResult.get();
5884   TheCall->setArg(0, FirstArg);
5885 
5886   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5887   if (!pointerType) {
5888     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5889         << FirstArg->getType() << FirstArg->getSourceRange();
5890     return ExprError();
5891   }
5892 
5893   QualType ValType = pointerType->getPointeeType();
5894   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5895       !ValType->isBlockPointerType()) {
5896     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5897         << FirstArg->getType() << FirstArg->getSourceRange();
5898     return ExprError();
5899   }
5900 
5901   if (ValType.isConstQualified()) {
5902     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5903         << FirstArg->getType() << FirstArg->getSourceRange();
5904     return ExprError();
5905   }
5906 
5907   switch (ValType.getObjCLifetime()) {
5908   case Qualifiers::OCL_None:
5909   case Qualifiers::OCL_ExplicitNone:
5910     // okay
5911     break;
5912 
5913   case Qualifiers::OCL_Weak:
5914   case Qualifiers::OCL_Strong:
5915   case Qualifiers::OCL_Autoreleasing:
5916     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5917         << ValType << FirstArg->getSourceRange();
5918     return ExprError();
5919   }
5920 
5921   // Strip any qualifiers off ValType.
5922   ValType = ValType.getUnqualifiedType();
5923 
5924   // The majority of builtins return a value, but a few have special return
5925   // types, so allow them to override appropriately below.
5926   QualType ResultType = ValType;
5927 
5928   // We need to figure out which concrete builtin this maps onto.  For example,
5929   // __sync_fetch_and_add with a 2 byte object turns into
5930   // __sync_fetch_and_add_2.
5931 #define BUILTIN_ROW(x) \
5932   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5933     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5934 
5935   static const unsigned BuiltinIndices[][5] = {
5936     BUILTIN_ROW(__sync_fetch_and_add),
5937     BUILTIN_ROW(__sync_fetch_and_sub),
5938     BUILTIN_ROW(__sync_fetch_and_or),
5939     BUILTIN_ROW(__sync_fetch_and_and),
5940     BUILTIN_ROW(__sync_fetch_and_xor),
5941     BUILTIN_ROW(__sync_fetch_and_nand),
5942 
5943     BUILTIN_ROW(__sync_add_and_fetch),
5944     BUILTIN_ROW(__sync_sub_and_fetch),
5945     BUILTIN_ROW(__sync_and_and_fetch),
5946     BUILTIN_ROW(__sync_or_and_fetch),
5947     BUILTIN_ROW(__sync_xor_and_fetch),
5948     BUILTIN_ROW(__sync_nand_and_fetch),
5949 
5950     BUILTIN_ROW(__sync_val_compare_and_swap),
5951     BUILTIN_ROW(__sync_bool_compare_and_swap),
5952     BUILTIN_ROW(__sync_lock_test_and_set),
5953     BUILTIN_ROW(__sync_lock_release),
5954     BUILTIN_ROW(__sync_swap)
5955   };
5956 #undef BUILTIN_ROW
5957 
5958   // Determine the index of the size.
5959   unsigned SizeIndex;
5960   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5961   case 1: SizeIndex = 0; break;
5962   case 2: SizeIndex = 1; break;
5963   case 4: SizeIndex = 2; break;
5964   case 8: SizeIndex = 3; break;
5965   case 16: SizeIndex = 4; break;
5966   default:
5967     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5968         << FirstArg->getType() << FirstArg->getSourceRange();
5969     return ExprError();
5970   }
5971 
5972   // Each of these builtins has one pointer argument, followed by some number of
5973   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5974   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5975   // as the number of fixed args.
5976   unsigned BuiltinID = FDecl->getBuiltinID();
5977   unsigned BuiltinIndex, NumFixed = 1;
5978   bool WarnAboutSemanticsChange = false;
5979   switch (BuiltinID) {
5980   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5981   case Builtin::BI__sync_fetch_and_add:
5982   case Builtin::BI__sync_fetch_and_add_1:
5983   case Builtin::BI__sync_fetch_and_add_2:
5984   case Builtin::BI__sync_fetch_and_add_4:
5985   case Builtin::BI__sync_fetch_and_add_8:
5986   case Builtin::BI__sync_fetch_and_add_16:
5987     BuiltinIndex = 0;
5988     break;
5989 
5990   case Builtin::BI__sync_fetch_and_sub:
5991   case Builtin::BI__sync_fetch_and_sub_1:
5992   case Builtin::BI__sync_fetch_and_sub_2:
5993   case Builtin::BI__sync_fetch_and_sub_4:
5994   case Builtin::BI__sync_fetch_and_sub_8:
5995   case Builtin::BI__sync_fetch_and_sub_16:
5996     BuiltinIndex = 1;
5997     break;
5998 
5999   case Builtin::BI__sync_fetch_and_or:
6000   case Builtin::BI__sync_fetch_and_or_1:
6001   case Builtin::BI__sync_fetch_and_or_2:
6002   case Builtin::BI__sync_fetch_and_or_4:
6003   case Builtin::BI__sync_fetch_and_or_8:
6004   case Builtin::BI__sync_fetch_and_or_16:
6005     BuiltinIndex = 2;
6006     break;
6007 
6008   case Builtin::BI__sync_fetch_and_and:
6009   case Builtin::BI__sync_fetch_and_and_1:
6010   case Builtin::BI__sync_fetch_and_and_2:
6011   case Builtin::BI__sync_fetch_and_and_4:
6012   case Builtin::BI__sync_fetch_and_and_8:
6013   case Builtin::BI__sync_fetch_and_and_16:
6014     BuiltinIndex = 3;
6015     break;
6016 
6017   case Builtin::BI__sync_fetch_and_xor:
6018   case Builtin::BI__sync_fetch_and_xor_1:
6019   case Builtin::BI__sync_fetch_and_xor_2:
6020   case Builtin::BI__sync_fetch_and_xor_4:
6021   case Builtin::BI__sync_fetch_and_xor_8:
6022   case Builtin::BI__sync_fetch_and_xor_16:
6023     BuiltinIndex = 4;
6024     break;
6025 
6026   case Builtin::BI__sync_fetch_and_nand:
6027   case Builtin::BI__sync_fetch_and_nand_1:
6028   case Builtin::BI__sync_fetch_and_nand_2:
6029   case Builtin::BI__sync_fetch_and_nand_4:
6030   case Builtin::BI__sync_fetch_and_nand_8:
6031   case Builtin::BI__sync_fetch_and_nand_16:
6032     BuiltinIndex = 5;
6033     WarnAboutSemanticsChange = true;
6034     break;
6035 
6036   case Builtin::BI__sync_add_and_fetch:
6037   case Builtin::BI__sync_add_and_fetch_1:
6038   case Builtin::BI__sync_add_and_fetch_2:
6039   case Builtin::BI__sync_add_and_fetch_4:
6040   case Builtin::BI__sync_add_and_fetch_8:
6041   case Builtin::BI__sync_add_and_fetch_16:
6042     BuiltinIndex = 6;
6043     break;
6044 
6045   case Builtin::BI__sync_sub_and_fetch:
6046   case Builtin::BI__sync_sub_and_fetch_1:
6047   case Builtin::BI__sync_sub_and_fetch_2:
6048   case Builtin::BI__sync_sub_and_fetch_4:
6049   case Builtin::BI__sync_sub_and_fetch_8:
6050   case Builtin::BI__sync_sub_and_fetch_16:
6051     BuiltinIndex = 7;
6052     break;
6053 
6054   case Builtin::BI__sync_and_and_fetch:
6055   case Builtin::BI__sync_and_and_fetch_1:
6056   case Builtin::BI__sync_and_and_fetch_2:
6057   case Builtin::BI__sync_and_and_fetch_4:
6058   case Builtin::BI__sync_and_and_fetch_8:
6059   case Builtin::BI__sync_and_and_fetch_16:
6060     BuiltinIndex = 8;
6061     break;
6062 
6063   case Builtin::BI__sync_or_and_fetch:
6064   case Builtin::BI__sync_or_and_fetch_1:
6065   case Builtin::BI__sync_or_and_fetch_2:
6066   case Builtin::BI__sync_or_and_fetch_4:
6067   case Builtin::BI__sync_or_and_fetch_8:
6068   case Builtin::BI__sync_or_and_fetch_16:
6069     BuiltinIndex = 9;
6070     break;
6071 
6072   case Builtin::BI__sync_xor_and_fetch:
6073   case Builtin::BI__sync_xor_and_fetch_1:
6074   case Builtin::BI__sync_xor_and_fetch_2:
6075   case Builtin::BI__sync_xor_and_fetch_4:
6076   case Builtin::BI__sync_xor_and_fetch_8:
6077   case Builtin::BI__sync_xor_and_fetch_16:
6078     BuiltinIndex = 10;
6079     break;
6080 
6081   case Builtin::BI__sync_nand_and_fetch:
6082   case Builtin::BI__sync_nand_and_fetch_1:
6083   case Builtin::BI__sync_nand_and_fetch_2:
6084   case Builtin::BI__sync_nand_and_fetch_4:
6085   case Builtin::BI__sync_nand_and_fetch_8:
6086   case Builtin::BI__sync_nand_and_fetch_16:
6087     BuiltinIndex = 11;
6088     WarnAboutSemanticsChange = true;
6089     break;
6090 
6091   case Builtin::BI__sync_val_compare_and_swap:
6092   case Builtin::BI__sync_val_compare_and_swap_1:
6093   case Builtin::BI__sync_val_compare_and_swap_2:
6094   case Builtin::BI__sync_val_compare_and_swap_4:
6095   case Builtin::BI__sync_val_compare_and_swap_8:
6096   case Builtin::BI__sync_val_compare_and_swap_16:
6097     BuiltinIndex = 12;
6098     NumFixed = 2;
6099     break;
6100 
6101   case Builtin::BI__sync_bool_compare_and_swap:
6102   case Builtin::BI__sync_bool_compare_and_swap_1:
6103   case Builtin::BI__sync_bool_compare_and_swap_2:
6104   case Builtin::BI__sync_bool_compare_and_swap_4:
6105   case Builtin::BI__sync_bool_compare_and_swap_8:
6106   case Builtin::BI__sync_bool_compare_and_swap_16:
6107     BuiltinIndex = 13;
6108     NumFixed = 2;
6109     ResultType = Context.BoolTy;
6110     break;
6111 
6112   case Builtin::BI__sync_lock_test_and_set:
6113   case Builtin::BI__sync_lock_test_and_set_1:
6114   case Builtin::BI__sync_lock_test_and_set_2:
6115   case Builtin::BI__sync_lock_test_and_set_4:
6116   case Builtin::BI__sync_lock_test_and_set_8:
6117   case Builtin::BI__sync_lock_test_and_set_16:
6118     BuiltinIndex = 14;
6119     break;
6120 
6121   case Builtin::BI__sync_lock_release:
6122   case Builtin::BI__sync_lock_release_1:
6123   case Builtin::BI__sync_lock_release_2:
6124   case Builtin::BI__sync_lock_release_4:
6125   case Builtin::BI__sync_lock_release_8:
6126   case Builtin::BI__sync_lock_release_16:
6127     BuiltinIndex = 15;
6128     NumFixed = 0;
6129     ResultType = Context.VoidTy;
6130     break;
6131 
6132   case Builtin::BI__sync_swap:
6133   case Builtin::BI__sync_swap_1:
6134   case Builtin::BI__sync_swap_2:
6135   case Builtin::BI__sync_swap_4:
6136   case Builtin::BI__sync_swap_8:
6137   case Builtin::BI__sync_swap_16:
6138     BuiltinIndex = 16;
6139     break;
6140   }
6141 
6142   // Now that we know how many fixed arguments we expect, first check that we
6143   // have at least that many.
6144   if (TheCall->getNumArgs() < 1+NumFixed) {
6145     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6146         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6147         << Callee->getSourceRange();
6148     return ExprError();
6149   }
6150 
6151   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6152       << Callee->getSourceRange();
6153 
6154   if (WarnAboutSemanticsChange) {
6155     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6156         << Callee->getSourceRange();
6157   }
6158 
6159   // Get the decl for the concrete builtin from this, we can tell what the
6160   // concrete integer type we should convert to is.
6161   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6162   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6163   FunctionDecl *NewBuiltinDecl;
6164   if (NewBuiltinID == BuiltinID)
6165     NewBuiltinDecl = FDecl;
6166   else {
6167     // Perform builtin lookup to avoid redeclaring it.
6168     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6169     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6170     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6171     assert(Res.getFoundDecl());
6172     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6173     if (!NewBuiltinDecl)
6174       return ExprError();
6175   }
6176 
6177   // The first argument --- the pointer --- has a fixed type; we
6178   // deduce the types of the rest of the arguments accordingly.  Walk
6179   // the remaining arguments, converting them to the deduced value type.
6180   for (unsigned i = 0; i != NumFixed; ++i) {
6181     ExprResult Arg = TheCall->getArg(i+1);
6182 
6183     // GCC does an implicit conversion to the pointer or integer ValType.  This
6184     // can fail in some cases (1i -> int**), check for this error case now.
6185     // Initialize the argument.
6186     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6187                                                    ValType, /*consume*/ false);
6188     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6189     if (Arg.isInvalid())
6190       return ExprError();
6191 
6192     // Okay, we have something that *can* be converted to the right type.  Check
6193     // to see if there is a potentially weird extension going on here.  This can
6194     // happen when you do an atomic operation on something like an char* and
6195     // pass in 42.  The 42 gets converted to char.  This is even more strange
6196     // for things like 45.123 -> char, etc.
6197     // FIXME: Do this check.
6198     TheCall->setArg(i+1, Arg.get());
6199   }
6200 
6201   // Create a new DeclRefExpr to refer to the new decl.
6202   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6203       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6204       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6205       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6206 
6207   // Set the callee in the CallExpr.
6208   // FIXME: This loses syntactic information.
6209   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6210   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6211                                               CK_BuiltinFnToFnPtr);
6212   TheCall->setCallee(PromotedCall.get());
6213 
6214   // Change the result type of the call to match the original value type. This
6215   // is arbitrary, but the codegen for these builtins ins design to handle it
6216   // gracefully.
6217   TheCall->setType(ResultType);
6218 
6219   // Prohibit use of _ExtInt with atomic builtins.
6220   // The arguments would have already been converted to the first argument's
6221   // type, so only need to check the first argument.
6222   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
6223   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
6224     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6225     return ExprError();
6226   }
6227 
6228   return TheCallResult;
6229 }
6230 
6231 /// SemaBuiltinNontemporalOverloaded - We have a call to
6232 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6233 /// overloaded function based on the pointer type of its last argument.
6234 ///
6235 /// This function goes through and does final semantic checking for these
6236 /// builtins.
6237 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6238   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6239   DeclRefExpr *DRE =
6240       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6241   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6242   unsigned BuiltinID = FDecl->getBuiltinID();
6243   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6244           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6245          "Unexpected nontemporal load/store builtin!");
6246   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6247   unsigned numArgs = isStore ? 2 : 1;
6248 
6249   // Ensure that we have the proper number of arguments.
6250   if (checkArgCount(*this, TheCall, numArgs))
6251     return ExprError();
6252 
6253   // Inspect the last argument of the nontemporal builtin.  This should always
6254   // be a pointer type, from which we imply the type of the memory access.
6255   // Because it is a pointer type, we don't have to worry about any implicit
6256   // casts here.
6257   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6258   ExprResult PointerArgResult =
6259       DefaultFunctionArrayLvalueConversion(PointerArg);
6260 
6261   if (PointerArgResult.isInvalid())
6262     return ExprError();
6263   PointerArg = PointerArgResult.get();
6264   TheCall->setArg(numArgs - 1, PointerArg);
6265 
6266   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6267   if (!pointerType) {
6268     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6269         << PointerArg->getType() << PointerArg->getSourceRange();
6270     return ExprError();
6271   }
6272 
6273   QualType ValType = pointerType->getPointeeType();
6274 
6275   // Strip any qualifiers off ValType.
6276   ValType = ValType.getUnqualifiedType();
6277   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6278       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6279       !ValType->isVectorType()) {
6280     Diag(DRE->getBeginLoc(),
6281          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6282         << PointerArg->getType() << PointerArg->getSourceRange();
6283     return ExprError();
6284   }
6285 
6286   if (!isStore) {
6287     TheCall->setType(ValType);
6288     return TheCallResult;
6289   }
6290 
6291   ExprResult ValArg = TheCall->getArg(0);
6292   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6293       Context, ValType, /*consume*/ false);
6294   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6295   if (ValArg.isInvalid())
6296     return ExprError();
6297 
6298   TheCall->setArg(0, ValArg.get());
6299   TheCall->setType(Context.VoidTy);
6300   return TheCallResult;
6301 }
6302 
6303 /// CheckObjCString - Checks that the argument to the builtin
6304 /// CFString constructor is correct
6305 /// Note: It might also make sense to do the UTF-16 conversion here (would
6306 /// simplify the backend).
6307 bool Sema::CheckObjCString(Expr *Arg) {
6308   Arg = Arg->IgnoreParenCasts();
6309   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6310 
6311   if (!Literal || !Literal->isAscii()) {
6312     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6313         << Arg->getSourceRange();
6314     return true;
6315   }
6316 
6317   if (Literal->containsNonAsciiOrNull()) {
6318     StringRef String = Literal->getString();
6319     unsigned NumBytes = String.size();
6320     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6321     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6322     llvm::UTF16 *ToPtr = &ToBuf[0];
6323 
6324     llvm::ConversionResult Result =
6325         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6326                                  ToPtr + NumBytes, llvm::strictConversion);
6327     // Check for conversion failure.
6328     if (Result != llvm::conversionOK)
6329       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6330           << Arg->getSourceRange();
6331   }
6332   return false;
6333 }
6334 
6335 /// CheckObjCString - Checks that the format string argument to the os_log()
6336 /// and os_trace() functions is correct, and converts it to const char *.
6337 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6338   Arg = Arg->IgnoreParenCasts();
6339   auto *Literal = dyn_cast<StringLiteral>(Arg);
6340   if (!Literal) {
6341     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6342       Literal = ObjcLiteral->getString();
6343     }
6344   }
6345 
6346   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6347     return ExprError(
6348         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6349         << Arg->getSourceRange());
6350   }
6351 
6352   ExprResult Result(Literal);
6353   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6354   InitializedEntity Entity =
6355       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6356   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6357   return Result;
6358 }
6359 
6360 /// Check that the user is calling the appropriate va_start builtin for the
6361 /// target and calling convention.
6362 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6363   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6364   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6365   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6366                     TT.getArch() == llvm::Triple::aarch64_32);
6367   bool IsWindows = TT.isOSWindows();
6368   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6369   if (IsX64 || IsAArch64) {
6370     CallingConv CC = CC_C;
6371     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6372       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6373     if (IsMSVAStart) {
6374       // Don't allow this in System V ABI functions.
6375       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6376         return S.Diag(Fn->getBeginLoc(),
6377                       diag::err_ms_va_start_used_in_sysv_function);
6378     } else {
6379       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6380       // On x64 Windows, don't allow this in System V ABI functions.
6381       // (Yes, that means there's no corresponding way to support variadic
6382       // System V ABI functions on Windows.)
6383       if ((IsWindows && CC == CC_X86_64SysV) ||
6384           (!IsWindows && CC == CC_Win64))
6385         return S.Diag(Fn->getBeginLoc(),
6386                       diag::err_va_start_used_in_wrong_abi_function)
6387                << !IsWindows;
6388     }
6389     return false;
6390   }
6391 
6392   if (IsMSVAStart)
6393     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6394   return false;
6395 }
6396 
6397 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6398                                              ParmVarDecl **LastParam = nullptr) {
6399   // Determine whether the current function, block, or obj-c method is variadic
6400   // and get its parameter list.
6401   bool IsVariadic = false;
6402   ArrayRef<ParmVarDecl *> Params;
6403   DeclContext *Caller = S.CurContext;
6404   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6405     IsVariadic = Block->isVariadic();
6406     Params = Block->parameters();
6407   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6408     IsVariadic = FD->isVariadic();
6409     Params = FD->parameters();
6410   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6411     IsVariadic = MD->isVariadic();
6412     // FIXME: This isn't correct for methods (results in bogus warning).
6413     Params = MD->parameters();
6414   } else if (isa<CapturedDecl>(Caller)) {
6415     // We don't support va_start in a CapturedDecl.
6416     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6417     return true;
6418   } else {
6419     // This must be some other declcontext that parses exprs.
6420     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6421     return true;
6422   }
6423 
6424   if (!IsVariadic) {
6425     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6426     return true;
6427   }
6428 
6429   if (LastParam)
6430     *LastParam = Params.empty() ? nullptr : Params.back();
6431 
6432   return false;
6433 }
6434 
6435 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6436 /// for validity.  Emit an error and return true on failure; return false
6437 /// on success.
6438 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6439   Expr *Fn = TheCall->getCallee();
6440 
6441   if (checkVAStartABI(*this, BuiltinID, Fn))
6442     return true;
6443 
6444   if (checkArgCount(*this, TheCall, 2))
6445     return true;
6446 
6447   // Type-check the first argument normally.
6448   if (checkBuiltinArgument(*this, TheCall, 0))
6449     return true;
6450 
6451   // Check that the current function is variadic, and get its last parameter.
6452   ParmVarDecl *LastParam;
6453   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6454     return true;
6455 
6456   // Verify that the second argument to the builtin is the last argument of the
6457   // current function or method.
6458   bool SecondArgIsLastNamedArgument = false;
6459   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6460 
6461   // These are valid if SecondArgIsLastNamedArgument is false after the next
6462   // block.
6463   QualType Type;
6464   SourceLocation ParamLoc;
6465   bool IsCRegister = false;
6466 
6467   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6468     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6469       SecondArgIsLastNamedArgument = PV == LastParam;
6470 
6471       Type = PV->getType();
6472       ParamLoc = PV->getLocation();
6473       IsCRegister =
6474           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6475     }
6476   }
6477 
6478   if (!SecondArgIsLastNamedArgument)
6479     Diag(TheCall->getArg(1)->getBeginLoc(),
6480          diag::warn_second_arg_of_va_start_not_last_named_param);
6481   else if (IsCRegister || Type->isReferenceType() ||
6482            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6483              // Promotable integers are UB, but enumerations need a bit of
6484              // extra checking to see what their promotable type actually is.
6485              if (!Type->isPromotableIntegerType())
6486                return false;
6487              if (!Type->isEnumeralType())
6488                return true;
6489              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6490              return !(ED &&
6491                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6492            }()) {
6493     unsigned Reason = 0;
6494     if (Type->isReferenceType())  Reason = 1;
6495     else if (IsCRegister)         Reason = 2;
6496     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6497     Diag(ParamLoc, diag::note_parameter_type) << Type;
6498   }
6499 
6500   TheCall->setType(Context.VoidTy);
6501   return false;
6502 }
6503 
6504 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6505   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6506     const LangOptions &LO = getLangOpts();
6507 
6508     if (LO.CPlusPlus)
6509       return Arg->getType()
6510                  .getCanonicalType()
6511                  .getTypePtr()
6512                  ->getPointeeType()
6513                  .withoutLocalFastQualifiers() == Context.CharTy;
6514 
6515     // In C, allow aliasing through `char *`, this is required for AArch64 at
6516     // least.
6517     return true;
6518   };
6519 
6520   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6521   //                 const char *named_addr);
6522 
6523   Expr *Func = Call->getCallee();
6524 
6525   if (Call->getNumArgs() < 3)
6526     return Diag(Call->getEndLoc(),
6527                 diag::err_typecheck_call_too_few_args_at_least)
6528            << 0 /*function call*/ << 3 << Call->getNumArgs();
6529 
6530   // Type-check the first argument normally.
6531   if (checkBuiltinArgument(*this, Call, 0))
6532     return true;
6533 
6534   // Check that the current function is variadic.
6535   if (checkVAStartIsInVariadicFunction(*this, Func))
6536     return true;
6537 
6538   // __va_start on Windows does not validate the parameter qualifiers
6539 
6540   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6541   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6542 
6543   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6544   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6545 
6546   const QualType &ConstCharPtrTy =
6547       Context.getPointerType(Context.CharTy.withConst());
6548   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6549     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6550         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6551         << 0                                      /* qualifier difference */
6552         << 3                                      /* parameter mismatch */
6553         << 2 << Arg1->getType() << ConstCharPtrTy;
6554 
6555   const QualType SizeTy = Context.getSizeType();
6556   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6557     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6558         << Arg2->getType() << SizeTy << 1 /* different class */
6559         << 0                              /* qualifier difference */
6560         << 3                              /* parameter mismatch */
6561         << 3 << Arg2->getType() << SizeTy;
6562 
6563   return false;
6564 }
6565 
6566 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6567 /// friends.  This is declared to take (...), so we have to check everything.
6568 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6569   if (checkArgCount(*this, TheCall, 2))
6570     return true;
6571 
6572   ExprResult OrigArg0 = TheCall->getArg(0);
6573   ExprResult OrigArg1 = TheCall->getArg(1);
6574 
6575   // Do standard promotions between the two arguments, returning their common
6576   // type.
6577   QualType Res = UsualArithmeticConversions(
6578       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6579   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6580     return true;
6581 
6582   // Make sure any conversions are pushed back into the call; this is
6583   // type safe since unordered compare builtins are declared as "_Bool
6584   // foo(...)".
6585   TheCall->setArg(0, OrigArg0.get());
6586   TheCall->setArg(1, OrigArg1.get());
6587 
6588   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6589     return false;
6590 
6591   // If the common type isn't a real floating type, then the arguments were
6592   // invalid for this operation.
6593   if (Res.isNull() || !Res->isRealFloatingType())
6594     return Diag(OrigArg0.get()->getBeginLoc(),
6595                 diag::err_typecheck_call_invalid_ordered_compare)
6596            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6597            << SourceRange(OrigArg0.get()->getBeginLoc(),
6598                           OrigArg1.get()->getEndLoc());
6599 
6600   return false;
6601 }
6602 
6603 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6604 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6605 /// to check everything. We expect the last argument to be a floating point
6606 /// value.
6607 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6608   if (checkArgCount(*this, TheCall, NumArgs))
6609     return true;
6610 
6611   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6612   // on all preceding parameters just being int.  Try all of those.
6613   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6614     Expr *Arg = TheCall->getArg(i);
6615 
6616     if (Arg->isTypeDependent())
6617       return false;
6618 
6619     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6620 
6621     if (Res.isInvalid())
6622       return true;
6623     TheCall->setArg(i, Res.get());
6624   }
6625 
6626   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6627 
6628   if (OrigArg->isTypeDependent())
6629     return false;
6630 
6631   // Usual Unary Conversions will convert half to float, which we want for
6632   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6633   // type how it is, but do normal L->Rvalue conversions.
6634   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6635     OrigArg = UsualUnaryConversions(OrigArg).get();
6636   else
6637     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6638   TheCall->setArg(NumArgs - 1, OrigArg);
6639 
6640   // This operation requires a non-_Complex floating-point number.
6641   if (!OrigArg->getType()->isRealFloatingType())
6642     return Diag(OrigArg->getBeginLoc(),
6643                 diag::err_typecheck_call_invalid_unary_fp)
6644            << OrigArg->getType() << OrigArg->getSourceRange();
6645 
6646   return false;
6647 }
6648 
6649 /// Perform semantic analysis for a call to __builtin_complex.
6650 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6651   if (checkArgCount(*this, TheCall, 2))
6652     return true;
6653 
6654   bool Dependent = false;
6655   for (unsigned I = 0; I != 2; ++I) {
6656     Expr *Arg = TheCall->getArg(I);
6657     QualType T = Arg->getType();
6658     if (T->isDependentType()) {
6659       Dependent = true;
6660       continue;
6661     }
6662 
6663     // Despite supporting _Complex int, GCC requires a real floating point type
6664     // for the operands of __builtin_complex.
6665     if (!T->isRealFloatingType()) {
6666       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6667              << Arg->getType() << Arg->getSourceRange();
6668     }
6669 
6670     ExprResult Converted = DefaultLvalueConversion(Arg);
6671     if (Converted.isInvalid())
6672       return true;
6673     TheCall->setArg(I, Converted.get());
6674   }
6675 
6676   if (Dependent) {
6677     TheCall->setType(Context.DependentTy);
6678     return false;
6679   }
6680 
6681   Expr *Real = TheCall->getArg(0);
6682   Expr *Imag = TheCall->getArg(1);
6683   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6684     return Diag(Real->getBeginLoc(),
6685                 diag::err_typecheck_call_different_arg_types)
6686            << Real->getType() << Imag->getType()
6687            << Real->getSourceRange() << Imag->getSourceRange();
6688   }
6689 
6690   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6691   // don't allow this builtin to form those types either.
6692   // FIXME: Should we allow these types?
6693   if (Real->getType()->isFloat16Type())
6694     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6695            << "_Float16";
6696   if (Real->getType()->isHalfType())
6697     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6698            << "half";
6699 
6700   TheCall->setType(Context.getComplexType(Real->getType()));
6701   return false;
6702 }
6703 
6704 // Customized Sema Checking for VSX builtins that have the following signature:
6705 // vector [...] builtinName(vector [...], vector [...], const int);
6706 // Which takes the same type of vectors (any legal vector type) for the first
6707 // two arguments and takes compile time constant for the third argument.
6708 // Example builtins are :
6709 // vector double vec_xxpermdi(vector double, vector double, int);
6710 // vector short vec_xxsldwi(vector short, vector short, int);
6711 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6712   unsigned ExpectedNumArgs = 3;
6713   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6714     return true;
6715 
6716   // Check the third argument is a compile time constant
6717   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6718     return Diag(TheCall->getBeginLoc(),
6719                 diag::err_vsx_builtin_nonconstant_argument)
6720            << 3 /* argument index */ << TheCall->getDirectCallee()
6721            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6722                           TheCall->getArg(2)->getEndLoc());
6723 
6724   QualType Arg1Ty = TheCall->getArg(0)->getType();
6725   QualType Arg2Ty = TheCall->getArg(1)->getType();
6726 
6727   // Check the type of argument 1 and argument 2 are vectors.
6728   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6729   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6730       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6731     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6732            << TheCall->getDirectCallee()
6733            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6734                           TheCall->getArg(1)->getEndLoc());
6735   }
6736 
6737   // Check the first two arguments are the same type.
6738   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6739     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6740            << TheCall->getDirectCallee()
6741            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6742                           TheCall->getArg(1)->getEndLoc());
6743   }
6744 
6745   // When default clang type checking is turned off and the customized type
6746   // checking is used, the returning type of the function must be explicitly
6747   // set. Otherwise it is _Bool by default.
6748   TheCall->setType(Arg1Ty);
6749 
6750   return false;
6751 }
6752 
6753 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6754 // This is declared to take (...), so we have to check everything.
6755 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6756   if (TheCall->getNumArgs() < 2)
6757     return ExprError(Diag(TheCall->getEndLoc(),
6758                           diag::err_typecheck_call_too_few_args_at_least)
6759                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6760                      << TheCall->getSourceRange());
6761 
6762   // Determine which of the following types of shufflevector we're checking:
6763   // 1) unary, vector mask: (lhs, mask)
6764   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6765   QualType resType = TheCall->getArg(0)->getType();
6766   unsigned numElements = 0;
6767 
6768   if (!TheCall->getArg(0)->isTypeDependent() &&
6769       !TheCall->getArg(1)->isTypeDependent()) {
6770     QualType LHSType = TheCall->getArg(0)->getType();
6771     QualType RHSType = TheCall->getArg(1)->getType();
6772 
6773     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6774       return ExprError(
6775           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6776           << TheCall->getDirectCallee()
6777           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6778                          TheCall->getArg(1)->getEndLoc()));
6779 
6780     numElements = LHSType->castAs<VectorType>()->getNumElements();
6781     unsigned numResElements = TheCall->getNumArgs() - 2;
6782 
6783     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6784     // with mask.  If so, verify that RHS is an integer vector type with the
6785     // same number of elts as lhs.
6786     if (TheCall->getNumArgs() == 2) {
6787       if (!RHSType->hasIntegerRepresentation() ||
6788           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6789         return ExprError(Diag(TheCall->getBeginLoc(),
6790                               diag::err_vec_builtin_incompatible_vector)
6791                          << TheCall->getDirectCallee()
6792                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6793                                         TheCall->getArg(1)->getEndLoc()));
6794     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6795       return ExprError(Diag(TheCall->getBeginLoc(),
6796                             diag::err_vec_builtin_incompatible_vector)
6797                        << TheCall->getDirectCallee()
6798                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6799                                       TheCall->getArg(1)->getEndLoc()));
6800     } else if (numElements != numResElements) {
6801       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6802       resType = Context.getVectorType(eltType, numResElements,
6803                                       VectorType::GenericVector);
6804     }
6805   }
6806 
6807   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6808     if (TheCall->getArg(i)->isTypeDependent() ||
6809         TheCall->getArg(i)->isValueDependent())
6810       continue;
6811 
6812     Optional<llvm::APSInt> Result;
6813     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6814       return ExprError(Diag(TheCall->getBeginLoc(),
6815                             diag::err_shufflevector_nonconstant_argument)
6816                        << TheCall->getArg(i)->getSourceRange());
6817 
6818     // Allow -1 which will be translated to undef in the IR.
6819     if (Result->isSigned() && Result->isAllOnes())
6820       continue;
6821 
6822     if (Result->getActiveBits() > 64 ||
6823         Result->getZExtValue() >= numElements * 2)
6824       return ExprError(Diag(TheCall->getBeginLoc(),
6825                             diag::err_shufflevector_argument_too_large)
6826                        << TheCall->getArg(i)->getSourceRange());
6827   }
6828 
6829   SmallVector<Expr*, 32> exprs;
6830 
6831   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6832     exprs.push_back(TheCall->getArg(i));
6833     TheCall->setArg(i, nullptr);
6834   }
6835 
6836   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6837                                          TheCall->getCallee()->getBeginLoc(),
6838                                          TheCall->getRParenLoc());
6839 }
6840 
6841 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6842 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6843                                        SourceLocation BuiltinLoc,
6844                                        SourceLocation RParenLoc) {
6845   ExprValueKind VK = VK_PRValue;
6846   ExprObjectKind OK = OK_Ordinary;
6847   QualType DstTy = TInfo->getType();
6848   QualType SrcTy = E->getType();
6849 
6850   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6851     return ExprError(Diag(BuiltinLoc,
6852                           diag::err_convertvector_non_vector)
6853                      << E->getSourceRange());
6854   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6855     return ExprError(Diag(BuiltinLoc,
6856                           diag::err_convertvector_non_vector_type));
6857 
6858   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6859     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6860     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6861     if (SrcElts != DstElts)
6862       return ExprError(Diag(BuiltinLoc,
6863                             diag::err_convertvector_incompatible_vector)
6864                        << E->getSourceRange());
6865   }
6866 
6867   return new (Context)
6868       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6869 }
6870 
6871 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6872 // This is declared to take (const void*, ...) and can take two
6873 // optional constant int args.
6874 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6875   unsigned NumArgs = TheCall->getNumArgs();
6876 
6877   if (NumArgs > 3)
6878     return Diag(TheCall->getEndLoc(),
6879                 diag::err_typecheck_call_too_many_args_at_most)
6880            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6881 
6882   // Argument 0 is checked for us and the remaining arguments must be
6883   // constant integers.
6884   for (unsigned i = 1; i != NumArgs; ++i)
6885     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6886       return true;
6887 
6888   return false;
6889 }
6890 
6891 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
6892 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
6893   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6894     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6895            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6896   if (checkArgCount(*this, TheCall, 1))
6897     return true;
6898   Expr *Arg = TheCall->getArg(0);
6899   if (Arg->isInstantiationDependent())
6900     return false;
6901 
6902   QualType ArgTy = Arg->getType();
6903   if (!ArgTy->hasFloatingRepresentation())
6904     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6905            << ArgTy;
6906   if (Arg->isLValue()) {
6907     ExprResult FirstArg = DefaultLvalueConversion(Arg);
6908     TheCall->setArg(0, FirstArg.get());
6909   }
6910   TheCall->setType(TheCall->getArg(0)->getType());
6911   return false;
6912 }
6913 
6914 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6915 // __assume does not evaluate its arguments, and should warn if its argument
6916 // has side effects.
6917 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6918   Expr *Arg = TheCall->getArg(0);
6919   if (Arg->isInstantiationDependent()) return false;
6920 
6921   if (Arg->HasSideEffects(Context))
6922     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6923         << Arg->getSourceRange()
6924         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6925 
6926   return false;
6927 }
6928 
6929 /// Handle __builtin_alloca_with_align. This is declared
6930 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6931 /// than 8.
6932 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6933   // The alignment must be a constant integer.
6934   Expr *Arg = TheCall->getArg(1);
6935 
6936   // We can't check the value of a dependent argument.
6937   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6938     if (const auto *UE =
6939             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6940       if (UE->getKind() == UETT_AlignOf ||
6941           UE->getKind() == UETT_PreferredAlignOf)
6942         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6943             << Arg->getSourceRange();
6944 
6945     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6946 
6947     if (!Result.isPowerOf2())
6948       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6949              << Arg->getSourceRange();
6950 
6951     if (Result < Context.getCharWidth())
6952       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6953              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6954 
6955     if (Result > std::numeric_limits<int32_t>::max())
6956       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6957              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6958   }
6959 
6960   return false;
6961 }
6962 
6963 /// Handle __builtin_assume_aligned. This is declared
6964 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6965 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6966   unsigned NumArgs = TheCall->getNumArgs();
6967 
6968   if (NumArgs > 3)
6969     return Diag(TheCall->getEndLoc(),
6970                 diag::err_typecheck_call_too_many_args_at_most)
6971            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6972 
6973   // The alignment must be a constant integer.
6974   Expr *Arg = TheCall->getArg(1);
6975 
6976   // We can't check the value of a dependent argument.
6977   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6978     llvm::APSInt Result;
6979     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6980       return true;
6981 
6982     if (!Result.isPowerOf2())
6983       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6984              << Arg->getSourceRange();
6985 
6986     if (Result > Sema::MaximumAlignment)
6987       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6988           << Arg->getSourceRange() << Sema::MaximumAlignment;
6989   }
6990 
6991   if (NumArgs > 2) {
6992     ExprResult Arg(TheCall->getArg(2));
6993     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6994       Context.getSizeType(), false);
6995     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6996     if (Arg.isInvalid()) return true;
6997     TheCall->setArg(2, Arg.get());
6998   }
6999 
7000   return false;
7001 }
7002 
7003 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
7004   unsigned BuiltinID =
7005       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
7006   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
7007 
7008   unsigned NumArgs = TheCall->getNumArgs();
7009   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
7010   if (NumArgs < NumRequiredArgs) {
7011     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
7012            << 0 /* function call */ << NumRequiredArgs << NumArgs
7013            << TheCall->getSourceRange();
7014   }
7015   if (NumArgs >= NumRequiredArgs + 0x100) {
7016     return Diag(TheCall->getEndLoc(),
7017                 diag::err_typecheck_call_too_many_args_at_most)
7018            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
7019            << TheCall->getSourceRange();
7020   }
7021   unsigned i = 0;
7022 
7023   // For formatting call, check buffer arg.
7024   if (!IsSizeCall) {
7025     ExprResult Arg(TheCall->getArg(i));
7026     InitializedEntity Entity = InitializedEntity::InitializeParameter(
7027         Context, Context.VoidPtrTy, false);
7028     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7029     if (Arg.isInvalid())
7030       return true;
7031     TheCall->setArg(i, Arg.get());
7032     i++;
7033   }
7034 
7035   // Check string literal arg.
7036   unsigned FormatIdx = i;
7037   {
7038     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
7039     if (Arg.isInvalid())
7040       return true;
7041     TheCall->setArg(i, Arg.get());
7042     i++;
7043   }
7044 
7045   // Make sure variadic args are scalar.
7046   unsigned FirstDataArg = i;
7047   while (i < NumArgs) {
7048     ExprResult Arg = DefaultVariadicArgumentPromotion(
7049         TheCall->getArg(i), VariadicFunction, nullptr);
7050     if (Arg.isInvalid())
7051       return true;
7052     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
7053     if (ArgSize.getQuantity() >= 0x100) {
7054       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
7055              << i << (int)ArgSize.getQuantity() << 0xff
7056              << TheCall->getSourceRange();
7057     }
7058     TheCall->setArg(i, Arg.get());
7059     i++;
7060   }
7061 
7062   // Check formatting specifiers. NOTE: We're only doing this for the non-size
7063   // call to avoid duplicate diagnostics.
7064   if (!IsSizeCall) {
7065     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
7066     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
7067     bool Success = CheckFormatArguments(
7068         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
7069         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
7070         CheckedVarArgs);
7071     if (!Success)
7072       return true;
7073   }
7074 
7075   if (IsSizeCall) {
7076     TheCall->setType(Context.getSizeType());
7077   } else {
7078     TheCall->setType(Context.VoidPtrTy);
7079   }
7080   return false;
7081 }
7082 
7083 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
7084 /// TheCall is a constant expression.
7085 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7086                                   llvm::APSInt &Result) {
7087   Expr *Arg = TheCall->getArg(ArgNum);
7088   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7089   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
7090 
7091   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
7092 
7093   Optional<llvm::APSInt> R;
7094   if (!(R = Arg->getIntegerConstantExpr(Context)))
7095     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7096            << FDecl->getDeclName() << Arg->getSourceRange();
7097   Result = *R;
7098   return false;
7099 }
7100 
7101 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
7102 /// TheCall is a constant expression in the range [Low, High].
7103 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
7104                                        int Low, int High, bool RangeIsError) {
7105   if (isConstantEvaluated())
7106     return false;
7107   llvm::APSInt Result;
7108 
7109   // We can't check the value of a dependent argument.
7110   Expr *Arg = TheCall->getArg(ArgNum);
7111   if (Arg->isTypeDependent() || Arg->isValueDependent())
7112     return false;
7113 
7114   // Check constant-ness first.
7115   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7116     return true;
7117 
7118   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7119     if (RangeIsError)
7120       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7121              << toString(Result, 10) << Low << High << Arg->getSourceRange();
7122     else
7123       // Defer the warning until we know if the code will be emitted so that
7124       // dead code can ignore this.
7125       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7126                           PDiag(diag::warn_argument_invalid_range)
7127                               << toString(Result, 10) << Low << High
7128                               << Arg->getSourceRange());
7129   }
7130 
7131   return false;
7132 }
7133 
7134 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7135 /// TheCall is a constant expression is a multiple of Num..
7136 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7137                                           unsigned Num) {
7138   llvm::APSInt Result;
7139 
7140   // We can't check the value of a dependent argument.
7141   Expr *Arg = TheCall->getArg(ArgNum);
7142   if (Arg->isTypeDependent() || Arg->isValueDependent())
7143     return false;
7144 
7145   // Check constant-ness first.
7146   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7147     return true;
7148 
7149   if (Result.getSExtValue() % Num != 0)
7150     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7151            << Num << Arg->getSourceRange();
7152 
7153   return false;
7154 }
7155 
7156 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7157 /// constant expression representing a power of 2.
7158 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7159   llvm::APSInt Result;
7160 
7161   // We can't check the value of a dependent argument.
7162   Expr *Arg = TheCall->getArg(ArgNum);
7163   if (Arg->isTypeDependent() || Arg->isValueDependent())
7164     return false;
7165 
7166   // Check constant-ness first.
7167   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7168     return true;
7169 
7170   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7171   // and only if x is a power of 2.
7172   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7173     return false;
7174 
7175   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7176          << Arg->getSourceRange();
7177 }
7178 
7179 static bool IsShiftedByte(llvm::APSInt Value) {
7180   if (Value.isNegative())
7181     return false;
7182 
7183   // Check if it's a shifted byte, by shifting it down
7184   while (true) {
7185     // If the value fits in the bottom byte, the check passes.
7186     if (Value < 0x100)
7187       return true;
7188 
7189     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7190     // fails.
7191     if ((Value & 0xFF) != 0)
7192       return false;
7193 
7194     // If the bottom 8 bits are all 0, but something above that is nonzero,
7195     // then shifting the value right by 8 bits won't affect whether it's a
7196     // shifted byte or not. So do that, and go round again.
7197     Value >>= 8;
7198   }
7199 }
7200 
7201 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7202 /// a constant expression representing an arbitrary byte value shifted left by
7203 /// a multiple of 8 bits.
7204 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7205                                              unsigned ArgBits) {
7206   llvm::APSInt Result;
7207 
7208   // We can't check the value of a dependent argument.
7209   Expr *Arg = TheCall->getArg(ArgNum);
7210   if (Arg->isTypeDependent() || Arg->isValueDependent())
7211     return false;
7212 
7213   // Check constant-ness first.
7214   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7215     return true;
7216 
7217   // Truncate to the given size.
7218   Result = Result.getLoBits(ArgBits);
7219   Result.setIsUnsigned(true);
7220 
7221   if (IsShiftedByte(Result))
7222     return false;
7223 
7224   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7225          << Arg->getSourceRange();
7226 }
7227 
7228 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7229 /// TheCall is a constant expression representing either a shifted byte value,
7230 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7231 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7232 /// Arm MVE intrinsics.
7233 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7234                                                    int ArgNum,
7235                                                    unsigned ArgBits) {
7236   llvm::APSInt Result;
7237 
7238   // We can't check the value of a dependent argument.
7239   Expr *Arg = TheCall->getArg(ArgNum);
7240   if (Arg->isTypeDependent() || Arg->isValueDependent())
7241     return false;
7242 
7243   // Check constant-ness first.
7244   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7245     return true;
7246 
7247   // Truncate to the given size.
7248   Result = Result.getLoBits(ArgBits);
7249   Result.setIsUnsigned(true);
7250 
7251   // Check to see if it's in either of the required forms.
7252   if (IsShiftedByte(Result) ||
7253       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7254     return false;
7255 
7256   return Diag(TheCall->getBeginLoc(),
7257               diag::err_argument_not_shifted_byte_or_xxff)
7258          << Arg->getSourceRange();
7259 }
7260 
7261 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7262 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7263   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7264     if (checkArgCount(*this, TheCall, 2))
7265       return true;
7266     Expr *Arg0 = TheCall->getArg(0);
7267     Expr *Arg1 = TheCall->getArg(1);
7268 
7269     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7270     if (FirstArg.isInvalid())
7271       return true;
7272     QualType FirstArgType = FirstArg.get()->getType();
7273     if (!FirstArgType->isAnyPointerType())
7274       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7275                << "first" << FirstArgType << Arg0->getSourceRange();
7276     TheCall->setArg(0, FirstArg.get());
7277 
7278     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7279     if (SecArg.isInvalid())
7280       return true;
7281     QualType SecArgType = SecArg.get()->getType();
7282     if (!SecArgType->isIntegerType())
7283       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7284                << "second" << SecArgType << Arg1->getSourceRange();
7285 
7286     // Derive the return type from the pointer argument.
7287     TheCall->setType(FirstArgType);
7288     return false;
7289   }
7290 
7291   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7292     if (checkArgCount(*this, TheCall, 2))
7293       return true;
7294 
7295     Expr *Arg0 = TheCall->getArg(0);
7296     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7297     if (FirstArg.isInvalid())
7298       return true;
7299     QualType FirstArgType = FirstArg.get()->getType();
7300     if (!FirstArgType->isAnyPointerType())
7301       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7302                << "first" << FirstArgType << Arg0->getSourceRange();
7303     TheCall->setArg(0, FirstArg.get());
7304 
7305     // Derive the return type from the pointer argument.
7306     TheCall->setType(FirstArgType);
7307 
7308     // Second arg must be an constant in range [0,15]
7309     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7310   }
7311 
7312   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7313     if (checkArgCount(*this, TheCall, 2))
7314       return true;
7315     Expr *Arg0 = TheCall->getArg(0);
7316     Expr *Arg1 = TheCall->getArg(1);
7317 
7318     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7319     if (FirstArg.isInvalid())
7320       return true;
7321     QualType FirstArgType = FirstArg.get()->getType();
7322     if (!FirstArgType->isAnyPointerType())
7323       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7324                << "first" << FirstArgType << Arg0->getSourceRange();
7325 
7326     QualType SecArgType = Arg1->getType();
7327     if (!SecArgType->isIntegerType())
7328       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7329                << "second" << SecArgType << Arg1->getSourceRange();
7330     TheCall->setType(Context.IntTy);
7331     return false;
7332   }
7333 
7334   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7335       BuiltinID == AArch64::BI__builtin_arm_stg) {
7336     if (checkArgCount(*this, TheCall, 1))
7337       return true;
7338     Expr *Arg0 = TheCall->getArg(0);
7339     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7340     if (FirstArg.isInvalid())
7341       return true;
7342 
7343     QualType FirstArgType = FirstArg.get()->getType();
7344     if (!FirstArgType->isAnyPointerType())
7345       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7346                << "first" << FirstArgType << Arg0->getSourceRange();
7347     TheCall->setArg(0, FirstArg.get());
7348 
7349     // Derive the return type from the pointer argument.
7350     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7351       TheCall->setType(FirstArgType);
7352     return false;
7353   }
7354 
7355   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7356     Expr *ArgA = TheCall->getArg(0);
7357     Expr *ArgB = TheCall->getArg(1);
7358 
7359     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7360     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7361 
7362     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7363       return true;
7364 
7365     QualType ArgTypeA = ArgExprA.get()->getType();
7366     QualType ArgTypeB = ArgExprB.get()->getType();
7367 
7368     auto isNull = [&] (Expr *E) -> bool {
7369       return E->isNullPointerConstant(
7370                         Context, Expr::NPC_ValueDependentIsNotNull); };
7371 
7372     // argument should be either a pointer or null
7373     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7374       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7375         << "first" << ArgTypeA << ArgA->getSourceRange();
7376 
7377     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7378       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7379         << "second" << ArgTypeB << ArgB->getSourceRange();
7380 
7381     // Ensure Pointee types are compatible
7382     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7383         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7384       QualType pointeeA = ArgTypeA->getPointeeType();
7385       QualType pointeeB = ArgTypeB->getPointeeType();
7386       if (!Context.typesAreCompatible(
7387              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7388              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7389         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7390           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7391           << ArgB->getSourceRange();
7392       }
7393     }
7394 
7395     // at least one argument should be pointer type
7396     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7397       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7398         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7399 
7400     if (isNull(ArgA)) // adopt type of the other pointer
7401       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7402 
7403     if (isNull(ArgB))
7404       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7405 
7406     TheCall->setArg(0, ArgExprA.get());
7407     TheCall->setArg(1, ArgExprB.get());
7408     TheCall->setType(Context.LongLongTy);
7409     return false;
7410   }
7411   assert(false && "Unhandled ARM MTE intrinsic");
7412   return true;
7413 }
7414 
7415 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7416 /// TheCall is an ARM/AArch64 special register string literal.
7417 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7418                                     int ArgNum, unsigned ExpectedFieldNum,
7419                                     bool AllowName) {
7420   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7421                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7422                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7423                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7424                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7425                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7426   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7427                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7428                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7429                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7430                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7431                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7432   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7433 
7434   // We can't check the value of a dependent argument.
7435   Expr *Arg = TheCall->getArg(ArgNum);
7436   if (Arg->isTypeDependent() || Arg->isValueDependent())
7437     return false;
7438 
7439   // Check if the argument is a string literal.
7440   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7441     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7442            << Arg->getSourceRange();
7443 
7444   // Check the type of special register given.
7445   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7446   SmallVector<StringRef, 6> Fields;
7447   Reg.split(Fields, ":");
7448 
7449   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7450     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7451            << Arg->getSourceRange();
7452 
7453   // If the string is the name of a register then we cannot check that it is
7454   // valid here but if the string is of one the forms described in ACLE then we
7455   // can check that the supplied fields are integers and within the valid
7456   // ranges.
7457   if (Fields.size() > 1) {
7458     bool FiveFields = Fields.size() == 5;
7459 
7460     bool ValidString = true;
7461     if (IsARMBuiltin) {
7462       ValidString &= Fields[0].startswith_insensitive("cp") ||
7463                      Fields[0].startswith_insensitive("p");
7464       if (ValidString)
7465         Fields[0] = Fields[0].drop_front(
7466             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7467 
7468       ValidString &= Fields[2].startswith_insensitive("c");
7469       if (ValidString)
7470         Fields[2] = Fields[2].drop_front(1);
7471 
7472       if (FiveFields) {
7473         ValidString &= Fields[3].startswith_insensitive("c");
7474         if (ValidString)
7475           Fields[3] = Fields[3].drop_front(1);
7476       }
7477     }
7478 
7479     SmallVector<int, 5> Ranges;
7480     if (FiveFields)
7481       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7482     else
7483       Ranges.append({15, 7, 15});
7484 
7485     for (unsigned i=0; i<Fields.size(); ++i) {
7486       int IntField;
7487       ValidString &= !Fields[i].getAsInteger(10, IntField);
7488       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7489     }
7490 
7491     if (!ValidString)
7492       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7493              << Arg->getSourceRange();
7494   } else if (IsAArch64Builtin && Fields.size() == 1) {
7495     // If the register name is one of those that appear in the condition below
7496     // and the special register builtin being used is one of the write builtins,
7497     // then we require that the argument provided for writing to the register
7498     // is an integer constant expression. This is because it will be lowered to
7499     // an MSR (immediate) instruction, so we need to know the immediate at
7500     // compile time.
7501     if (TheCall->getNumArgs() != 2)
7502       return false;
7503 
7504     std::string RegLower = Reg.lower();
7505     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7506         RegLower != "pan" && RegLower != "uao")
7507       return false;
7508 
7509     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7510   }
7511 
7512   return false;
7513 }
7514 
7515 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7516 /// Emit an error and return true on failure; return false on success.
7517 /// TypeStr is a string containing the type descriptor of the value returned by
7518 /// the builtin and the descriptors of the expected type of the arguments.
7519 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
7520                                  const char *TypeStr) {
7521 
7522   assert((TypeStr[0] != '\0') &&
7523          "Invalid types in PPC MMA builtin declaration");
7524 
7525   switch (BuiltinID) {
7526   default:
7527     // This function is called in CheckPPCBuiltinFunctionCall where the
7528     // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
7529     // we are isolating the pair vector memop builtins that can be used with mma
7530     // off so the default case is every builtin that requires mma and paired
7531     // vector memops.
7532     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7533                          diag::err_ppc_builtin_only_on_arch, "10") ||
7534         SemaFeatureCheck(*this, TheCall, "mma",
7535                          diag::err_ppc_builtin_only_on_arch, "10"))
7536       return true;
7537     break;
7538   case PPC::BI__builtin_vsx_lxvp:
7539   case PPC::BI__builtin_vsx_stxvp:
7540   case PPC::BI__builtin_vsx_assemble_pair:
7541   case PPC::BI__builtin_vsx_disassemble_pair:
7542     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7543                          diag::err_ppc_builtin_only_on_arch, "10"))
7544       return true;
7545     break;
7546   }
7547 
7548   unsigned Mask = 0;
7549   unsigned ArgNum = 0;
7550 
7551   // The first type in TypeStr is the type of the value returned by the
7552   // builtin. So we first read that type and change the type of TheCall.
7553   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7554   TheCall->setType(type);
7555 
7556   while (*TypeStr != '\0') {
7557     Mask = 0;
7558     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7559     if (ArgNum >= TheCall->getNumArgs()) {
7560       ArgNum++;
7561       break;
7562     }
7563 
7564     Expr *Arg = TheCall->getArg(ArgNum);
7565     QualType PassedType = Arg->getType();
7566     QualType StrippedRVType = PassedType.getCanonicalType();
7567 
7568     // Strip Restrict/Volatile qualifiers.
7569     if (StrippedRVType.isRestrictQualified() ||
7570         StrippedRVType.isVolatileQualified())
7571       StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
7572 
7573     // The only case where the argument type and expected type are allowed to
7574     // mismatch is if the argument type is a non-void pointer (or array) and
7575     // expected type is a void pointer.
7576     if (StrippedRVType != ExpectedType)
7577       if (!(ExpectedType->isVoidPointerType() &&
7578             (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
7579         return Diag(Arg->getBeginLoc(),
7580                     diag::err_typecheck_convert_incompatible)
7581                << PassedType << ExpectedType << 1 << 0 << 0;
7582 
7583     // If the value of the Mask is not 0, we have a constraint in the size of
7584     // the integer argument so here we ensure the argument is a constant that
7585     // is in the valid range.
7586     if (Mask != 0 &&
7587         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7588       return true;
7589 
7590     ArgNum++;
7591   }
7592 
7593   // In case we exited early from the previous loop, there are other types to
7594   // read from TypeStr. So we need to read them all to ensure we have the right
7595   // number of arguments in TheCall and if it is not the case, to display a
7596   // better error message.
7597   while (*TypeStr != '\0') {
7598     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7599     ArgNum++;
7600   }
7601   if (checkArgCount(*this, TheCall, ArgNum))
7602     return true;
7603 
7604   return false;
7605 }
7606 
7607 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7608 /// This checks that the target supports __builtin_longjmp and
7609 /// that val is a constant 1.
7610 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7611   if (!Context.getTargetInfo().hasSjLjLowering())
7612     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7613            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7614 
7615   Expr *Arg = TheCall->getArg(1);
7616   llvm::APSInt Result;
7617 
7618   // TODO: This is less than ideal. Overload this to take a value.
7619   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7620     return true;
7621 
7622   if (Result != 1)
7623     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7624            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7625 
7626   return false;
7627 }
7628 
7629 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7630 /// This checks that the target supports __builtin_setjmp.
7631 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7632   if (!Context.getTargetInfo().hasSjLjLowering())
7633     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7634            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7635   return false;
7636 }
7637 
7638 namespace {
7639 
7640 class UncoveredArgHandler {
7641   enum { Unknown = -1, AllCovered = -2 };
7642 
7643   signed FirstUncoveredArg = Unknown;
7644   SmallVector<const Expr *, 4> DiagnosticExprs;
7645 
7646 public:
7647   UncoveredArgHandler() = default;
7648 
7649   bool hasUncoveredArg() const {
7650     return (FirstUncoveredArg >= 0);
7651   }
7652 
7653   unsigned getUncoveredArg() const {
7654     assert(hasUncoveredArg() && "no uncovered argument");
7655     return FirstUncoveredArg;
7656   }
7657 
7658   void setAllCovered() {
7659     // A string has been found with all arguments covered, so clear out
7660     // the diagnostics.
7661     DiagnosticExprs.clear();
7662     FirstUncoveredArg = AllCovered;
7663   }
7664 
7665   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7666     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7667 
7668     // Don't update if a previous string covers all arguments.
7669     if (FirstUncoveredArg == AllCovered)
7670       return;
7671 
7672     // UncoveredArgHandler tracks the highest uncovered argument index
7673     // and with it all the strings that match this index.
7674     if (NewFirstUncoveredArg == FirstUncoveredArg)
7675       DiagnosticExprs.push_back(StrExpr);
7676     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7677       DiagnosticExprs.clear();
7678       DiagnosticExprs.push_back(StrExpr);
7679       FirstUncoveredArg = NewFirstUncoveredArg;
7680     }
7681   }
7682 
7683   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7684 };
7685 
7686 enum StringLiteralCheckType {
7687   SLCT_NotALiteral,
7688   SLCT_UncheckedLiteral,
7689   SLCT_CheckedLiteral
7690 };
7691 
7692 } // namespace
7693 
7694 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7695                                      BinaryOperatorKind BinOpKind,
7696                                      bool AddendIsRight) {
7697   unsigned BitWidth = Offset.getBitWidth();
7698   unsigned AddendBitWidth = Addend.getBitWidth();
7699   // There might be negative interim results.
7700   if (Addend.isUnsigned()) {
7701     Addend = Addend.zext(++AddendBitWidth);
7702     Addend.setIsSigned(true);
7703   }
7704   // Adjust the bit width of the APSInts.
7705   if (AddendBitWidth > BitWidth) {
7706     Offset = Offset.sext(AddendBitWidth);
7707     BitWidth = AddendBitWidth;
7708   } else if (BitWidth > AddendBitWidth) {
7709     Addend = Addend.sext(BitWidth);
7710   }
7711 
7712   bool Ov = false;
7713   llvm::APSInt ResOffset = Offset;
7714   if (BinOpKind == BO_Add)
7715     ResOffset = Offset.sadd_ov(Addend, Ov);
7716   else {
7717     assert(AddendIsRight && BinOpKind == BO_Sub &&
7718            "operator must be add or sub with addend on the right");
7719     ResOffset = Offset.ssub_ov(Addend, Ov);
7720   }
7721 
7722   // We add an offset to a pointer here so we should support an offset as big as
7723   // possible.
7724   if (Ov) {
7725     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7726            "index (intermediate) result too big");
7727     Offset = Offset.sext(2 * BitWidth);
7728     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7729     return;
7730   }
7731 
7732   Offset = ResOffset;
7733 }
7734 
7735 namespace {
7736 
7737 // This is a wrapper class around StringLiteral to support offsetted string
7738 // literals as format strings. It takes the offset into account when returning
7739 // the string and its length or the source locations to display notes correctly.
7740 class FormatStringLiteral {
7741   const StringLiteral *FExpr;
7742   int64_t Offset;
7743 
7744  public:
7745   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7746       : FExpr(fexpr), Offset(Offset) {}
7747 
7748   StringRef getString() const {
7749     return FExpr->getString().drop_front(Offset);
7750   }
7751 
7752   unsigned getByteLength() const {
7753     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7754   }
7755 
7756   unsigned getLength() const { return FExpr->getLength() - Offset; }
7757   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7758 
7759   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7760 
7761   QualType getType() const { return FExpr->getType(); }
7762 
7763   bool isAscii() const { return FExpr->isAscii(); }
7764   bool isWide() const { return FExpr->isWide(); }
7765   bool isUTF8() const { return FExpr->isUTF8(); }
7766   bool isUTF16() const { return FExpr->isUTF16(); }
7767   bool isUTF32() const { return FExpr->isUTF32(); }
7768   bool isPascal() const { return FExpr->isPascal(); }
7769 
7770   SourceLocation getLocationOfByte(
7771       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7772       const TargetInfo &Target, unsigned *StartToken = nullptr,
7773       unsigned *StartTokenByteOffset = nullptr) const {
7774     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7775                                     StartToken, StartTokenByteOffset);
7776   }
7777 
7778   SourceLocation getBeginLoc() const LLVM_READONLY {
7779     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7780   }
7781 
7782   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7783 };
7784 
7785 }  // namespace
7786 
7787 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7788                               const Expr *OrigFormatExpr,
7789                               ArrayRef<const Expr *> Args,
7790                               bool HasVAListArg, unsigned format_idx,
7791                               unsigned firstDataArg,
7792                               Sema::FormatStringType Type,
7793                               bool inFunctionCall,
7794                               Sema::VariadicCallType CallType,
7795                               llvm::SmallBitVector &CheckedVarArgs,
7796                               UncoveredArgHandler &UncoveredArg,
7797                               bool IgnoreStringsWithoutSpecifiers);
7798 
7799 // Determine if an expression is a string literal or constant string.
7800 // If this function returns false on the arguments to a function expecting a
7801 // format string, we will usually need to emit a warning.
7802 // True string literals are then checked by CheckFormatString.
7803 static StringLiteralCheckType
7804 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7805                       bool HasVAListArg, unsigned format_idx,
7806                       unsigned firstDataArg, Sema::FormatStringType Type,
7807                       Sema::VariadicCallType CallType, bool InFunctionCall,
7808                       llvm::SmallBitVector &CheckedVarArgs,
7809                       UncoveredArgHandler &UncoveredArg,
7810                       llvm::APSInt Offset,
7811                       bool IgnoreStringsWithoutSpecifiers = false) {
7812   if (S.isConstantEvaluated())
7813     return SLCT_NotALiteral;
7814  tryAgain:
7815   assert(Offset.isSigned() && "invalid offset");
7816 
7817   if (E->isTypeDependent() || E->isValueDependent())
7818     return SLCT_NotALiteral;
7819 
7820   E = E->IgnoreParenCasts();
7821 
7822   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7823     // Technically -Wformat-nonliteral does not warn about this case.
7824     // The behavior of printf and friends in this case is implementation
7825     // dependent.  Ideally if the format string cannot be null then
7826     // it should have a 'nonnull' attribute in the function prototype.
7827     return SLCT_UncheckedLiteral;
7828 
7829   switch (E->getStmtClass()) {
7830   case Stmt::BinaryConditionalOperatorClass:
7831   case Stmt::ConditionalOperatorClass: {
7832     // The expression is a literal if both sub-expressions were, and it was
7833     // completely checked only if both sub-expressions were checked.
7834     const AbstractConditionalOperator *C =
7835         cast<AbstractConditionalOperator>(E);
7836 
7837     // Determine whether it is necessary to check both sub-expressions, for
7838     // example, because the condition expression is a constant that can be
7839     // evaluated at compile time.
7840     bool CheckLeft = true, CheckRight = true;
7841 
7842     bool Cond;
7843     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7844                                                  S.isConstantEvaluated())) {
7845       if (Cond)
7846         CheckRight = false;
7847       else
7848         CheckLeft = false;
7849     }
7850 
7851     // We need to maintain the offsets for the right and the left hand side
7852     // separately to check if every possible indexed expression is a valid
7853     // string literal. They might have different offsets for different string
7854     // literals in the end.
7855     StringLiteralCheckType Left;
7856     if (!CheckLeft)
7857       Left = SLCT_UncheckedLiteral;
7858     else {
7859       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7860                                    HasVAListArg, format_idx, firstDataArg,
7861                                    Type, CallType, InFunctionCall,
7862                                    CheckedVarArgs, UncoveredArg, Offset,
7863                                    IgnoreStringsWithoutSpecifiers);
7864       if (Left == SLCT_NotALiteral || !CheckRight) {
7865         return Left;
7866       }
7867     }
7868 
7869     StringLiteralCheckType Right = checkFormatStringExpr(
7870         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7871         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7872         IgnoreStringsWithoutSpecifiers);
7873 
7874     return (CheckLeft && Left < Right) ? Left : Right;
7875   }
7876 
7877   case Stmt::ImplicitCastExprClass:
7878     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7879     goto tryAgain;
7880 
7881   case Stmt::OpaqueValueExprClass:
7882     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7883       E = src;
7884       goto tryAgain;
7885     }
7886     return SLCT_NotALiteral;
7887 
7888   case Stmt::PredefinedExprClass:
7889     // While __func__, etc., are technically not string literals, they
7890     // cannot contain format specifiers and thus are not a security
7891     // liability.
7892     return SLCT_UncheckedLiteral;
7893 
7894   case Stmt::DeclRefExprClass: {
7895     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7896 
7897     // As an exception, do not flag errors for variables binding to
7898     // const string literals.
7899     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7900       bool isConstant = false;
7901       QualType T = DR->getType();
7902 
7903       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7904         isConstant = AT->getElementType().isConstant(S.Context);
7905       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7906         isConstant = T.isConstant(S.Context) &&
7907                      PT->getPointeeType().isConstant(S.Context);
7908       } else if (T->isObjCObjectPointerType()) {
7909         // In ObjC, there is usually no "const ObjectPointer" type,
7910         // so don't check if the pointee type is constant.
7911         isConstant = T.isConstant(S.Context);
7912       }
7913 
7914       if (isConstant) {
7915         if (const Expr *Init = VD->getAnyInitializer()) {
7916           // Look through initializers like const char c[] = { "foo" }
7917           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7918             if (InitList->isStringLiteralInit())
7919               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7920           }
7921           return checkFormatStringExpr(S, Init, Args,
7922                                        HasVAListArg, format_idx,
7923                                        firstDataArg, Type, CallType,
7924                                        /*InFunctionCall*/ false, CheckedVarArgs,
7925                                        UncoveredArg, Offset);
7926         }
7927       }
7928 
7929       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7930       // special check to see if the format string is a function parameter
7931       // of the function calling the printf function.  If the function
7932       // has an attribute indicating it is a printf-like function, then we
7933       // should suppress warnings concerning non-literals being used in a call
7934       // to a vprintf function.  For example:
7935       //
7936       // void
7937       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7938       //      va_list ap;
7939       //      va_start(ap, fmt);
7940       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7941       //      ...
7942       // }
7943       if (HasVAListArg) {
7944         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7945           if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) {
7946             int PVIndex = PV->getFunctionScopeIndex() + 1;
7947             for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7948               // adjust for implicit parameter
7949               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
7950                 if (MD->isInstance())
7951                   ++PVIndex;
7952               // We also check if the formats are compatible.
7953               // We can't pass a 'scanf' string to a 'printf' function.
7954               if (PVIndex == PVFormat->getFormatIdx() &&
7955                   Type == S.GetFormatStringType(PVFormat))
7956                 return SLCT_UncheckedLiteral;
7957             }
7958           }
7959         }
7960       }
7961     }
7962 
7963     return SLCT_NotALiteral;
7964   }
7965 
7966   case Stmt::CallExprClass:
7967   case Stmt::CXXMemberCallExprClass: {
7968     const CallExpr *CE = cast<CallExpr>(E);
7969     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7970       bool IsFirst = true;
7971       StringLiteralCheckType CommonResult;
7972       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7973         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7974         StringLiteralCheckType Result = checkFormatStringExpr(
7975             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7976             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7977             IgnoreStringsWithoutSpecifiers);
7978         if (IsFirst) {
7979           CommonResult = Result;
7980           IsFirst = false;
7981         }
7982       }
7983       if (!IsFirst)
7984         return CommonResult;
7985 
7986       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7987         unsigned BuiltinID = FD->getBuiltinID();
7988         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7989             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7990           const Expr *Arg = CE->getArg(0);
7991           return checkFormatStringExpr(S, Arg, Args,
7992                                        HasVAListArg, format_idx,
7993                                        firstDataArg, Type, CallType,
7994                                        InFunctionCall, CheckedVarArgs,
7995                                        UncoveredArg, Offset,
7996                                        IgnoreStringsWithoutSpecifiers);
7997         }
7998       }
7999     }
8000 
8001     return SLCT_NotALiteral;
8002   }
8003   case Stmt::ObjCMessageExprClass: {
8004     const auto *ME = cast<ObjCMessageExpr>(E);
8005     if (const auto *MD = ME->getMethodDecl()) {
8006       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
8007         // As a special case heuristic, if we're using the method -[NSBundle
8008         // localizedStringForKey:value:table:], ignore any key strings that lack
8009         // format specifiers. The idea is that if the key doesn't have any
8010         // format specifiers then its probably just a key to map to the
8011         // localized strings. If it does have format specifiers though, then its
8012         // likely that the text of the key is the format string in the
8013         // programmer's language, and should be checked.
8014         const ObjCInterfaceDecl *IFace;
8015         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
8016             IFace->getIdentifier()->isStr("NSBundle") &&
8017             MD->getSelector().isKeywordSelector(
8018                 {"localizedStringForKey", "value", "table"})) {
8019           IgnoreStringsWithoutSpecifiers = true;
8020         }
8021 
8022         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
8023         return checkFormatStringExpr(
8024             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8025             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8026             IgnoreStringsWithoutSpecifiers);
8027       }
8028     }
8029 
8030     return SLCT_NotALiteral;
8031   }
8032   case Stmt::ObjCStringLiteralClass:
8033   case Stmt::StringLiteralClass: {
8034     const StringLiteral *StrE = nullptr;
8035 
8036     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
8037       StrE = ObjCFExpr->getString();
8038     else
8039       StrE = cast<StringLiteral>(E);
8040 
8041     if (StrE) {
8042       if (Offset.isNegative() || Offset > StrE->getLength()) {
8043         // TODO: It would be better to have an explicit warning for out of
8044         // bounds literals.
8045         return SLCT_NotALiteral;
8046       }
8047       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
8048       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
8049                         firstDataArg, Type, InFunctionCall, CallType,
8050                         CheckedVarArgs, UncoveredArg,
8051                         IgnoreStringsWithoutSpecifiers);
8052       return SLCT_CheckedLiteral;
8053     }
8054 
8055     return SLCT_NotALiteral;
8056   }
8057   case Stmt::BinaryOperatorClass: {
8058     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
8059 
8060     // A string literal + an int offset is still a string literal.
8061     if (BinOp->isAdditiveOp()) {
8062       Expr::EvalResult LResult, RResult;
8063 
8064       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
8065           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8066       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
8067           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8068 
8069       if (LIsInt != RIsInt) {
8070         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
8071 
8072         if (LIsInt) {
8073           if (BinOpKind == BO_Add) {
8074             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
8075             E = BinOp->getRHS();
8076             goto tryAgain;
8077           }
8078         } else {
8079           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
8080           E = BinOp->getLHS();
8081           goto tryAgain;
8082         }
8083       }
8084     }
8085 
8086     return SLCT_NotALiteral;
8087   }
8088   case Stmt::UnaryOperatorClass: {
8089     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
8090     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
8091     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
8092       Expr::EvalResult IndexResult;
8093       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
8094                                        Expr::SE_NoSideEffects,
8095                                        S.isConstantEvaluated())) {
8096         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
8097                    /*RHS is int*/ true);
8098         E = ASE->getBase();
8099         goto tryAgain;
8100       }
8101     }
8102 
8103     return SLCT_NotALiteral;
8104   }
8105 
8106   default:
8107     return SLCT_NotALiteral;
8108   }
8109 }
8110 
8111 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
8112   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
8113       .Case("scanf", FST_Scanf)
8114       .Cases("printf", "printf0", FST_Printf)
8115       .Cases("NSString", "CFString", FST_NSString)
8116       .Case("strftime", FST_Strftime)
8117       .Case("strfmon", FST_Strfmon)
8118       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
8119       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
8120       .Case("os_trace", FST_OSLog)
8121       .Case("os_log", FST_OSLog)
8122       .Default(FST_Unknown);
8123 }
8124 
8125 /// CheckFormatArguments - Check calls to printf and scanf (and similar
8126 /// functions) for correct use of format strings.
8127 /// Returns true if a format string has been fully checked.
8128 bool Sema::CheckFormatArguments(const FormatAttr *Format,
8129                                 ArrayRef<const Expr *> Args,
8130                                 bool IsCXXMember,
8131                                 VariadicCallType CallType,
8132                                 SourceLocation Loc, SourceRange Range,
8133                                 llvm::SmallBitVector &CheckedVarArgs) {
8134   FormatStringInfo FSI;
8135   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
8136     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
8137                                 FSI.FirstDataArg, GetFormatStringType(Format),
8138                                 CallType, Loc, Range, CheckedVarArgs);
8139   return false;
8140 }
8141 
8142 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8143                                 bool HasVAListArg, unsigned format_idx,
8144                                 unsigned firstDataArg, FormatStringType Type,
8145                                 VariadicCallType CallType,
8146                                 SourceLocation Loc, SourceRange Range,
8147                                 llvm::SmallBitVector &CheckedVarArgs) {
8148   // CHECK: printf/scanf-like function is called with no format string.
8149   if (format_idx >= Args.size()) {
8150     Diag(Loc, diag::warn_missing_format_string) << Range;
8151     return false;
8152   }
8153 
8154   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8155 
8156   // CHECK: format string is not a string literal.
8157   //
8158   // Dynamically generated format strings are difficult to
8159   // automatically vet at compile time.  Requiring that format strings
8160   // are string literals: (1) permits the checking of format strings by
8161   // the compiler and thereby (2) can practically remove the source of
8162   // many format string exploits.
8163 
8164   // Format string can be either ObjC string (e.g. @"%d") or
8165   // C string (e.g. "%d")
8166   // ObjC string uses the same format specifiers as C string, so we can use
8167   // the same format string checking logic for both ObjC and C strings.
8168   UncoveredArgHandler UncoveredArg;
8169   StringLiteralCheckType CT =
8170       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8171                             format_idx, firstDataArg, Type, CallType,
8172                             /*IsFunctionCall*/ true, CheckedVarArgs,
8173                             UncoveredArg,
8174                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8175 
8176   // Generate a diagnostic where an uncovered argument is detected.
8177   if (UncoveredArg.hasUncoveredArg()) {
8178     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8179     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8180     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8181   }
8182 
8183   if (CT != SLCT_NotALiteral)
8184     // Literal format string found, check done!
8185     return CT == SLCT_CheckedLiteral;
8186 
8187   // Strftime is particular as it always uses a single 'time' argument,
8188   // so it is safe to pass a non-literal string.
8189   if (Type == FST_Strftime)
8190     return false;
8191 
8192   // Do not emit diag when the string param is a macro expansion and the
8193   // format is either NSString or CFString. This is a hack to prevent
8194   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8195   // which are usually used in place of NS and CF string literals.
8196   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8197   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8198     return false;
8199 
8200   // If there are no arguments specified, warn with -Wformat-security, otherwise
8201   // warn only with -Wformat-nonliteral.
8202   if (Args.size() == firstDataArg) {
8203     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8204       << OrigFormatExpr->getSourceRange();
8205     switch (Type) {
8206     default:
8207       break;
8208     case FST_Kprintf:
8209     case FST_FreeBSDKPrintf:
8210     case FST_Printf:
8211       Diag(FormatLoc, diag::note_format_security_fixit)
8212         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8213       break;
8214     case FST_NSString:
8215       Diag(FormatLoc, diag::note_format_security_fixit)
8216         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8217       break;
8218     }
8219   } else {
8220     Diag(FormatLoc, diag::warn_format_nonliteral)
8221       << OrigFormatExpr->getSourceRange();
8222   }
8223   return false;
8224 }
8225 
8226 namespace {
8227 
8228 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8229 protected:
8230   Sema &S;
8231   const FormatStringLiteral *FExpr;
8232   const Expr *OrigFormatExpr;
8233   const Sema::FormatStringType FSType;
8234   const unsigned FirstDataArg;
8235   const unsigned NumDataArgs;
8236   const char *Beg; // Start of format string.
8237   const bool HasVAListArg;
8238   ArrayRef<const Expr *> Args;
8239   unsigned FormatIdx;
8240   llvm::SmallBitVector CoveredArgs;
8241   bool usesPositionalArgs = false;
8242   bool atFirstArg = true;
8243   bool inFunctionCall;
8244   Sema::VariadicCallType CallType;
8245   llvm::SmallBitVector &CheckedVarArgs;
8246   UncoveredArgHandler &UncoveredArg;
8247 
8248 public:
8249   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8250                      const Expr *origFormatExpr,
8251                      const Sema::FormatStringType type, unsigned firstDataArg,
8252                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8253                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8254                      bool inFunctionCall, Sema::VariadicCallType callType,
8255                      llvm::SmallBitVector &CheckedVarArgs,
8256                      UncoveredArgHandler &UncoveredArg)
8257       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8258         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8259         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8260         inFunctionCall(inFunctionCall), CallType(callType),
8261         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8262     CoveredArgs.resize(numDataArgs);
8263     CoveredArgs.reset();
8264   }
8265 
8266   void DoneProcessing();
8267 
8268   void HandleIncompleteSpecifier(const char *startSpecifier,
8269                                  unsigned specifierLen) override;
8270 
8271   void HandleInvalidLengthModifier(
8272                            const analyze_format_string::FormatSpecifier &FS,
8273                            const analyze_format_string::ConversionSpecifier &CS,
8274                            const char *startSpecifier, unsigned specifierLen,
8275                            unsigned DiagID);
8276 
8277   void HandleNonStandardLengthModifier(
8278                     const analyze_format_string::FormatSpecifier &FS,
8279                     const char *startSpecifier, unsigned specifierLen);
8280 
8281   void HandleNonStandardConversionSpecifier(
8282                     const analyze_format_string::ConversionSpecifier &CS,
8283                     const char *startSpecifier, unsigned specifierLen);
8284 
8285   void HandlePosition(const char *startPos, unsigned posLen) override;
8286 
8287   void HandleInvalidPosition(const char *startSpecifier,
8288                              unsigned specifierLen,
8289                              analyze_format_string::PositionContext p) override;
8290 
8291   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8292 
8293   void HandleNullChar(const char *nullCharacter) override;
8294 
8295   template <typename Range>
8296   static void
8297   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8298                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8299                        bool IsStringLocation, Range StringRange,
8300                        ArrayRef<FixItHint> Fixit = None);
8301 
8302 protected:
8303   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8304                                         const char *startSpec,
8305                                         unsigned specifierLen,
8306                                         const char *csStart, unsigned csLen);
8307 
8308   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8309                                          const char *startSpec,
8310                                          unsigned specifierLen);
8311 
8312   SourceRange getFormatStringRange();
8313   CharSourceRange getSpecifierRange(const char *startSpecifier,
8314                                     unsigned specifierLen);
8315   SourceLocation getLocationOfByte(const char *x);
8316 
8317   const Expr *getDataArg(unsigned i) const;
8318 
8319   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8320                     const analyze_format_string::ConversionSpecifier &CS,
8321                     const char *startSpecifier, unsigned specifierLen,
8322                     unsigned argIndex);
8323 
8324   template <typename Range>
8325   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8326                             bool IsStringLocation, Range StringRange,
8327                             ArrayRef<FixItHint> Fixit = None);
8328 };
8329 
8330 } // namespace
8331 
8332 SourceRange CheckFormatHandler::getFormatStringRange() {
8333   return OrigFormatExpr->getSourceRange();
8334 }
8335 
8336 CharSourceRange CheckFormatHandler::
8337 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8338   SourceLocation Start = getLocationOfByte(startSpecifier);
8339   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8340 
8341   // Advance the end SourceLocation by one due to half-open ranges.
8342   End = End.getLocWithOffset(1);
8343 
8344   return CharSourceRange::getCharRange(Start, End);
8345 }
8346 
8347 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8348   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8349                                   S.getLangOpts(), S.Context.getTargetInfo());
8350 }
8351 
8352 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8353                                                    unsigned specifierLen){
8354   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8355                        getLocationOfByte(startSpecifier),
8356                        /*IsStringLocation*/true,
8357                        getSpecifierRange(startSpecifier, specifierLen));
8358 }
8359 
8360 void CheckFormatHandler::HandleInvalidLengthModifier(
8361     const analyze_format_string::FormatSpecifier &FS,
8362     const analyze_format_string::ConversionSpecifier &CS,
8363     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8364   using namespace analyze_format_string;
8365 
8366   const LengthModifier &LM = FS.getLengthModifier();
8367   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8368 
8369   // See if we know how to fix this length modifier.
8370   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8371   if (FixedLM) {
8372     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8373                          getLocationOfByte(LM.getStart()),
8374                          /*IsStringLocation*/true,
8375                          getSpecifierRange(startSpecifier, specifierLen));
8376 
8377     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8378       << FixedLM->toString()
8379       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8380 
8381   } else {
8382     FixItHint Hint;
8383     if (DiagID == diag::warn_format_nonsensical_length)
8384       Hint = FixItHint::CreateRemoval(LMRange);
8385 
8386     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8387                          getLocationOfByte(LM.getStart()),
8388                          /*IsStringLocation*/true,
8389                          getSpecifierRange(startSpecifier, specifierLen),
8390                          Hint);
8391   }
8392 }
8393 
8394 void CheckFormatHandler::HandleNonStandardLengthModifier(
8395     const analyze_format_string::FormatSpecifier &FS,
8396     const char *startSpecifier, unsigned specifierLen) {
8397   using namespace analyze_format_string;
8398 
8399   const LengthModifier &LM = FS.getLengthModifier();
8400   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8401 
8402   // See if we know how to fix this length modifier.
8403   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8404   if (FixedLM) {
8405     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8406                            << LM.toString() << 0,
8407                          getLocationOfByte(LM.getStart()),
8408                          /*IsStringLocation*/true,
8409                          getSpecifierRange(startSpecifier, specifierLen));
8410 
8411     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8412       << FixedLM->toString()
8413       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8414 
8415   } else {
8416     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8417                            << LM.toString() << 0,
8418                          getLocationOfByte(LM.getStart()),
8419                          /*IsStringLocation*/true,
8420                          getSpecifierRange(startSpecifier, specifierLen));
8421   }
8422 }
8423 
8424 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8425     const analyze_format_string::ConversionSpecifier &CS,
8426     const char *startSpecifier, unsigned specifierLen) {
8427   using namespace analyze_format_string;
8428 
8429   // See if we know how to fix this conversion specifier.
8430   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8431   if (FixedCS) {
8432     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8433                           << CS.toString() << /*conversion specifier*/1,
8434                          getLocationOfByte(CS.getStart()),
8435                          /*IsStringLocation*/true,
8436                          getSpecifierRange(startSpecifier, specifierLen));
8437 
8438     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8439     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8440       << FixedCS->toString()
8441       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8442   } else {
8443     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8444                           << CS.toString() << /*conversion specifier*/1,
8445                          getLocationOfByte(CS.getStart()),
8446                          /*IsStringLocation*/true,
8447                          getSpecifierRange(startSpecifier, specifierLen));
8448   }
8449 }
8450 
8451 void CheckFormatHandler::HandlePosition(const char *startPos,
8452                                         unsigned posLen) {
8453   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8454                                getLocationOfByte(startPos),
8455                                /*IsStringLocation*/true,
8456                                getSpecifierRange(startPos, posLen));
8457 }
8458 
8459 void
8460 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8461                                      analyze_format_string::PositionContext p) {
8462   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8463                          << (unsigned) p,
8464                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8465                        getSpecifierRange(startPos, posLen));
8466 }
8467 
8468 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8469                                             unsigned posLen) {
8470   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8471                                getLocationOfByte(startPos),
8472                                /*IsStringLocation*/true,
8473                                getSpecifierRange(startPos, posLen));
8474 }
8475 
8476 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8477   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8478     // The presence of a null character is likely an error.
8479     EmitFormatDiagnostic(
8480       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8481       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8482       getFormatStringRange());
8483   }
8484 }
8485 
8486 // Note that this may return NULL if there was an error parsing or building
8487 // one of the argument expressions.
8488 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8489   return Args[FirstDataArg + i];
8490 }
8491 
8492 void CheckFormatHandler::DoneProcessing() {
8493   // Does the number of data arguments exceed the number of
8494   // format conversions in the format string?
8495   if (!HasVAListArg) {
8496       // Find any arguments that weren't covered.
8497     CoveredArgs.flip();
8498     signed notCoveredArg = CoveredArgs.find_first();
8499     if (notCoveredArg >= 0) {
8500       assert((unsigned)notCoveredArg < NumDataArgs);
8501       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8502     } else {
8503       UncoveredArg.setAllCovered();
8504     }
8505   }
8506 }
8507 
8508 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8509                                    const Expr *ArgExpr) {
8510   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8511          "Invalid state");
8512 
8513   if (!ArgExpr)
8514     return;
8515 
8516   SourceLocation Loc = ArgExpr->getBeginLoc();
8517 
8518   if (S.getSourceManager().isInSystemMacro(Loc))
8519     return;
8520 
8521   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8522   for (auto E : DiagnosticExprs)
8523     PDiag << E->getSourceRange();
8524 
8525   CheckFormatHandler::EmitFormatDiagnostic(
8526                                   S, IsFunctionCall, DiagnosticExprs[0],
8527                                   PDiag, Loc, /*IsStringLocation*/false,
8528                                   DiagnosticExprs[0]->getSourceRange());
8529 }
8530 
8531 bool
8532 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8533                                                      SourceLocation Loc,
8534                                                      const char *startSpec,
8535                                                      unsigned specifierLen,
8536                                                      const char *csStart,
8537                                                      unsigned csLen) {
8538   bool keepGoing = true;
8539   if (argIndex < NumDataArgs) {
8540     // Consider the argument coverered, even though the specifier doesn't
8541     // make sense.
8542     CoveredArgs.set(argIndex);
8543   }
8544   else {
8545     // If argIndex exceeds the number of data arguments we
8546     // don't issue a warning because that is just a cascade of warnings (and
8547     // they may have intended '%%' anyway). We don't want to continue processing
8548     // the format string after this point, however, as we will like just get
8549     // gibberish when trying to match arguments.
8550     keepGoing = false;
8551   }
8552 
8553   StringRef Specifier(csStart, csLen);
8554 
8555   // If the specifier in non-printable, it could be the first byte of a UTF-8
8556   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8557   // hex value.
8558   std::string CodePointStr;
8559   if (!llvm::sys::locale::isPrint(*csStart)) {
8560     llvm::UTF32 CodePoint;
8561     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8562     const llvm::UTF8 *E =
8563         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8564     llvm::ConversionResult Result =
8565         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8566 
8567     if (Result != llvm::conversionOK) {
8568       unsigned char FirstChar = *csStart;
8569       CodePoint = (llvm::UTF32)FirstChar;
8570     }
8571 
8572     llvm::raw_string_ostream OS(CodePointStr);
8573     if (CodePoint < 256)
8574       OS << "\\x" << llvm::format("%02x", CodePoint);
8575     else if (CodePoint <= 0xFFFF)
8576       OS << "\\u" << llvm::format("%04x", CodePoint);
8577     else
8578       OS << "\\U" << llvm::format("%08x", CodePoint);
8579     OS.flush();
8580     Specifier = CodePointStr;
8581   }
8582 
8583   EmitFormatDiagnostic(
8584       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8585       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8586 
8587   return keepGoing;
8588 }
8589 
8590 void
8591 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8592                                                       const char *startSpec,
8593                                                       unsigned specifierLen) {
8594   EmitFormatDiagnostic(
8595     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8596     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8597 }
8598 
8599 bool
8600 CheckFormatHandler::CheckNumArgs(
8601   const analyze_format_string::FormatSpecifier &FS,
8602   const analyze_format_string::ConversionSpecifier &CS,
8603   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8604 
8605   if (argIndex >= NumDataArgs) {
8606     PartialDiagnostic PDiag = FS.usesPositionalArg()
8607       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8608            << (argIndex+1) << NumDataArgs)
8609       : S.PDiag(diag::warn_printf_insufficient_data_args);
8610     EmitFormatDiagnostic(
8611       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8612       getSpecifierRange(startSpecifier, specifierLen));
8613 
8614     // Since more arguments than conversion tokens are given, by extension
8615     // all arguments are covered, so mark this as so.
8616     UncoveredArg.setAllCovered();
8617     return false;
8618   }
8619   return true;
8620 }
8621 
8622 template<typename Range>
8623 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8624                                               SourceLocation Loc,
8625                                               bool IsStringLocation,
8626                                               Range StringRange,
8627                                               ArrayRef<FixItHint> FixIt) {
8628   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8629                        Loc, IsStringLocation, StringRange, FixIt);
8630 }
8631 
8632 /// If the format string is not within the function call, emit a note
8633 /// so that the function call and string are in diagnostic messages.
8634 ///
8635 /// \param InFunctionCall if true, the format string is within the function
8636 /// call and only one diagnostic message will be produced.  Otherwise, an
8637 /// extra note will be emitted pointing to location of the format string.
8638 ///
8639 /// \param ArgumentExpr the expression that is passed as the format string
8640 /// argument in the function call.  Used for getting locations when two
8641 /// diagnostics are emitted.
8642 ///
8643 /// \param PDiag the callee should already have provided any strings for the
8644 /// diagnostic message.  This function only adds locations and fixits
8645 /// to diagnostics.
8646 ///
8647 /// \param Loc primary location for diagnostic.  If two diagnostics are
8648 /// required, one will be at Loc and a new SourceLocation will be created for
8649 /// the other one.
8650 ///
8651 /// \param IsStringLocation if true, Loc points to the format string should be
8652 /// used for the note.  Otherwise, Loc points to the argument list and will
8653 /// be used with PDiag.
8654 ///
8655 /// \param StringRange some or all of the string to highlight.  This is
8656 /// templated so it can accept either a CharSourceRange or a SourceRange.
8657 ///
8658 /// \param FixIt optional fix it hint for the format string.
8659 template <typename Range>
8660 void CheckFormatHandler::EmitFormatDiagnostic(
8661     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8662     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8663     Range StringRange, ArrayRef<FixItHint> FixIt) {
8664   if (InFunctionCall) {
8665     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8666     D << StringRange;
8667     D << FixIt;
8668   } else {
8669     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8670       << ArgumentExpr->getSourceRange();
8671 
8672     const Sema::SemaDiagnosticBuilder &Note =
8673       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8674              diag::note_format_string_defined);
8675 
8676     Note << StringRange;
8677     Note << FixIt;
8678   }
8679 }
8680 
8681 //===--- CHECK: Printf format string checking ------------------------------===//
8682 
8683 namespace {
8684 
8685 class CheckPrintfHandler : public CheckFormatHandler {
8686 public:
8687   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8688                      const Expr *origFormatExpr,
8689                      const Sema::FormatStringType type, unsigned firstDataArg,
8690                      unsigned numDataArgs, bool isObjC, const char *beg,
8691                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8692                      unsigned formatIdx, bool inFunctionCall,
8693                      Sema::VariadicCallType CallType,
8694                      llvm::SmallBitVector &CheckedVarArgs,
8695                      UncoveredArgHandler &UncoveredArg)
8696       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8697                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8698                            inFunctionCall, CallType, CheckedVarArgs,
8699                            UncoveredArg) {}
8700 
8701   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8702 
8703   /// Returns true if '%@' specifiers are allowed in the format string.
8704   bool allowsObjCArg() const {
8705     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8706            FSType == Sema::FST_OSTrace;
8707   }
8708 
8709   bool HandleInvalidPrintfConversionSpecifier(
8710                                       const analyze_printf::PrintfSpecifier &FS,
8711                                       const char *startSpecifier,
8712                                       unsigned specifierLen) override;
8713 
8714   void handleInvalidMaskType(StringRef MaskType) override;
8715 
8716   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8717                              const char *startSpecifier,
8718                              unsigned specifierLen) override;
8719   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8720                        const char *StartSpecifier,
8721                        unsigned SpecifierLen,
8722                        const Expr *E);
8723 
8724   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8725                     const char *startSpecifier, unsigned specifierLen);
8726   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8727                            const analyze_printf::OptionalAmount &Amt,
8728                            unsigned type,
8729                            const char *startSpecifier, unsigned specifierLen);
8730   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8731                   const analyze_printf::OptionalFlag &flag,
8732                   const char *startSpecifier, unsigned specifierLen);
8733   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8734                          const analyze_printf::OptionalFlag &ignoredFlag,
8735                          const analyze_printf::OptionalFlag &flag,
8736                          const char *startSpecifier, unsigned specifierLen);
8737   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8738                            const Expr *E);
8739 
8740   void HandleEmptyObjCModifierFlag(const char *startFlag,
8741                                    unsigned flagLen) override;
8742 
8743   void HandleInvalidObjCModifierFlag(const char *startFlag,
8744                                             unsigned flagLen) override;
8745 
8746   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8747                                            const char *flagsEnd,
8748                                            const char *conversionPosition)
8749                                              override;
8750 };
8751 
8752 } // namespace
8753 
8754 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8755                                       const analyze_printf::PrintfSpecifier &FS,
8756                                       const char *startSpecifier,
8757                                       unsigned specifierLen) {
8758   const analyze_printf::PrintfConversionSpecifier &CS =
8759     FS.getConversionSpecifier();
8760 
8761   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8762                                           getLocationOfByte(CS.getStart()),
8763                                           startSpecifier, specifierLen,
8764                                           CS.getStart(), CS.getLength());
8765 }
8766 
8767 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8768   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8769 }
8770 
8771 bool CheckPrintfHandler::HandleAmount(
8772                                const analyze_format_string::OptionalAmount &Amt,
8773                                unsigned k, const char *startSpecifier,
8774                                unsigned specifierLen) {
8775   if (Amt.hasDataArgument()) {
8776     if (!HasVAListArg) {
8777       unsigned argIndex = Amt.getArgIndex();
8778       if (argIndex >= NumDataArgs) {
8779         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8780                                << k,
8781                              getLocationOfByte(Amt.getStart()),
8782                              /*IsStringLocation*/true,
8783                              getSpecifierRange(startSpecifier, specifierLen));
8784         // Don't do any more checking.  We will just emit
8785         // spurious errors.
8786         return false;
8787       }
8788 
8789       // Type check the data argument.  It should be an 'int'.
8790       // Although not in conformance with C99, we also allow the argument to be
8791       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8792       // doesn't emit a warning for that case.
8793       CoveredArgs.set(argIndex);
8794       const Expr *Arg = getDataArg(argIndex);
8795       if (!Arg)
8796         return false;
8797 
8798       QualType T = Arg->getType();
8799 
8800       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8801       assert(AT.isValid());
8802 
8803       if (!AT.matchesType(S.Context, T)) {
8804         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8805                                << k << AT.getRepresentativeTypeName(S.Context)
8806                                << T << Arg->getSourceRange(),
8807                              getLocationOfByte(Amt.getStart()),
8808                              /*IsStringLocation*/true,
8809                              getSpecifierRange(startSpecifier, specifierLen));
8810         // Don't do any more checking.  We will just emit
8811         // spurious errors.
8812         return false;
8813       }
8814     }
8815   }
8816   return true;
8817 }
8818 
8819 void CheckPrintfHandler::HandleInvalidAmount(
8820                                       const analyze_printf::PrintfSpecifier &FS,
8821                                       const analyze_printf::OptionalAmount &Amt,
8822                                       unsigned type,
8823                                       const char *startSpecifier,
8824                                       unsigned specifierLen) {
8825   const analyze_printf::PrintfConversionSpecifier &CS =
8826     FS.getConversionSpecifier();
8827 
8828   FixItHint fixit =
8829     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8830       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8831                                  Amt.getConstantLength()))
8832       : FixItHint();
8833 
8834   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8835                          << type << CS.toString(),
8836                        getLocationOfByte(Amt.getStart()),
8837                        /*IsStringLocation*/true,
8838                        getSpecifierRange(startSpecifier, specifierLen),
8839                        fixit);
8840 }
8841 
8842 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8843                                     const analyze_printf::OptionalFlag &flag,
8844                                     const char *startSpecifier,
8845                                     unsigned specifierLen) {
8846   // Warn about pointless flag with a fixit removal.
8847   const analyze_printf::PrintfConversionSpecifier &CS =
8848     FS.getConversionSpecifier();
8849   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8850                          << flag.toString() << CS.toString(),
8851                        getLocationOfByte(flag.getPosition()),
8852                        /*IsStringLocation*/true,
8853                        getSpecifierRange(startSpecifier, specifierLen),
8854                        FixItHint::CreateRemoval(
8855                          getSpecifierRange(flag.getPosition(), 1)));
8856 }
8857 
8858 void CheckPrintfHandler::HandleIgnoredFlag(
8859                                 const analyze_printf::PrintfSpecifier &FS,
8860                                 const analyze_printf::OptionalFlag &ignoredFlag,
8861                                 const analyze_printf::OptionalFlag &flag,
8862                                 const char *startSpecifier,
8863                                 unsigned specifierLen) {
8864   // Warn about ignored flag with a fixit removal.
8865   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8866                          << ignoredFlag.toString() << flag.toString(),
8867                        getLocationOfByte(ignoredFlag.getPosition()),
8868                        /*IsStringLocation*/true,
8869                        getSpecifierRange(startSpecifier, specifierLen),
8870                        FixItHint::CreateRemoval(
8871                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8872 }
8873 
8874 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8875                                                      unsigned flagLen) {
8876   // Warn about an empty flag.
8877   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8878                        getLocationOfByte(startFlag),
8879                        /*IsStringLocation*/true,
8880                        getSpecifierRange(startFlag, flagLen));
8881 }
8882 
8883 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8884                                                        unsigned flagLen) {
8885   // Warn about an invalid flag.
8886   auto Range = getSpecifierRange(startFlag, flagLen);
8887   StringRef flag(startFlag, flagLen);
8888   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8889                       getLocationOfByte(startFlag),
8890                       /*IsStringLocation*/true,
8891                       Range, FixItHint::CreateRemoval(Range));
8892 }
8893 
8894 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8895     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8896     // Warn about using '[...]' without a '@' conversion.
8897     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8898     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8899     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8900                          getLocationOfByte(conversionPosition),
8901                          /*IsStringLocation*/true,
8902                          Range, FixItHint::CreateRemoval(Range));
8903 }
8904 
8905 // Determines if the specified is a C++ class or struct containing
8906 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8907 // "c_str()").
8908 template<typename MemberKind>
8909 static llvm::SmallPtrSet<MemberKind*, 1>
8910 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8911   const RecordType *RT = Ty->getAs<RecordType>();
8912   llvm::SmallPtrSet<MemberKind*, 1> Results;
8913 
8914   if (!RT)
8915     return Results;
8916   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8917   if (!RD || !RD->getDefinition())
8918     return Results;
8919 
8920   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8921                  Sema::LookupMemberName);
8922   R.suppressDiagnostics();
8923 
8924   // We just need to include all members of the right kind turned up by the
8925   // filter, at this point.
8926   if (S.LookupQualifiedName(R, RT->getDecl()))
8927     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8928       NamedDecl *decl = (*I)->getUnderlyingDecl();
8929       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8930         Results.insert(FK);
8931     }
8932   return Results;
8933 }
8934 
8935 /// Check if we could call '.c_str()' on an object.
8936 ///
8937 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8938 /// allow the call, or if it would be ambiguous).
8939 bool Sema::hasCStrMethod(const Expr *E) {
8940   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8941 
8942   MethodSet Results =
8943       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8944   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8945        MI != ME; ++MI)
8946     if ((*MI)->getMinRequiredArguments() == 0)
8947       return true;
8948   return false;
8949 }
8950 
8951 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8952 // better diagnostic if so. AT is assumed to be valid.
8953 // Returns true when a c_str() conversion method is found.
8954 bool CheckPrintfHandler::checkForCStrMembers(
8955     const analyze_printf::ArgType &AT, const Expr *E) {
8956   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8957 
8958   MethodSet Results =
8959       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8960 
8961   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8962        MI != ME; ++MI) {
8963     const CXXMethodDecl *Method = *MI;
8964     if (Method->getMinRequiredArguments() == 0 &&
8965         AT.matchesType(S.Context, Method->getReturnType())) {
8966       // FIXME: Suggest parens if the expression needs them.
8967       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8968       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8969           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8970       return true;
8971     }
8972   }
8973 
8974   return false;
8975 }
8976 
8977 bool
8978 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8979                                             &FS,
8980                                           const char *startSpecifier,
8981                                           unsigned specifierLen) {
8982   using namespace analyze_format_string;
8983   using namespace analyze_printf;
8984 
8985   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8986 
8987   if (FS.consumesDataArgument()) {
8988     if (atFirstArg) {
8989         atFirstArg = false;
8990         usesPositionalArgs = FS.usesPositionalArg();
8991     }
8992     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8993       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8994                                         startSpecifier, specifierLen);
8995       return false;
8996     }
8997   }
8998 
8999   // First check if the field width, precision, and conversion specifier
9000   // have matching data arguments.
9001   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
9002                     startSpecifier, specifierLen)) {
9003     return false;
9004   }
9005 
9006   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
9007                     startSpecifier, specifierLen)) {
9008     return false;
9009   }
9010 
9011   if (!CS.consumesDataArgument()) {
9012     // FIXME: Technically specifying a precision or field width here
9013     // makes no sense.  Worth issuing a warning at some point.
9014     return true;
9015   }
9016 
9017   // Consume the argument.
9018   unsigned argIndex = FS.getArgIndex();
9019   if (argIndex < NumDataArgs) {
9020     // The check to see if the argIndex is valid will come later.
9021     // We set the bit here because we may exit early from this
9022     // function if we encounter some other error.
9023     CoveredArgs.set(argIndex);
9024   }
9025 
9026   // FreeBSD kernel extensions.
9027   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9028       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9029     // We need at least two arguments.
9030     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9031       return false;
9032 
9033     // Claim the second argument.
9034     CoveredArgs.set(argIndex + 1);
9035 
9036     // Type check the first argument (int for %b, pointer for %D)
9037     const Expr *Ex = getDataArg(argIndex);
9038     const analyze_printf::ArgType &AT =
9039       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
9040         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
9041     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9042       EmitFormatDiagnostic(
9043           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9044               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9045               << false << Ex->getSourceRange(),
9046           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9047           getSpecifierRange(startSpecifier, specifierLen));
9048 
9049     // Type check the second argument (char * for both %b and %D)
9050     Ex = getDataArg(argIndex + 1);
9051     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9052     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9053       EmitFormatDiagnostic(
9054           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9055               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9056               << false << Ex->getSourceRange(),
9057           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9058           getSpecifierRange(startSpecifier, specifierLen));
9059 
9060      return true;
9061   }
9062 
9063   // Check for using an Objective-C specific conversion specifier
9064   // in a non-ObjC literal.
9065   if (!allowsObjCArg() && CS.isObjCArg()) {
9066     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9067                                                   specifierLen);
9068   }
9069 
9070   // %P can only be used with os_log.
9071   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
9072     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9073                                                   specifierLen);
9074   }
9075 
9076   // %n is not allowed with os_log.
9077   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
9078     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9079                          getLocationOfByte(CS.getStart()),
9080                          /*IsStringLocation*/ false,
9081                          getSpecifierRange(startSpecifier, specifierLen));
9082 
9083     return true;
9084   }
9085 
9086   // Only scalars are allowed for os_trace.
9087   if (FSType == Sema::FST_OSTrace &&
9088       (CS.getKind() == ConversionSpecifier::PArg ||
9089        CS.getKind() == ConversionSpecifier::sArg ||
9090        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9091     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9092                                                   specifierLen);
9093   }
9094 
9095   // Check for use of public/private annotation outside of os_log().
9096   if (FSType != Sema::FST_OSLog) {
9097     if (FS.isPublic().isSet()) {
9098       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9099                                << "public",
9100                            getLocationOfByte(FS.isPublic().getPosition()),
9101                            /*IsStringLocation*/ false,
9102                            getSpecifierRange(startSpecifier, specifierLen));
9103     }
9104     if (FS.isPrivate().isSet()) {
9105       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9106                                << "private",
9107                            getLocationOfByte(FS.isPrivate().getPosition()),
9108                            /*IsStringLocation*/ false,
9109                            getSpecifierRange(startSpecifier, specifierLen));
9110     }
9111   }
9112 
9113   // Check for invalid use of field width
9114   if (!FS.hasValidFieldWidth()) {
9115     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9116         startSpecifier, specifierLen);
9117   }
9118 
9119   // Check for invalid use of precision
9120   if (!FS.hasValidPrecision()) {
9121     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9122         startSpecifier, specifierLen);
9123   }
9124 
9125   // Precision is mandatory for %P specifier.
9126   if (CS.getKind() == ConversionSpecifier::PArg &&
9127       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9128     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9129                          getLocationOfByte(startSpecifier),
9130                          /*IsStringLocation*/ false,
9131                          getSpecifierRange(startSpecifier, specifierLen));
9132   }
9133 
9134   // Check each flag does not conflict with any other component.
9135   if (!FS.hasValidThousandsGroupingPrefix())
9136     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9137   if (!FS.hasValidLeadingZeros())
9138     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9139   if (!FS.hasValidPlusPrefix())
9140     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9141   if (!FS.hasValidSpacePrefix())
9142     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9143   if (!FS.hasValidAlternativeForm())
9144     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9145   if (!FS.hasValidLeftJustified())
9146     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9147 
9148   // Check that flags are not ignored by another flag
9149   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9150     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9151         startSpecifier, specifierLen);
9152   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9153     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9154             startSpecifier, specifierLen);
9155 
9156   // Check the length modifier is valid with the given conversion specifier.
9157   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9158                                  S.getLangOpts()))
9159     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9160                                 diag::warn_format_nonsensical_length);
9161   else if (!FS.hasStandardLengthModifier())
9162     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9163   else if (!FS.hasStandardLengthConversionCombination())
9164     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9165                                 diag::warn_format_non_standard_conversion_spec);
9166 
9167   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9168     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9169 
9170   // The remaining checks depend on the data arguments.
9171   if (HasVAListArg)
9172     return true;
9173 
9174   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9175     return false;
9176 
9177   const Expr *Arg = getDataArg(argIndex);
9178   if (!Arg)
9179     return true;
9180 
9181   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9182 }
9183 
9184 static bool requiresParensToAddCast(const Expr *E) {
9185   // FIXME: We should have a general way to reason about operator
9186   // precedence and whether parens are actually needed here.
9187   // Take care of a few common cases where they aren't.
9188   const Expr *Inside = E->IgnoreImpCasts();
9189   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9190     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9191 
9192   switch (Inside->getStmtClass()) {
9193   case Stmt::ArraySubscriptExprClass:
9194   case Stmt::CallExprClass:
9195   case Stmt::CharacterLiteralClass:
9196   case Stmt::CXXBoolLiteralExprClass:
9197   case Stmt::DeclRefExprClass:
9198   case Stmt::FloatingLiteralClass:
9199   case Stmt::IntegerLiteralClass:
9200   case Stmt::MemberExprClass:
9201   case Stmt::ObjCArrayLiteralClass:
9202   case Stmt::ObjCBoolLiteralExprClass:
9203   case Stmt::ObjCBoxedExprClass:
9204   case Stmt::ObjCDictionaryLiteralClass:
9205   case Stmt::ObjCEncodeExprClass:
9206   case Stmt::ObjCIvarRefExprClass:
9207   case Stmt::ObjCMessageExprClass:
9208   case Stmt::ObjCPropertyRefExprClass:
9209   case Stmt::ObjCStringLiteralClass:
9210   case Stmt::ObjCSubscriptRefExprClass:
9211   case Stmt::ParenExprClass:
9212   case Stmt::StringLiteralClass:
9213   case Stmt::UnaryOperatorClass:
9214     return false;
9215   default:
9216     return true;
9217   }
9218 }
9219 
9220 static std::pair<QualType, StringRef>
9221 shouldNotPrintDirectly(const ASTContext &Context,
9222                        QualType IntendedTy,
9223                        const Expr *E) {
9224   // Use a 'while' to peel off layers of typedefs.
9225   QualType TyTy = IntendedTy;
9226   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9227     StringRef Name = UserTy->getDecl()->getName();
9228     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9229       .Case("CFIndex", Context.getNSIntegerType())
9230       .Case("NSInteger", Context.getNSIntegerType())
9231       .Case("NSUInteger", Context.getNSUIntegerType())
9232       .Case("SInt32", Context.IntTy)
9233       .Case("UInt32", Context.UnsignedIntTy)
9234       .Default(QualType());
9235 
9236     if (!CastTy.isNull())
9237       return std::make_pair(CastTy, Name);
9238 
9239     TyTy = UserTy->desugar();
9240   }
9241 
9242   // Strip parens if necessary.
9243   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9244     return shouldNotPrintDirectly(Context,
9245                                   PE->getSubExpr()->getType(),
9246                                   PE->getSubExpr());
9247 
9248   // If this is a conditional expression, then its result type is constructed
9249   // via usual arithmetic conversions and thus there might be no necessary
9250   // typedef sugar there.  Recurse to operands to check for NSInteger &
9251   // Co. usage condition.
9252   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9253     QualType TrueTy, FalseTy;
9254     StringRef TrueName, FalseName;
9255 
9256     std::tie(TrueTy, TrueName) =
9257       shouldNotPrintDirectly(Context,
9258                              CO->getTrueExpr()->getType(),
9259                              CO->getTrueExpr());
9260     std::tie(FalseTy, FalseName) =
9261       shouldNotPrintDirectly(Context,
9262                              CO->getFalseExpr()->getType(),
9263                              CO->getFalseExpr());
9264 
9265     if (TrueTy == FalseTy)
9266       return std::make_pair(TrueTy, TrueName);
9267     else if (TrueTy.isNull())
9268       return std::make_pair(FalseTy, FalseName);
9269     else if (FalseTy.isNull())
9270       return std::make_pair(TrueTy, TrueName);
9271   }
9272 
9273   return std::make_pair(QualType(), StringRef());
9274 }
9275 
9276 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9277 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9278 /// type do not count.
9279 static bool
9280 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9281   QualType From = ICE->getSubExpr()->getType();
9282   QualType To = ICE->getType();
9283   // It's an integer promotion if the destination type is the promoted
9284   // source type.
9285   if (ICE->getCastKind() == CK_IntegralCast &&
9286       From->isPromotableIntegerType() &&
9287       S.Context.getPromotedIntegerType(From) == To)
9288     return true;
9289   // Look through vector types, since we do default argument promotion for
9290   // those in OpenCL.
9291   if (const auto *VecTy = From->getAs<ExtVectorType>())
9292     From = VecTy->getElementType();
9293   if (const auto *VecTy = To->getAs<ExtVectorType>())
9294     To = VecTy->getElementType();
9295   // It's a floating promotion if the source type is a lower rank.
9296   return ICE->getCastKind() == CK_FloatingCast &&
9297          S.Context.getFloatingTypeOrder(From, To) < 0;
9298 }
9299 
9300 bool
9301 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9302                                     const char *StartSpecifier,
9303                                     unsigned SpecifierLen,
9304                                     const Expr *E) {
9305   using namespace analyze_format_string;
9306   using namespace analyze_printf;
9307 
9308   // Now type check the data expression that matches the
9309   // format specifier.
9310   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9311   if (!AT.isValid())
9312     return true;
9313 
9314   QualType ExprTy = E->getType();
9315   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9316     ExprTy = TET->getUnderlyingExpr()->getType();
9317   }
9318 
9319   // Diagnose attempts to print a boolean value as a character. Unlike other
9320   // -Wformat diagnostics, this is fine from a type perspective, but it still
9321   // doesn't make sense.
9322   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9323       E->isKnownToHaveBooleanValue()) {
9324     const CharSourceRange &CSR =
9325         getSpecifierRange(StartSpecifier, SpecifierLen);
9326     SmallString<4> FSString;
9327     llvm::raw_svector_ostream os(FSString);
9328     FS.toString(os);
9329     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9330                              << FSString,
9331                          E->getExprLoc(), false, CSR);
9332     return true;
9333   }
9334 
9335   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9336   if (Match == analyze_printf::ArgType::Match)
9337     return true;
9338 
9339   // Look through argument promotions for our error message's reported type.
9340   // This includes the integral and floating promotions, but excludes array
9341   // and function pointer decay (seeing that an argument intended to be a
9342   // string has type 'char [6]' is probably more confusing than 'char *') and
9343   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9344   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9345     if (isArithmeticArgumentPromotion(S, ICE)) {
9346       E = ICE->getSubExpr();
9347       ExprTy = E->getType();
9348 
9349       // Check if we didn't match because of an implicit cast from a 'char'
9350       // or 'short' to an 'int'.  This is done because printf is a varargs
9351       // function.
9352       if (ICE->getType() == S.Context.IntTy ||
9353           ICE->getType() == S.Context.UnsignedIntTy) {
9354         // All further checking is done on the subexpression
9355         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9356             AT.matchesType(S.Context, ExprTy);
9357         if (ImplicitMatch == analyze_printf::ArgType::Match)
9358           return true;
9359         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9360             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9361           Match = ImplicitMatch;
9362       }
9363     }
9364   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9365     // Special case for 'a', which has type 'int' in C.
9366     // Note, however, that we do /not/ want to treat multibyte constants like
9367     // 'MooV' as characters! This form is deprecated but still exists. In
9368     // addition, don't treat expressions as of type 'char' if one byte length
9369     // modifier is provided.
9370     if (ExprTy == S.Context.IntTy &&
9371         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9372       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9373         ExprTy = S.Context.CharTy;
9374   }
9375 
9376   // Look through enums to their underlying type.
9377   bool IsEnum = false;
9378   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9379     ExprTy = EnumTy->getDecl()->getIntegerType();
9380     IsEnum = true;
9381   }
9382 
9383   // %C in an Objective-C context prints a unichar, not a wchar_t.
9384   // If the argument is an integer of some kind, believe the %C and suggest
9385   // a cast instead of changing the conversion specifier.
9386   QualType IntendedTy = ExprTy;
9387   if (isObjCContext() &&
9388       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9389     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9390         !ExprTy->isCharType()) {
9391       // 'unichar' is defined as a typedef of unsigned short, but we should
9392       // prefer using the typedef if it is visible.
9393       IntendedTy = S.Context.UnsignedShortTy;
9394 
9395       // While we are here, check if the value is an IntegerLiteral that happens
9396       // to be within the valid range.
9397       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9398         const llvm::APInt &V = IL->getValue();
9399         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9400           return true;
9401       }
9402 
9403       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9404                           Sema::LookupOrdinaryName);
9405       if (S.LookupName(Result, S.getCurScope())) {
9406         NamedDecl *ND = Result.getFoundDecl();
9407         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9408           if (TD->getUnderlyingType() == IntendedTy)
9409             IntendedTy = S.Context.getTypedefType(TD);
9410       }
9411     }
9412   }
9413 
9414   // Special-case some of Darwin's platform-independence types by suggesting
9415   // casts to primitive types that are known to be large enough.
9416   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9417   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9418     QualType CastTy;
9419     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9420     if (!CastTy.isNull()) {
9421       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9422       // (long in ASTContext). Only complain to pedants.
9423       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9424           (AT.isSizeT() || AT.isPtrdiffT()) &&
9425           AT.matchesType(S.Context, CastTy))
9426         Match = ArgType::NoMatchPedantic;
9427       IntendedTy = CastTy;
9428       ShouldNotPrintDirectly = true;
9429     }
9430   }
9431 
9432   // We may be able to offer a FixItHint if it is a supported type.
9433   PrintfSpecifier fixedFS = FS;
9434   bool Success =
9435       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9436 
9437   if (Success) {
9438     // Get the fix string from the fixed format specifier
9439     SmallString<16> buf;
9440     llvm::raw_svector_ostream os(buf);
9441     fixedFS.toString(os);
9442 
9443     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9444 
9445     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9446       unsigned Diag;
9447       switch (Match) {
9448       case ArgType::Match: llvm_unreachable("expected non-matching");
9449       case ArgType::NoMatchPedantic:
9450         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9451         break;
9452       case ArgType::NoMatchTypeConfusion:
9453         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9454         break;
9455       case ArgType::NoMatch:
9456         Diag = diag::warn_format_conversion_argument_type_mismatch;
9457         break;
9458       }
9459 
9460       // In this case, the specifier is wrong and should be changed to match
9461       // the argument.
9462       EmitFormatDiagnostic(S.PDiag(Diag)
9463                                << AT.getRepresentativeTypeName(S.Context)
9464                                << IntendedTy << IsEnum << E->getSourceRange(),
9465                            E->getBeginLoc(),
9466                            /*IsStringLocation*/ false, SpecRange,
9467                            FixItHint::CreateReplacement(SpecRange, os.str()));
9468     } else {
9469       // The canonical type for formatting this value is different from the
9470       // actual type of the expression. (This occurs, for example, with Darwin's
9471       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9472       // should be printed as 'long' for 64-bit compatibility.)
9473       // Rather than emitting a normal format/argument mismatch, we want to
9474       // add a cast to the recommended type (and correct the format string
9475       // if necessary).
9476       SmallString<16> CastBuf;
9477       llvm::raw_svector_ostream CastFix(CastBuf);
9478       CastFix << "(";
9479       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9480       CastFix << ")";
9481 
9482       SmallVector<FixItHint,4> Hints;
9483       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9484         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9485 
9486       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9487         // If there's already a cast present, just replace it.
9488         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9489         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9490 
9491       } else if (!requiresParensToAddCast(E)) {
9492         // If the expression has high enough precedence,
9493         // just write the C-style cast.
9494         Hints.push_back(
9495             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9496       } else {
9497         // Otherwise, add parens around the expression as well as the cast.
9498         CastFix << "(";
9499         Hints.push_back(
9500             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9501 
9502         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9503         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9504       }
9505 
9506       if (ShouldNotPrintDirectly) {
9507         // The expression has a type that should not be printed directly.
9508         // We extract the name from the typedef because we don't want to show
9509         // the underlying type in the diagnostic.
9510         StringRef Name;
9511         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9512           Name = TypedefTy->getDecl()->getName();
9513         else
9514           Name = CastTyName;
9515         unsigned Diag = Match == ArgType::NoMatchPedantic
9516                             ? diag::warn_format_argument_needs_cast_pedantic
9517                             : diag::warn_format_argument_needs_cast;
9518         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9519                                            << E->getSourceRange(),
9520                              E->getBeginLoc(), /*IsStringLocation=*/false,
9521                              SpecRange, Hints);
9522       } else {
9523         // In this case, the expression could be printed using a different
9524         // specifier, but we've decided that the specifier is probably correct
9525         // and we should cast instead. Just use the normal warning message.
9526         EmitFormatDiagnostic(
9527             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9528                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9529                 << E->getSourceRange(),
9530             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9531       }
9532     }
9533   } else {
9534     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9535                                                    SpecifierLen);
9536     // Since the warning for passing non-POD types to variadic functions
9537     // was deferred until now, we emit a warning for non-POD
9538     // arguments here.
9539     switch (S.isValidVarArgType(ExprTy)) {
9540     case Sema::VAK_Valid:
9541     case Sema::VAK_ValidInCXX11: {
9542       unsigned Diag;
9543       switch (Match) {
9544       case ArgType::Match: llvm_unreachable("expected non-matching");
9545       case ArgType::NoMatchPedantic:
9546         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9547         break;
9548       case ArgType::NoMatchTypeConfusion:
9549         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9550         break;
9551       case ArgType::NoMatch:
9552         Diag = diag::warn_format_conversion_argument_type_mismatch;
9553         break;
9554       }
9555 
9556       EmitFormatDiagnostic(
9557           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9558                         << IsEnum << CSR << E->getSourceRange(),
9559           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9560       break;
9561     }
9562     case Sema::VAK_Undefined:
9563     case Sema::VAK_MSVCUndefined:
9564       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9565                                << S.getLangOpts().CPlusPlus11 << ExprTy
9566                                << CallType
9567                                << AT.getRepresentativeTypeName(S.Context) << CSR
9568                                << E->getSourceRange(),
9569                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9570       checkForCStrMembers(AT, E);
9571       break;
9572 
9573     case Sema::VAK_Invalid:
9574       if (ExprTy->isObjCObjectType())
9575         EmitFormatDiagnostic(
9576             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9577                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9578                 << AT.getRepresentativeTypeName(S.Context) << CSR
9579                 << E->getSourceRange(),
9580             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9581       else
9582         // FIXME: If this is an initializer list, suggest removing the braces
9583         // or inserting a cast to the target type.
9584         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9585             << isa<InitListExpr>(E) << ExprTy << CallType
9586             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9587       break;
9588     }
9589 
9590     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9591            "format string specifier index out of range");
9592     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9593   }
9594 
9595   return true;
9596 }
9597 
9598 //===--- CHECK: Scanf format string checking ------------------------------===//
9599 
9600 namespace {
9601 
9602 class CheckScanfHandler : public CheckFormatHandler {
9603 public:
9604   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9605                     const Expr *origFormatExpr, Sema::FormatStringType type,
9606                     unsigned firstDataArg, unsigned numDataArgs,
9607                     const char *beg, bool hasVAListArg,
9608                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9609                     bool inFunctionCall, Sema::VariadicCallType CallType,
9610                     llvm::SmallBitVector &CheckedVarArgs,
9611                     UncoveredArgHandler &UncoveredArg)
9612       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9613                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9614                            inFunctionCall, CallType, CheckedVarArgs,
9615                            UncoveredArg) {}
9616 
9617   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9618                             const char *startSpecifier,
9619                             unsigned specifierLen) override;
9620 
9621   bool HandleInvalidScanfConversionSpecifier(
9622           const analyze_scanf::ScanfSpecifier &FS,
9623           const char *startSpecifier,
9624           unsigned specifierLen) override;
9625 
9626   void HandleIncompleteScanList(const char *start, const char *end) override;
9627 };
9628 
9629 } // namespace
9630 
9631 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9632                                                  const char *end) {
9633   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9634                        getLocationOfByte(end), /*IsStringLocation*/true,
9635                        getSpecifierRange(start, end - start));
9636 }
9637 
9638 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9639                                         const analyze_scanf::ScanfSpecifier &FS,
9640                                         const char *startSpecifier,
9641                                         unsigned specifierLen) {
9642   const analyze_scanf::ScanfConversionSpecifier &CS =
9643     FS.getConversionSpecifier();
9644 
9645   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9646                                           getLocationOfByte(CS.getStart()),
9647                                           startSpecifier, specifierLen,
9648                                           CS.getStart(), CS.getLength());
9649 }
9650 
9651 bool CheckScanfHandler::HandleScanfSpecifier(
9652                                        const analyze_scanf::ScanfSpecifier &FS,
9653                                        const char *startSpecifier,
9654                                        unsigned specifierLen) {
9655   using namespace analyze_scanf;
9656   using namespace analyze_format_string;
9657 
9658   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9659 
9660   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9661   // be used to decide if we are using positional arguments consistently.
9662   if (FS.consumesDataArgument()) {
9663     if (atFirstArg) {
9664       atFirstArg = false;
9665       usesPositionalArgs = FS.usesPositionalArg();
9666     }
9667     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9668       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9669                                         startSpecifier, specifierLen);
9670       return false;
9671     }
9672   }
9673 
9674   // Check if the field with is non-zero.
9675   const OptionalAmount &Amt = FS.getFieldWidth();
9676   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9677     if (Amt.getConstantAmount() == 0) {
9678       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9679                                                    Amt.getConstantLength());
9680       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9681                            getLocationOfByte(Amt.getStart()),
9682                            /*IsStringLocation*/true, R,
9683                            FixItHint::CreateRemoval(R));
9684     }
9685   }
9686 
9687   if (!FS.consumesDataArgument()) {
9688     // FIXME: Technically specifying a precision or field width here
9689     // makes no sense.  Worth issuing a warning at some point.
9690     return true;
9691   }
9692 
9693   // Consume the argument.
9694   unsigned argIndex = FS.getArgIndex();
9695   if (argIndex < NumDataArgs) {
9696       // The check to see if the argIndex is valid will come later.
9697       // We set the bit here because we may exit early from this
9698       // function if we encounter some other error.
9699     CoveredArgs.set(argIndex);
9700   }
9701 
9702   // Check the length modifier is valid with the given conversion specifier.
9703   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9704                                  S.getLangOpts()))
9705     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9706                                 diag::warn_format_nonsensical_length);
9707   else if (!FS.hasStandardLengthModifier())
9708     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9709   else if (!FS.hasStandardLengthConversionCombination())
9710     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9711                                 diag::warn_format_non_standard_conversion_spec);
9712 
9713   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9714     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9715 
9716   // The remaining checks depend on the data arguments.
9717   if (HasVAListArg)
9718     return true;
9719 
9720   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9721     return false;
9722 
9723   // Check that the argument type matches the format specifier.
9724   const Expr *Ex = getDataArg(argIndex);
9725   if (!Ex)
9726     return true;
9727 
9728   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9729 
9730   if (!AT.isValid()) {
9731     return true;
9732   }
9733 
9734   analyze_format_string::ArgType::MatchKind Match =
9735       AT.matchesType(S.Context, Ex->getType());
9736   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9737   if (Match == analyze_format_string::ArgType::Match)
9738     return true;
9739 
9740   ScanfSpecifier fixedFS = FS;
9741   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9742                                  S.getLangOpts(), S.Context);
9743 
9744   unsigned Diag =
9745       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9746                : diag::warn_format_conversion_argument_type_mismatch;
9747 
9748   if (Success) {
9749     // Get the fix string from the fixed format specifier.
9750     SmallString<128> buf;
9751     llvm::raw_svector_ostream os(buf);
9752     fixedFS.toString(os);
9753 
9754     EmitFormatDiagnostic(
9755         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9756                       << Ex->getType() << false << Ex->getSourceRange(),
9757         Ex->getBeginLoc(),
9758         /*IsStringLocation*/ false,
9759         getSpecifierRange(startSpecifier, specifierLen),
9760         FixItHint::CreateReplacement(
9761             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9762   } else {
9763     EmitFormatDiagnostic(S.PDiag(Diag)
9764                              << AT.getRepresentativeTypeName(S.Context)
9765                              << Ex->getType() << false << Ex->getSourceRange(),
9766                          Ex->getBeginLoc(),
9767                          /*IsStringLocation*/ false,
9768                          getSpecifierRange(startSpecifier, specifierLen));
9769   }
9770 
9771   return true;
9772 }
9773 
9774 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9775                               const Expr *OrigFormatExpr,
9776                               ArrayRef<const Expr *> Args,
9777                               bool HasVAListArg, unsigned format_idx,
9778                               unsigned firstDataArg,
9779                               Sema::FormatStringType Type,
9780                               bool inFunctionCall,
9781                               Sema::VariadicCallType CallType,
9782                               llvm::SmallBitVector &CheckedVarArgs,
9783                               UncoveredArgHandler &UncoveredArg,
9784                               bool IgnoreStringsWithoutSpecifiers) {
9785   // CHECK: is the format string a wide literal?
9786   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9787     CheckFormatHandler::EmitFormatDiagnostic(
9788         S, inFunctionCall, Args[format_idx],
9789         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9790         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9791     return;
9792   }
9793 
9794   // Str - The format string.  NOTE: this is NOT null-terminated!
9795   StringRef StrRef = FExpr->getString();
9796   const char *Str = StrRef.data();
9797   // Account for cases where the string literal is truncated in a declaration.
9798   const ConstantArrayType *T =
9799     S.Context.getAsConstantArrayType(FExpr->getType());
9800   assert(T && "String literal not of constant array type!");
9801   size_t TypeSize = T->getSize().getZExtValue();
9802   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9803   const unsigned numDataArgs = Args.size() - firstDataArg;
9804 
9805   if (IgnoreStringsWithoutSpecifiers &&
9806       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9807           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9808     return;
9809 
9810   // Emit a warning if the string literal is truncated and does not contain an
9811   // embedded null character.
9812   if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9813     CheckFormatHandler::EmitFormatDiagnostic(
9814         S, inFunctionCall, Args[format_idx],
9815         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9816         FExpr->getBeginLoc(),
9817         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9818     return;
9819   }
9820 
9821   // CHECK: empty format string?
9822   if (StrLen == 0 && numDataArgs > 0) {
9823     CheckFormatHandler::EmitFormatDiagnostic(
9824         S, inFunctionCall, Args[format_idx],
9825         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9826         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9827     return;
9828   }
9829 
9830   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9831       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9832       Type == Sema::FST_OSTrace) {
9833     CheckPrintfHandler H(
9834         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9835         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9836         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9837         CheckedVarArgs, UncoveredArg);
9838 
9839     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9840                                                   S.getLangOpts(),
9841                                                   S.Context.getTargetInfo(),
9842                                             Type == Sema::FST_FreeBSDKPrintf))
9843       H.DoneProcessing();
9844   } else if (Type == Sema::FST_Scanf) {
9845     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9846                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9847                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9848 
9849     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9850                                                  S.getLangOpts(),
9851                                                  S.Context.getTargetInfo()))
9852       H.DoneProcessing();
9853   } // TODO: handle other formats
9854 }
9855 
9856 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9857   // Str - The format string.  NOTE: this is NOT null-terminated!
9858   StringRef StrRef = FExpr->getString();
9859   const char *Str = StrRef.data();
9860   // Account for cases where the string literal is truncated in a declaration.
9861   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9862   assert(T && "String literal not of constant array type!");
9863   size_t TypeSize = T->getSize().getZExtValue();
9864   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9865   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9866                                                          getLangOpts(),
9867                                                          Context.getTargetInfo());
9868 }
9869 
9870 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9871 
9872 // Returns the related absolute value function that is larger, of 0 if one
9873 // does not exist.
9874 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9875   switch (AbsFunction) {
9876   default:
9877     return 0;
9878 
9879   case Builtin::BI__builtin_abs:
9880     return Builtin::BI__builtin_labs;
9881   case Builtin::BI__builtin_labs:
9882     return Builtin::BI__builtin_llabs;
9883   case Builtin::BI__builtin_llabs:
9884     return 0;
9885 
9886   case Builtin::BI__builtin_fabsf:
9887     return Builtin::BI__builtin_fabs;
9888   case Builtin::BI__builtin_fabs:
9889     return Builtin::BI__builtin_fabsl;
9890   case Builtin::BI__builtin_fabsl:
9891     return 0;
9892 
9893   case Builtin::BI__builtin_cabsf:
9894     return Builtin::BI__builtin_cabs;
9895   case Builtin::BI__builtin_cabs:
9896     return Builtin::BI__builtin_cabsl;
9897   case Builtin::BI__builtin_cabsl:
9898     return 0;
9899 
9900   case Builtin::BIabs:
9901     return Builtin::BIlabs;
9902   case Builtin::BIlabs:
9903     return Builtin::BIllabs;
9904   case Builtin::BIllabs:
9905     return 0;
9906 
9907   case Builtin::BIfabsf:
9908     return Builtin::BIfabs;
9909   case Builtin::BIfabs:
9910     return Builtin::BIfabsl;
9911   case Builtin::BIfabsl:
9912     return 0;
9913 
9914   case Builtin::BIcabsf:
9915    return Builtin::BIcabs;
9916   case Builtin::BIcabs:
9917     return Builtin::BIcabsl;
9918   case Builtin::BIcabsl:
9919     return 0;
9920   }
9921 }
9922 
9923 // Returns the argument type of the absolute value function.
9924 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9925                                              unsigned AbsType) {
9926   if (AbsType == 0)
9927     return QualType();
9928 
9929   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9930   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9931   if (Error != ASTContext::GE_None)
9932     return QualType();
9933 
9934   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9935   if (!FT)
9936     return QualType();
9937 
9938   if (FT->getNumParams() != 1)
9939     return QualType();
9940 
9941   return FT->getParamType(0);
9942 }
9943 
9944 // Returns the best absolute value function, or zero, based on type and
9945 // current absolute value function.
9946 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9947                                    unsigned AbsFunctionKind) {
9948   unsigned BestKind = 0;
9949   uint64_t ArgSize = Context.getTypeSize(ArgType);
9950   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9951        Kind = getLargerAbsoluteValueFunction(Kind)) {
9952     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9953     if (Context.getTypeSize(ParamType) >= ArgSize) {
9954       if (BestKind == 0)
9955         BestKind = Kind;
9956       else if (Context.hasSameType(ParamType, ArgType)) {
9957         BestKind = Kind;
9958         break;
9959       }
9960     }
9961   }
9962   return BestKind;
9963 }
9964 
9965 enum AbsoluteValueKind {
9966   AVK_Integer,
9967   AVK_Floating,
9968   AVK_Complex
9969 };
9970 
9971 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9972   if (T->isIntegralOrEnumerationType())
9973     return AVK_Integer;
9974   if (T->isRealFloatingType())
9975     return AVK_Floating;
9976   if (T->isAnyComplexType())
9977     return AVK_Complex;
9978 
9979   llvm_unreachable("Type not integer, floating, or complex");
9980 }
9981 
9982 // Changes the absolute value function to a different type.  Preserves whether
9983 // the function is a builtin.
9984 static unsigned changeAbsFunction(unsigned AbsKind,
9985                                   AbsoluteValueKind ValueKind) {
9986   switch (ValueKind) {
9987   case AVK_Integer:
9988     switch (AbsKind) {
9989     default:
9990       return 0;
9991     case Builtin::BI__builtin_fabsf:
9992     case Builtin::BI__builtin_fabs:
9993     case Builtin::BI__builtin_fabsl:
9994     case Builtin::BI__builtin_cabsf:
9995     case Builtin::BI__builtin_cabs:
9996     case Builtin::BI__builtin_cabsl:
9997       return Builtin::BI__builtin_abs;
9998     case Builtin::BIfabsf:
9999     case Builtin::BIfabs:
10000     case Builtin::BIfabsl:
10001     case Builtin::BIcabsf:
10002     case Builtin::BIcabs:
10003     case Builtin::BIcabsl:
10004       return Builtin::BIabs;
10005     }
10006   case AVK_Floating:
10007     switch (AbsKind) {
10008     default:
10009       return 0;
10010     case Builtin::BI__builtin_abs:
10011     case Builtin::BI__builtin_labs:
10012     case Builtin::BI__builtin_llabs:
10013     case Builtin::BI__builtin_cabsf:
10014     case Builtin::BI__builtin_cabs:
10015     case Builtin::BI__builtin_cabsl:
10016       return Builtin::BI__builtin_fabsf;
10017     case Builtin::BIabs:
10018     case Builtin::BIlabs:
10019     case Builtin::BIllabs:
10020     case Builtin::BIcabsf:
10021     case Builtin::BIcabs:
10022     case Builtin::BIcabsl:
10023       return Builtin::BIfabsf;
10024     }
10025   case AVK_Complex:
10026     switch (AbsKind) {
10027     default:
10028       return 0;
10029     case Builtin::BI__builtin_abs:
10030     case Builtin::BI__builtin_labs:
10031     case Builtin::BI__builtin_llabs:
10032     case Builtin::BI__builtin_fabsf:
10033     case Builtin::BI__builtin_fabs:
10034     case Builtin::BI__builtin_fabsl:
10035       return Builtin::BI__builtin_cabsf;
10036     case Builtin::BIabs:
10037     case Builtin::BIlabs:
10038     case Builtin::BIllabs:
10039     case Builtin::BIfabsf:
10040     case Builtin::BIfabs:
10041     case Builtin::BIfabsl:
10042       return Builtin::BIcabsf;
10043     }
10044   }
10045   llvm_unreachable("Unable to convert function");
10046 }
10047 
10048 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10049   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10050   if (!FnInfo)
10051     return 0;
10052 
10053   switch (FDecl->getBuiltinID()) {
10054   default:
10055     return 0;
10056   case Builtin::BI__builtin_abs:
10057   case Builtin::BI__builtin_fabs:
10058   case Builtin::BI__builtin_fabsf:
10059   case Builtin::BI__builtin_fabsl:
10060   case Builtin::BI__builtin_labs:
10061   case Builtin::BI__builtin_llabs:
10062   case Builtin::BI__builtin_cabs:
10063   case Builtin::BI__builtin_cabsf:
10064   case Builtin::BI__builtin_cabsl:
10065   case Builtin::BIabs:
10066   case Builtin::BIlabs:
10067   case Builtin::BIllabs:
10068   case Builtin::BIfabs:
10069   case Builtin::BIfabsf:
10070   case Builtin::BIfabsl:
10071   case Builtin::BIcabs:
10072   case Builtin::BIcabsf:
10073   case Builtin::BIcabsl:
10074     return FDecl->getBuiltinID();
10075   }
10076   llvm_unreachable("Unknown Builtin type");
10077 }
10078 
10079 // If the replacement is valid, emit a note with replacement function.
10080 // Additionally, suggest including the proper header if not already included.
10081 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10082                             unsigned AbsKind, QualType ArgType) {
10083   bool EmitHeaderHint = true;
10084   const char *HeaderName = nullptr;
10085   const char *FunctionName = nullptr;
10086   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10087     FunctionName = "std::abs";
10088     if (ArgType->isIntegralOrEnumerationType()) {
10089       HeaderName = "cstdlib";
10090     } else if (ArgType->isRealFloatingType()) {
10091       HeaderName = "cmath";
10092     } else {
10093       llvm_unreachable("Invalid Type");
10094     }
10095 
10096     // Lookup all std::abs
10097     if (NamespaceDecl *Std = S.getStdNamespace()) {
10098       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10099       R.suppressDiagnostics();
10100       S.LookupQualifiedName(R, Std);
10101 
10102       for (const auto *I : R) {
10103         const FunctionDecl *FDecl = nullptr;
10104         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10105           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10106         } else {
10107           FDecl = dyn_cast<FunctionDecl>(I);
10108         }
10109         if (!FDecl)
10110           continue;
10111 
10112         // Found std::abs(), check that they are the right ones.
10113         if (FDecl->getNumParams() != 1)
10114           continue;
10115 
10116         // Check that the parameter type can handle the argument.
10117         QualType ParamType = FDecl->getParamDecl(0)->getType();
10118         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10119             S.Context.getTypeSize(ArgType) <=
10120                 S.Context.getTypeSize(ParamType)) {
10121           // Found a function, don't need the header hint.
10122           EmitHeaderHint = false;
10123           break;
10124         }
10125       }
10126     }
10127   } else {
10128     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10129     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10130 
10131     if (HeaderName) {
10132       DeclarationName DN(&S.Context.Idents.get(FunctionName));
10133       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10134       R.suppressDiagnostics();
10135       S.LookupName(R, S.getCurScope());
10136 
10137       if (R.isSingleResult()) {
10138         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10139         if (FD && FD->getBuiltinID() == AbsKind) {
10140           EmitHeaderHint = false;
10141         } else {
10142           return;
10143         }
10144       } else if (!R.empty()) {
10145         return;
10146       }
10147     }
10148   }
10149 
10150   S.Diag(Loc, diag::note_replace_abs_function)
10151       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10152 
10153   if (!HeaderName)
10154     return;
10155 
10156   if (!EmitHeaderHint)
10157     return;
10158 
10159   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10160                                                     << FunctionName;
10161 }
10162 
10163 template <std::size_t StrLen>
10164 static bool IsStdFunction(const FunctionDecl *FDecl,
10165                           const char (&Str)[StrLen]) {
10166   if (!FDecl)
10167     return false;
10168   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10169     return false;
10170   if (!FDecl->isInStdNamespace())
10171     return false;
10172 
10173   return true;
10174 }
10175 
10176 // Warn when using the wrong abs() function.
10177 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10178                                       const FunctionDecl *FDecl) {
10179   if (Call->getNumArgs() != 1)
10180     return;
10181 
10182   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10183   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10184   if (AbsKind == 0 && !IsStdAbs)
10185     return;
10186 
10187   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10188   QualType ParamType = Call->getArg(0)->getType();
10189 
10190   // Unsigned types cannot be negative.  Suggest removing the absolute value
10191   // function call.
10192   if (ArgType->isUnsignedIntegerType()) {
10193     const char *FunctionName =
10194         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10195     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10196     Diag(Call->getExprLoc(), diag::note_remove_abs)
10197         << FunctionName
10198         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10199     return;
10200   }
10201 
10202   // Taking the absolute value of a pointer is very suspicious, they probably
10203   // wanted to index into an array, dereference a pointer, call a function, etc.
10204   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10205     unsigned DiagType = 0;
10206     if (ArgType->isFunctionType())
10207       DiagType = 1;
10208     else if (ArgType->isArrayType())
10209       DiagType = 2;
10210 
10211     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10212     return;
10213   }
10214 
10215   // std::abs has overloads which prevent most of the absolute value problems
10216   // from occurring.
10217   if (IsStdAbs)
10218     return;
10219 
10220   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10221   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10222 
10223   // The argument and parameter are the same kind.  Check if they are the right
10224   // size.
10225   if (ArgValueKind == ParamValueKind) {
10226     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10227       return;
10228 
10229     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10230     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10231         << FDecl << ArgType << ParamType;
10232 
10233     if (NewAbsKind == 0)
10234       return;
10235 
10236     emitReplacement(*this, Call->getExprLoc(),
10237                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10238     return;
10239   }
10240 
10241   // ArgValueKind != ParamValueKind
10242   // The wrong type of absolute value function was used.  Attempt to find the
10243   // proper one.
10244   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10245   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10246   if (NewAbsKind == 0)
10247     return;
10248 
10249   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10250       << FDecl << ParamValueKind << ArgValueKind;
10251 
10252   emitReplacement(*this, Call->getExprLoc(),
10253                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10254 }
10255 
10256 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10257 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10258                                 const FunctionDecl *FDecl) {
10259   if (!Call || !FDecl) return;
10260 
10261   // Ignore template specializations and macros.
10262   if (inTemplateInstantiation()) return;
10263   if (Call->getExprLoc().isMacroID()) return;
10264 
10265   // Only care about the one template argument, two function parameter std::max
10266   if (Call->getNumArgs() != 2) return;
10267   if (!IsStdFunction(FDecl, "max")) return;
10268   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10269   if (!ArgList) return;
10270   if (ArgList->size() != 1) return;
10271 
10272   // Check that template type argument is unsigned integer.
10273   const auto& TA = ArgList->get(0);
10274   if (TA.getKind() != TemplateArgument::Type) return;
10275   QualType ArgType = TA.getAsType();
10276   if (!ArgType->isUnsignedIntegerType()) return;
10277 
10278   // See if either argument is a literal zero.
10279   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10280     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10281     if (!MTE) return false;
10282     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10283     if (!Num) return false;
10284     if (Num->getValue() != 0) return false;
10285     return true;
10286   };
10287 
10288   const Expr *FirstArg = Call->getArg(0);
10289   const Expr *SecondArg = Call->getArg(1);
10290   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10291   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10292 
10293   // Only warn when exactly one argument is zero.
10294   if (IsFirstArgZero == IsSecondArgZero) return;
10295 
10296   SourceRange FirstRange = FirstArg->getSourceRange();
10297   SourceRange SecondRange = SecondArg->getSourceRange();
10298 
10299   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10300 
10301   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10302       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10303 
10304   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10305   SourceRange RemovalRange;
10306   if (IsFirstArgZero) {
10307     RemovalRange = SourceRange(FirstRange.getBegin(),
10308                                SecondRange.getBegin().getLocWithOffset(-1));
10309   } else {
10310     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10311                                SecondRange.getEnd());
10312   }
10313 
10314   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10315         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10316         << FixItHint::CreateRemoval(RemovalRange);
10317 }
10318 
10319 //===--- CHECK: Standard memory functions ---------------------------------===//
10320 
10321 /// Takes the expression passed to the size_t parameter of functions
10322 /// such as memcmp, strncat, etc and warns if it's a comparison.
10323 ///
10324 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10325 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10326                                            IdentifierInfo *FnName,
10327                                            SourceLocation FnLoc,
10328                                            SourceLocation RParenLoc) {
10329   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10330   if (!Size)
10331     return false;
10332 
10333   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10334   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10335     return false;
10336 
10337   SourceRange SizeRange = Size->getSourceRange();
10338   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10339       << SizeRange << FnName;
10340   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10341       << FnName
10342       << FixItHint::CreateInsertion(
10343              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10344       << FixItHint::CreateRemoval(RParenLoc);
10345   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10346       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10347       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10348                                     ")");
10349 
10350   return true;
10351 }
10352 
10353 /// Determine whether the given type is or contains a dynamic class type
10354 /// (e.g., whether it has a vtable).
10355 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10356                                                      bool &IsContained) {
10357   // Look through array types while ignoring qualifiers.
10358   const Type *Ty = T->getBaseElementTypeUnsafe();
10359   IsContained = false;
10360 
10361   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10362   RD = RD ? RD->getDefinition() : nullptr;
10363   if (!RD || RD->isInvalidDecl())
10364     return nullptr;
10365 
10366   if (RD->isDynamicClass())
10367     return RD;
10368 
10369   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10370   // It's impossible for a class to transitively contain itself by value, so
10371   // infinite recursion is impossible.
10372   for (auto *FD : RD->fields()) {
10373     bool SubContained;
10374     if (const CXXRecordDecl *ContainedRD =
10375             getContainedDynamicClass(FD->getType(), SubContained)) {
10376       IsContained = true;
10377       return ContainedRD;
10378     }
10379   }
10380 
10381   return nullptr;
10382 }
10383 
10384 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10385   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10386     if (Unary->getKind() == UETT_SizeOf)
10387       return Unary;
10388   return nullptr;
10389 }
10390 
10391 /// If E is a sizeof expression, returns its argument expression,
10392 /// otherwise returns NULL.
10393 static const Expr *getSizeOfExprArg(const Expr *E) {
10394   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10395     if (!SizeOf->isArgumentType())
10396       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10397   return nullptr;
10398 }
10399 
10400 /// If E is a sizeof expression, returns its argument type.
10401 static QualType getSizeOfArgType(const Expr *E) {
10402   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10403     return SizeOf->getTypeOfArgument();
10404   return QualType();
10405 }
10406 
10407 namespace {
10408 
10409 struct SearchNonTrivialToInitializeField
10410     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10411   using Super =
10412       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10413 
10414   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10415 
10416   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10417                      SourceLocation SL) {
10418     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10419       asDerived().visitArray(PDIK, AT, SL);
10420       return;
10421     }
10422 
10423     Super::visitWithKind(PDIK, FT, SL);
10424   }
10425 
10426   void visitARCStrong(QualType FT, SourceLocation SL) {
10427     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10428   }
10429   void visitARCWeak(QualType FT, SourceLocation SL) {
10430     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10431   }
10432   void visitStruct(QualType FT, SourceLocation SL) {
10433     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10434       visit(FD->getType(), FD->getLocation());
10435   }
10436   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10437                   const ArrayType *AT, SourceLocation SL) {
10438     visit(getContext().getBaseElementType(AT), SL);
10439   }
10440   void visitTrivial(QualType FT, SourceLocation SL) {}
10441 
10442   static void diag(QualType RT, const Expr *E, Sema &S) {
10443     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10444   }
10445 
10446   ASTContext &getContext() { return S.getASTContext(); }
10447 
10448   const Expr *E;
10449   Sema &S;
10450 };
10451 
10452 struct SearchNonTrivialToCopyField
10453     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10454   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10455 
10456   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10457 
10458   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10459                      SourceLocation SL) {
10460     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10461       asDerived().visitArray(PCK, AT, SL);
10462       return;
10463     }
10464 
10465     Super::visitWithKind(PCK, FT, SL);
10466   }
10467 
10468   void visitARCStrong(QualType FT, SourceLocation SL) {
10469     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10470   }
10471   void visitARCWeak(QualType FT, SourceLocation SL) {
10472     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10473   }
10474   void visitStruct(QualType FT, SourceLocation SL) {
10475     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10476       visit(FD->getType(), FD->getLocation());
10477   }
10478   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10479                   SourceLocation SL) {
10480     visit(getContext().getBaseElementType(AT), SL);
10481   }
10482   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10483                 SourceLocation SL) {}
10484   void visitTrivial(QualType FT, SourceLocation SL) {}
10485   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10486 
10487   static void diag(QualType RT, const Expr *E, Sema &S) {
10488     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10489   }
10490 
10491   ASTContext &getContext() { return S.getASTContext(); }
10492 
10493   const Expr *E;
10494   Sema &S;
10495 };
10496 
10497 }
10498 
10499 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10500 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10501   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10502 
10503   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10504     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10505       return false;
10506 
10507     return doesExprLikelyComputeSize(BO->getLHS()) ||
10508            doesExprLikelyComputeSize(BO->getRHS());
10509   }
10510 
10511   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10512 }
10513 
10514 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10515 ///
10516 /// \code
10517 ///   #define MACRO 0
10518 ///   foo(MACRO);
10519 ///   foo(0);
10520 /// \endcode
10521 ///
10522 /// This should return true for the first call to foo, but not for the second
10523 /// (regardless of whether foo is a macro or function).
10524 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10525                                         SourceLocation CallLoc,
10526                                         SourceLocation ArgLoc) {
10527   if (!CallLoc.isMacroID())
10528     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10529 
10530   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10531          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10532 }
10533 
10534 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10535 /// last two arguments transposed.
10536 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10537   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10538     return;
10539 
10540   const Expr *SizeArg =
10541     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10542 
10543   auto isLiteralZero = [](const Expr *E) {
10544     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10545   };
10546 
10547   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10548   SourceLocation CallLoc = Call->getRParenLoc();
10549   SourceManager &SM = S.getSourceManager();
10550   if (isLiteralZero(SizeArg) &&
10551       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10552 
10553     SourceLocation DiagLoc = SizeArg->getExprLoc();
10554 
10555     // Some platforms #define bzero to __builtin_memset. See if this is the
10556     // case, and if so, emit a better diagnostic.
10557     if (BId == Builtin::BIbzero ||
10558         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10559                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10560       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10561       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10562     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10563       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10564       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10565     }
10566     return;
10567   }
10568 
10569   // If the second argument to a memset is a sizeof expression and the third
10570   // isn't, this is also likely an error. This should catch
10571   // 'memset(buf, sizeof(buf), 0xff)'.
10572   if (BId == Builtin::BImemset &&
10573       doesExprLikelyComputeSize(Call->getArg(1)) &&
10574       !doesExprLikelyComputeSize(Call->getArg(2))) {
10575     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10576     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10577     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10578     return;
10579   }
10580 }
10581 
10582 /// Check for dangerous or invalid arguments to memset().
10583 ///
10584 /// This issues warnings on known problematic, dangerous or unspecified
10585 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10586 /// function calls.
10587 ///
10588 /// \param Call The call expression to diagnose.
10589 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10590                                    unsigned BId,
10591                                    IdentifierInfo *FnName) {
10592   assert(BId != 0);
10593 
10594   // It is possible to have a non-standard definition of memset.  Validate
10595   // we have enough arguments, and if not, abort further checking.
10596   unsigned ExpectedNumArgs =
10597       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10598   if (Call->getNumArgs() < ExpectedNumArgs)
10599     return;
10600 
10601   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10602                       BId == Builtin::BIstrndup ? 1 : 2);
10603   unsigned LenArg =
10604       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10605   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10606 
10607   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10608                                      Call->getBeginLoc(), Call->getRParenLoc()))
10609     return;
10610 
10611   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10612   CheckMemaccessSize(*this, BId, Call);
10613 
10614   // We have special checking when the length is a sizeof expression.
10615   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10616   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10617   llvm::FoldingSetNodeID SizeOfArgID;
10618 
10619   // Although widely used, 'bzero' is not a standard function. Be more strict
10620   // with the argument types before allowing diagnostics and only allow the
10621   // form bzero(ptr, sizeof(...)).
10622   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10623   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10624     return;
10625 
10626   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10627     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10628     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10629 
10630     QualType DestTy = Dest->getType();
10631     QualType PointeeTy;
10632     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10633       PointeeTy = DestPtrTy->getPointeeType();
10634 
10635       // Never warn about void type pointers. This can be used to suppress
10636       // false positives.
10637       if (PointeeTy->isVoidType())
10638         continue;
10639 
10640       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10641       // actually comparing the expressions for equality. Because computing the
10642       // expression IDs can be expensive, we only do this if the diagnostic is
10643       // enabled.
10644       if (SizeOfArg &&
10645           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10646                            SizeOfArg->getExprLoc())) {
10647         // We only compute IDs for expressions if the warning is enabled, and
10648         // cache the sizeof arg's ID.
10649         if (SizeOfArgID == llvm::FoldingSetNodeID())
10650           SizeOfArg->Profile(SizeOfArgID, Context, true);
10651         llvm::FoldingSetNodeID DestID;
10652         Dest->Profile(DestID, Context, true);
10653         if (DestID == SizeOfArgID) {
10654           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10655           //       over sizeof(src) as well.
10656           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10657           StringRef ReadableName = FnName->getName();
10658 
10659           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10660             if (UnaryOp->getOpcode() == UO_AddrOf)
10661               ActionIdx = 1; // If its an address-of operator, just remove it.
10662           if (!PointeeTy->isIncompleteType() &&
10663               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10664             ActionIdx = 2; // If the pointee's size is sizeof(char),
10665                            // suggest an explicit length.
10666 
10667           // If the function is defined as a builtin macro, do not show macro
10668           // expansion.
10669           SourceLocation SL = SizeOfArg->getExprLoc();
10670           SourceRange DSR = Dest->getSourceRange();
10671           SourceRange SSR = SizeOfArg->getSourceRange();
10672           SourceManager &SM = getSourceManager();
10673 
10674           if (SM.isMacroArgExpansion(SL)) {
10675             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10676             SL = SM.getSpellingLoc(SL);
10677             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10678                              SM.getSpellingLoc(DSR.getEnd()));
10679             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10680                              SM.getSpellingLoc(SSR.getEnd()));
10681           }
10682 
10683           DiagRuntimeBehavior(SL, SizeOfArg,
10684                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10685                                 << ReadableName
10686                                 << PointeeTy
10687                                 << DestTy
10688                                 << DSR
10689                                 << SSR);
10690           DiagRuntimeBehavior(SL, SizeOfArg,
10691                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10692                                 << ActionIdx
10693                                 << SSR);
10694 
10695           break;
10696         }
10697       }
10698 
10699       // Also check for cases where the sizeof argument is the exact same
10700       // type as the memory argument, and where it points to a user-defined
10701       // record type.
10702       if (SizeOfArgTy != QualType()) {
10703         if (PointeeTy->isRecordType() &&
10704             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10705           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10706                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10707                                 << FnName << SizeOfArgTy << ArgIdx
10708                                 << PointeeTy << Dest->getSourceRange()
10709                                 << LenExpr->getSourceRange());
10710           break;
10711         }
10712       }
10713     } else if (DestTy->isArrayType()) {
10714       PointeeTy = DestTy;
10715     }
10716 
10717     if (PointeeTy == QualType())
10718       continue;
10719 
10720     // Always complain about dynamic classes.
10721     bool IsContained;
10722     if (const CXXRecordDecl *ContainedRD =
10723             getContainedDynamicClass(PointeeTy, IsContained)) {
10724 
10725       unsigned OperationType = 0;
10726       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10727       // "overwritten" if we're warning about the destination for any call
10728       // but memcmp; otherwise a verb appropriate to the call.
10729       if (ArgIdx != 0 || IsCmp) {
10730         if (BId == Builtin::BImemcpy)
10731           OperationType = 1;
10732         else if(BId == Builtin::BImemmove)
10733           OperationType = 2;
10734         else if (IsCmp)
10735           OperationType = 3;
10736       }
10737 
10738       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10739                           PDiag(diag::warn_dyn_class_memaccess)
10740                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10741                               << IsContained << ContainedRD << OperationType
10742                               << Call->getCallee()->getSourceRange());
10743     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10744              BId != Builtin::BImemset)
10745       DiagRuntimeBehavior(
10746         Dest->getExprLoc(), Dest,
10747         PDiag(diag::warn_arc_object_memaccess)
10748           << ArgIdx << FnName << PointeeTy
10749           << Call->getCallee()->getSourceRange());
10750     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10751       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10752           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10753         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10754                             PDiag(diag::warn_cstruct_memaccess)
10755                                 << ArgIdx << FnName << PointeeTy << 0);
10756         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10757       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10758                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10759         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10760                             PDiag(diag::warn_cstruct_memaccess)
10761                                 << ArgIdx << FnName << PointeeTy << 1);
10762         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10763       } else {
10764         continue;
10765       }
10766     } else
10767       continue;
10768 
10769     DiagRuntimeBehavior(
10770       Dest->getExprLoc(), Dest,
10771       PDiag(diag::note_bad_memaccess_silence)
10772         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10773     break;
10774   }
10775 }
10776 
10777 // A little helper routine: ignore addition and subtraction of integer literals.
10778 // This intentionally does not ignore all integer constant expressions because
10779 // we don't want to remove sizeof().
10780 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10781   Ex = Ex->IgnoreParenCasts();
10782 
10783   while (true) {
10784     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10785     if (!BO || !BO->isAdditiveOp())
10786       break;
10787 
10788     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10789     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10790 
10791     if (isa<IntegerLiteral>(RHS))
10792       Ex = LHS;
10793     else if (isa<IntegerLiteral>(LHS))
10794       Ex = RHS;
10795     else
10796       break;
10797   }
10798 
10799   return Ex;
10800 }
10801 
10802 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10803                                                       ASTContext &Context) {
10804   // Only handle constant-sized or VLAs, but not flexible members.
10805   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10806     // Only issue the FIXIT for arrays of size > 1.
10807     if (CAT->getSize().getSExtValue() <= 1)
10808       return false;
10809   } else if (!Ty->isVariableArrayType()) {
10810     return false;
10811   }
10812   return true;
10813 }
10814 
10815 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10816 // be the size of the source, instead of the destination.
10817 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10818                                     IdentifierInfo *FnName) {
10819 
10820   // Don't crash if the user has the wrong number of arguments
10821   unsigned NumArgs = Call->getNumArgs();
10822   if ((NumArgs != 3) && (NumArgs != 4))
10823     return;
10824 
10825   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10826   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10827   const Expr *CompareWithSrc = nullptr;
10828 
10829   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10830                                      Call->getBeginLoc(), Call->getRParenLoc()))
10831     return;
10832 
10833   // Look for 'strlcpy(dst, x, sizeof(x))'
10834   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10835     CompareWithSrc = Ex;
10836   else {
10837     // Look for 'strlcpy(dst, x, strlen(x))'
10838     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10839       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10840           SizeCall->getNumArgs() == 1)
10841         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10842     }
10843   }
10844 
10845   if (!CompareWithSrc)
10846     return;
10847 
10848   // Determine if the argument to sizeof/strlen is equal to the source
10849   // argument.  In principle there's all kinds of things you could do
10850   // here, for instance creating an == expression and evaluating it with
10851   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10852   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10853   if (!SrcArgDRE)
10854     return;
10855 
10856   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10857   if (!CompareWithSrcDRE ||
10858       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10859     return;
10860 
10861   const Expr *OriginalSizeArg = Call->getArg(2);
10862   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10863       << OriginalSizeArg->getSourceRange() << FnName;
10864 
10865   // Output a FIXIT hint if the destination is an array (rather than a
10866   // pointer to an array).  This could be enhanced to handle some
10867   // pointers if we know the actual size, like if DstArg is 'array+2'
10868   // we could say 'sizeof(array)-2'.
10869   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10870   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10871     return;
10872 
10873   SmallString<128> sizeString;
10874   llvm::raw_svector_ostream OS(sizeString);
10875   OS << "sizeof(";
10876   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10877   OS << ")";
10878 
10879   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10880       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10881                                       OS.str());
10882 }
10883 
10884 /// Check if two expressions refer to the same declaration.
10885 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10886   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10887     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10888       return D1->getDecl() == D2->getDecl();
10889   return false;
10890 }
10891 
10892 static const Expr *getStrlenExprArg(const Expr *E) {
10893   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10894     const FunctionDecl *FD = CE->getDirectCallee();
10895     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10896       return nullptr;
10897     return CE->getArg(0)->IgnoreParenCasts();
10898   }
10899   return nullptr;
10900 }
10901 
10902 // Warn on anti-patterns as the 'size' argument to strncat.
10903 // The correct size argument should look like following:
10904 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10905 void Sema::CheckStrncatArguments(const CallExpr *CE,
10906                                  IdentifierInfo *FnName) {
10907   // Don't crash if the user has the wrong number of arguments.
10908   if (CE->getNumArgs() < 3)
10909     return;
10910   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10911   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10912   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10913 
10914   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10915                                      CE->getRParenLoc()))
10916     return;
10917 
10918   // Identify common expressions, which are wrongly used as the size argument
10919   // to strncat and may lead to buffer overflows.
10920   unsigned PatternType = 0;
10921   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10922     // - sizeof(dst)
10923     if (referToTheSameDecl(SizeOfArg, DstArg))
10924       PatternType = 1;
10925     // - sizeof(src)
10926     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10927       PatternType = 2;
10928   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10929     if (BE->getOpcode() == BO_Sub) {
10930       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10931       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10932       // - sizeof(dst) - strlen(dst)
10933       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10934           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10935         PatternType = 1;
10936       // - sizeof(src) - (anything)
10937       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10938         PatternType = 2;
10939     }
10940   }
10941 
10942   if (PatternType == 0)
10943     return;
10944 
10945   // Generate the diagnostic.
10946   SourceLocation SL = LenArg->getBeginLoc();
10947   SourceRange SR = LenArg->getSourceRange();
10948   SourceManager &SM = getSourceManager();
10949 
10950   // If the function is defined as a builtin macro, do not show macro expansion.
10951   if (SM.isMacroArgExpansion(SL)) {
10952     SL = SM.getSpellingLoc(SL);
10953     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10954                      SM.getSpellingLoc(SR.getEnd()));
10955   }
10956 
10957   // Check if the destination is an array (rather than a pointer to an array).
10958   QualType DstTy = DstArg->getType();
10959   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10960                                                                     Context);
10961   if (!isKnownSizeArray) {
10962     if (PatternType == 1)
10963       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10964     else
10965       Diag(SL, diag::warn_strncat_src_size) << SR;
10966     return;
10967   }
10968 
10969   if (PatternType == 1)
10970     Diag(SL, diag::warn_strncat_large_size) << SR;
10971   else
10972     Diag(SL, diag::warn_strncat_src_size) << SR;
10973 
10974   SmallString<128> sizeString;
10975   llvm::raw_svector_ostream OS(sizeString);
10976   OS << "sizeof(";
10977   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10978   OS << ") - ";
10979   OS << "strlen(";
10980   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10981   OS << ") - 1";
10982 
10983   Diag(SL, diag::note_strncat_wrong_size)
10984     << FixItHint::CreateReplacement(SR, OS.str());
10985 }
10986 
10987 namespace {
10988 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10989                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10990   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10991     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10992         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10993     return;
10994   }
10995 }
10996 
10997 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10998                                  const UnaryOperator *UnaryExpr) {
10999   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11000     const Decl *D = Lvalue->getDecl();
11001     if (isa<DeclaratorDecl>(D))
11002       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
11003         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11004   }
11005 
11006   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11007     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11008                                       Lvalue->getMemberDecl());
11009 }
11010 
11011 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11012                             const UnaryOperator *UnaryExpr) {
11013   const auto *Lambda = dyn_cast<LambdaExpr>(
11014       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11015   if (!Lambda)
11016     return;
11017 
11018   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11019       << CalleeName << 2 /*object: lambda expression*/;
11020 }
11021 
11022 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11023                                   const DeclRefExpr *Lvalue) {
11024   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11025   if (Var == nullptr)
11026     return;
11027 
11028   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11029       << CalleeName << 0 /*object: */ << Var;
11030 }
11031 
11032 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11033                             const CastExpr *Cast) {
11034   SmallString<128> SizeString;
11035   llvm::raw_svector_ostream OS(SizeString);
11036 
11037   clang::CastKind Kind = Cast->getCastKind();
11038   if (Kind == clang::CK_BitCast &&
11039       !Cast->getSubExpr()->getType()->isFunctionPointerType())
11040     return;
11041   if (Kind == clang::CK_IntegralToPointer &&
11042       !isa<IntegerLiteral>(
11043           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11044     return;
11045 
11046   switch (Cast->getCastKind()) {
11047   case clang::CK_BitCast:
11048   case clang::CK_IntegralToPointer:
11049   case clang::CK_FunctionToPointerDecay:
11050     OS << '\'';
11051     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11052     OS << '\'';
11053     break;
11054   default:
11055     return;
11056   }
11057 
11058   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11059       << CalleeName << 0 /*object: */ << OS.str();
11060 }
11061 } // namespace
11062 
11063 /// Alerts the user that they are attempting to free a non-malloc'd object.
11064 void Sema::CheckFreeArguments(const CallExpr *E) {
11065   const std::string CalleeName =
11066       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11067 
11068   { // Prefer something that doesn't involve a cast to make things simpler.
11069     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11070     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11071       switch (UnaryExpr->getOpcode()) {
11072       case UnaryOperator::Opcode::UO_AddrOf:
11073         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11074       case UnaryOperator::Opcode::UO_Plus:
11075         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11076       default:
11077         break;
11078       }
11079 
11080     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11081       if (Lvalue->getType()->isArrayType())
11082         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11083 
11084     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11085       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11086           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11087       return;
11088     }
11089 
11090     if (isa<BlockExpr>(Arg)) {
11091       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11092           << CalleeName << 1 /*object: block*/;
11093       return;
11094     }
11095   }
11096   // Maybe the cast was important, check after the other cases.
11097   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11098     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11099 }
11100 
11101 void
11102 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11103                          SourceLocation ReturnLoc,
11104                          bool isObjCMethod,
11105                          const AttrVec *Attrs,
11106                          const FunctionDecl *FD) {
11107   // Check if the return value is null but should not be.
11108   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11109        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
11110       CheckNonNullExpr(*this, RetValExp))
11111     Diag(ReturnLoc, diag::warn_null_ret)
11112       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11113 
11114   // C++11 [basic.stc.dynamic.allocation]p4:
11115   //   If an allocation function declared with a non-throwing
11116   //   exception-specification fails to allocate storage, it shall return
11117   //   a null pointer. Any other allocation function that fails to allocate
11118   //   storage shall indicate failure only by throwing an exception [...]
11119   if (FD) {
11120     OverloadedOperatorKind Op = FD->getOverloadedOperator();
11121     if (Op == OO_New || Op == OO_Array_New) {
11122       const FunctionProtoType *Proto
11123         = FD->getType()->castAs<FunctionProtoType>();
11124       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11125           CheckNonNullExpr(*this, RetValExp))
11126         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11127           << FD << getLangOpts().CPlusPlus11;
11128     }
11129   }
11130 
11131   // PPC MMA non-pointer types are not allowed as return type. Checking the type
11132   // here prevent the user from using a PPC MMA type as trailing return type.
11133   if (Context.getTargetInfo().getTriple().isPPC64())
11134     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11135 }
11136 
11137 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
11138 
11139 /// Check for comparisons of floating point operands using != and ==.
11140 /// Issue a warning if these are no self-comparisons, as they are not likely
11141 /// to do what the programmer intended.
11142 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
11143   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11144   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11145 
11146   // Special case: check for x == x (which is OK).
11147   // Do not emit warnings for such cases.
11148   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11149     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11150       if (DRL->getDecl() == DRR->getDecl())
11151         return;
11152 
11153   // Special case: check for comparisons against literals that can be exactly
11154   //  represented by APFloat.  In such cases, do not emit a warning.  This
11155   //  is a heuristic: often comparison against such literals are used to
11156   //  detect if a value in a variable has not changed.  This clearly can
11157   //  lead to false negatives.
11158   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11159     if (FLL->isExact())
11160       return;
11161   } else
11162     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11163       if (FLR->isExact())
11164         return;
11165 
11166   // Check for comparisons with builtin types.
11167   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11168     if (CL->getBuiltinCallee())
11169       return;
11170 
11171   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11172     if (CR->getBuiltinCallee())
11173       return;
11174 
11175   // Emit the diagnostic.
11176   Diag(Loc, diag::warn_floatingpoint_eq)
11177     << LHS->getSourceRange() << RHS->getSourceRange();
11178 }
11179 
11180 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11181 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11182 
11183 namespace {
11184 
11185 /// Structure recording the 'active' range of an integer-valued
11186 /// expression.
11187 struct IntRange {
11188   /// The number of bits active in the int. Note that this includes exactly one
11189   /// sign bit if !NonNegative.
11190   unsigned Width;
11191 
11192   /// True if the int is known not to have negative values. If so, all leading
11193   /// bits before Width are known zero, otherwise they are known to be the
11194   /// same as the MSB within Width.
11195   bool NonNegative;
11196 
11197   IntRange(unsigned Width, bool NonNegative)
11198       : Width(Width), NonNegative(NonNegative) {}
11199 
11200   /// Number of bits excluding the sign bit.
11201   unsigned valueBits() const {
11202     return NonNegative ? Width : Width - 1;
11203   }
11204 
11205   /// Returns the range of the bool type.
11206   static IntRange forBoolType() {
11207     return IntRange(1, true);
11208   }
11209 
11210   /// Returns the range of an opaque value of the given integral type.
11211   static IntRange forValueOfType(ASTContext &C, QualType T) {
11212     return forValueOfCanonicalType(C,
11213                           T->getCanonicalTypeInternal().getTypePtr());
11214   }
11215 
11216   /// Returns the range of an opaque value of a canonical integral type.
11217   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11218     assert(T->isCanonicalUnqualified());
11219 
11220     if (const VectorType *VT = dyn_cast<VectorType>(T))
11221       T = VT->getElementType().getTypePtr();
11222     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11223       T = CT->getElementType().getTypePtr();
11224     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11225       T = AT->getValueType().getTypePtr();
11226 
11227     if (!C.getLangOpts().CPlusPlus) {
11228       // For enum types in C code, use the underlying datatype.
11229       if (const EnumType *ET = dyn_cast<EnumType>(T))
11230         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11231     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11232       // For enum types in C++, use the known bit width of the enumerators.
11233       EnumDecl *Enum = ET->getDecl();
11234       // In C++11, enums can have a fixed underlying type. Use this type to
11235       // compute the range.
11236       if (Enum->isFixed()) {
11237         return IntRange(C.getIntWidth(QualType(T, 0)),
11238                         !ET->isSignedIntegerOrEnumerationType());
11239       }
11240 
11241       unsigned NumPositive = Enum->getNumPositiveBits();
11242       unsigned NumNegative = Enum->getNumNegativeBits();
11243 
11244       if (NumNegative == 0)
11245         return IntRange(NumPositive, true/*NonNegative*/);
11246       else
11247         return IntRange(std::max(NumPositive + 1, NumNegative),
11248                         false/*NonNegative*/);
11249     }
11250 
11251     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11252       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11253 
11254     const BuiltinType *BT = cast<BuiltinType>(T);
11255     assert(BT->isInteger());
11256 
11257     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11258   }
11259 
11260   /// Returns the "target" range of a canonical integral type, i.e.
11261   /// the range of values expressible in the type.
11262   ///
11263   /// This matches forValueOfCanonicalType except that enums have the
11264   /// full range of their type, not the range of their enumerators.
11265   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11266     assert(T->isCanonicalUnqualified());
11267 
11268     if (const VectorType *VT = dyn_cast<VectorType>(T))
11269       T = VT->getElementType().getTypePtr();
11270     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11271       T = CT->getElementType().getTypePtr();
11272     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11273       T = AT->getValueType().getTypePtr();
11274     if (const EnumType *ET = dyn_cast<EnumType>(T))
11275       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11276 
11277     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11278       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11279 
11280     const BuiltinType *BT = cast<BuiltinType>(T);
11281     assert(BT->isInteger());
11282 
11283     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11284   }
11285 
11286   /// Returns the supremum of two ranges: i.e. their conservative merge.
11287   static IntRange join(IntRange L, IntRange R) {
11288     bool Unsigned = L.NonNegative && R.NonNegative;
11289     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11290                     L.NonNegative && R.NonNegative);
11291   }
11292 
11293   /// Return the range of a bitwise-AND of the two ranges.
11294   static IntRange bit_and(IntRange L, IntRange R) {
11295     unsigned Bits = std::max(L.Width, R.Width);
11296     bool NonNegative = false;
11297     if (L.NonNegative) {
11298       Bits = std::min(Bits, L.Width);
11299       NonNegative = true;
11300     }
11301     if (R.NonNegative) {
11302       Bits = std::min(Bits, R.Width);
11303       NonNegative = true;
11304     }
11305     return IntRange(Bits, NonNegative);
11306   }
11307 
11308   /// Return the range of a sum of the two ranges.
11309   static IntRange sum(IntRange L, IntRange R) {
11310     bool Unsigned = L.NonNegative && R.NonNegative;
11311     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11312                     Unsigned);
11313   }
11314 
11315   /// Return the range of a difference of the two ranges.
11316   static IntRange difference(IntRange L, IntRange R) {
11317     // We need a 1-bit-wider range if:
11318     //   1) LHS can be negative: least value can be reduced.
11319     //   2) RHS can be negative: greatest value can be increased.
11320     bool CanWiden = !L.NonNegative || !R.NonNegative;
11321     bool Unsigned = L.NonNegative && R.Width == 0;
11322     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11323                         !Unsigned,
11324                     Unsigned);
11325   }
11326 
11327   /// Return the range of a product of the two ranges.
11328   static IntRange product(IntRange L, IntRange R) {
11329     // If both LHS and RHS can be negative, we can form
11330     //   -2^L * -2^R = 2^(L + R)
11331     // which requires L + R + 1 value bits to represent.
11332     bool CanWiden = !L.NonNegative && !R.NonNegative;
11333     bool Unsigned = L.NonNegative && R.NonNegative;
11334     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11335                     Unsigned);
11336   }
11337 
11338   /// Return the range of a remainder operation between the two ranges.
11339   static IntRange rem(IntRange L, IntRange R) {
11340     // The result of a remainder can't be larger than the result of
11341     // either side. The sign of the result is the sign of the LHS.
11342     bool Unsigned = L.NonNegative;
11343     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11344                     Unsigned);
11345   }
11346 };
11347 
11348 } // namespace
11349 
11350 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11351                               unsigned MaxWidth) {
11352   if (value.isSigned() && value.isNegative())
11353     return IntRange(value.getMinSignedBits(), false);
11354 
11355   if (value.getBitWidth() > MaxWidth)
11356     value = value.trunc(MaxWidth);
11357 
11358   // isNonNegative() just checks the sign bit without considering
11359   // signedness.
11360   return IntRange(value.getActiveBits(), true);
11361 }
11362 
11363 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11364                               unsigned MaxWidth) {
11365   if (result.isInt())
11366     return GetValueRange(C, result.getInt(), MaxWidth);
11367 
11368   if (result.isVector()) {
11369     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11370     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11371       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11372       R = IntRange::join(R, El);
11373     }
11374     return R;
11375   }
11376 
11377   if (result.isComplexInt()) {
11378     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11379     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11380     return IntRange::join(R, I);
11381   }
11382 
11383   // This can happen with lossless casts to intptr_t of "based" lvalues.
11384   // Assume it might use arbitrary bits.
11385   // FIXME: The only reason we need to pass the type in here is to get
11386   // the sign right on this one case.  It would be nice if APValue
11387   // preserved this.
11388   assert(result.isLValue() || result.isAddrLabelDiff());
11389   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11390 }
11391 
11392 static QualType GetExprType(const Expr *E) {
11393   QualType Ty = E->getType();
11394   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11395     Ty = AtomicRHS->getValueType();
11396   return Ty;
11397 }
11398 
11399 /// Pseudo-evaluate the given integer expression, estimating the
11400 /// range of values it might take.
11401 ///
11402 /// \param MaxWidth The width to which the value will be truncated.
11403 /// \param Approximate If \c true, return a likely range for the result: in
11404 ///        particular, assume that arithmetic on narrower types doesn't leave
11405 ///        those types. If \c false, return a range including all possible
11406 ///        result values.
11407 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11408                              bool InConstantContext, bool Approximate) {
11409   E = E->IgnoreParens();
11410 
11411   // Try a full evaluation first.
11412   Expr::EvalResult result;
11413   if (E->EvaluateAsRValue(result, C, InConstantContext))
11414     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11415 
11416   // I think we only want to look through implicit casts here; if the
11417   // user has an explicit widening cast, we should treat the value as
11418   // being of the new, wider type.
11419   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11420     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11421       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11422                           Approximate);
11423 
11424     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11425 
11426     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11427                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11428 
11429     // Assume that non-integer casts can span the full range of the type.
11430     if (!isIntegerCast)
11431       return OutputTypeRange;
11432 
11433     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11434                                      std::min(MaxWidth, OutputTypeRange.Width),
11435                                      InConstantContext, Approximate);
11436 
11437     // Bail out if the subexpr's range is as wide as the cast type.
11438     if (SubRange.Width >= OutputTypeRange.Width)
11439       return OutputTypeRange;
11440 
11441     // Otherwise, we take the smaller width, and we're non-negative if
11442     // either the output type or the subexpr is.
11443     return IntRange(SubRange.Width,
11444                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11445   }
11446 
11447   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11448     // If we can fold the condition, just take that operand.
11449     bool CondResult;
11450     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11451       return GetExprRange(C,
11452                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11453                           MaxWidth, InConstantContext, Approximate);
11454 
11455     // Otherwise, conservatively merge.
11456     // GetExprRange requires an integer expression, but a throw expression
11457     // results in a void type.
11458     Expr *E = CO->getTrueExpr();
11459     IntRange L = E->getType()->isVoidType()
11460                      ? IntRange{0, true}
11461                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11462     E = CO->getFalseExpr();
11463     IntRange R = E->getType()->isVoidType()
11464                      ? IntRange{0, true}
11465                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11466     return IntRange::join(L, R);
11467   }
11468 
11469   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11470     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11471 
11472     switch (BO->getOpcode()) {
11473     case BO_Cmp:
11474       llvm_unreachable("builtin <=> should have class type");
11475 
11476     // Boolean-valued operations are single-bit and positive.
11477     case BO_LAnd:
11478     case BO_LOr:
11479     case BO_LT:
11480     case BO_GT:
11481     case BO_LE:
11482     case BO_GE:
11483     case BO_EQ:
11484     case BO_NE:
11485       return IntRange::forBoolType();
11486 
11487     // The type of the assignments is the type of the LHS, so the RHS
11488     // is not necessarily the same type.
11489     case BO_MulAssign:
11490     case BO_DivAssign:
11491     case BO_RemAssign:
11492     case BO_AddAssign:
11493     case BO_SubAssign:
11494     case BO_XorAssign:
11495     case BO_OrAssign:
11496       // TODO: bitfields?
11497       return IntRange::forValueOfType(C, GetExprType(E));
11498 
11499     // Simple assignments just pass through the RHS, which will have
11500     // been coerced to the LHS type.
11501     case BO_Assign:
11502       // TODO: bitfields?
11503       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11504                           Approximate);
11505 
11506     // Operations with opaque sources are black-listed.
11507     case BO_PtrMemD:
11508     case BO_PtrMemI:
11509       return IntRange::forValueOfType(C, GetExprType(E));
11510 
11511     // Bitwise-and uses the *infinum* of the two source ranges.
11512     case BO_And:
11513     case BO_AndAssign:
11514       Combine = IntRange::bit_and;
11515       break;
11516 
11517     // Left shift gets black-listed based on a judgement call.
11518     case BO_Shl:
11519       // ...except that we want to treat '1 << (blah)' as logically
11520       // positive.  It's an important idiom.
11521       if (IntegerLiteral *I
11522             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11523         if (I->getValue() == 1) {
11524           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11525           return IntRange(R.Width, /*NonNegative*/ true);
11526         }
11527       }
11528       LLVM_FALLTHROUGH;
11529 
11530     case BO_ShlAssign:
11531       return IntRange::forValueOfType(C, GetExprType(E));
11532 
11533     // Right shift by a constant can narrow its left argument.
11534     case BO_Shr:
11535     case BO_ShrAssign: {
11536       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11537                                 Approximate);
11538 
11539       // If the shift amount is a positive constant, drop the width by
11540       // that much.
11541       if (Optional<llvm::APSInt> shift =
11542               BO->getRHS()->getIntegerConstantExpr(C)) {
11543         if (shift->isNonNegative()) {
11544           unsigned zext = shift->getZExtValue();
11545           if (zext >= L.Width)
11546             L.Width = (L.NonNegative ? 0 : 1);
11547           else
11548             L.Width -= zext;
11549         }
11550       }
11551 
11552       return L;
11553     }
11554 
11555     // Comma acts as its right operand.
11556     case BO_Comma:
11557       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11558                           Approximate);
11559 
11560     case BO_Add:
11561       if (!Approximate)
11562         Combine = IntRange::sum;
11563       break;
11564 
11565     case BO_Sub:
11566       if (BO->getLHS()->getType()->isPointerType())
11567         return IntRange::forValueOfType(C, GetExprType(E));
11568       if (!Approximate)
11569         Combine = IntRange::difference;
11570       break;
11571 
11572     case BO_Mul:
11573       if (!Approximate)
11574         Combine = IntRange::product;
11575       break;
11576 
11577     // The width of a division result is mostly determined by the size
11578     // of the LHS.
11579     case BO_Div: {
11580       // Don't 'pre-truncate' the operands.
11581       unsigned opWidth = C.getIntWidth(GetExprType(E));
11582       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11583                                 Approximate);
11584 
11585       // If the divisor is constant, use that.
11586       if (Optional<llvm::APSInt> divisor =
11587               BO->getRHS()->getIntegerConstantExpr(C)) {
11588         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11589         if (log2 >= L.Width)
11590           L.Width = (L.NonNegative ? 0 : 1);
11591         else
11592           L.Width = std::min(L.Width - log2, MaxWidth);
11593         return L;
11594       }
11595 
11596       // Otherwise, just use the LHS's width.
11597       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11598       // could be -1.
11599       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11600                                 Approximate);
11601       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11602     }
11603 
11604     case BO_Rem:
11605       Combine = IntRange::rem;
11606       break;
11607 
11608     // The default behavior is okay for these.
11609     case BO_Xor:
11610     case BO_Or:
11611       break;
11612     }
11613 
11614     // Combine the two ranges, but limit the result to the type in which we
11615     // performed the computation.
11616     QualType T = GetExprType(E);
11617     unsigned opWidth = C.getIntWidth(T);
11618     IntRange L =
11619         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11620     IntRange R =
11621         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11622     IntRange C = Combine(L, R);
11623     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11624     C.Width = std::min(C.Width, MaxWidth);
11625     return C;
11626   }
11627 
11628   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11629     switch (UO->getOpcode()) {
11630     // Boolean-valued operations are white-listed.
11631     case UO_LNot:
11632       return IntRange::forBoolType();
11633 
11634     // Operations with opaque sources are black-listed.
11635     case UO_Deref:
11636     case UO_AddrOf: // should be impossible
11637       return IntRange::forValueOfType(C, GetExprType(E));
11638 
11639     default:
11640       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11641                           Approximate);
11642     }
11643   }
11644 
11645   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11646     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11647                         Approximate);
11648 
11649   if (const auto *BitField = E->getSourceBitField())
11650     return IntRange(BitField->getBitWidthValue(C),
11651                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11652 
11653   return IntRange::forValueOfType(C, GetExprType(E));
11654 }
11655 
11656 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11657                              bool InConstantContext, bool Approximate) {
11658   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11659                       Approximate);
11660 }
11661 
11662 /// Checks whether the given value, which currently has the given
11663 /// source semantics, has the same value when coerced through the
11664 /// target semantics.
11665 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11666                                  const llvm::fltSemantics &Src,
11667                                  const llvm::fltSemantics &Tgt) {
11668   llvm::APFloat truncated = value;
11669 
11670   bool ignored;
11671   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11672   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11673 
11674   return truncated.bitwiseIsEqual(value);
11675 }
11676 
11677 /// Checks whether the given value, which currently has the given
11678 /// source semantics, has the same value when coerced through the
11679 /// target semantics.
11680 ///
11681 /// The value might be a vector of floats (or a complex number).
11682 static bool IsSameFloatAfterCast(const APValue &value,
11683                                  const llvm::fltSemantics &Src,
11684                                  const llvm::fltSemantics &Tgt) {
11685   if (value.isFloat())
11686     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11687 
11688   if (value.isVector()) {
11689     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11690       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11691         return false;
11692     return true;
11693   }
11694 
11695   assert(value.isComplexFloat());
11696   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11697           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11698 }
11699 
11700 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11701                                        bool IsListInit = false);
11702 
11703 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11704   // Suppress cases where we are comparing against an enum constant.
11705   if (const DeclRefExpr *DR =
11706       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11707     if (isa<EnumConstantDecl>(DR->getDecl()))
11708       return true;
11709 
11710   // Suppress cases where the value is expanded from a macro, unless that macro
11711   // is how a language represents a boolean literal. This is the case in both C
11712   // and Objective-C.
11713   SourceLocation BeginLoc = E->getBeginLoc();
11714   if (BeginLoc.isMacroID()) {
11715     StringRef MacroName = Lexer::getImmediateMacroName(
11716         BeginLoc, S.getSourceManager(), S.getLangOpts());
11717     return MacroName != "YES" && MacroName != "NO" &&
11718            MacroName != "true" && MacroName != "false";
11719   }
11720 
11721   return false;
11722 }
11723 
11724 static bool isKnownToHaveUnsignedValue(Expr *E) {
11725   return E->getType()->isIntegerType() &&
11726          (!E->getType()->isSignedIntegerType() ||
11727           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11728 }
11729 
11730 namespace {
11731 /// The promoted range of values of a type. In general this has the
11732 /// following structure:
11733 ///
11734 ///     |-----------| . . . |-----------|
11735 ///     ^           ^       ^           ^
11736 ///    Min       HoleMin  HoleMax      Max
11737 ///
11738 /// ... where there is only a hole if a signed type is promoted to unsigned
11739 /// (in which case Min and Max are the smallest and largest representable
11740 /// values).
11741 struct PromotedRange {
11742   // Min, or HoleMax if there is a hole.
11743   llvm::APSInt PromotedMin;
11744   // Max, or HoleMin if there is a hole.
11745   llvm::APSInt PromotedMax;
11746 
11747   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11748     if (R.Width == 0)
11749       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11750     else if (R.Width >= BitWidth && !Unsigned) {
11751       // Promotion made the type *narrower*. This happens when promoting
11752       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11753       // Treat all values of 'signed int' as being in range for now.
11754       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11755       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11756     } else {
11757       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11758                         .extOrTrunc(BitWidth);
11759       PromotedMin.setIsUnsigned(Unsigned);
11760 
11761       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11762                         .extOrTrunc(BitWidth);
11763       PromotedMax.setIsUnsigned(Unsigned);
11764     }
11765   }
11766 
11767   // Determine whether this range is contiguous (has no hole).
11768   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11769 
11770   // Where a constant value is within the range.
11771   enum ComparisonResult {
11772     LT = 0x1,
11773     LE = 0x2,
11774     GT = 0x4,
11775     GE = 0x8,
11776     EQ = 0x10,
11777     NE = 0x20,
11778     InRangeFlag = 0x40,
11779 
11780     Less = LE | LT | NE,
11781     Min = LE | InRangeFlag,
11782     InRange = InRangeFlag,
11783     Max = GE | InRangeFlag,
11784     Greater = GE | GT | NE,
11785 
11786     OnlyValue = LE | GE | EQ | InRangeFlag,
11787     InHole = NE
11788   };
11789 
11790   ComparisonResult compare(const llvm::APSInt &Value) const {
11791     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11792            Value.isUnsigned() == PromotedMin.isUnsigned());
11793     if (!isContiguous()) {
11794       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11795       if (Value.isMinValue()) return Min;
11796       if (Value.isMaxValue()) return Max;
11797       if (Value >= PromotedMin) return InRange;
11798       if (Value <= PromotedMax) return InRange;
11799       return InHole;
11800     }
11801 
11802     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11803     case -1: return Less;
11804     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11805     case 1:
11806       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11807       case -1: return InRange;
11808       case 0: return Max;
11809       case 1: return Greater;
11810       }
11811     }
11812 
11813     llvm_unreachable("impossible compare result");
11814   }
11815 
11816   static llvm::Optional<StringRef>
11817   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11818     if (Op == BO_Cmp) {
11819       ComparisonResult LTFlag = LT, GTFlag = GT;
11820       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11821 
11822       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11823       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11824       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11825       return llvm::None;
11826     }
11827 
11828     ComparisonResult TrueFlag, FalseFlag;
11829     if (Op == BO_EQ) {
11830       TrueFlag = EQ;
11831       FalseFlag = NE;
11832     } else if (Op == BO_NE) {
11833       TrueFlag = NE;
11834       FalseFlag = EQ;
11835     } else {
11836       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11837         TrueFlag = LT;
11838         FalseFlag = GE;
11839       } else {
11840         TrueFlag = GT;
11841         FalseFlag = LE;
11842       }
11843       if (Op == BO_GE || Op == BO_LE)
11844         std::swap(TrueFlag, FalseFlag);
11845     }
11846     if (R & TrueFlag)
11847       return StringRef("true");
11848     if (R & FalseFlag)
11849       return StringRef("false");
11850     return llvm::None;
11851   }
11852 };
11853 }
11854 
11855 static bool HasEnumType(Expr *E) {
11856   // Strip off implicit integral promotions.
11857   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11858     if (ICE->getCastKind() != CK_IntegralCast &&
11859         ICE->getCastKind() != CK_NoOp)
11860       break;
11861     E = ICE->getSubExpr();
11862   }
11863 
11864   return E->getType()->isEnumeralType();
11865 }
11866 
11867 static int classifyConstantValue(Expr *Constant) {
11868   // The values of this enumeration are used in the diagnostics
11869   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11870   enum ConstantValueKind {
11871     Miscellaneous = 0,
11872     LiteralTrue,
11873     LiteralFalse
11874   };
11875   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11876     return BL->getValue() ? ConstantValueKind::LiteralTrue
11877                           : ConstantValueKind::LiteralFalse;
11878   return ConstantValueKind::Miscellaneous;
11879 }
11880 
11881 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11882                                         Expr *Constant, Expr *Other,
11883                                         const llvm::APSInt &Value,
11884                                         bool RhsConstant) {
11885   if (S.inTemplateInstantiation())
11886     return false;
11887 
11888   Expr *OriginalOther = Other;
11889 
11890   Constant = Constant->IgnoreParenImpCasts();
11891   Other = Other->IgnoreParenImpCasts();
11892 
11893   // Suppress warnings on tautological comparisons between values of the same
11894   // enumeration type. There are only two ways we could warn on this:
11895   //  - If the constant is outside the range of representable values of
11896   //    the enumeration. In such a case, we should warn about the cast
11897   //    to enumeration type, not about the comparison.
11898   //  - If the constant is the maximum / minimum in-range value. For an
11899   //    enumeratin type, such comparisons can be meaningful and useful.
11900   if (Constant->getType()->isEnumeralType() &&
11901       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11902     return false;
11903 
11904   IntRange OtherValueRange = GetExprRange(
11905       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11906 
11907   QualType OtherT = Other->getType();
11908   if (const auto *AT = OtherT->getAs<AtomicType>())
11909     OtherT = AT->getValueType();
11910   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11911 
11912   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11913   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11914   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11915                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11916                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11917 
11918   // Whether we're treating Other as being a bool because of the form of
11919   // expression despite it having another type (typically 'int' in C).
11920   bool OtherIsBooleanDespiteType =
11921       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11922   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11923     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11924 
11925   // Check if all values in the range of possible values of this expression
11926   // lead to the same comparison outcome.
11927   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11928                                         Value.isUnsigned());
11929   auto Cmp = OtherPromotedValueRange.compare(Value);
11930   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11931   if (!Result)
11932     return false;
11933 
11934   // Also consider the range determined by the type alone. This allows us to
11935   // classify the warning under the proper diagnostic group.
11936   bool TautologicalTypeCompare = false;
11937   {
11938     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11939                                          Value.isUnsigned());
11940     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11941     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11942                                                        RhsConstant)) {
11943       TautologicalTypeCompare = true;
11944       Cmp = TypeCmp;
11945       Result = TypeResult;
11946     }
11947   }
11948 
11949   // Don't warn if the non-constant operand actually always evaluates to the
11950   // same value.
11951   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11952     return false;
11953 
11954   // Suppress the diagnostic for an in-range comparison if the constant comes
11955   // from a macro or enumerator. We don't want to diagnose
11956   //
11957   //   some_long_value <= INT_MAX
11958   //
11959   // when sizeof(int) == sizeof(long).
11960   bool InRange = Cmp & PromotedRange::InRangeFlag;
11961   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11962     return false;
11963 
11964   // A comparison of an unsigned bit-field against 0 is really a type problem,
11965   // even though at the type level the bit-field might promote to 'signed int'.
11966   if (Other->refersToBitField() && InRange && Value == 0 &&
11967       Other->getType()->isUnsignedIntegerOrEnumerationType())
11968     TautologicalTypeCompare = true;
11969 
11970   // If this is a comparison to an enum constant, include that
11971   // constant in the diagnostic.
11972   const EnumConstantDecl *ED = nullptr;
11973   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11974     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11975 
11976   // Should be enough for uint128 (39 decimal digits)
11977   SmallString<64> PrettySourceValue;
11978   llvm::raw_svector_ostream OS(PrettySourceValue);
11979   if (ED) {
11980     OS << '\'' << *ED << "' (" << Value << ")";
11981   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11982                Constant->IgnoreParenImpCasts())) {
11983     OS << (BL->getValue() ? "YES" : "NO");
11984   } else {
11985     OS << Value;
11986   }
11987 
11988   if (!TautologicalTypeCompare) {
11989     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11990         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11991         << E->getOpcodeStr() << OS.str() << *Result
11992         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11993     return true;
11994   }
11995 
11996   if (IsObjCSignedCharBool) {
11997     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11998                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11999                               << OS.str() << *Result);
12000     return true;
12001   }
12002 
12003   // FIXME: We use a somewhat different formatting for the in-range cases and
12004   // cases involving boolean values for historical reasons. We should pick a
12005   // consistent way of presenting these diagnostics.
12006   if (!InRange || Other->isKnownToHaveBooleanValue()) {
12007 
12008     S.DiagRuntimeBehavior(
12009         E->getOperatorLoc(), E,
12010         S.PDiag(!InRange ? diag::warn_out_of_range_compare
12011                          : diag::warn_tautological_bool_compare)
12012             << OS.str() << classifyConstantValue(Constant) << OtherT
12013             << OtherIsBooleanDespiteType << *Result
12014             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12015   } else {
12016     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12017     unsigned Diag =
12018         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12019             ? (HasEnumType(OriginalOther)
12020                    ? diag::warn_unsigned_enum_always_true_comparison
12021                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12022                               : diag::warn_unsigned_always_true_comparison)
12023             : diag::warn_tautological_constant_compare;
12024 
12025     S.Diag(E->getOperatorLoc(), Diag)
12026         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12027         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12028   }
12029 
12030   return true;
12031 }
12032 
12033 /// Analyze the operands of the given comparison.  Implements the
12034 /// fallback case from AnalyzeComparison.
12035 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12036   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12037   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12038 }
12039 
12040 /// Implements -Wsign-compare.
12041 ///
12042 /// \param E the binary operator to check for warnings
12043 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12044   // The type the comparison is being performed in.
12045   QualType T = E->getLHS()->getType();
12046 
12047   // Only analyze comparison operators where both sides have been converted to
12048   // the same type.
12049   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12050     return AnalyzeImpConvsInComparison(S, E);
12051 
12052   // Don't analyze value-dependent comparisons directly.
12053   if (E->isValueDependent())
12054     return AnalyzeImpConvsInComparison(S, E);
12055 
12056   Expr *LHS = E->getLHS();
12057   Expr *RHS = E->getRHS();
12058 
12059   if (T->isIntegralType(S.Context)) {
12060     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
12061     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
12062 
12063     // We don't care about expressions whose result is a constant.
12064     if (RHSValue && LHSValue)
12065       return AnalyzeImpConvsInComparison(S, E);
12066 
12067     // We only care about expressions where just one side is literal
12068     if ((bool)RHSValue ^ (bool)LHSValue) {
12069       // Is the constant on the RHS or LHS?
12070       const bool RhsConstant = (bool)RHSValue;
12071       Expr *Const = RhsConstant ? RHS : LHS;
12072       Expr *Other = RhsConstant ? LHS : RHS;
12073       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12074 
12075       // Check whether an integer constant comparison results in a value
12076       // of 'true' or 'false'.
12077       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12078         return AnalyzeImpConvsInComparison(S, E);
12079     }
12080   }
12081 
12082   if (!T->hasUnsignedIntegerRepresentation()) {
12083     // We don't do anything special if this isn't an unsigned integral
12084     // comparison:  we're only interested in integral comparisons, and
12085     // signed comparisons only happen in cases we don't care to warn about.
12086     return AnalyzeImpConvsInComparison(S, E);
12087   }
12088 
12089   LHS = LHS->IgnoreParenImpCasts();
12090   RHS = RHS->IgnoreParenImpCasts();
12091 
12092   if (!S.getLangOpts().CPlusPlus) {
12093     // Avoid warning about comparison of integers with different signs when
12094     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12095     // the type of `E`.
12096     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12097       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12098     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12099       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12100   }
12101 
12102   // Check to see if one of the (unmodified) operands is of different
12103   // signedness.
12104   Expr *signedOperand, *unsignedOperand;
12105   if (LHS->getType()->hasSignedIntegerRepresentation()) {
12106     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12107            "unsigned comparison between two signed integer expressions?");
12108     signedOperand = LHS;
12109     unsignedOperand = RHS;
12110   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12111     signedOperand = RHS;
12112     unsignedOperand = LHS;
12113   } else {
12114     return AnalyzeImpConvsInComparison(S, E);
12115   }
12116 
12117   // Otherwise, calculate the effective range of the signed operand.
12118   IntRange signedRange = GetExprRange(
12119       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
12120 
12121   // Go ahead and analyze implicit conversions in the operands.  Note
12122   // that we skip the implicit conversions on both sides.
12123   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
12124   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
12125 
12126   // If the signed range is non-negative, -Wsign-compare won't fire.
12127   if (signedRange.NonNegative)
12128     return;
12129 
12130   // For (in)equality comparisons, if the unsigned operand is a
12131   // constant which cannot collide with a overflowed signed operand,
12132   // then reinterpreting the signed operand as unsigned will not
12133   // change the result of the comparison.
12134   if (E->isEqualityOp()) {
12135     unsigned comparisonWidth = S.Context.getIntWidth(T);
12136     IntRange unsignedRange =
12137         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
12138                      /*Approximate*/ true);
12139 
12140     // We should never be unable to prove that the unsigned operand is
12141     // non-negative.
12142     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12143 
12144     if (unsignedRange.Width < comparisonWidth)
12145       return;
12146   }
12147 
12148   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12149                         S.PDiag(diag::warn_mixed_sign_comparison)
12150                             << LHS->getType() << RHS->getType()
12151                             << LHS->getSourceRange() << RHS->getSourceRange());
12152 }
12153 
12154 /// Analyzes an attempt to assign the given value to a bitfield.
12155 ///
12156 /// Returns true if there was something fishy about the attempt.
12157 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12158                                       SourceLocation InitLoc) {
12159   assert(Bitfield->isBitField());
12160   if (Bitfield->isInvalidDecl())
12161     return false;
12162 
12163   // White-list bool bitfields.
12164   QualType BitfieldType = Bitfield->getType();
12165   if (BitfieldType->isBooleanType())
12166      return false;
12167 
12168   if (BitfieldType->isEnumeralType()) {
12169     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12170     // If the underlying enum type was not explicitly specified as an unsigned
12171     // type and the enum contain only positive values, MSVC++ will cause an
12172     // inconsistency by storing this as a signed type.
12173     if (S.getLangOpts().CPlusPlus11 &&
12174         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12175         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12176         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12177       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12178           << BitfieldEnumDecl;
12179     }
12180   }
12181 
12182   if (Bitfield->getType()->isBooleanType())
12183     return false;
12184 
12185   // Ignore value- or type-dependent expressions.
12186   if (Bitfield->getBitWidth()->isValueDependent() ||
12187       Bitfield->getBitWidth()->isTypeDependent() ||
12188       Init->isValueDependent() ||
12189       Init->isTypeDependent())
12190     return false;
12191 
12192   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12193   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12194 
12195   Expr::EvalResult Result;
12196   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12197                                    Expr::SE_AllowSideEffects)) {
12198     // The RHS is not constant.  If the RHS has an enum type, make sure the
12199     // bitfield is wide enough to hold all the values of the enum without
12200     // truncation.
12201     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12202       EnumDecl *ED = EnumTy->getDecl();
12203       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12204 
12205       // Enum types are implicitly signed on Windows, so check if there are any
12206       // negative enumerators to see if the enum was intended to be signed or
12207       // not.
12208       bool SignedEnum = ED->getNumNegativeBits() > 0;
12209 
12210       // Check for surprising sign changes when assigning enum values to a
12211       // bitfield of different signedness.  If the bitfield is signed and we
12212       // have exactly the right number of bits to store this unsigned enum,
12213       // suggest changing the enum to an unsigned type. This typically happens
12214       // on Windows where unfixed enums always use an underlying type of 'int'.
12215       unsigned DiagID = 0;
12216       if (SignedEnum && !SignedBitfield) {
12217         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12218       } else if (SignedBitfield && !SignedEnum &&
12219                  ED->getNumPositiveBits() == FieldWidth) {
12220         DiagID = diag::warn_signed_bitfield_enum_conversion;
12221       }
12222 
12223       if (DiagID) {
12224         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12225         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12226         SourceRange TypeRange =
12227             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12228         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12229             << SignedEnum << TypeRange;
12230       }
12231 
12232       // Compute the required bitwidth. If the enum has negative values, we need
12233       // one more bit than the normal number of positive bits to represent the
12234       // sign bit.
12235       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12236                                                   ED->getNumNegativeBits())
12237                                        : ED->getNumPositiveBits();
12238 
12239       // Check the bitwidth.
12240       if (BitsNeeded > FieldWidth) {
12241         Expr *WidthExpr = Bitfield->getBitWidth();
12242         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12243             << Bitfield << ED;
12244         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12245             << BitsNeeded << ED << WidthExpr->getSourceRange();
12246       }
12247     }
12248 
12249     return false;
12250   }
12251 
12252   llvm::APSInt Value = Result.Val.getInt();
12253 
12254   unsigned OriginalWidth = Value.getBitWidth();
12255 
12256   if (!Value.isSigned() || Value.isNegative())
12257     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12258       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12259         OriginalWidth = Value.getMinSignedBits();
12260 
12261   if (OriginalWidth <= FieldWidth)
12262     return false;
12263 
12264   // Compute the value which the bitfield will contain.
12265   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12266   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12267 
12268   // Check whether the stored value is equal to the original value.
12269   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12270   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12271     return false;
12272 
12273   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12274   // therefore don't strictly fit into a signed bitfield of width 1.
12275   if (FieldWidth == 1 && Value == 1)
12276     return false;
12277 
12278   std::string PrettyValue = toString(Value, 10);
12279   std::string PrettyTrunc = toString(TruncatedValue, 10);
12280 
12281   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12282     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12283     << Init->getSourceRange();
12284 
12285   return true;
12286 }
12287 
12288 /// Analyze the given simple or compound assignment for warning-worthy
12289 /// operations.
12290 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12291   // Just recurse on the LHS.
12292   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12293 
12294   // We want to recurse on the RHS as normal unless we're assigning to
12295   // a bitfield.
12296   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12297     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12298                                   E->getOperatorLoc())) {
12299       // Recurse, ignoring any implicit conversions on the RHS.
12300       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12301                                         E->getOperatorLoc());
12302     }
12303   }
12304 
12305   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12306 
12307   // Diagnose implicitly sequentially-consistent atomic assignment.
12308   if (E->getLHS()->getType()->isAtomicType())
12309     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12310 }
12311 
12312 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12313 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12314                             SourceLocation CContext, unsigned diag,
12315                             bool pruneControlFlow = false) {
12316   if (pruneControlFlow) {
12317     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12318                           S.PDiag(diag)
12319                               << SourceType << T << E->getSourceRange()
12320                               << SourceRange(CContext));
12321     return;
12322   }
12323   S.Diag(E->getExprLoc(), diag)
12324     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12325 }
12326 
12327 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12328 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12329                             SourceLocation CContext,
12330                             unsigned diag, bool pruneControlFlow = false) {
12331   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12332 }
12333 
12334 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12335   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12336       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12337 }
12338 
12339 static void adornObjCBoolConversionDiagWithTernaryFixit(
12340     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12341   Expr *Ignored = SourceExpr->IgnoreImplicit();
12342   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12343     Ignored = OVE->getSourceExpr();
12344   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12345                      isa<BinaryOperator>(Ignored) ||
12346                      isa<CXXOperatorCallExpr>(Ignored);
12347   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12348   if (NeedsParens)
12349     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12350             << FixItHint::CreateInsertion(EndLoc, ")");
12351   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12352 }
12353 
12354 /// Diagnose an implicit cast from a floating point value to an integer value.
12355 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12356                                     SourceLocation CContext) {
12357   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12358   const bool PruneWarnings = S.inTemplateInstantiation();
12359 
12360   Expr *InnerE = E->IgnoreParenImpCasts();
12361   // We also want to warn on, e.g., "int i = -1.234"
12362   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12363     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12364       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12365 
12366   const bool IsLiteral =
12367       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12368 
12369   llvm::APFloat Value(0.0);
12370   bool IsConstant =
12371     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12372   if (!IsConstant) {
12373     if (isObjCSignedCharBool(S, T)) {
12374       return adornObjCBoolConversionDiagWithTernaryFixit(
12375           S, E,
12376           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12377               << E->getType());
12378     }
12379 
12380     return DiagnoseImpCast(S, E, T, CContext,
12381                            diag::warn_impcast_float_integer, PruneWarnings);
12382   }
12383 
12384   bool isExact = false;
12385 
12386   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12387                             T->hasUnsignedIntegerRepresentation());
12388   llvm::APFloat::opStatus Result = Value.convertToInteger(
12389       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12390 
12391   // FIXME: Force the precision of the source value down so we don't print
12392   // digits which are usually useless (we don't really care here if we
12393   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12394   // would automatically print the shortest representation, but it's a bit
12395   // tricky to implement.
12396   SmallString<16> PrettySourceValue;
12397   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12398   precision = (precision * 59 + 195) / 196;
12399   Value.toString(PrettySourceValue, precision);
12400 
12401   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12402     return adornObjCBoolConversionDiagWithTernaryFixit(
12403         S, E,
12404         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12405             << PrettySourceValue);
12406   }
12407 
12408   if (Result == llvm::APFloat::opOK && isExact) {
12409     if (IsLiteral) return;
12410     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12411                            PruneWarnings);
12412   }
12413 
12414   // Conversion of a floating-point value to a non-bool integer where the
12415   // integral part cannot be represented by the integer type is undefined.
12416   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12417     return DiagnoseImpCast(
12418         S, E, T, CContext,
12419         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12420                   : diag::warn_impcast_float_to_integer_out_of_range,
12421         PruneWarnings);
12422 
12423   unsigned DiagID = 0;
12424   if (IsLiteral) {
12425     // Warn on floating point literal to integer.
12426     DiagID = diag::warn_impcast_literal_float_to_integer;
12427   } else if (IntegerValue == 0) {
12428     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12429       return DiagnoseImpCast(S, E, T, CContext,
12430                              diag::warn_impcast_float_integer, PruneWarnings);
12431     }
12432     // Warn on non-zero to zero conversion.
12433     DiagID = diag::warn_impcast_float_to_integer_zero;
12434   } else {
12435     if (IntegerValue.isUnsigned()) {
12436       if (!IntegerValue.isMaxValue()) {
12437         return DiagnoseImpCast(S, E, T, CContext,
12438                                diag::warn_impcast_float_integer, PruneWarnings);
12439       }
12440     } else {  // IntegerValue.isSigned()
12441       if (!IntegerValue.isMaxSignedValue() &&
12442           !IntegerValue.isMinSignedValue()) {
12443         return DiagnoseImpCast(S, E, T, CContext,
12444                                diag::warn_impcast_float_integer, PruneWarnings);
12445       }
12446     }
12447     // Warn on evaluatable floating point expression to integer conversion.
12448     DiagID = diag::warn_impcast_float_to_integer;
12449   }
12450 
12451   SmallString<16> PrettyTargetValue;
12452   if (IsBool)
12453     PrettyTargetValue = Value.isZero() ? "false" : "true";
12454   else
12455     IntegerValue.toString(PrettyTargetValue);
12456 
12457   if (PruneWarnings) {
12458     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12459                           S.PDiag(DiagID)
12460                               << E->getType() << T.getUnqualifiedType()
12461                               << PrettySourceValue << PrettyTargetValue
12462                               << E->getSourceRange() << SourceRange(CContext));
12463   } else {
12464     S.Diag(E->getExprLoc(), DiagID)
12465         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12466         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12467   }
12468 }
12469 
12470 /// Analyze the given compound assignment for the possible losing of
12471 /// floating-point precision.
12472 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12473   assert(isa<CompoundAssignOperator>(E) &&
12474          "Must be compound assignment operation");
12475   // Recurse on the LHS and RHS in here
12476   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12477   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12478 
12479   if (E->getLHS()->getType()->isAtomicType())
12480     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12481 
12482   // Now check the outermost expression
12483   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12484   const auto *RBT = cast<CompoundAssignOperator>(E)
12485                         ->getComputationResultType()
12486                         ->getAs<BuiltinType>();
12487 
12488   // The below checks assume source is floating point.
12489   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12490 
12491   // If source is floating point but target is an integer.
12492   if (ResultBT->isInteger())
12493     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12494                            E->getExprLoc(), diag::warn_impcast_float_integer);
12495 
12496   if (!ResultBT->isFloatingPoint())
12497     return;
12498 
12499   // If both source and target are floating points, warn about losing precision.
12500   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12501       QualType(ResultBT, 0), QualType(RBT, 0));
12502   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12503     // warn about dropping FP rank.
12504     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12505                     diag::warn_impcast_float_result_precision);
12506 }
12507 
12508 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12509                                       IntRange Range) {
12510   if (!Range.Width) return "0";
12511 
12512   llvm::APSInt ValueInRange = Value;
12513   ValueInRange.setIsSigned(!Range.NonNegative);
12514   ValueInRange = ValueInRange.trunc(Range.Width);
12515   return toString(ValueInRange, 10);
12516 }
12517 
12518 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12519   if (!isa<ImplicitCastExpr>(Ex))
12520     return false;
12521 
12522   Expr *InnerE = Ex->IgnoreParenImpCasts();
12523   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12524   const Type *Source =
12525     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12526   if (Target->isDependentType())
12527     return false;
12528 
12529   const BuiltinType *FloatCandidateBT =
12530     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12531   const Type *BoolCandidateType = ToBool ? Target : Source;
12532 
12533   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12534           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12535 }
12536 
12537 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12538                                              SourceLocation CC) {
12539   unsigned NumArgs = TheCall->getNumArgs();
12540   for (unsigned i = 0; i < NumArgs; ++i) {
12541     Expr *CurrA = TheCall->getArg(i);
12542     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12543       continue;
12544 
12545     bool IsSwapped = ((i > 0) &&
12546         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12547     IsSwapped |= ((i < (NumArgs - 1)) &&
12548         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12549     if (IsSwapped) {
12550       // Warn on this floating-point to bool conversion.
12551       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12552                       CurrA->getType(), CC,
12553                       diag::warn_impcast_floating_point_to_bool);
12554     }
12555   }
12556 }
12557 
12558 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12559                                    SourceLocation CC) {
12560   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12561                         E->getExprLoc()))
12562     return;
12563 
12564   // Don't warn on functions which have return type nullptr_t.
12565   if (isa<CallExpr>(E))
12566     return;
12567 
12568   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12569   const Expr::NullPointerConstantKind NullKind =
12570       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12571   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12572     return;
12573 
12574   // Return if target type is a safe conversion.
12575   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12576       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12577     return;
12578 
12579   SourceLocation Loc = E->getSourceRange().getBegin();
12580 
12581   // Venture through the macro stacks to get to the source of macro arguments.
12582   // The new location is a better location than the complete location that was
12583   // passed in.
12584   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12585   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12586 
12587   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12588   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12589     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12590         Loc, S.SourceMgr, S.getLangOpts());
12591     if (MacroName == "NULL")
12592       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12593   }
12594 
12595   // Only warn if the null and context location are in the same macro expansion.
12596   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12597     return;
12598 
12599   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12600       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12601       << FixItHint::CreateReplacement(Loc,
12602                                       S.getFixItZeroLiteralForType(T, Loc));
12603 }
12604 
12605 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12606                                   ObjCArrayLiteral *ArrayLiteral);
12607 
12608 static void
12609 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12610                            ObjCDictionaryLiteral *DictionaryLiteral);
12611 
12612 /// Check a single element within a collection literal against the
12613 /// target element type.
12614 static void checkObjCCollectionLiteralElement(Sema &S,
12615                                               QualType TargetElementType,
12616                                               Expr *Element,
12617                                               unsigned ElementKind) {
12618   // Skip a bitcast to 'id' or qualified 'id'.
12619   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12620     if (ICE->getCastKind() == CK_BitCast &&
12621         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12622       Element = ICE->getSubExpr();
12623   }
12624 
12625   QualType ElementType = Element->getType();
12626   ExprResult ElementResult(Element);
12627   if (ElementType->getAs<ObjCObjectPointerType>() &&
12628       S.CheckSingleAssignmentConstraints(TargetElementType,
12629                                          ElementResult,
12630                                          false, false)
12631         != Sema::Compatible) {
12632     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12633         << ElementType << ElementKind << TargetElementType
12634         << Element->getSourceRange();
12635   }
12636 
12637   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12638     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12639   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12640     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12641 }
12642 
12643 /// Check an Objective-C array literal being converted to the given
12644 /// target type.
12645 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12646                                   ObjCArrayLiteral *ArrayLiteral) {
12647   if (!S.NSArrayDecl)
12648     return;
12649 
12650   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12651   if (!TargetObjCPtr)
12652     return;
12653 
12654   if (TargetObjCPtr->isUnspecialized() ||
12655       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12656         != S.NSArrayDecl->getCanonicalDecl())
12657     return;
12658 
12659   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12660   if (TypeArgs.size() != 1)
12661     return;
12662 
12663   QualType TargetElementType = TypeArgs[0];
12664   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12665     checkObjCCollectionLiteralElement(S, TargetElementType,
12666                                       ArrayLiteral->getElement(I),
12667                                       0);
12668   }
12669 }
12670 
12671 /// Check an Objective-C dictionary literal being converted to the given
12672 /// target type.
12673 static void
12674 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12675                            ObjCDictionaryLiteral *DictionaryLiteral) {
12676   if (!S.NSDictionaryDecl)
12677     return;
12678 
12679   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12680   if (!TargetObjCPtr)
12681     return;
12682 
12683   if (TargetObjCPtr->isUnspecialized() ||
12684       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12685         != S.NSDictionaryDecl->getCanonicalDecl())
12686     return;
12687 
12688   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12689   if (TypeArgs.size() != 2)
12690     return;
12691 
12692   QualType TargetKeyType = TypeArgs[0];
12693   QualType TargetObjectType = TypeArgs[1];
12694   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12695     auto Element = DictionaryLiteral->getKeyValueElement(I);
12696     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12697     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12698   }
12699 }
12700 
12701 // Helper function to filter out cases for constant width constant conversion.
12702 // Don't warn on char array initialization or for non-decimal values.
12703 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12704                                           SourceLocation CC) {
12705   // If initializing from a constant, and the constant starts with '0',
12706   // then it is a binary, octal, or hexadecimal.  Allow these constants
12707   // to fill all the bits, even if there is a sign change.
12708   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12709     const char FirstLiteralCharacter =
12710         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12711     if (FirstLiteralCharacter == '0')
12712       return false;
12713   }
12714 
12715   // If the CC location points to a '{', and the type is char, then assume
12716   // assume it is an array initialization.
12717   if (CC.isValid() && T->isCharType()) {
12718     const char FirstContextCharacter =
12719         S.getSourceManager().getCharacterData(CC)[0];
12720     if (FirstContextCharacter == '{')
12721       return false;
12722   }
12723 
12724   return true;
12725 }
12726 
12727 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12728   const auto *IL = dyn_cast<IntegerLiteral>(E);
12729   if (!IL) {
12730     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12731       if (UO->getOpcode() == UO_Minus)
12732         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12733     }
12734   }
12735 
12736   return IL;
12737 }
12738 
12739 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12740   E = E->IgnoreParenImpCasts();
12741   SourceLocation ExprLoc = E->getExprLoc();
12742 
12743   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12744     BinaryOperator::Opcode Opc = BO->getOpcode();
12745     Expr::EvalResult Result;
12746     // Do not diagnose unsigned shifts.
12747     if (Opc == BO_Shl) {
12748       const auto *LHS = getIntegerLiteral(BO->getLHS());
12749       const auto *RHS = getIntegerLiteral(BO->getRHS());
12750       if (LHS && LHS->getValue() == 0)
12751         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12752       else if (!E->isValueDependent() && LHS && RHS &&
12753                RHS->getValue().isNonNegative() &&
12754                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12755         S.Diag(ExprLoc, diag::warn_left_shift_always)
12756             << (Result.Val.getInt() != 0);
12757       else if (E->getType()->isSignedIntegerType())
12758         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12759     }
12760   }
12761 
12762   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12763     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12764     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12765     if (!LHS || !RHS)
12766       return;
12767     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12768         (RHS->getValue() == 0 || RHS->getValue() == 1))
12769       // Do not diagnose common idioms.
12770       return;
12771     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12772       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12773   }
12774 }
12775 
12776 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12777                                     SourceLocation CC,
12778                                     bool *ICContext = nullptr,
12779                                     bool IsListInit = false) {
12780   if (E->isTypeDependent() || E->isValueDependent()) return;
12781 
12782   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12783   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12784   if (Source == Target) return;
12785   if (Target->isDependentType()) return;
12786 
12787   // If the conversion context location is invalid don't complain. We also
12788   // don't want to emit a warning if the issue occurs from the expansion of
12789   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12790   // delay this check as long as possible. Once we detect we are in that
12791   // scenario, we just return.
12792   if (CC.isInvalid())
12793     return;
12794 
12795   if (Source->isAtomicType())
12796     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12797 
12798   // Diagnose implicit casts to bool.
12799   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12800     if (isa<StringLiteral>(E))
12801       // Warn on string literal to bool.  Checks for string literals in logical
12802       // and expressions, for instance, assert(0 && "error here"), are
12803       // prevented by a check in AnalyzeImplicitConversions().
12804       return DiagnoseImpCast(S, E, T, CC,
12805                              diag::warn_impcast_string_literal_to_bool);
12806     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12807         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12808       // This covers the literal expressions that evaluate to Objective-C
12809       // objects.
12810       return DiagnoseImpCast(S, E, T, CC,
12811                              diag::warn_impcast_objective_c_literal_to_bool);
12812     }
12813     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12814       // Warn on pointer to bool conversion that is always true.
12815       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12816                                      SourceRange(CC));
12817     }
12818   }
12819 
12820   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12821   // is a typedef for signed char (macOS), then that constant value has to be 1
12822   // or 0.
12823   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12824     Expr::EvalResult Result;
12825     if (E->EvaluateAsInt(Result, S.getASTContext(),
12826                          Expr::SE_AllowSideEffects)) {
12827       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12828         adornObjCBoolConversionDiagWithTernaryFixit(
12829             S, E,
12830             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12831                 << toString(Result.Val.getInt(), 10));
12832       }
12833       return;
12834     }
12835   }
12836 
12837   // Check implicit casts from Objective-C collection literals to specialized
12838   // collection types, e.g., NSArray<NSString *> *.
12839   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12840     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12841   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12842     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12843 
12844   // Strip vector types.
12845   if (isa<VectorType>(Source)) {
12846     if (Target->isVLSTBuiltinType() &&
12847         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
12848                                          QualType(Source, 0)) ||
12849          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
12850                                             QualType(Source, 0))))
12851       return;
12852 
12853     if (!isa<VectorType>(Target)) {
12854       if (S.SourceMgr.isInSystemMacro(CC))
12855         return;
12856       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12857     }
12858 
12859     // If the vector cast is cast between two vectors of the same size, it is
12860     // a bitcast, not a conversion.
12861     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12862       return;
12863 
12864     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12865     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12866   }
12867   if (auto VecTy = dyn_cast<VectorType>(Target))
12868     Target = VecTy->getElementType().getTypePtr();
12869 
12870   // Strip complex types.
12871   if (isa<ComplexType>(Source)) {
12872     if (!isa<ComplexType>(Target)) {
12873       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12874         return;
12875 
12876       return DiagnoseImpCast(S, E, T, CC,
12877                              S.getLangOpts().CPlusPlus
12878                                  ? diag::err_impcast_complex_scalar
12879                                  : diag::warn_impcast_complex_scalar);
12880     }
12881 
12882     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12883     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12884   }
12885 
12886   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12887   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12888 
12889   // If the source is floating point...
12890   if (SourceBT && SourceBT->isFloatingPoint()) {
12891     // ...and the target is floating point...
12892     if (TargetBT && TargetBT->isFloatingPoint()) {
12893       // ...then warn if we're dropping FP rank.
12894 
12895       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12896           QualType(SourceBT, 0), QualType(TargetBT, 0));
12897       if (Order > 0) {
12898         // Don't warn about float constants that are precisely
12899         // representable in the target type.
12900         Expr::EvalResult result;
12901         if (E->EvaluateAsRValue(result, S.Context)) {
12902           // Value might be a float, a float vector, or a float complex.
12903           if (IsSameFloatAfterCast(result.Val,
12904                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12905                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12906             return;
12907         }
12908 
12909         if (S.SourceMgr.isInSystemMacro(CC))
12910           return;
12911 
12912         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12913       }
12914       // ... or possibly if we're increasing rank, too
12915       else if (Order < 0) {
12916         if (S.SourceMgr.isInSystemMacro(CC))
12917           return;
12918 
12919         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12920       }
12921       return;
12922     }
12923 
12924     // If the target is integral, always warn.
12925     if (TargetBT && TargetBT->isInteger()) {
12926       if (S.SourceMgr.isInSystemMacro(CC))
12927         return;
12928 
12929       DiagnoseFloatingImpCast(S, E, T, CC);
12930     }
12931 
12932     // Detect the case where a call result is converted from floating-point to
12933     // to bool, and the final argument to the call is converted from bool, to
12934     // discover this typo:
12935     //
12936     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12937     //
12938     // FIXME: This is an incredibly special case; is there some more general
12939     // way to detect this class of misplaced-parentheses bug?
12940     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12941       // Check last argument of function call to see if it is an
12942       // implicit cast from a type matching the type the result
12943       // is being cast to.
12944       CallExpr *CEx = cast<CallExpr>(E);
12945       if (unsigned NumArgs = CEx->getNumArgs()) {
12946         Expr *LastA = CEx->getArg(NumArgs - 1);
12947         Expr *InnerE = LastA->IgnoreParenImpCasts();
12948         if (isa<ImplicitCastExpr>(LastA) &&
12949             InnerE->getType()->isBooleanType()) {
12950           // Warn on this floating-point to bool conversion
12951           DiagnoseImpCast(S, E, T, CC,
12952                           diag::warn_impcast_floating_point_to_bool);
12953         }
12954       }
12955     }
12956     return;
12957   }
12958 
12959   // Valid casts involving fixed point types should be accounted for here.
12960   if (Source->isFixedPointType()) {
12961     if (Target->isUnsaturatedFixedPointType()) {
12962       Expr::EvalResult Result;
12963       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12964                                   S.isConstantEvaluated())) {
12965         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12966         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12967         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12968         if (Value > MaxVal || Value < MinVal) {
12969           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12970                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12971                                     << Value.toString() << T
12972                                     << E->getSourceRange()
12973                                     << clang::SourceRange(CC));
12974           return;
12975         }
12976       }
12977     } else if (Target->isIntegerType()) {
12978       Expr::EvalResult Result;
12979       if (!S.isConstantEvaluated() &&
12980           E->EvaluateAsFixedPoint(Result, S.Context,
12981                                   Expr::SE_AllowSideEffects)) {
12982         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12983 
12984         bool Overflowed;
12985         llvm::APSInt IntResult = FXResult.convertToInt(
12986             S.Context.getIntWidth(T),
12987             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12988 
12989         if (Overflowed) {
12990           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12991                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12992                                     << FXResult.toString() << T
12993                                     << E->getSourceRange()
12994                                     << clang::SourceRange(CC));
12995           return;
12996         }
12997       }
12998     }
12999   } else if (Target->isUnsaturatedFixedPointType()) {
13000     if (Source->isIntegerType()) {
13001       Expr::EvalResult Result;
13002       if (!S.isConstantEvaluated() &&
13003           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
13004         llvm::APSInt Value = Result.Val.getInt();
13005 
13006         bool Overflowed;
13007         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13008             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
13009 
13010         if (Overflowed) {
13011           S.DiagRuntimeBehavior(E->getExprLoc(), E,
13012                                 S.PDiag(diag::warn_impcast_fixed_point_range)
13013                                     << toString(Value, /*Radix=*/10) << T
13014                                     << E->getSourceRange()
13015                                     << clang::SourceRange(CC));
13016           return;
13017         }
13018       }
13019     }
13020   }
13021 
13022   // If we are casting an integer type to a floating point type without
13023   // initialization-list syntax, we might lose accuracy if the floating
13024   // point type has a narrower significand than the integer type.
13025   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13026       TargetBT->isFloatingType() && !IsListInit) {
13027     // Determine the number of precision bits in the source integer type.
13028     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
13029                                         /*Approximate*/ true);
13030     unsigned int SourcePrecision = SourceRange.Width;
13031 
13032     // Determine the number of precision bits in the
13033     // target floating point type.
13034     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13035         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13036 
13037     if (SourcePrecision > 0 && TargetPrecision > 0 &&
13038         SourcePrecision > TargetPrecision) {
13039 
13040       if (Optional<llvm::APSInt> SourceInt =
13041               E->getIntegerConstantExpr(S.Context)) {
13042         // If the source integer is a constant, convert it to the target
13043         // floating point type. Issue a warning if the value changes
13044         // during the whole conversion.
13045         llvm::APFloat TargetFloatValue(
13046             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13047         llvm::APFloat::opStatus ConversionStatus =
13048             TargetFloatValue.convertFromAPInt(
13049                 *SourceInt, SourceBT->isSignedInteger(),
13050                 llvm::APFloat::rmNearestTiesToEven);
13051 
13052         if (ConversionStatus != llvm::APFloat::opOK) {
13053           SmallString<32> PrettySourceValue;
13054           SourceInt->toString(PrettySourceValue, 10);
13055           SmallString<32> PrettyTargetValue;
13056           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13057 
13058           S.DiagRuntimeBehavior(
13059               E->getExprLoc(), E,
13060               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
13061                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
13062                   << E->getSourceRange() << clang::SourceRange(CC));
13063         }
13064       } else {
13065         // Otherwise, the implicit conversion may lose precision.
13066         DiagnoseImpCast(S, E, T, CC,
13067                         diag::warn_impcast_integer_float_precision);
13068       }
13069     }
13070   }
13071 
13072   DiagnoseNullConversion(S, E, T, CC);
13073 
13074   S.DiscardMisalignedMemberAddress(Target, E);
13075 
13076   if (Target->isBooleanType())
13077     DiagnoseIntInBoolContext(S, E);
13078 
13079   if (!Source->isIntegerType() || !Target->isIntegerType())
13080     return;
13081 
13082   // TODO: remove this early return once the false positives for constant->bool
13083   // in templates, macros, etc, are reduced or removed.
13084   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13085     return;
13086 
13087   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
13088       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13089     return adornObjCBoolConversionDiagWithTernaryFixit(
13090         S, E,
13091         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13092             << E->getType());
13093   }
13094 
13095   IntRange SourceTypeRange =
13096       IntRange::forTargetOfCanonicalType(S.Context, Source);
13097   IntRange LikelySourceRange =
13098       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
13099   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
13100 
13101   if (LikelySourceRange.Width > TargetRange.Width) {
13102     // If the source is a constant, use a default-on diagnostic.
13103     // TODO: this should happen for bitfield stores, too.
13104     Expr::EvalResult Result;
13105     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
13106                          S.isConstantEvaluated())) {
13107       llvm::APSInt Value(32);
13108       Value = Result.Val.getInt();
13109 
13110       if (S.SourceMgr.isInSystemMacro(CC))
13111         return;
13112 
13113       std::string PrettySourceValue = toString(Value, 10);
13114       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13115 
13116       S.DiagRuntimeBehavior(
13117           E->getExprLoc(), E,
13118           S.PDiag(diag::warn_impcast_integer_precision_constant)
13119               << PrettySourceValue << PrettyTargetValue << E->getType() << T
13120               << E->getSourceRange() << SourceRange(CC));
13121       return;
13122     }
13123 
13124     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13125     if (S.SourceMgr.isInSystemMacro(CC))
13126       return;
13127 
13128     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
13129       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
13130                              /* pruneControlFlow */ true);
13131     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
13132   }
13133 
13134   if (TargetRange.Width > SourceTypeRange.Width) {
13135     if (auto *UO = dyn_cast<UnaryOperator>(E))
13136       if (UO->getOpcode() == UO_Minus)
13137         if (Source->isUnsignedIntegerType()) {
13138           if (Target->isUnsignedIntegerType())
13139             return DiagnoseImpCast(S, E, T, CC,
13140                                    diag::warn_impcast_high_order_zero_bits);
13141           if (Target->isSignedIntegerType())
13142             return DiagnoseImpCast(S, E, T, CC,
13143                                    diag::warn_impcast_nonnegative_result);
13144         }
13145   }
13146 
13147   if (TargetRange.Width == LikelySourceRange.Width &&
13148       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13149       Source->isSignedIntegerType()) {
13150     // Warn when doing a signed to signed conversion, warn if the positive
13151     // source value is exactly the width of the target type, which will
13152     // cause a negative value to be stored.
13153 
13154     Expr::EvalResult Result;
13155     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13156         !S.SourceMgr.isInSystemMacro(CC)) {
13157       llvm::APSInt Value = Result.Val.getInt();
13158       if (isSameWidthConstantConversion(S, E, T, CC)) {
13159         std::string PrettySourceValue = toString(Value, 10);
13160         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13161 
13162         S.DiagRuntimeBehavior(
13163             E->getExprLoc(), E,
13164             S.PDiag(diag::warn_impcast_integer_precision_constant)
13165                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13166                 << E->getSourceRange() << SourceRange(CC));
13167         return;
13168       }
13169     }
13170 
13171     // Fall through for non-constants to give a sign conversion warning.
13172   }
13173 
13174   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13175       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13176        LikelySourceRange.Width == TargetRange.Width)) {
13177     if (S.SourceMgr.isInSystemMacro(CC))
13178       return;
13179 
13180     unsigned DiagID = diag::warn_impcast_integer_sign;
13181 
13182     // Traditionally, gcc has warned about this under -Wsign-compare.
13183     // We also want to warn about it in -Wconversion.
13184     // So if -Wconversion is off, use a completely identical diagnostic
13185     // in the sign-compare group.
13186     // The conditional-checking code will
13187     if (ICContext) {
13188       DiagID = diag::warn_impcast_integer_sign_conditional;
13189       *ICContext = true;
13190     }
13191 
13192     return DiagnoseImpCast(S, E, T, CC, DiagID);
13193   }
13194 
13195   // Diagnose conversions between different enumeration types.
13196   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13197   // type, to give us better diagnostics.
13198   QualType SourceType = E->getType();
13199   if (!S.getLangOpts().CPlusPlus) {
13200     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13201       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13202         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13203         SourceType = S.Context.getTypeDeclType(Enum);
13204         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13205       }
13206   }
13207 
13208   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13209     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13210       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13211           TargetEnum->getDecl()->hasNameForLinkage() &&
13212           SourceEnum != TargetEnum) {
13213         if (S.SourceMgr.isInSystemMacro(CC))
13214           return;
13215 
13216         return DiagnoseImpCast(S, E, SourceType, T, CC,
13217                                diag::warn_impcast_different_enum_types);
13218       }
13219 }
13220 
13221 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13222                                      SourceLocation CC, QualType T);
13223 
13224 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13225                                     SourceLocation CC, bool &ICContext) {
13226   E = E->IgnoreParenImpCasts();
13227 
13228   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13229     return CheckConditionalOperator(S, CO, CC, T);
13230 
13231   AnalyzeImplicitConversions(S, E, CC);
13232   if (E->getType() != T)
13233     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13234 }
13235 
13236 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13237                                      SourceLocation CC, QualType T) {
13238   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13239 
13240   Expr *TrueExpr = E->getTrueExpr();
13241   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13242     TrueExpr = BCO->getCommon();
13243 
13244   bool Suspicious = false;
13245   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13246   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13247 
13248   if (T->isBooleanType())
13249     DiagnoseIntInBoolContext(S, E);
13250 
13251   // If -Wconversion would have warned about either of the candidates
13252   // for a signedness conversion to the context type...
13253   if (!Suspicious) return;
13254 
13255   // ...but it's currently ignored...
13256   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13257     return;
13258 
13259   // ...then check whether it would have warned about either of the
13260   // candidates for a signedness conversion to the condition type.
13261   if (E->getType() == T) return;
13262 
13263   Suspicious = false;
13264   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13265                           E->getType(), CC, &Suspicious);
13266   if (!Suspicious)
13267     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13268                             E->getType(), CC, &Suspicious);
13269 }
13270 
13271 /// Check conversion of given expression to boolean.
13272 /// Input argument E is a logical expression.
13273 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13274   if (S.getLangOpts().Bool)
13275     return;
13276   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13277     return;
13278   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13279 }
13280 
13281 namespace {
13282 struct AnalyzeImplicitConversionsWorkItem {
13283   Expr *E;
13284   SourceLocation CC;
13285   bool IsListInit;
13286 };
13287 }
13288 
13289 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13290 /// that should be visited are added to WorkList.
13291 static void AnalyzeImplicitConversions(
13292     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13293     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13294   Expr *OrigE = Item.E;
13295   SourceLocation CC = Item.CC;
13296 
13297   QualType T = OrigE->getType();
13298   Expr *E = OrigE->IgnoreParenImpCasts();
13299 
13300   // Propagate whether we are in a C++ list initialization expression.
13301   // If so, we do not issue warnings for implicit int-float conversion
13302   // precision loss, because C++11 narrowing already handles it.
13303   bool IsListInit = Item.IsListInit ||
13304                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13305 
13306   if (E->isTypeDependent() || E->isValueDependent())
13307     return;
13308 
13309   Expr *SourceExpr = E;
13310   // Examine, but don't traverse into the source expression of an
13311   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13312   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13313   // evaluate it in the context of checking the specific conversion to T though.
13314   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13315     if (auto *Src = OVE->getSourceExpr())
13316       SourceExpr = Src;
13317 
13318   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13319     if (UO->getOpcode() == UO_Not &&
13320         UO->getSubExpr()->isKnownToHaveBooleanValue())
13321       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13322           << OrigE->getSourceRange() << T->isBooleanType()
13323           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13324 
13325   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
13326     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13327         BO->getLHS()->isKnownToHaveBooleanValue() &&
13328         BO->getRHS()->isKnownToHaveBooleanValue() &&
13329         BO->getLHS()->HasSideEffects(S.Context) &&
13330         BO->getRHS()->HasSideEffects(S.Context)) {
13331       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13332           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
13333           << FixItHint::CreateReplacement(
13334                  BO->getOperatorLoc(),
13335                  (BO->getOpcode() == BO_And ? "&&" : "||"));
13336       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13337     }
13338 
13339   // For conditional operators, we analyze the arguments as if they
13340   // were being fed directly into the output.
13341   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13342     CheckConditionalOperator(S, CO, CC, T);
13343     return;
13344   }
13345 
13346   // Check implicit argument conversions for function calls.
13347   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13348     CheckImplicitArgumentConversions(S, Call, CC);
13349 
13350   // Go ahead and check any implicit conversions we might have skipped.
13351   // The non-canonical typecheck is just an optimization;
13352   // CheckImplicitConversion will filter out dead implicit conversions.
13353   if (SourceExpr->getType() != T)
13354     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13355 
13356   // Now continue drilling into this expression.
13357 
13358   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13359     // The bound subexpressions in a PseudoObjectExpr are not reachable
13360     // as transitive children.
13361     // FIXME: Use a more uniform representation for this.
13362     for (auto *SE : POE->semantics())
13363       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13364         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13365   }
13366 
13367   // Skip past explicit casts.
13368   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13369     E = CE->getSubExpr()->IgnoreParenImpCasts();
13370     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13371       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13372     WorkList.push_back({E, CC, IsListInit});
13373     return;
13374   }
13375 
13376   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13377     // Do a somewhat different check with comparison operators.
13378     if (BO->isComparisonOp())
13379       return AnalyzeComparison(S, BO);
13380 
13381     // And with simple assignments.
13382     if (BO->getOpcode() == BO_Assign)
13383       return AnalyzeAssignment(S, BO);
13384     // And with compound assignments.
13385     if (BO->isAssignmentOp())
13386       return AnalyzeCompoundAssignment(S, BO);
13387   }
13388 
13389   // These break the otherwise-useful invariant below.  Fortunately,
13390   // we don't really need to recurse into them, because any internal
13391   // expressions should have been analyzed already when they were
13392   // built into statements.
13393   if (isa<StmtExpr>(E)) return;
13394 
13395   // Don't descend into unevaluated contexts.
13396   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13397 
13398   // Now just recurse over the expression's children.
13399   CC = E->getExprLoc();
13400   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13401   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13402   for (Stmt *SubStmt : E->children()) {
13403     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13404     if (!ChildExpr)
13405       continue;
13406 
13407     if (IsLogicalAndOperator &&
13408         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13409       // Ignore checking string literals that are in logical and operators.
13410       // This is a common pattern for asserts.
13411       continue;
13412     WorkList.push_back({ChildExpr, CC, IsListInit});
13413   }
13414 
13415   if (BO && BO->isLogicalOp()) {
13416     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13417     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13418       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13419 
13420     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13421     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13422       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13423   }
13424 
13425   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13426     if (U->getOpcode() == UO_LNot) {
13427       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13428     } else if (U->getOpcode() != UO_AddrOf) {
13429       if (U->getSubExpr()->getType()->isAtomicType())
13430         S.Diag(U->getSubExpr()->getBeginLoc(),
13431                diag::warn_atomic_implicit_seq_cst);
13432     }
13433   }
13434 }
13435 
13436 /// AnalyzeImplicitConversions - Find and report any interesting
13437 /// implicit conversions in the given expression.  There are a couple
13438 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13439 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13440                                        bool IsListInit/*= false*/) {
13441   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13442   WorkList.push_back({OrigE, CC, IsListInit});
13443   while (!WorkList.empty())
13444     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13445 }
13446 
13447 /// Diagnose integer type and any valid implicit conversion to it.
13448 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13449   // Taking into account implicit conversions,
13450   // allow any integer.
13451   if (!E->getType()->isIntegerType()) {
13452     S.Diag(E->getBeginLoc(),
13453            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13454     return true;
13455   }
13456   // Potentially emit standard warnings for implicit conversions if enabled
13457   // using -Wconversion.
13458   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13459   return false;
13460 }
13461 
13462 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13463 // Returns true when emitting a warning about taking the address of a reference.
13464 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13465                               const PartialDiagnostic &PD) {
13466   E = E->IgnoreParenImpCasts();
13467 
13468   const FunctionDecl *FD = nullptr;
13469 
13470   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13471     if (!DRE->getDecl()->getType()->isReferenceType())
13472       return false;
13473   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13474     if (!M->getMemberDecl()->getType()->isReferenceType())
13475       return false;
13476   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13477     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13478       return false;
13479     FD = Call->getDirectCallee();
13480   } else {
13481     return false;
13482   }
13483 
13484   SemaRef.Diag(E->getExprLoc(), PD);
13485 
13486   // If possible, point to location of function.
13487   if (FD) {
13488     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13489   }
13490 
13491   return true;
13492 }
13493 
13494 // Returns true if the SourceLocation is expanded from any macro body.
13495 // Returns false if the SourceLocation is invalid, is from not in a macro
13496 // expansion, or is from expanded from a top-level macro argument.
13497 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13498   if (Loc.isInvalid())
13499     return false;
13500 
13501   while (Loc.isMacroID()) {
13502     if (SM.isMacroBodyExpansion(Loc))
13503       return true;
13504     Loc = SM.getImmediateMacroCallerLoc(Loc);
13505   }
13506 
13507   return false;
13508 }
13509 
13510 /// Diagnose pointers that are always non-null.
13511 /// \param E the expression containing the pointer
13512 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13513 /// compared to a null pointer
13514 /// \param IsEqual True when the comparison is equal to a null pointer
13515 /// \param Range Extra SourceRange to highlight in the diagnostic
13516 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13517                                         Expr::NullPointerConstantKind NullKind,
13518                                         bool IsEqual, SourceRange Range) {
13519   if (!E)
13520     return;
13521 
13522   // Don't warn inside macros.
13523   if (E->getExprLoc().isMacroID()) {
13524     const SourceManager &SM = getSourceManager();
13525     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13526         IsInAnyMacroBody(SM, Range.getBegin()))
13527       return;
13528   }
13529   E = E->IgnoreImpCasts();
13530 
13531   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13532 
13533   if (isa<CXXThisExpr>(E)) {
13534     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13535                                 : diag::warn_this_bool_conversion;
13536     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13537     return;
13538   }
13539 
13540   bool IsAddressOf = false;
13541 
13542   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13543     if (UO->getOpcode() != UO_AddrOf)
13544       return;
13545     IsAddressOf = true;
13546     E = UO->getSubExpr();
13547   }
13548 
13549   if (IsAddressOf) {
13550     unsigned DiagID = IsCompare
13551                           ? diag::warn_address_of_reference_null_compare
13552                           : diag::warn_address_of_reference_bool_conversion;
13553     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13554                                          << IsEqual;
13555     if (CheckForReference(*this, E, PD)) {
13556       return;
13557     }
13558   }
13559 
13560   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13561     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13562     std::string Str;
13563     llvm::raw_string_ostream S(Str);
13564     E->printPretty(S, nullptr, getPrintingPolicy());
13565     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13566                                 : diag::warn_cast_nonnull_to_bool;
13567     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13568       << E->getSourceRange() << Range << IsEqual;
13569     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13570   };
13571 
13572   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13573   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13574     if (auto *Callee = Call->getDirectCallee()) {
13575       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13576         ComplainAboutNonnullParamOrCall(A);
13577         return;
13578       }
13579     }
13580   }
13581 
13582   // Expect to find a single Decl.  Skip anything more complicated.
13583   ValueDecl *D = nullptr;
13584   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13585     D = R->getDecl();
13586   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13587     D = M->getMemberDecl();
13588   }
13589 
13590   // Weak Decls can be null.
13591   if (!D || D->isWeak())
13592     return;
13593 
13594   // Check for parameter decl with nonnull attribute
13595   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13596     if (getCurFunction() &&
13597         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13598       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13599         ComplainAboutNonnullParamOrCall(A);
13600         return;
13601       }
13602 
13603       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13604         // Skip function template not specialized yet.
13605         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13606           return;
13607         auto ParamIter = llvm::find(FD->parameters(), PV);
13608         assert(ParamIter != FD->param_end());
13609         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13610 
13611         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13612           if (!NonNull->args_size()) {
13613               ComplainAboutNonnullParamOrCall(NonNull);
13614               return;
13615           }
13616 
13617           for (const ParamIdx &ArgNo : NonNull->args()) {
13618             if (ArgNo.getASTIndex() == ParamNo) {
13619               ComplainAboutNonnullParamOrCall(NonNull);
13620               return;
13621             }
13622           }
13623         }
13624       }
13625     }
13626   }
13627 
13628   QualType T = D->getType();
13629   const bool IsArray = T->isArrayType();
13630   const bool IsFunction = T->isFunctionType();
13631 
13632   // Address of function is used to silence the function warning.
13633   if (IsAddressOf && IsFunction) {
13634     return;
13635   }
13636 
13637   // Found nothing.
13638   if (!IsAddressOf && !IsFunction && !IsArray)
13639     return;
13640 
13641   // Pretty print the expression for the diagnostic.
13642   std::string Str;
13643   llvm::raw_string_ostream S(Str);
13644   E->printPretty(S, nullptr, getPrintingPolicy());
13645 
13646   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13647                               : diag::warn_impcast_pointer_to_bool;
13648   enum {
13649     AddressOf,
13650     FunctionPointer,
13651     ArrayPointer
13652   } DiagType;
13653   if (IsAddressOf)
13654     DiagType = AddressOf;
13655   else if (IsFunction)
13656     DiagType = FunctionPointer;
13657   else if (IsArray)
13658     DiagType = ArrayPointer;
13659   else
13660     llvm_unreachable("Could not determine diagnostic.");
13661   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13662                                 << Range << IsEqual;
13663 
13664   if (!IsFunction)
13665     return;
13666 
13667   // Suggest '&' to silence the function warning.
13668   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13669       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13670 
13671   // Check to see if '()' fixit should be emitted.
13672   QualType ReturnType;
13673   UnresolvedSet<4> NonTemplateOverloads;
13674   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13675   if (ReturnType.isNull())
13676     return;
13677 
13678   if (IsCompare) {
13679     // There are two cases here.  If there is null constant, the only suggest
13680     // for a pointer return type.  If the null is 0, then suggest if the return
13681     // type is a pointer or an integer type.
13682     if (!ReturnType->isPointerType()) {
13683       if (NullKind == Expr::NPCK_ZeroExpression ||
13684           NullKind == Expr::NPCK_ZeroLiteral) {
13685         if (!ReturnType->isIntegerType())
13686           return;
13687       } else {
13688         return;
13689       }
13690     }
13691   } else { // !IsCompare
13692     // For function to bool, only suggest if the function pointer has bool
13693     // return type.
13694     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13695       return;
13696   }
13697   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13698       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13699 }
13700 
13701 /// Diagnoses "dangerous" implicit conversions within the given
13702 /// expression (which is a full expression).  Implements -Wconversion
13703 /// and -Wsign-compare.
13704 ///
13705 /// \param CC the "context" location of the implicit conversion, i.e.
13706 ///   the most location of the syntactic entity requiring the implicit
13707 ///   conversion
13708 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13709   // Don't diagnose in unevaluated contexts.
13710   if (isUnevaluatedContext())
13711     return;
13712 
13713   // Don't diagnose for value- or type-dependent expressions.
13714   if (E->isTypeDependent() || E->isValueDependent())
13715     return;
13716 
13717   // Check for array bounds violations in cases where the check isn't triggered
13718   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13719   // ArraySubscriptExpr is on the RHS of a variable initialization.
13720   CheckArrayAccess(E);
13721 
13722   // This is not the right CC for (e.g.) a variable initialization.
13723   AnalyzeImplicitConversions(*this, E, CC);
13724 }
13725 
13726 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13727 /// Input argument E is a logical expression.
13728 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13729   ::CheckBoolLikeConversion(*this, E, CC);
13730 }
13731 
13732 /// Diagnose when expression is an integer constant expression and its evaluation
13733 /// results in integer overflow
13734 void Sema::CheckForIntOverflow (Expr *E) {
13735   // Use a work list to deal with nested struct initializers.
13736   SmallVector<Expr *, 2> Exprs(1, E);
13737 
13738   do {
13739     Expr *OriginalE = Exprs.pop_back_val();
13740     Expr *E = OriginalE->IgnoreParenCasts();
13741 
13742     if (isa<BinaryOperator>(E)) {
13743       E->EvaluateForOverflow(Context);
13744       continue;
13745     }
13746 
13747     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13748       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13749     else if (isa<ObjCBoxedExpr>(OriginalE))
13750       E->EvaluateForOverflow(Context);
13751     else if (auto Call = dyn_cast<CallExpr>(E))
13752       Exprs.append(Call->arg_begin(), Call->arg_end());
13753     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13754       Exprs.append(Message->arg_begin(), Message->arg_end());
13755   } while (!Exprs.empty());
13756 }
13757 
13758 namespace {
13759 
13760 /// Visitor for expressions which looks for unsequenced operations on the
13761 /// same object.
13762 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13763   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13764 
13765   /// A tree of sequenced regions within an expression. Two regions are
13766   /// unsequenced if one is an ancestor or a descendent of the other. When we
13767   /// finish processing an expression with sequencing, such as a comma
13768   /// expression, we fold its tree nodes into its parent, since they are
13769   /// unsequenced with respect to nodes we will visit later.
13770   class SequenceTree {
13771     struct Value {
13772       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13773       unsigned Parent : 31;
13774       unsigned Merged : 1;
13775     };
13776     SmallVector<Value, 8> Values;
13777 
13778   public:
13779     /// A region within an expression which may be sequenced with respect
13780     /// to some other region.
13781     class Seq {
13782       friend class SequenceTree;
13783 
13784       unsigned Index;
13785 
13786       explicit Seq(unsigned N) : Index(N) {}
13787 
13788     public:
13789       Seq() : Index(0) {}
13790     };
13791 
13792     SequenceTree() { Values.push_back(Value(0)); }
13793     Seq root() const { return Seq(0); }
13794 
13795     /// Create a new sequence of operations, which is an unsequenced
13796     /// subset of \p Parent. This sequence of operations is sequenced with
13797     /// respect to other children of \p Parent.
13798     Seq allocate(Seq Parent) {
13799       Values.push_back(Value(Parent.Index));
13800       return Seq(Values.size() - 1);
13801     }
13802 
13803     /// Merge a sequence of operations into its parent.
13804     void merge(Seq S) {
13805       Values[S.Index].Merged = true;
13806     }
13807 
13808     /// Determine whether two operations are unsequenced. This operation
13809     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13810     /// should have been merged into its parent as appropriate.
13811     bool isUnsequenced(Seq Cur, Seq Old) {
13812       unsigned C = representative(Cur.Index);
13813       unsigned Target = representative(Old.Index);
13814       while (C >= Target) {
13815         if (C == Target)
13816           return true;
13817         C = Values[C].Parent;
13818       }
13819       return false;
13820     }
13821 
13822   private:
13823     /// Pick a representative for a sequence.
13824     unsigned representative(unsigned K) {
13825       if (Values[K].Merged)
13826         // Perform path compression as we go.
13827         return Values[K].Parent = representative(Values[K].Parent);
13828       return K;
13829     }
13830   };
13831 
13832   /// An object for which we can track unsequenced uses.
13833   using Object = const NamedDecl *;
13834 
13835   /// Different flavors of object usage which we track. We only track the
13836   /// least-sequenced usage of each kind.
13837   enum UsageKind {
13838     /// A read of an object. Multiple unsequenced reads are OK.
13839     UK_Use,
13840 
13841     /// A modification of an object which is sequenced before the value
13842     /// computation of the expression, such as ++n in C++.
13843     UK_ModAsValue,
13844 
13845     /// A modification of an object which is not sequenced before the value
13846     /// computation of the expression, such as n++.
13847     UK_ModAsSideEffect,
13848 
13849     UK_Count = UK_ModAsSideEffect + 1
13850   };
13851 
13852   /// Bundle together a sequencing region and the expression corresponding
13853   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13854   struct Usage {
13855     const Expr *UsageExpr;
13856     SequenceTree::Seq Seq;
13857 
13858     Usage() : UsageExpr(nullptr), Seq() {}
13859   };
13860 
13861   struct UsageInfo {
13862     Usage Uses[UK_Count];
13863 
13864     /// Have we issued a diagnostic for this object already?
13865     bool Diagnosed;
13866 
13867     UsageInfo() : Uses(), Diagnosed(false) {}
13868   };
13869   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13870 
13871   Sema &SemaRef;
13872 
13873   /// Sequenced regions within the expression.
13874   SequenceTree Tree;
13875 
13876   /// Declaration modifications and references which we have seen.
13877   UsageInfoMap UsageMap;
13878 
13879   /// The region we are currently within.
13880   SequenceTree::Seq Region;
13881 
13882   /// Filled in with declarations which were modified as a side-effect
13883   /// (that is, post-increment operations).
13884   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13885 
13886   /// Expressions to check later. We defer checking these to reduce
13887   /// stack usage.
13888   SmallVectorImpl<const Expr *> &WorkList;
13889 
13890   /// RAII object wrapping the visitation of a sequenced subexpression of an
13891   /// expression. At the end of this process, the side-effects of the evaluation
13892   /// become sequenced with respect to the value computation of the result, so
13893   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13894   /// UK_ModAsValue.
13895   struct SequencedSubexpression {
13896     SequencedSubexpression(SequenceChecker &Self)
13897       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13898       Self.ModAsSideEffect = &ModAsSideEffect;
13899     }
13900 
13901     ~SequencedSubexpression() {
13902       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13903         // Add a new usage with usage kind UK_ModAsValue, and then restore
13904         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13905         // the previous one was empty).
13906         UsageInfo &UI = Self.UsageMap[M.first];
13907         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13908         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13909         SideEffectUsage = M.second;
13910       }
13911       Self.ModAsSideEffect = OldModAsSideEffect;
13912     }
13913 
13914     SequenceChecker &Self;
13915     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13916     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13917   };
13918 
13919   /// RAII object wrapping the visitation of a subexpression which we might
13920   /// choose to evaluate as a constant. If any subexpression is evaluated and
13921   /// found to be non-constant, this allows us to suppress the evaluation of
13922   /// the outer expression.
13923   class EvaluationTracker {
13924   public:
13925     EvaluationTracker(SequenceChecker &Self)
13926         : Self(Self), Prev(Self.EvalTracker) {
13927       Self.EvalTracker = this;
13928     }
13929 
13930     ~EvaluationTracker() {
13931       Self.EvalTracker = Prev;
13932       if (Prev)
13933         Prev->EvalOK &= EvalOK;
13934     }
13935 
13936     bool evaluate(const Expr *E, bool &Result) {
13937       if (!EvalOK || E->isValueDependent())
13938         return false;
13939       EvalOK = E->EvaluateAsBooleanCondition(
13940           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13941       return EvalOK;
13942     }
13943 
13944   private:
13945     SequenceChecker &Self;
13946     EvaluationTracker *Prev;
13947     bool EvalOK = true;
13948   } *EvalTracker = nullptr;
13949 
13950   /// Find the object which is produced by the specified expression,
13951   /// if any.
13952   Object getObject(const Expr *E, bool Mod) const {
13953     E = E->IgnoreParenCasts();
13954     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13955       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13956         return getObject(UO->getSubExpr(), Mod);
13957     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13958       if (BO->getOpcode() == BO_Comma)
13959         return getObject(BO->getRHS(), Mod);
13960       if (Mod && BO->isAssignmentOp())
13961         return getObject(BO->getLHS(), Mod);
13962     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13963       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13964       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13965         return ME->getMemberDecl();
13966     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13967       // FIXME: If this is a reference, map through to its value.
13968       return DRE->getDecl();
13969     return nullptr;
13970   }
13971 
13972   /// Note that an object \p O was modified or used by an expression
13973   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13974   /// the object \p O as obtained via the \p UsageMap.
13975   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13976     // Get the old usage for the given object and usage kind.
13977     Usage &U = UI.Uses[UK];
13978     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13979       // If we have a modification as side effect and are in a sequenced
13980       // subexpression, save the old Usage so that we can restore it later
13981       // in SequencedSubexpression::~SequencedSubexpression.
13982       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13983         ModAsSideEffect->push_back(std::make_pair(O, U));
13984       // Then record the new usage with the current sequencing region.
13985       U.UsageExpr = UsageExpr;
13986       U.Seq = Region;
13987     }
13988   }
13989 
13990   /// Check whether a modification or use of an object \p O in an expression
13991   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13992   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13993   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13994   /// usage and false we are checking for a mod-use unsequenced usage.
13995   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13996                   UsageKind OtherKind, bool IsModMod) {
13997     if (UI.Diagnosed)
13998       return;
13999 
14000     const Usage &U = UI.Uses[OtherKind];
14001     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14002       return;
14003 
14004     const Expr *Mod = U.UsageExpr;
14005     const Expr *ModOrUse = UsageExpr;
14006     if (OtherKind == UK_Use)
14007       std::swap(Mod, ModOrUse);
14008 
14009     SemaRef.DiagRuntimeBehavior(
14010         Mod->getExprLoc(), {Mod, ModOrUse},
14011         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14012                                : diag::warn_unsequenced_mod_use)
14013             << O << SourceRange(ModOrUse->getExprLoc()));
14014     UI.Diagnosed = true;
14015   }
14016 
14017   // A note on note{Pre, Post}{Use, Mod}:
14018   //
14019   // (It helps to follow the algorithm with an expression such as
14020   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14021   //  operations before C++17 and both are well-defined in C++17).
14022   //
14023   // When visiting a node which uses/modify an object we first call notePreUse
14024   // or notePreMod before visiting its sub-expression(s). At this point the
14025   // children of the current node have not yet been visited and so the eventual
14026   // uses/modifications resulting from the children of the current node have not
14027   // been recorded yet.
14028   //
14029   // We then visit the children of the current node. After that notePostUse or
14030   // notePostMod is called. These will 1) detect an unsequenced modification
14031   // as side effect (as in "k++ + k") and 2) add a new usage with the
14032   // appropriate usage kind.
14033   //
14034   // We also have to be careful that some operation sequences modification as
14035   // side effect as well (for example: || or ,). To account for this we wrap
14036   // the visitation of such a sub-expression (for example: the LHS of || or ,)
14037   // with SequencedSubexpression. SequencedSubexpression is an RAII object
14038   // which record usages which are modifications as side effect, and then
14039   // downgrade them (or more accurately restore the previous usage which was a
14040   // modification as side effect) when exiting the scope of the sequenced
14041   // subexpression.
14042 
14043   void notePreUse(Object O, const Expr *UseExpr) {
14044     UsageInfo &UI = UsageMap[O];
14045     // Uses conflict with other modifications.
14046     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14047   }
14048 
14049   void notePostUse(Object O, const Expr *UseExpr) {
14050     UsageInfo &UI = UsageMap[O];
14051     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14052                /*IsModMod=*/false);
14053     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14054   }
14055 
14056   void notePreMod(Object O, const Expr *ModExpr) {
14057     UsageInfo &UI = UsageMap[O];
14058     // Modifications conflict with other modifications and with uses.
14059     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14060     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14061   }
14062 
14063   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14064     UsageInfo &UI = UsageMap[O];
14065     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14066                /*IsModMod=*/true);
14067     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14068   }
14069 
14070 public:
14071   SequenceChecker(Sema &S, const Expr *E,
14072                   SmallVectorImpl<const Expr *> &WorkList)
14073       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14074     Visit(E);
14075     // Silence a -Wunused-private-field since WorkList is now unused.
14076     // TODO: Evaluate if it can be used, and if not remove it.
14077     (void)this->WorkList;
14078   }
14079 
14080   void VisitStmt(const Stmt *S) {
14081     // Skip all statements which aren't expressions for now.
14082   }
14083 
14084   void VisitExpr(const Expr *E) {
14085     // By default, just recurse to evaluated subexpressions.
14086     Base::VisitStmt(E);
14087   }
14088 
14089   void VisitCastExpr(const CastExpr *E) {
14090     Object O = Object();
14091     if (E->getCastKind() == CK_LValueToRValue)
14092       O = getObject(E->getSubExpr(), false);
14093 
14094     if (O)
14095       notePreUse(O, E);
14096     VisitExpr(E);
14097     if (O)
14098       notePostUse(O, E);
14099   }
14100 
14101   void VisitSequencedExpressions(const Expr *SequencedBefore,
14102                                  const Expr *SequencedAfter) {
14103     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14104     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14105     SequenceTree::Seq OldRegion = Region;
14106 
14107     {
14108       SequencedSubexpression SeqBefore(*this);
14109       Region = BeforeRegion;
14110       Visit(SequencedBefore);
14111     }
14112 
14113     Region = AfterRegion;
14114     Visit(SequencedAfter);
14115 
14116     Region = OldRegion;
14117 
14118     Tree.merge(BeforeRegion);
14119     Tree.merge(AfterRegion);
14120   }
14121 
14122   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14123     // C++17 [expr.sub]p1:
14124     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14125     //   expression E1 is sequenced before the expression E2.
14126     if (SemaRef.getLangOpts().CPlusPlus17)
14127       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14128     else {
14129       Visit(ASE->getLHS());
14130       Visit(ASE->getRHS());
14131     }
14132   }
14133 
14134   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14135   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14136   void VisitBinPtrMem(const BinaryOperator *BO) {
14137     // C++17 [expr.mptr.oper]p4:
14138     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14139     //  the expression E1 is sequenced before the expression E2.
14140     if (SemaRef.getLangOpts().CPlusPlus17)
14141       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14142     else {
14143       Visit(BO->getLHS());
14144       Visit(BO->getRHS());
14145     }
14146   }
14147 
14148   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14149   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14150   void VisitBinShlShr(const BinaryOperator *BO) {
14151     // C++17 [expr.shift]p4:
14152     //  The expression E1 is sequenced before the expression E2.
14153     if (SemaRef.getLangOpts().CPlusPlus17)
14154       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14155     else {
14156       Visit(BO->getLHS());
14157       Visit(BO->getRHS());
14158     }
14159   }
14160 
14161   void VisitBinComma(const BinaryOperator *BO) {
14162     // C++11 [expr.comma]p1:
14163     //   Every value computation and side effect associated with the left
14164     //   expression is sequenced before every value computation and side
14165     //   effect associated with the right expression.
14166     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14167   }
14168 
14169   void VisitBinAssign(const BinaryOperator *BO) {
14170     SequenceTree::Seq RHSRegion;
14171     SequenceTree::Seq LHSRegion;
14172     if (SemaRef.getLangOpts().CPlusPlus17) {
14173       RHSRegion = Tree.allocate(Region);
14174       LHSRegion = Tree.allocate(Region);
14175     } else {
14176       RHSRegion = Region;
14177       LHSRegion = Region;
14178     }
14179     SequenceTree::Seq OldRegion = Region;
14180 
14181     // C++11 [expr.ass]p1:
14182     //  [...] the assignment is sequenced after the value computation
14183     //  of the right and left operands, [...]
14184     //
14185     // so check it before inspecting the operands and update the
14186     // map afterwards.
14187     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14188     if (O)
14189       notePreMod(O, BO);
14190 
14191     if (SemaRef.getLangOpts().CPlusPlus17) {
14192       // C++17 [expr.ass]p1:
14193       //  [...] The right operand is sequenced before the left operand. [...]
14194       {
14195         SequencedSubexpression SeqBefore(*this);
14196         Region = RHSRegion;
14197         Visit(BO->getRHS());
14198       }
14199 
14200       Region = LHSRegion;
14201       Visit(BO->getLHS());
14202 
14203       if (O && isa<CompoundAssignOperator>(BO))
14204         notePostUse(O, BO);
14205 
14206     } else {
14207       // C++11 does not specify any sequencing between the LHS and RHS.
14208       Region = LHSRegion;
14209       Visit(BO->getLHS());
14210 
14211       if (O && isa<CompoundAssignOperator>(BO))
14212         notePostUse(O, BO);
14213 
14214       Region = RHSRegion;
14215       Visit(BO->getRHS());
14216     }
14217 
14218     // C++11 [expr.ass]p1:
14219     //  the assignment is sequenced [...] before the value computation of the
14220     //  assignment expression.
14221     // C11 6.5.16/3 has no such rule.
14222     Region = OldRegion;
14223     if (O)
14224       notePostMod(O, BO,
14225                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14226                                                   : UK_ModAsSideEffect);
14227     if (SemaRef.getLangOpts().CPlusPlus17) {
14228       Tree.merge(RHSRegion);
14229       Tree.merge(LHSRegion);
14230     }
14231   }
14232 
14233   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14234     VisitBinAssign(CAO);
14235   }
14236 
14237   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14238   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14239   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14240     Object O = getObject(UO->getSubExpr(), true);
14241     if (!O)
14242       return VisitExpr(UO);
14243 
14244     notePreMod(O, UO);
14245     Visit(UO->getSubExpr());
14246     // C++11 [expr.pre.incr]p1:
14247     //   the expression ++x is equivalent to x+=1
14248     notePostMod(O, UO,
14249                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14250                                                 : UK_ModAsSideEffect);
14251   }
14252 
14253   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14254   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14255   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14256     Object O = getObject(UO->getSubExpr(), true);
14257     if (!O)
14258       return VisitExpr(UO);
14259 
14260     notePreMod(O, UO);
14261     Visit(UO->getSubExpr());
14262     notePostMod(O, UO, UK_ModAsSideEffect);
14263   }
14264 
14265   void VisitBinLOr(const BinaryOperator *BO) {
14266     // C++11 [expr.log.or]p2:
14267     //  If the second expression is evaluated, every value computation and
14268     //  side effect associated with the first expression is sequenced before
14269     //  every value computation and side effect associated with the
14270     //  second expression.
14271     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14272     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14273     SequenceTree::Seq OldRegion = Region;
14274 
14275     EvaluationTracker Eval(*this);
14276     {
14277       SequencedSubexpression Sequenced(*this);
14278       Region = LHSRegion;
14279       Visit(BO->getLHS());
14280     }
14281 
14282     // C++11 [expr.log.or]p1:
14283     //  [...] the second operand is not evaluated if the first operand
14284     //  evaluates to true.
14285     bool EvalResult = false;
14286     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14287     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14288     if (ShouldVisitRHS) {
14289       Region = RHSRegion;
14290       Visit(BO->getRHS());
14291     }
14292 
14293     Region = OldRegion;
14294     Tree.merge(LHSRegion);
14295     Tree.merge(RHSRegion);
14296   }
14297 
14298   void VisitBinLAnd(const BinaryOperator *BO) {
14299     // C++11 [expr.log.and]p2:
14300     //  If the second expression is evaluated, every value computation and
14301     //  side effect associated with the first expression is sequenced before
14302     //  every value computation and side effect associated with the
14303     //  second expression.
14304     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14305     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14306     SequenceTree::Seq OldRegion = Region;
14307 
14308     EvaluationTracker Eval(*this);
14309     {
14310       SequencedSubexpression Sequenced(*this);
14311       Region = LHSRegion;
14312       Visit(BO->getLHS());
14313     }
14314 
14315     // C++11 [expr.log.and]p1:
14316     //  [...] the second operand is not evaluated if the first operand is false.
14317     bool EvalResult = false;
14318     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14319     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14320     if (ShouldVisitRHS) {
14321       Region = RHSRegion;
14322       Visit(BO->getRHS());
14323     }
14324 
14325     Region = OldRegion;
14326     Tree.merge(LHSRegion);
14327     Tree.merge(RHSRegion);
14328   }
14329 
14330   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14331     // C++11 [expr.cond]p1:
14332     //  [...] Every value computation and side effect associated with the first
14333     //  expression is sequenced before every value computation and side effect
14334     //  associated with the second or third expression.
14335     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14336 
14337     // No sequencing is specified between the true and false expression.
14338     // However since exactly one of both is going to be evaluated we can
14339     // consider them to be sequenced. This is needed to avoid warning on
14340     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14341     // both the true and false expressions because we can't evaluate x.
14342     // This will still allow us to detect an expression like (pre C++17)
14343     // "(x ? y += 1 : y += 2) = y".
14344     //
14345     // We don't wrap the visitation of the true and false expression with
14346     // SequencedSubexpression because we don't want to downgrade modifications
14347     // as side effect in the true and false expressions after the visition
14348     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14349     // not warn between the two "y++", but we should warn between the "y++"
14350     // and the "y".
14351     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14352     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14353     SequenceTree::Seq OldRegion = Region;
14354 
14355     EvaluationTracker Eval(*this);
14356     {
14357       SequencedSubexpression Sequenced(*this);
14358       Region = ConditionRegion;
14359       Visit(CO->getCond());
14360     }
14361 
14362     // C++11 [expr.cond]p1:
14363     // [...] The first expression is contextually converted to bool (Clause 4).
14364     // It is evaluated and if it is true, the result of the conditional
14365     // expression is the value of the second expression, otherwise that of the
14366     // third expression. Only one of the second and third expressions is
14367     // evaluated. [...]
14368     bool EvalResult = false;
14369     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14370     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14371     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14372     if (ShouldVisitTrueExpr) {
14373       Region = TrueRegion;
14374       Visit(CO->getTrueExpr());
14375     }
14376     if (ShouldVisitFalseExpr) {
14377       Region = FalseRegion;
14378       Visit(CO->getFalseExpr());
14379     }
14380 
14381     Region = OldRegion;
14382     Tree.merge(ConditionRegion);
14383     Tree.merge(TrueRegion);
14384     Tree.merge(FalseRegion);
14385   }
14386 
14387   void VisitCallExpr(const CallExpr *CE) {
14388     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14389 
14390     if (CE->isUnevaluatedBuiltinCall(Context))
14391       return;
14392 
14393     // C++11 [intro.execution]p15:
14394     //   When calling a function [...], every value computation and side effect
14395     //   associated with any argument expression, or with the postfix expression
14396     //   designating the called function, is sequenced before execution of every
14397     //   expression or statement in the body of the function [and thus before
14398     //   the value computation of its result].
14399     SequencedSubexpression Sequenced(*this);
14400     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14401       // C++17 [expr.call]p5
14402       //   The postfix-expression is sequenced before each expression in the
14403       //   expression-list and any default argument. [...]
14404       SequenceTree::Seq CalleeRegion;
14405       SequenceTree::Seq OtherRegion;
14406       if (SemaRef.getLangOpts().CPlusPlus17) {
14407         CalleeRegion = Tree.allocate(Region);
14408         OtherRegion = Tree.allocate(Region);
14409       } else {
14410         CalleeRegion = Region;
14411         OtherRegion = Region;
14412       }
14413       SequenceTree::Seq OldRegion = Region;
14414 
14415       // Visit the callee expression first.
14416       Region = CalleeRegion;
14417       if (SemaRef.getLangOpts().CPlusPlus17) {
14418         SequencedSubexpression Sequenced(*this);
14419         Visit(CE->getCallee());
14420       } else {
14421         Visit(CE->getCallee());
14422       }
14423 
14424       // Then visit the argument expressions.
14425       Region = OtherRegion;
14426       for (const Expr *Argument : CE->arguments())
14427         Visit(Argument);
14428 
14429       Region = OldRegion;
14430       if (SemaRef.getLangOpts().CPlusPlus17) {
14431         Tree.merge(CalleeRegion);
14432         Tree.merge(OtherRegion);
14433       }
14434     });
14435   }
14436 
14437   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14438     // C++17 [over.match.oper]p2:
14439     //   [...] the operator notation is first transformed to the equivalent
14440     //   function-call notation as summarized in Table 12 (where @ denotes one
14441     //   of the operators covered in the specified subclause). However, the
14442     //   operands are sequenced in the order prescribed for the built-in
14443     //   operator (Clause 8).
14444     //
14445     // From the above only overloaded binary operators and overloaded call
14446     // operators have sequencing rules in C++17 that we need to handle
14447     // separately.
14448     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14449         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14450       return VisitCallExpr(CXXOCE);
14451 
14452     enum {
14453       NoSequencing,
14454       LHSBeforeRHS,
14455       RHSBeforeLHS,
14456       LHSBeforeRest
14457     } SequencingKind;
14458     switch (CXXOCE->getOperator()) {
14459     case OO_Equal:
14460     case OO_PlusEqual:
14461     case OO_MinusEqual:
14462     case OO_StarEqual:
14463     case OO_SlashEqual:
14464     case OO_PercentEqual:
14465     case OO_CaretEqual:
14466     case OO_AmpEqual:
14467     case OO_PipeEqual:
14468     case OO_LessLessEqual:
14469     case OO_GreaterGreaterEqual:
14470       SequencingKind = RHSBeforeLHS;
14471       break;
14472 
14473     case OO_LessLess:
14474     case OO_GreaterGreater:
14475     case OO_AmpAmp:
14476     case OO_PipePipe:
14477     case OO_Comma:
14478     case OO_ArrowStar:
14479     case OO_Subscript:
14480       SequencingKind = LHSBeforeRHS;
14481       break;
14482 
14483     case OO_Call:
14484       SequencingKind = LHSBeforeRest;
14485       break;
14486 
14487     default:
14488       SequencingKind = NoSequencing;
14489       break;
14490     }
14491 
14492     if (SequencingKind == NoSequencing)
14493       return VisitCallExpr(CXXOCE);
14494 
14495     // This is a call, so all subexpressions are sequenced before the result.
14496     SequencedSubexpression Sequenced(*this);
14497 
14498     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14499       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14500              "Should only get there with C++17 and above!");
14501       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14502              "Should only get there with an overloaded binary operator"
14503              " or an overloaded call operator!");
14504 
14505       if (SequencingKind == LHSBeforeRest) {
14506         assert(CXXOCE->getOperator() == OO_Call &&
14507                "We should only have an overloaded call operator here!");
14508 
14509         // This is very similar to VisitCallExpr, except that we only have the
14510         // C++17 case. The postfix-expression is the first argument of the
14511         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14512         // are in the following arguments.
14513         //
14514         // Note that we intentionally do not visit the callee expression since
14515         // it is just a decayed reference to a function.
14516         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14517         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14518         SequenceTree::Seq OldRegion = Region;
14519 
14520         assert(CXXOCE->getNumArgs() >= 1 &&
14521                "An overloaded call operator must have at least one argument"
14522                " for the postfix-expression!");
14523         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14524         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14525                                           CXXOCE->getNumArgs() - 1);
14526 
14527         // Visit the postfix-expression first.
14528         {
14529           Region = PostfixExprRegion;
14530           SequencedSubexpression Sequenced(*this);
14531           Visit(PostfixExpr);
14532         }
14533 
14534         // Then visit the argument expressions.
14535         Region = ArgsRegion;
14536         for (const Expr *Arg : Args)
14537           Visit(Arg);
14538 
14539         Region = OldRegion;
14540         Tree.merge(PostfixExprRegion);
14541         Tree.merge(ArgsRegion);
14542       } else {
14543         assert(CXXOCE->getNumArgs() == 2 &&
14544                "Should only have two arguments here!");
14545         assert((SequencingKind == LHSBeforeRHS ||
14546                 SequencingKind == RHSBeforeLHS) &&
14547                "Unexpected sequencing kind!");
14548 
14549         // We do not visit the callee expression since it is just a decayed
14550         // reference to a function.
14551         const Expr *E1 = CXXOCE->getArg(0);
14552         const Expr *E2 = CXXOCE->getArg(1);
14553         if (SequencingKind == RHSBeforeLHS)
14554           std::swap(E1, E2);
14555 
14556         return VisitSequencedExpressions(E1, E2);
14557       }
14558     });
14559   }
14560 
14561   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14562     // This is a call, so all subexpressions are sequenced before the result.
14563     SequencedSubexpression Sequenced(*this);
14564 
14565     if (!CCE->isListInitialization())
14566       return VisitExpr(CCE);
14567 
14568     // In C++11, list initializations are sequenced.
14569     SmallVector<SequenceTree::Seq, 32> Elts;
14570     SequenceTree::Seq Parent = Region;
14571     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14572                                               E = CCE->arg_end();
14573          I != E; ++I) {
14574       Region = Tree.allocate(Parent);
14575       Elts.push_back(Region);
14576       Visit(*I);
14577     }
14578 
14579     // Forget that the initializers are sequenced.
14580     Region = Parent;
14581     for (unsigned I = 0; I < Elts.size(); ++I)
14582       Tree.merge(Elts[I]);
14583   }
14584 
14585   void VisitInitListExpr(const InitListExpr *ILE) {
14586     if (!SemaRef.getLangOpts().CPlusPlus11)
14587       return VisitExpr(ILE);
14588 
14589     // In C++11, list initializations are sequenced.
14590     SmallVector<SequenceTree::Seq, 32> Elts;
14591     SequenceTree::Seq Parent = Region;
14592     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14593       const Expr *E = ILE->getInit(I);
14594       if (!E)
14595         continue;
14596       Region = Tree.allocate(Parent);
14597       Elts.push_back(Region);
14598       Visit(E);
14599     }
14600 
14601     // Forget that the initializers are sequenced.
14602     Region = Parent;
14603     for (unsigned I = 0; I < Elts.size(); ++I)
14604       Tree.merge(Elts[I]);
14605   }
14606 };
14607 
14608 } // namespace
14609 
14610 void Sema::CheckUnsequencedOperations(const Expr *E) {
14611   SmallVector<const Expr *, 8> WorkList;
14612   WorkList.push_back(E);
14613   while (!WorkList.empty()) {
14614     const Expr *Item = WorkList.pop_back_val();
14615     SequenceChecker(*this, Item, WorkList);
14616   }
14617 }
14618 
14619 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14620                               bool IsConstexpr) {
14621   llvm::SaveAndRestore<bool> ConstantContext(
14622       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14623   CheckImplicitConversions(E, CheckLoc);
14624   if (!E->isInstantiationDependent())
14625     CheckUnsequencedOperations(E);
14626   if (!IsConstexpr && !E->isValueDependent())
14627     CheckForIntOverflow(E);
14628   DiagnoseMisalignedMembers();
14629 }
14630 
14631 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14632                                        FieldDecl *BitField,
14633                                        Expr *Init) {
14634   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14635 }
14636 
14637 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14638                                          SourceLocation Loc) {
14639   if (!PType->isVariablyModifiedType())
14640     return;
14641   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14642     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14643     return;
14644   }
14645   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14646     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14647     return;
14648   }
14649   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14650     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14651     return;
14652   }
14653 
14654   const ArrayType *AT = S.Context.getAsArrayType(PType);
14655   if (!AT)
14656     return;
14657 
14658   if (AT->getSizeModifier() != ArrayType::Star) {
14659     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14660     return;
14661   }
14662 
14663   S.Diag(Loc, diag::err_array_star_in_function_definition);
14664 }
14665 
14666 /// CheckParmsForFunctionDef - Check that the parameters of the given
14667 /// function are appropriate for the definition of a function. This
14668 /// takes care of any checks that cannot be performed on the
14669 /// declaration itself, e.g., that the types of each of the function
14670 /// parameters are complete.
14671 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14672                                     bool CheckParameterNames) {
14673   bool HasInvalidParm = false;
14674   for (ParmVarDecl *Param : Parameters) {
14675     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14676     // function declarator that is part of a function definition of
14677     // that function shall not have incomplete type.
14678     //
14679     // This is also C++ [dcl.fct]p6.
14680     if (!Param->isInvalidDecl() &&
14681         RequireCompleteType(Param->getLocation(), Param->getType(),
14682                             diag::err_typecheck_decl_incomplete_type)) {
14683       Param->setInvalidDecl();
14684       HasInvalidParm = true;
14685     }
14686 
14687     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14688     // declaration of each parameter shall include an identifier.
14689     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14690         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14691       // Diagnose this as an extension in C17 and earlier.
14692       if (!getLangOpts().C2x)
14693         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14694     }
14695 
14696     // C99 6.7.5.3p12:
14697     //   If the function declarator is not part of a definition of that
14698     //   function, parameters may have incomplete type and may use the [*]
14699     //   notation in their sequences of declarator specifiers to specify
14700     //   variable length array types.
14701     QualType PType = Param->getOriginalType();
14702     // FIXME: This diagnostic should point the '[*]' if source-location
14703     // information is added for it.
14704     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14705 
14706     // If the parameter is a c++ class type and it has to be destructed in the
14707     // callee function, declare the destructor so that it can be called by the
14708     // callee function. Do not perform any direct access check on the dtor here.
14709     if (!Param->isInvalidDecl()) {
14710       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14711         if (!ClassDecl->isInvalidDecl() &&
14712             !ClassDecl->hasIrrelevantDestructor() &&
14713             !ClassDecl->isDependentContext() &&
14714             ClassDecl->isParamDestroyedInCallee()) {
14715           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14716           MarkFunctionReferenced(Param->getLocation(), Destructor);
14717           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14718         }
14719       }
14720     }
14721 
14722     // Parameters with the pass_object_size attribute only need to be marked
14723     // constant at function definitions. Because we lack information about
14724     // whether we're on a declaration or definition when we're instantiating the
14725     // attribute, we need to check for constness here.
14726     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14727       if (!Param->getType().isConstQualified())
14728         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14729             << Attr->getSpelling() << 1;
14730 
14731     // Check for parameter names shadowing fields from the class.
14732     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14733       // The owning context for the parameter should be the function, but we
14734       // want to see if this function's declaration context is a record.
14735       DeclContext *DC = Param->getDeclContext();
14736       if (DC && DC->isFunctionOrMethod()) {
14737         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14738           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14739                                      RD, /*DeclIsField*/ false);
14740       }
14741     }
14742   }
14743 
14744   return HasInvalidParm;
14745 }
14746 
14747 Optional<std::pair<CharUnits, CharUnits>>
14748 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14749 
14750 /// Compute the alignment and offset of the base class object given the
14751 /// derived-to-base cast expression and the alignment and offset of the derived
14752 /// class object.
14753 static std::pair<CharUnits, CharUnits>
14754 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14755                                    CharUnits BaseAlignment, CharUnits Offset,
14756                                    ASTContext &Ctx) {
14757   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14758        ++PathI) {
14759     const CXXBaseSpecifier *Base = *PathI;
14760     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14761     if (Base->isVirtual()) {
14762       // The complete object may have a lower alignment than the non-virtual
14763       // alignment of the base, in which case the base may be misaligned. Choose
14764       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14765       // conservative lower bound of the complete object alignment.
14766       CharUnits NonVirtualAlignment =
14767           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14768       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14769       Offset = CharUnits::Zero();
14770     } else {
14771       const ASTRecordLayout &RL =
14772           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14773       Offset += RL.getBaseClassOffset(BaseDecl);
14774     }
14775     DerivedType = Base->getType();
14776   }
14777 
14778   return std::make_pair(BaseAlignment, Offset);
14779 }
14780 
14781 /// Compute the alignment and offset of a binary additive operator.
14782 static Optional<std::pair<CharUnits, CharUnits>>
14783 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14784                                      bool IsSub, ASTContext &Ctx) {
14785   QualType PointeeType = PtrE->getType()->getPointeeType();
14786 
14787   if (!PointeeType->isConstantSizeType())
14788     return llvm::None;
14789 
14790   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14791 
14792   if (!P)
14793     return llvm::None;
14794 
14795   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14796   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14797     CharUnits Offset = EltSize * IdxRes->getExtValue();
14798     if (IsSub)
14799       Offset = -Offset;
14800     return std::make_pair(P->first, P->second + Offset);
14801   }
14802 
14803   // If the integer expression isn't a constant expression, compute the lower
14804   // bound of the alignment using the alignment and offset of the pointer
14805   // expression and the element size.
14806   return std::make_pair(
14807       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14808       CharUnits::Zero());
14809 }
14810 
14811 /// This helper function takes an lvalue expression and returns the alignment of
14812 /// a VarDecl and a constant offset from the VarDecl.
14813 Optional<std::pair<CharUnits, CharUnits>>
14814 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14815   E = E->IgnoreParens();
14816   switch (E->getStmtClass()) {
14817   default:
14818     break;
14819   case Stmt::CStyleCastExprClass:
14820   case Stmt::CXXStaticCastExprClass:
14821   case Stmt::ImplicitCastExprClass: {
14822     auto *CE = cast<CastExpr>(E);
14823     const Expr *From = CE->getSubExpr();
14824     switch (CE->getCastKind()) {
14825     default:
14826       break;
14827     case CK_NoOp:
14828       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14829     case CK_UncheckedDerivedToBase:
14830     case CK_DerivedToBase: {
14831       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14832       if (!P)
14833         break;
14834       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14835                                                 P->second, Ctx);
14836     }
14837     }
14838     break;
14839   }
14840   case Stmt::ArraySubscriptExprClass: {
14841     auto *ASE = cast<ArraySubscriptExpr>(E);
14842     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14843                                                 false, Ctx);
14844   }
14845   case Stmt::DeclRefExprClass: {
14846     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14847       // FIXME: If VD is captured by copy or is an escaping __block variable,
14848       // use the alignment of VD's type.
14849       if (!VD->getType()->isReferenceType())
14850         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14851       if (VD->hasInit())
14852         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14853     }
14854     break;
14855   }
14856   case Stmt::MemberExprClass: {
14857     auto *ME = cast<MemberExpr>(E);
14858     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14859     if (!FD || FD->getType()->isReferenceType() ||
14860         FD->getParent()->isInvalidDecl())
14861       break;
14862     Optional<std::pair<CharUnits, CharUnits>> P;
14863     if (ME->isArrow())
14864       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14865     else
14866       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14867     if (!P)
14868       break;
14869     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14870     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14871     return std::make_pair(P->first,
14872                           P->second + CharUnits::fromQuantity(Offset));
14873   }
14874   case Stmt::UnaryOperatorClass: {
14875     auto *UO = cast<UnaryOperator>(E);
14876     switch (UO->getOpcode()) {
14877     default:
14878       break;
14879     case UO_Deref:
14880       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14881     }
14882     break;
14883   }
14884   case Stmt::BinaryOperatorClass: {
14885     auto *BO = cast<BinaryOperator>(E);
14886     auto Opcode = BO->getOpcode();
14887     switch (Opcode) {
14888     default:
14889       break;
14890     case BO_Comma:
14891       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14892     }
14893     break;
14894   }
14895   }
14896   return llvm::None;
14897 }
14898 
14899 /// This helper function takes a pointer expression and returns the alignment of
14900 /// a VarDecl and a constant offset from the VarDecl.
14901 Optional<std::pair<CharUnits, CharUnits>>
14902 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14903   E = E->IgnoreParens();
14904   switch (E->getStmtClass()) {
14905   default:
14906     break;
14907   case Stmt::CStyleCastExprClass:
14908   case Stmt::CXXStaticCastExprClass:
14909   case Stmt::ImplicitCastExprClass: {
14910     auto *CE = cast<CastExpr>(E);
14911     const Expr *From = CE->getSubExpr();
14912     switch (CE->getCastKind()) {
14913     default:
14914       break;
14915     case CK_NoOp:
14916       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14917     case CK_ArrayToPointerDecay:
14918       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14919     case CK_UncheckedDerivedToBase:
14920     case CK_DerivedToBase: {
14921       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14922       if (!P)
14923         break;
14924       return getDerivedToBaseAlignmentAndOffset(
14925           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14926     }
14927     }
14928     break;
14929   }
14930   case Stmt::CXXThisExprClass: {
14931     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14932     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14933     return std::make_pair(Alignment, CharUnits::Zero());
14934   }
14935   case Stmt::UnaryOperatorClass: {
14936     auto *UO = cast<UnaryOperator>(E);
14937     if (UO->getOpcode() == UO_AddrOf)
14938       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14939     break;
14940   }
14941   case Stmt::BinaryOperatorClass: {
14942     auto *BO = cast<BinaryOperator>(E);
14943     auto Opcode = BO->getOpcode();
14944     switch (Opcode) {
14945     default:
14946       break;
14947     case BO_Add:
14948     case BO_Sub: {
14949       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14950       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14951         std::swap(LHS, RHS);
14952       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14953                                                   Ctx);
14954     }
14955     case BO_Comma:
14956       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14957     }
14958     break;
14959   }
14960   }
14961   return llvm::None;
14962 }
14963 
14964 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14965   // See if we can compute the alignment of a VarDecl and an offset from it.
14966   Optional<std::pair<CharUnits, CharUnits>> P =
14967       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14968 
14969   if (P)
14970     return P->first.alignmentAtOffset(P->second);
14971 
14972   // If that failed, return the type's alignment.
14973   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14974 }
14975 
14976 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14977 /// pointer cast increases the alignment requirements.
14978 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14979   // This is actually a lot of work to potentially be doing on every
14980   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14981   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14982     return;
14983 
14984   // Ignore dependent types.
14985   if (T->isDependentType() || Op->getType()->isDependentType())
14986     return;
14987 
14988   // Require that the destination be a pointer type.
14989   const PointerType *DestPtr = T->getAs<PointerType>();
14990   if (!DestPtr) return;
14991 
14992   // If the destination has alignment 1, we're done.
14993   QualType DestPointee = DestPtr->getPointeeType();
14994   if (DestPointee->isIncompleteType()) return;
14995   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14996   if (DestAlign.isOne()) return;
14997 
14998   // Require that the source be a pointer type.
14999   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15000   if (!SrcPtr) return;
15001   QualType SrcPointee = SrcPtr->getPointeeType();
15002 
15003   // Explicitly allow casts from cv void*.  We already implicitly
15004   // allowed casts to cv void*, since they have alignment 1.
15005   // Also allow casts involving incomplete types, which implicitly
15006   // includes 'void'.
15007   if (SrcPointee->isIncompleteType()) return;
15008 
15009   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15010 
15011   if (SrcAlign >= DestAlign) return;
15012 
15013   Diag(TRange.getBegin(), diag::warn_cast_align)
15014     << Op->getType() << T
15015     << static_cast<unsigned>(SrcAlign.getQuantity())
15016     << static_cast<unsigned>(DestAlign.getQuantity())
15017     << TRange << Op->getSourceRange();
15018 }
15019 
15020 /// Check whether this array fits the idiom of a size-one tail padded
15021 /// array member of a struct.
15022 ///
15023 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
15024 /// commonly used to emulate flexible arrays in C89 code.
15025 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
15026                                     const NamedDecl *ND) {
15027   if (Size != 1 || !ND) return false;
15028 
15029   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
15030   if (!FD) return false;
15031 
15032   // Don't consider sizes resulting from macro expansions or template argument
15033   // substitution to form C89 tail-padded arrays.
15034 
15035   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
15036   while (TInfo) {
15037     TypeLoc TL = TInfo->getTypeLoc();
15038     // Look through typedefs.
15039     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
15040       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
15041       TInfo = TDL->getTypeSourceInfo();
15042       continue;
15043     }
15044     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
15045       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
15046       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
15047         return false;
15048     }
15049     break;
15050   }
15051 
15052   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
15053   if (!RD) return false;
15054   if (RD->isUnion()) return false;
15055   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15056     if (!CRD->isStandardLayout()) return false;
15057   }
15058 
15059   // See if this is the last field decl in the record.
15060   const Decl *D = FD;
15061   while ((D = D->getNextDeclInContext()))
15062     if (isa<FieldDecl>(D))
15063       return false;
15064   return true;
15065 }
15066 
15067 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15068                             const ArraySubscriptExpr *ASE,
15069                             bool AllowOnePastEnd, bool IndexNegated) {
15070   // Already diagnosed by the constant evaluator.
15071   if (isConstantEvaluated())
15072     return;
15073 
15074   IndexExpr = IndexExpr->IgnoreParenImpCasts();
15075   if (IndexExpr->isValueDependent())
15076     return;
15077 
15078   const Type *EffectiveType =
15079       BaseExpr->getType()->getPointeeOrArrayElementType();
15080   BaseExpr = BaseExpr->IgnoreParenCasts();
15081   const ConstantArrayType *ArrayTy =
15082       Context.getAsConstantArrayType(BaseExpr->getType());
15083 
15084   const Type *BaseType =
15085       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15086   bool IsUnboundedArray = (BaseType == nullptr);
15087   if (EffectiveType->isDependentType() ||
15088       (!IsUnboundedArray && BaseType->isDependentType()))
15089     return;
15090 
15091   Expr::EvalResult Result;
15092   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15093     return;
15094 
15095   llvm::APSInt index = Result.Val.getInt();
15096   if (IndexNegated) {
15097     index.setIsUnsigned(false);
15098     index = -index;
15099   }
15100 
15101   const NamedDecl *ND = nullptr;
15102   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15103     ND = DRE->getDecl();
15104   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
15105     ND = ME->getMemberDecl();
15106 
15107   if (IsUnboundedArray) {
15108     if (index.isUnsigned() || !index.isNegative()) {
15109       const auto &ASTC = getASTContext();
15110       unsigned AddrBits =
15111           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
15112               EffectiveType->getCanonicalTypeInternal()));
15113       if (index.getBitWidth() < AddrBits)
15114         index = index.zext(AddrBits);
15115       Optional<CharUnits> ElemCharUnits =
15116           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15117       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15118       // pointer) bounds-checking isn't meaningful.
15119       if (!ElemCharUnits)
15120         return;
15121       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15122       // If index has more active bits than address space, we already know
15123       // we have a bounds violation to warn about.  Otherwise, compute
15124       // address of (index + 1)th element, and warn about bounds violation
15125       // only if that address exceeds address space.
15126       if (index.getActiveBits() <= AddrBits) {
15127         bool Overflow;
15128         llvm::APInt Product(index);
15129         Product += 1;
15130         Product = Product.umul_ov(ElemBytes, Overflow);
15131         if (!Overflow && Product.getActiveBits() <= AddrBits)
15132           return;
15133       }
15134 
15135       // Need to compute max possible elements in address space, since that
15136       // is included in diag message.
15137       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15138       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15139       MaxElems += 1;
15140       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15141       MaxElems = MaxElems.udiv(ElemBytes);
15142 
15143       unsigned DiagID =
15144           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15145               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15146 
15147       // Diag message shows element size in bits and in "bytes" (platform-
15148       // dependent CharUnits)
15149       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15150                           PDiag(DiagID)
15151                               << toString(index, 10, true) << AddrBits
15152                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15153                               << toString(ElemBytes, 10, false)
15154                               << toString(MaxElems, 10, false)
15155                               << (unsigned)MaxElems.getLimitedValue(~0U)
15156                               << IndexExpr->getSourceRange());
15157 
15158       if (!ND) {
15159         // Try harder to find a NamedDecl to point at in the note.
15160         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15161           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15162         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15163           ND = DRE->getDecl();
15164         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15165           ND = ME->getMemberDecl();
15166       }
15167 
15168       if (ND)
15169         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15170                             PDiag(diag::note_array_declared_here) << ND);
15171     }
15172     return;
15173   }
15174 
15175   if (index.isUnsigned() || !index.isNegative()) {
15176     // It is possible that the type of the base expression after
15177     // IgnoreParenCasts is incomplete, even though the type of the base
15178     // expression before IgnoreParenCasts is complete (see PR39746 for an
15179     // example). In this case we have no information about whether the array
15180     // access exceeds the array bounds. However we can still diagnose an array
15181     // access which precedes the array bounds.
15182     if (BaseType->isIncompleteType())
15183       return;
15184 
15185     llvm::APInt size = ArrayTy->getSize();
15186     if (!size.isStrictlyPositive())
15187       return;
15188 
15189     if (BaseType != EffectiveType) {
15190       // Make sure we're comparing apples to apples when comparing index to size
15191       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15192       uint64_t array_typesize = Context.getTypeSize(BaseType);
15193       // Handle ptrarith_typesize being zero, such as when casting to void*
15194       if (!ptrarith_typesize) ptrarith_typesize = 1;
15195       if (ptrarith_typesize != array_typesize) {
15196         // There's a cast to a different size type involved
15197         uint64_t ratio = array_typesize / ptrarith_typesize;
15198         // TODO: Be smarter about handling cases where array_typesize is not a
15199         // multiple of ptrarith_typesize
15200         if (ptrarith_typesize * ratio == array_typesize)
15201           size *= llvm::APInt(size.getBitWidth(), ratio);
15202       }
15203     }
15204 
15205     if (size.getBitWidth() > index.getBitWidth())
15206       index = index.zext(size.getBitWidth());
15207     else if (size.getBitWidth() < index.getBitWidth())
15208       size = size.zext(index.getBitWidth());
15209 
15210     // For array subscripting the index must be less than size, but for pointer
15211     // arithmetic also allow the index (offset) to be equal to size since
15212     // computing the next address after the end of the array is legal and
15213     // commonly done e.g. in C++ iterators and range-based for loops.
15214     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15215       return;
15216 
15217     // Also don't warn for arrays of size 1 which are members of some
15218     // structure. These are often used to approximate flexible arrays in C89
15219     // code.
15220     if (IsTailPaddedMemberArray(*this, size, ND))
15221       return;
15222 
15223     // Suppress the warning if the subscript expression (as identified by the
15224     // ']' location) and the index expression are both from macro expansions
15225     // within a system header.
15226     if (ASE) {
15227       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15228           ASE->getRBracketLoc());
15229       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15230         SourceLocation IndexLoc =
15231             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15232         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15233           return;
15234       }
15235     }
15236 
15237     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15238                           : diag::warn_ptr_arith_exceeds_bounds;
15239 
15240     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15241                         PDiag(DiagID) << toString(index, 10, true)
15242                                       << toString(size, 10, true)
15243                                       << (unsigned)size.getLimitedValue(~0U)
15244                                       << IndexExpr->getSourceRange());
15245   } else {
15246     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15247     if (!ASE) {
15248       DiagID = diag::warn_ptr_arith_precedes_bounds;
15249       if (index.isNegative()) index = -index;
15250     }
15251 
15252     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15253                         PDiag(DiagID) << toString(index, 10, true)
15254                                       << IndexExpr->getSourceRange());
15255   }
15256 
15257   if (!ND) {
15258     // Try harder to find a NamedDecl to point at in the note.
15259     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15260       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15261     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15262       ND = DRE->getDecl();
15263     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15264       ND = ME->getMemberDecl();
15265   }
15266 
15267   if (ND)
15268     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15269                         PDiag(diag::note_array_declared_here) << ND);
15270 }
15271 
15272 void Sema::CheckArrayAccess(const Expr *expr) {
15273   int AllowOnePastEnd = 0;
15274   while (expr) {
15275     expr = expr->IgnoreParenImpCasts();
15276     switch (expr->getStmtClass()) {
15277       case Stmt::ArraySubscriptExprClass: {
15278         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15279         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15280                          AllowOnePastEnd > 0);
15281         expr = ASE->getBase();
15282         break;
15283       }
15284       case Stmt::MemberExprClass: {
15285         expr = cast<MemberExpr>(expr)->getBase();
15286         break;
15287       }
15288       case Stmt::OMPArraySectionExprClass: {
15289         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15290         if (ASE->getLowerBound())
15291           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15292                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15293         return;
15294       }
15295       case Stmt::UnaryOperatorClass: {
15296         // Only unwrap the * and & unary operators
15297         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15298         expr = UO->getSubExpr();
15299         switch (UO->getOpcode()) {
15300           case UO_AddrOf:
15301             AllowOnePastEnd++;
15302             break;
15303           case UO_Deref:
15304             AllowOnePastEnd--;
15305             break;
15306           default:
15307             return;
15308         }
15309         break;
15310       }
15311       case Stmt::ConditionalOperatorClass: {
15312         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15313         if (const Expr *lhs = cond->getLHS())
15314           CheckArrayAccess(lhs);
15315         if (const Expr *rhs = cond->getRHS())
15316           CheckArrayAccess(rhs);
15317         return;
15318       }
15319       case Stmt::CXXOperatorCallExprClass: {
15320         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15321         for (const auto *Arg : OCE->arguments())
15322           CheckArrayAccess(Arg);
15323         return;
15324       }
15325       default:
15326         return;
15327     }
15328   }
15329 }
15330 
15331 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15332 
15333 namespace {
15334 
15335 struct RetainCycleOwner {
15336   VarDecl *Variable = nullptr;
15337   SourceRange Range;
15338   SourceLocation Loc;
15339   bool Indirect = false;
15340 
15341   RetainCycleOwner() = default;
15342 
15343   void setLocsFrom(Expr *e) {
15344     Loc = e->getExprLoc();
15345     Range = e->getSourceRange();
15346   }
15347 };
15348 
15349 } // namespace
15350 
15351 /// Consider whether capturing the given variable can possibly lead to
15352 /// a retain cycle.
15353 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15354   // In ARC, it's captured strongly iff the variable has __strong
15355   // lifetime.  In MRR, it's captured strongly if the variable is
15356   // __block and has an appropriate type.
15357   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15358     return false;
15359 
15360   owner.Variable = var;
15361   if (ref)
15362     owner.setLocsFrom(ref);
15363   return true;
15364 }
15365 
15366 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15367   while (true) {
15368     e = e->IgnoreParens();
15369     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15370       switch (cast->getCastKind()) {
15371       case CK_BitCast:
15372       case CK_LValueBitCast:
15373       case CK_LValueToRValue:
15374       case CK_ARCReclaimReturnedObject:
15375         e = cast->getSubExpr();
15376         continue;
15377 
15378       default:
15379         return false;
15380       }
15381     }
15382 
15383     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15384       ObjCIvarDecl *ivar = ref->getDecl();
15385       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15386         return false;
15387 
15388       // Try to find a retain cycle in the base.
15389       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15390         return false;
15391 
15392       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15393       owner.Indirect = true;
15394       return true;
15395     }
15396 
15397     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15398       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15399       if (!var) return false;
15400       return considerVariable(var, ref, owner);
15401     }
15402 
15403     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15404       if (member->isArrow()) return false;
15405 
15406       // Don't count this as an indirect ownership.
15407       e = member->getBase();
15408       continue;
15409     }
15410 
15411     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15412       // Only pay attention to pseudo-objects on property references.
15413       ObjCPropertyRefExpr *pre
15414         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15415                                               ->IgnoreParens());
15416       if (!pre) return false;
15417       if (pre->isImplicitProperty()) return false;
15418       ObjCPropertyDecl *property = pre->getExplicitProperty();
15419       if (!property->isRetaining() &&
15420           !(property->getPropertyIvarDecl() &&
15421             property->getPropertyIvarDecl()->getType()
15422               .getObjCLifetime() == Qualifiers::OCL_Strong))
15423           return false;
15424 
15425       owner.Indirect = true;
15426       if (pre->isSuperReceiver()) {
15427         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15428         if (!owner.Variable)
15429           return false;
15430         owner.Loc = pre->getLocation();
15431         owner.Range = pre->getSourceRange();
15432         return true;
15433       }
15434       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15435                               ->getSourceExpr());
15436       continue;
15437     }
15438 
15439     // Array ivars?
15440 
15441     return false;
15442   }
15443 }
15444 
15445 namespace {
15446 
15447   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15448     ASTContext &Context;
15449     VarDecl *Variable;
15450     Expr *Capturer = nullptr;
15451     bool VarWillBeReased = false;
15452 
15453     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15454         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15455           Context(Context), Variable(variable) {}
15456 
15457     void VisitDeclRefExpr(DeclRefExpr *ref) {
15458       if (ref->getDecl() == Variable && !Capturer)
15459         Capturer = ref;
15460     }
15461 
15462     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15463       if (Capturer) return;
15464       Visit(ref->getBase());
15465       if (Capturer && ref->isFreeIvar())
15466         Capturer = ref;
15467     }
15468 
15469     void VisitBlockExpr(BlockExpr *block) {
15470       // Look inside nested blocks
15471       if (block->getBlockDecl()->capturesVariable(Variable))
15472         Visit(block->getBlockDecl()->getBody());
15473     }
15474 
15475     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15476       if (Capturer) return;
15477       if (OVE->getSourceExpr())
15478         Visit(OVE->getSourceExpr());
15479     }
15480 
15481     void VisitBinaryOperator(BinaryOperator *BinOp) {
15482       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15483         return;
15484       Expr *LHS = BinOp->getLHS();
15485       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15486         if (DRE->getDecl() != Variable)
15487           return;
15488         if (Expr *RHS = BinOp->getRHS()) {
15489           RHS = RHS->IgnoreParenCasts();
15490           Optional<llvm::APSInt> Value;
15491           VarWillBeReased =
15492               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15493                *Value == 0);
15494         }
15495       }
15496     }
15497   };
15498 
15499 } // namespace
15500 
15501 /// Check whether the given argument is a block which captures a
15502 /// variable.
15503 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15504   assert(owner.Variable && owner.Loc.isValid());
15505 
15506   e = e->IgnoreParenCasts();
15507 
15508   // Look through [^{...} copy] and Block_copy(^{...}).
15509   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15510     Selector Cmd = ME->getSelector();
15511     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15512       e = ME->getInstanceReceiver();
15513       if (!e)
15514         return nullptr;
15515       e = e->IgnoreParenCasts();
15516     }
15517   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15518     if (CE->getNumArgs() == 1) {
15519       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15520       if (Fn) {
15521         const IdentifierInfo *FnI = Fn->getIdentifier();
15522         if (FnI && FnI->isStr("_Block_copy")) {
15523           e = CE->getArg(0)->IgnoreParenCasts();
15524         }
15525       }
15526     }
15527   }
15528 
15529   BlockExpr *block = dyn_cast<BlockExpr>(e);
15530   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15531     return nullptr;
15532 
15533   FindCaptureVisitor visitor(S.Context, owner.Variable);
15534   visitor.Visit(block->getBlockDecl()->getBody());
15535   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15536 }
15537 
15538 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15539                                 RetainCycleOwner &owner) {
15540   assert(capturer);
15541   assert(owner.Variable && owner.Loc.isValid());
15542 
15543   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15544     << owner.Variable << capturer->getSourceRange();
15545   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15546     << owner.Indirect << owner.Range;
15547 }
15548 
15549 /// Check for a keyword selector that starts with the word 'add' or
15550 /// 'set'.
15551 static bool isSetterLikeSelector(Selector sel) {
15552   if (sel.isUnarySelector()) return false;
15553 
15554   StringRef str = sel.getNameForSlot(0);
15555   while (!str.empty() && str.front() == '_') str = str.substr(1);
15556   if (str.startswith("set"))
15557     str = str.substr(3);
15558   else if (str.startswith("add")) {
15559     // Specially allow 'addOperationWithBlock:'.
15560     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15561       return false;
15562     str = str.substr(3);
15563   }
15564   else
15565     return false;
15566 
15567   if (str.empty()) return true;
15568   return !isLowercase(str.front());
15569 }
15570 
15571 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15572                                                     ObjCMessageExpr *Message) {
15573   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15574                                                 Message->getReceiverInterface(),
15575                                                 NSAPI::ClassId_NSMutableArray);
15576   if (!IsMutableArray) {
15577     return None;
15578   }
15579 
15580   Selector Sel = Message->getSelector();
15581 
15582   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15583     S.NSAPIObj->getNSArrayMethodKind(Sel);
15584   if (!MKOpt) {
15585     return None;
15586   }
15587 
15588   NSAPI::NSArrayMethodKind MK = *MKOpt;
15589 
15590   switch (MK) {
15591     case NSAPI::NSMutableArr_addObject:
15592     case NSAPI::NSMutableArr_insertObjectAtIndex:
15593     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15594       return 0;
15595     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15596       return 1;
15597 
15598     default:
15599       return None;
15600   }
15601 
15602   return None;
15603 }
15604 
15605 static
15606 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15607                                                   ObjCMessageExpr *Message) {
15608   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15609                                             Message->getReceiverInterface(),
15610                                             NSAPI::ClassId_NSMutableDictionary);
15611   if (!IsMutableDictionary) {
15612     return None;
15613   }
15614 
15615   Selector Sel = Message->getSelector();
15616 
15617   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15618     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15619   if (!MKOpt) {
15620     return None;
15621   }
15622 
15623   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15624 
15625   switch (MK) {
15626     case NSAPI::NSMutableDict_setObjectForKey:
15627     case NSAPI::NSMutableDict_setValueForKey:
15628     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15629       return 0;
15630 
15631     default:
15632       return None;
15633   }
15634 
15635   return None;
15636 }
15637 
15638 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15639   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15640                                                 Message->getReceiverInterface(),
15641                                                 NSAPI::ClassId_NSMutableSet);
15642 
15643   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15644                                             Message->getReceiverInterface(),
15645                                             NSAPI::ClassId_NSMutableOrderedSet);
15646   if (!IsMutableSet && !IsMutableOrderedSet) {
15647     return None;
15648   }
15649 
15650   Selector Sel = Message->getSelector();
15651 
15652   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15653   if (!MKOpt) {
15654     return None;
15655   }
15656 
15657   NSAPI::NSSetMethodKind MK = *MKOpt;
15658 
15659   switch (MK) {
15660     case NSAPI::NSMutableSet_addObject:
15661     case NSAPI::NSOrderedSet_setObjectAtIndex:
15662     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15663     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15664       return 0;
15665     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15666       return 1;
15667   }
15668 
15669   return None;
15670 }
15671 
15672 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15673   if (!Message->isInstanceMessage()) {
15674     return;
15675   }
15676 
15677   Optional<int> ArgOpt;
15678 
15679   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15680       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15681       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15682     return;
15683   }
15684 
15685   int ArgIndex = *ArgOpt;
15686 
15687   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15688   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15689     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15690   }
15691 
15692   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15693     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15694       if (ArgRE->isObjCSelfExpr()) {
15695         Diag(Message->getSourceRange().getBegin(),
15696              diag::warn_objc_circular_container)
15697           << ArgRE->getDecl() << StringRef("'super'");
15698       }
15699     }
15700   } else {
15701     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15702 
15703     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15704       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15705     }
15706 
15707     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15708       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15709         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15710           ValueDecl *Decl = ReceiverRE->getDecl();
15711           Diag(Message->getSourceRange().getBegin(),
15712                diag::warn_objc_circular_container)
15713             << Decl << Decl;
15714           if (!ArgRE->isObjCSelfExpr()) {
15715             Diag(Decl->getLocation(),
15716                  diag::note_objc_circular_container_declared_here)
15717               << Decl;
15718           }
15719         }
15720       }
15721     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15722       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15723         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15724           ObjCIvarDecl *Decl = IvarRE->getDecl();
15725           Diag(Message->getSourceRange().getBegin(),
15726                diag::warn_objc_circular_container)
15727             << Decl << Decl;
15728           Diag(Decl->getLocation(),
15729                diag::note_objc_circular_container_declared_here)
15730             << Decl;
15731         }
15732       }
15733     }
15734   }
15735 }
15736 
15737 /// Check a message send to see if it's likely to cause a retain cycle.
15738 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15739   // Only check instance methods whose selector looks like a setter.
15740   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15741     return;
15742 
15743   // Try to find a variable that the receiver is strongly owned by.
15744   RetainCycleOwner owner;
15745   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15746     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15747       return;
15748   } else {
15749     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15750     owner.Variable = getCurMethodDecl()->getSelfDecl();
15751     owner.Loc = msg->getSuperLoc();
15752     owner.Range = msg->getSuperLoc();
15753   }
15754 
15755   // Check whether the receiver is captured by any of the arguments.
15756   const ObjCMethodDecl *MD = msg->getMethodDecl();
15757   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15758     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15759       // noescape blocks should not be retained by the method.
15760       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15761         continue;
15762       return diagnoseRetainCycle(*this, capturer, owner);
15763     }
15764   }
15765 }
15766 
15767 /// Check a property assign to see if it's likely to cause a retain cycle.
15768 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15769   RetainCycleOwner owner;
15770   if (!findRetainCycleOwner(*this, receiver, owner))
15771     return;
15772 
15773   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15774     diagnoseRetainCycle(*this, capturer, owner);
15775 }
15776 
15777 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15778   RetainCycleOwner Owner;
15779   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15780     return;
15781 
15782   // Because we don't have an expression for the variable, we have to set the
15783   // location explicitly here.
15784   Owner.Loc = Var->getLocation();
15785   Owner.Range = Var->getSourceRange();
15786 
15787   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15788     diagnoseRetainCycle(*this, Capturer, Owner);
15789 }
15790 
15791 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15792                                      Expr *RHS, bool isProperty) {
15793   // Check if RHS is an Objective-C object literal, which also can get
15794   // immediately zapped in a weak reference.  Note that we explicitly
15795   // allow ObjCStringLiterals, since those are designed to never really die.
15796   RHS = RHS->IgnoreParenImpCasts();
15797 
15798   // This enum needs to match with the 'select' in
15799   // warn_objc_arc_literal_assign (off-by-1).
15800   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15801   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15802     return false;
15803 
15804   S.Diag(Loc, diag::warn_arc_literal_assign)
15805     << (unsigned) Kind
15806     << (isProperty ? 0 : 1)
15807     << RHS->getSourceRange();
15808 
15809   return true;
15810 }
15811 
15812 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15813                                     Qualifiers::ObjCLifetime LT,
15814                                     Expr *RHS, bool isProperty) {
15815   // Strip off any implicit cast added to get to the one ARC-specific.
15816   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15817     if (cast->getCastKind() == CK_ARCConsumeObject) {
15818       S.Diag(Loc, diag::warn_arc_retained_assign)
15819         << (LT == Qualifiers::OCL_ExplicitNone)
15820         << (isProperty ? 0 : 1)
15821         << RHS->getSourceRange();
15822       return true;
15823     }
15824     RHS = cast->getSubExpr();
15825   }
15826 
15827   if (LT == Qualifiers::OCL_Weak &&
15828       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15829     return true;
15830 
15831   return false;
15832 }
15833 
15834 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15835                               QualType LHS, Expr *RHS) {
15836   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15837 
15838   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15839     return false;
15840 
15841   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15842     return true;
15843 
15844   return false;
15845 }
15846 
15847 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15848                               Expr *LHS, Expr *RHS) {
15849   QualType LHSType;
15850   // PropertyRef on LHS type need be directly obtained from
15851   // its declaration as it has a PseudoType.
15852   ObjCPropertyRefExpr *PRE
15853     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15854   if (PRE && !PRE->isImplicitProperty()) {
15855     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15856     if (PD)
15857       LHSType = PD->getType();
15858   }
15859 
15860   if (LHSType.isNull())
15861     LHSType = LHS->getType();
15862 
15863   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15864 
15865   if (LT == Qualifiers::OCL_Weak) {
15866     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15867       getCurFunction()->markSafeWeakUse(LHS);
15868   }
15869 
15870   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15871     return;
15872 
15873   // FIXME. Check for other life times.
15874   if (LT != Qualifiers::OCL_None)
15875     return;
15876 
15877   if (PRE) {
15878     if (PRE->isImplicitProperty())
15879       return;
15880     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15881     if (!PD)
15882       return;
15883 
15884     unsigned Attributes = PD->getPropertyAttributes();
15885     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15886       // when 'assign' attribute was not explicitly specified
15887       // by user, ignore it and rely on property type itself
15888       // for lifetime info.
15889       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15890       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15891           LHSType->isObjCRetainableType())
15892         return;
15893 
15894       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15895         if (cast->getCastKind() == CK_ARCConsumeObject) {
15896           Diag(Loc, diag::warn_arc_retained_property_assign)
15897           << RHS->getSourceRange();
15898           return;
15899         }
15900         RHS = cast->getSubExpr();
15901       }
15902     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15903       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15904         return;
15905     }
15906   }
15907 }
15908 
15909 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15910 
15911 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15912                                         SourceLocation StmtLoc,
15913                                         const NullStmt *Body) {
15914   // Do not warn if the body is a macro that expands to nothing, e.g:
15915   //
15916   // #define CALL(x)
15917   // if (condition)
15918   //   CALL(0);
15919   if (Body->hasLeadingEmptyMacro())
15920     return false;
15921 
15922   // Get line numbers of statement and body.
15923   bool StmtLineInvalid;
15924   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15925                                                       &StmtLineInvalid);
15926   if (StmtLineInvalid)
15927     return false;
15928 
15929   bool BodyLineInvalid;
15930   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15931                                                       &BodyLineInvalid);
15932   if (BodyLineInvalid)
15933     return false;
15934 
15935   // Warn if null statement and body are on the same line.
15936   if (StmtLine != BodyLine)
15937     return false;
15938 
15939   return true;
15940 }
15941 
15942 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15943                                  const Stmt *Body,
15944                                  unsigned DiagID) {
15945   // Since this is a syntactic check, don't emit diagnostic for template
15946   // instantiations, this just adds noise.
15947   if (CurrentInstantiationScope)
15948     return;
15949 
15950   // The body should be a null statement.
15951   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15952   if (!NBody)
15953     return;
15954 
15955   // Do the usual checks.
15956   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15957     return;
15958 
15959   Diag(NBody->getSemiLoc(), DiagID);
15960   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15961 }
15962 
15963 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15964                                  const Stmt *PossibleBody) {
15965   assert(!CurrentInstantiationScope); // Ensured by caller
15966 
15967   SourceLocation StmtLoc;
15968   const Stmt *Body;
15969   unsigned DiagID;
15970   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15971     StmtLoc = FS->getRParenLoc();
15972     Body = FS->getBody();
15973     DiagID = diag::warn_empty_for_body;
15974   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15975     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15976     Body = WS->getBody();
15977     DiagID = diag::warn_empty_while_body;
15978   } else
15979     return; // Neither `for' nor `while'.
15980 
15981   // The body should be a null statement.
15982   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15983   if (!NBody)
15984     return;
15985 
15986   // Skip expensive checks if diagnostic is disabled.
15987   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15988     return;
15989 
15990   // Do the usual checks.
15991   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15992     return;
15993 
15994   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15995   // noise level low, emit diagnostics only if for/while is followed by a
15996   // CompoundStmt, e.g.:
15997   //    for (int i = 0; i < n; i++);
15998   //    {
15999   //      a(i);
16000   //    }
16001   // or if for/while is followed by a statement with more indentation
16002   // than for/while itself:
16003   //    for (int i = 0; i < n; i++);
16004   //      a(i);
16005   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16006   if (!ProbableTypo) {
16007     bool BodyColInvalid;
16008     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16009         PossibleBody->getBeginLoc(), &BodyColInvalid);
16010     if (BodyColInvalid)
16011       return;
16012 
16013     bool StmtColInvalid;
16014     unsigned StmtCol =
16015         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16016     if (StmtColInvalid)
16017       return;
16018 
16019     if (BodyCol > StmtCol)
16020       ProbableTypo = true;
16021   }
16022 
16023   if (ProbableTypo) {
16024     Diag(NBody->getSemiLoc(), DiagID);
16025     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16026   }
16027 }
16028 
16029 //===--- CHECK: Warn on self move with std::move. -------------------------===//
16030 
16031 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
16032 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16033                              SourceLocation OpLoc) {
16034   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16035     return;
16036 
16037   if (inTemplateInstantiation())
16038     return;
16039 
16040   // Strip parens and casts away.
16041   LHSExpr = LHSExpr->IgnoreParenImpCasts();
16042   RHSExpr = RHSExpr->IgnoreParenImpCasts();
16043 
16044   // Check for a call expression
16045   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
16046   if (!CE || CE->getNumArgs() != 1)
16047     return;
16048 
16049   // Check for a call to std::move
16050   if (!CE->isCallToStdMove())
16051     return;
16052 
16053   // Get argument from std::move
16054   RHSExpr = CE->getArg(0);
16055 
16056   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16057   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16058 
16059   // Two DeclRefExpr's, check that the decls are the same.
16060   if (LHSDeclRef && RHSDeclRef) {
16061     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16062       return;
16063     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16064         RHSDeclRef->getDecl()->getCanonicalDecl())
16065       return;
16066 
16067     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16068                                         << LHSExpr->getSourceRange()
16069                                         << RHSExpr->getSourceRange();
16070     return;
16071   }
16072 
16073   // Member variables require a different approach to check for self moves.
16074   // MemberExpr's are the same if every nested MemberExpr refers to the same
16075   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16076   // the base Expr's are CXXThisExpr's.
16077   const Expr *LHSBase = LHSExpr;
16078   const Expr *RHSBase = RHSExpr;
16079   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16080   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16081   if (!LHSME || !RHSME)
16082     return;
16083 
16084   while (LHSME && RHSME) {
16085     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16086         RHSME->getMemberDecl()->getCanonicalDecl())
16087       return;
16088 
16089     LHSBase = LHSME->getBase();
16090     RHSBase = RHSME->getBase();
16091     LHSME = dyn_cast<MemberExpr>(LHSBase);
16092     RHSME = dyn_cast<MemberExpr>(RHSBase);
16093   }
16094 
16095   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16096   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16097   if (LHSDeclRef && RHSDeclRef) {
16098     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16099       return;
16100     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16101         RHSDeclRef->getDecl()->getCanonicalDecl())
16102       return;
16103 
16104     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16105                                         << LHSExpr->getSourceRange()
16106                                         << RHSExpr->getSourceRange();
16107     return;
16108   }
16109 
16110   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16111     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16112                                         << LHSExpr->getSourceRange()
16113                                         << RHSExpr->getSourceRange();
16114 }
16115 
16116 //===--- Layout compatibility ----------------------------------------------//
16117 
16118 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
16119 
16120 /// Check if two enumeration types are layout-compatible.
16121 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
16122   // C++11 [dcl.enum] p8:
16123   // Two enumeration types are layout-compatible if they have the same
16124   // underlying type.
16125   return ED1->isComplete() && ED2->isComplete() &&
16126          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16127 }
16128 
16129 /// Check if two fields are layout-compatible.
16130 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
16131                                FieldDecl *Field2) {
16132   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16133     return false;
16134 
16135   if (Field1->isBitField() != Field2->isBitField())
16136     return false;
16137 
16138   if (Field1->isBitField()) {
16139     // Make sure that the bit-fields are the same length.
16140     unsigned Bits1 = Field1->getBitWidthValue(C);
16141     unsigned Bits2 = Field2->getBitWidthValue(C);
16142 
16143     if (Bits1 != Bits2)
16144       return false;
16145   }
16146 
16147   return true;
16148 }
16149 
16150 /// Check if two standard-layout structs are layout-compatible.
16151 /// (C++11 [class.mem] p17)
16152 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16153                                      RecordDecl *RD2) {
16154   // If both records are C++ classes, check that base classes match.
16155   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16156     // If one of records is a CXXRecordDecl we are in C++ mode,
16157     // thus the other one is a CXXRecordDecl, too.
16158     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16159     // Check number of base classes.
16160     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16161       return false;
16162 
16163     // Check the base classes.
16164     for (CXXRecordDecl::base_class_const_iterator
16165                Base1 = D1CXX->bases_begin(),
16166            BaseEnd1 = D1CXX->bases_end(),
16167               Base2 = D2CXX->bases_begin();
16168          Base1 != BaseEnd1;
16169          ++Base1, ++Base2) {
16170       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16171         return false;
16172     }
16173   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16174     // If only RD2 is a C++ class, it should have zero base classes.
16175     if (D2CXX->getNumBases() > 0)
16176       return false;
16177   }
16178 
16179   // Check the fields.
16180   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16181                              Field2End = RD2->field_end(),
16182                              Field1 = RD1->field_begin(),
16183                              Field1End = RD1->field_end();
16184   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16185     if (!isLayoutCompatible(C, *Field1, *Field2))
16186       return false;
16187   }
16188   if (Field1 != Field1End || Field2 != Field2End)
16189     return false;
16190 
16191   return true;
16192 }
16193 
16194 /// Check if two standard-layout unions are layout-compatible.
16195 /// (C++11 [class.mem] p18)
16196 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16197                                     RecordDecl *RD2) {
16198   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16199   for (auto *Field2 : RD2->fields())
16200     UnmatchedFields.insert(Field2);
16201 
16202   for (auto *Field1 : RD1->fields()) {
16203     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16204         I = UnmatchedFields.begin(),
16205         E = UnmatchedFields.end();
16206 
16207     for ( ; I != E; ++I) {
16208       if (isLayoutCompatible(C, Field1, *I)) {
16209         bool Result = UnmatchedFields.erase(*I);
16210         (void) Result;
16211         assert(Result);
16212         break;
16213       }
16214     }
16215     if (I == E)
16216       return false;
16217   }
16218 
16219   return UnmatchedFields.empty();
16220 }
16221 
16222 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16223                                RecordDecl *RD2) {
16224   if (RD1->isUnion() != RD2->isUnion())
16225     return false;
16226 
16227   if (RD1->isUnion())
16228     return isLayoutCompatibleUnion(C, RD1, RD2);
16229   else
16230     return isLayoutCompatibleStruct(C, RD1, RD2);
16231 }
16232 
16233 /// Check if two types are layout-compatible in C++11 sense.
16234 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16235   if (T1.isNull() || T2.isNull())
16236     return false;
16237 
16238   // C++11 [basic.types] p11:
16239   // If two types T1 and T2 are the same type, then T1 and T2 are
16240   // layout-compatible types.
16241   if (C.hasSameType(T1, T2))
16242     return true;
16243 
16244   T1 = T1.getCanonicalType().getUnqualifiedType();
16245   T2 = T2.getCanonicalType().getUnqualifiedType();
16246 
16247   const Type::TypeClass TC1 = T1->getTypeClass();
16248   const Type::TypeClass TC2 = T2->getTypeClass();
16249 
16250   if (TC1 != TC2)
16251     return false;
16252 
16253   if (TC1 == Type::Enum) {
16254     return isLayoutCompatible(C,
16255                               cast<EnumType>(T1)->getDecl(),
16256                               cast<EnumType>(T2)->getDecl());
16257   } else if (TC1 == Type::Record) {
16258     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16259       return false;
16260 
16261     return isLayoutCompatible(C,
16262                               cast<RecordType>(T1)->getDecl(),
16263                               cast<RecordType>(T2)->getDecl());
16264   }
16265 
16266   return false;
16267 }
16268 
16269 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16270 
16271 /// Given a type tag expression find the type tag itself.
16272 ///
16273 /// \param TypeExpr Type tag expression, as it appears in user's code.
16274 ///
16275 /// \param VD Declaration of an identifier that appears in a type tag.
16276 ///
16277 /// \param MagicValue Type tag magic value.
16278 ///
16279 /// \param isConstantEvaluated whether the evalaution should be performed in
16280 
16281 /// constant context.
16282 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16283                             const ValueDecl **VD, uint64_t *MagicValue,
16284                             bool isConstantEvaluated) {
16285   while(true) {
16286     if (!TypeExpr)
16287       return false;
16288 
16289     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16290 
16291     switch (TypeExpr->getStmtClass()) {
16292     case Stmt::UnaryOperatorClass: {
16293       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16294       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16295         TypeExpr = UO->getSubExpr();
16296         continue;
16297       }
16298       return false;
16299     }
16300 
16301     case Stmt::DeclRefExprClass: {
16302       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16303       *VD = DRE->getDecl();
16304       return true;
16305     }
16306 
16307     case Stmt::IntegerLiteralClass: {
16308       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16309       llvm::APInt MagicValueAPInt = IL->getValue();
16310       if (MagicValueAPInt.getActiveBits() <= 64) {
16311         *MagicValue = MagicValueAPInt.getZExtValue();
16312         return true;
16313       } else
16314         return false;
16315     }
16316 
16317     case Stmt::BinaryConditionalOperatorClass:
16318     case Stmt::ConditionalOperatorClass: {
16319       const AbstractConditionalOperator *ACO =
16320           cast<AbstractConditionalOperator>(TypeExpr);
16321       bool Result;
16322       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16323                                                      isConstantEvaluated)) {
16324         if (Result)
16325           TypeExpr = ACO->getTrueExpr();
16326         else
16327           TypeExpr = ACO->getFalseExpr();
16328         continue;
16329       }
16330       return false;
16331     }
16332 
16333     case Stmt::BinaryOperatorClass: {
16334       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16335       if (BO->getOpcode() == BO_Comma) {
16336         TypeExpr = BO->getRHS();
16337         continue;
16338       }
16339       return false;
16340     }
16341 
16342     default:
16343       return false;
16344     }
16345   }
16346 }
16347 
16348 /// Retrieve the C type corresponding to type tag TypeExpr.
16349 ///
16350 /// \param TypeExpr Expression that specifies a type tag.
16351 ///
16352 /// \param MagicValues Registered magic values.
16353 ///
16354 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16355 ///        kind.
16356 ///
16357 /// \param TypeInfo Information about the corresponding C type.
16358 ///
16359 /// \param isConstantEvaluated whether the evalaution should be performed in
16360 /// constant context.
16361 ///
16362 /// \returns true if the corresponding C type was found.
16363 static bool GetMatchingCType(
16364     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16365     const ASTContext &Ctx,
16366     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16367         *MagicValues,
16368     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16369     bool isConstantEvaluated) {
16370   FoundWrongKind = false;
16371 
16372   // Variable declaration that has type_tag_for_datatype attribute.
16373   const ValueDecl *VD = nullptr;
16374 
16375   uint64_t MagicValue;
16376 
16377   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16378     return false;
16379 
16380   if (VD) {
16381     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16382       if (I->getArgumentKind() != ArgumentKind) {
16383         FoundWrongKind = true;
16384         return false;
16385       }
16386       TypeInfo.Type = I->getMatchingCType();
16387       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16388       TypeInfo.MustBeNull = I->getMustBeNull();
16389       return true;
16390     }
16391     return false;
16392   }
16393 
16394   if (!MagicValues)
16395     return false;
16396 
16397   llvm::DenseMap<Sema::TypeTagMagicValue,
16398                  Sema::TypeTagData>::const_iterator I =
16399       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16400   if (I == MagicValues->end())
16401     return false;
16402 
16403   TypeInfo = I->second;
16404   return true;
16405 }
16406 
16407 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16408                                       uint64_t MagicValue, QualType Type,
16409                                       bool LayoutCompatible,
16410                                       bool MustBeNull) {
16411   if (!TypeTagForDatatypeMagicValues)
16412     TypeTagForDatatypeMagicValues.reset(
16413         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16414 
16415   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16416   (*TypeTagForDatatypeMagicValues)[Magic] =
16417       TypeTagData(Type, LayoutCompatible, MustBeNull);
16418 }
16419 
16420 static bool IsSameCharType(QualType T1, QualType T2) {
16421   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16422   if (!BT1)
16423     return false;
16424 
16425   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16426   if (!BT2)
16427     return false;
16428 
16429   BuiltinType::Kind T1Kind = BT1->getKind();
16430   BuiltinType::Kind T2Kind = BT2->getKind();
16431 
16432   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16433          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16434          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16435          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16436 }
16437 
16438 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16439                                     const ArrayRef<const Expr *> ExprArgs,
16440                                     SourceLocation CallSiteLoc) {
16441   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16442   bool IsPointerAttr = Attr->getIsPointer();
16443 
16444   // Retrieve the argument representing the 'type_tag'.
16445   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16446   if (TypeTagIdxAST >= ExprArgs.size()) {
16447     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16448         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16449     return;
16450   }
16451   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16452   bool FoundWrongKind;
16453   TypeTagData TypeInfo;
16454   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16455                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16456                         TypeInfo, isConstantEvaluated())) {
16457     if (FoundWrongKind)
16458       Diag(TypeTagExpr->getExprLoc(),
16459            diag::warn_type_tag_for_datatype_wrong_kind)
16460         << TypeTagExpr->getSourceRange();
16461     return;
16462   }
16463 
16464   // Retrieve the argument representing the 'arg_idx'.
16465   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16466   if (ArgumentIdxAST >= ExprArgs.size()) {
16467     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16468         << 1 << Attr->getArgumentIdx().getSourceIndex();
16469     return;
16470   }
16471   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16472   if (IsPointerAttr) {
16473     // Skip implicit cast of pointer to `void *' (as a function argument).
16474     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16475       if (ICE->getType()->isVoidPointerType() &&
16476           ICE->getCastKind() == CK_BitCast)
16477         ArgumentExpr = ICE->getSubExpr();
16478   }
16479   QualType ArgumentType = ArgumentExpr->getType();
16480 
16481   // Passing a `void*' pointer shouldn't trigger a warning.
16482   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16483     return;
16484 
16485   if (TypeInfo.MustBeNull) {
16486     // Type tag with matching void type requires a null pointer.
16487     if (!ArgumentExpr->isNullPointerConstant(Context,
16488                                              Expr::NPC_ValueDependentIsNotNull)) {
16489       Diag(ArgumentExpr->getExprLoc(),
16490            diag::warn_type_safety_null_pointer_required)
16491           << ArgumentKind->getName()
16492           << ArgumentExpr->getSourceRange()
16493           << TypeTagExpr->getSourceRange();
16494     }
16495     return;
16496   }
16497 
16498   QualType RequiredType = TypeInfo.Type;
16499   if (IsPointerAttr)
16500     RequiredType = Context.getPointerType(RequiredType);
16501 
16502   bool mismatch = false;
16503   if (!TypeInfo.LayoutCompatible) {
16504     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16505 
16506     // C++11 [basic.fundamental] p1:
16507     // Plain char, signed char, and unsigned char are three distinct types.
16508     //
16509     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16510     // char' depending on the current char signedness mode.
16511     if (mismatch)
16512       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16513                                            RequiredType->getPointeeType())) ||
16514           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16515         mismatch = false;
16516   } else
16517     if (IsPointerAttr)
16518       mismatch = !isLayoutCompatible(Context,
16519                                      ArgumentType->getPointeeType(),
16520                                      RequiredType->getPointeeType());
16521     else
16522       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16523 
16524   if (mismatch)
16525     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16526         << ArgumentType << ArgumentKind
16527         << TypeInfo.LayoutCompatible << RequiredType
16528         << ArgumentExpr->getSourceRange()
16529         << TypeTagExpr->getSourceRange();
16530 }
16531 
16532 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16533                                          CharUnits Alignment) {
16534   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16535 }
16536 
16537 void Sema::DiagnoseMisalignedMembers() {
16538   for (MisalignedMember &m : MisalignedMembers) {
16539     const NamedDecl *ND = m.RD;
16540     if (ND->getName().empty()) {
16541       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16542         ND = TD;
16543     }
16544     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16545         << m.MD << ND << m.E->getSourceRange();
16546   }
16547   MisalignedMembers.clear();
16548 }
16549 
16550 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16551   E = E->IgnoreParens();
16552   if (!T->isPointerType() && !T->isIntegerType())
16553     return;
16554   if (isa<UnaryOperator>(E) &&
16555       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16556     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16557     if (isa<MemberExpr>(Op)) {
16558       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16559       if (MA != MisalignedMembers.end() &&
16560           (T->isIntegerType() ||
16561            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16562                                    Context.getTypeAlignInChars(
16563                                        T->getPointeeType()) <= MA->Alignment))))
16564         MisalignedMembers.erase(MA);
16565     }
16566   }
16567 }
16568 
16569 void Sema::RefersToMemberWithReducedAlignment(
16570     Expr *E,
16571     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16572         Action) {
16573   const auto *ME = dyn_cast<MemberExpr>(E);
16574   if (!ME)
16575     return;
16576 
16577   // No need to check expressions with an __unaligned-qualified type.
16578   if (E->getType().getQualifiers().hasUnaligned())
16579     return;
16580 
16581   // For a chain of MemberExpr like "a.b.c.d" this list
16582   // will keep FieldDecl's like [d, c, b].
16583   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16584   const MemberExpr *TopME = nullptr;
16585   bool AnyIsPacked = false;
16586   do {
16587     QualType BaseType = ME->getBase()->getType();
16588     if (BaseType->isDependentType())
16589       return;
16590     if (ME->isArrow())
16591       BaseType = BaseType->getPointeeType();
16592     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16593     if (RD->isInvalidDecl())
16594       return;
16595 
16596     ValueDecl *MD = ME->getMemberDecl();
16597     auto *FD = dyn_cast<FieldDecl>(MD);
16598     // We do not care about non-data members.
16599     if (!FD || FD->isInvalidDecl())
16600       return;
16601 
16602     AnyIsPacked =
16603         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16604     ReverseMemberChain.push_back(FD);
16605 
16606     TopME = ME;
16607     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16608   } while (ME);
16609   assert(TopME && "We did not compute a topmost MemberExpr!");
16610 
16611   // Not the scope of this diagnostic.
16612   if (!AnyIsPacked)
16613     return;
16614 
16615   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16616   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16617   // TODO: The innermost base of the member expression may be too complicated.
16618   // For now, just disregard these cases. This is left for future
16619   // improvement.
16620   if (!DRE && !isa<CXXThisExpr>(TopBase))
16621       return;
16622 
16623   // Alignment expected by the whole expression.
16624   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16625 
16626   // No need to do anything else with this case.
16627   if (ExpectedAlignment.isOne())
16628     return;
16629 
16630   // Synthesize offset of the whole access.
16631   CharUnits Offset;
16632   for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16633     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16634 
16635   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16636   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16637       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16638 
16639   // The base expression of the innermost MemberExpr may give
16640   // stronger guarantees than the class containing the member.
16641   if (DRE && !TopME->isArrow()) {
16642     const ValueDecl *VD = DRE->getDecl();
16643     if (!VD->getType()->isReferenceType())
16644       CompleteObjectAlignment =
16645           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16646   }
16647 
16648   // Check if the synthesized offset fulfills the alignment.
16649   if (Offset % ExpectedAlignment != 0 ||
16650       // It may fulfill the offset it but the effective alignment may still be
16651       // lower than the expected expression alignment.
16652       CompleteObjectAlignment < ExpectedAlignment) {
16653     // If this happens, we want to determine a sensible culprit of this.
16654     // Intuitively, watching the chain of member expressions from right to
16655     // left, we start with the required alignment (as required by the field
16656     // type) but some packed attribute in that chain has reduced the alignment.
16657     // It may happen that another packed structure increases it again. But if
16658     // we are here such increase has not been enough. So pointing the first
16659     // FieldDecl that either is packed or else its RecordDecl is,
16660     // seems reasonable.
16661     FieldDecl *FD = nullptr;
16662     CharUnits Alignment;
16663     for (FieldDecl *FDI : ReverseMemberChain) {
16664       if (FDI->hasAttr<PackedAttr>() ||
16665           FDI->getParent()->hasAttr<PackedAttr>()) {
16666         FD = FDI;
16667         Alignment = std::min(
16668             Context.getTypeAlignInChars(FD->getType()),
16669             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16670         break;
16671       }
16672     }
16673     assert(FD && "We did not find a packed FieldDecl!");
16674     Action(E, FD->getParent(), FD, Alignment);
16675   }
16676 }
16677 
16678 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16679   using namespace std::placeholders;
16680 
16681   RefersToMemberWithReducedAlignment(
16682       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16683                      _2, _3, _4));
16684 }
16685 
16686 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
16687 // not a valid type, emit an error message and return true. Otherwise return
16688 // false.
16689 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
16690                                         QualType Ty) {
16691   if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
16692     S.Diag(Loc, diag::err_builtin_invalid_arg_type)
16693         << 1 << /* vector, integer or float ty*/ 0 << Ty;
16694     return true;
16695   }
16696   return false;
16697 }
16698 
16699 bool Sema::SemaBuiltinElementwiseMathOneArg(CallExpr *TheCall) {
16700   if (checkArgCount(*this, TheCall, 1))
16701     return true;
16702 
16703   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16704   SourceLocation ArgLoc = TheCall->getArg(0)->getBeginLoc();
16705   if (A.isInvalid())
16706     return true;
16707 
16708   TheCall->setArg(0, A.get());
16709   QualType TyA = A.get()->getType();
16710   if (checkMathBuiltinElementType(*this, ArgLoc, TyA))
16711     return true;
16712 
16713   QualType EltTy = TyA;
16714   if (auto *VecTy = EltTy->getAs<VectorType>())
16715     EltTy = VecTy->getElementType();
16716   if (EltTy->isUnsignedIntegerType())
16717     return Diag(ArgLoc, diag::err_builtin_invalid_arg_type)
16718            << 1 << /*signed integer or float ty*/ 3 << TyA;
16719 
16720   TheCall->setType(TyA);
16721   return false;
16722 }
16723 
16724 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
16725   if (checkArgCount(*this, TheCall, 2))
16726     return true;
16727 
16728   ExprResult A = TheCall->getArg(0);
16729   ExprResult B = TheCall->getArg(1);
16730   // Do standard promotions between the two arguments, returning their common
16731   // type.
16732   QualType Res =
16733       UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
16734   if (A.isInvalid() || B.isInvalid())
16735     return true;
16736 
16737   QualType TyA = A.get()->getType();
16738   QualType TyB = B.get()->getType();
16739 
16740   if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
16741     return Diag(A.get()->getBeginLoc(),
16742                 diag::err_typecheck_call_different_arg_types)
16743            << TyA << TyB;
16744 
16745   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
16746     return true;
16747 
16748   TheCall->setArg(0, A.get());
16749   TheCall->setArg(1, B.get());
16750   TheCall->setType(Res);
16751   return false;
16752 }
16753 
16754 bool Sema::SemaBuiltinReduceMath(CallExpr *TheCall) {
16755   if (checkArgCount(*this, TheCall, 1))
16756     return true;
16757 
16758   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16759   if (A.isInvalid())
16760     return true;
16761 
16762   TheCall->setArg(0, A.get());
16763   const VectorType *TyA = A.get()->getType()->getAs<VectorType>();
16764   if (!TyA) {
16765     SourceLocation ArgLoc = TheCall->getArg(0)->getBeginLoc();
16766     return Diag(ArgLoc, diag::err_builtin_invalid_arg_type)
16767            << 1 << /* vector ty*/ 4 << A.get()->getType();
16768   }
16769 
16770   TheCall->setType(TyA->getElementType());
16771   return false;
16772 }
16773 
16774 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16775                                             ExprResult CallResult) {
16776   if (checkArgCount(*this, TheCall, 1))
16777     return ExprError();
16778 
16779   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16780   if (MatrixArg.isInvalid())
16781     return MatrixArg;
16782   Expr *Matrix = MatrixArg.get();
16783 
16784   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16785   if (!MType) {
16786     Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16787         << 1 << /* matrix ty*/ 1 << Matrix->getType();
16788     return ExprError();
16789   }
16790 
16791   // Create returned matrix type by swapping rows and columns of the argument
16792   // matrix type.
16793   QualType ResultType = Context.getConstantMatrixType(
16794       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16795 
16796   // Change the return type to the type of the returned matrix.
16797   TheCall->setType(ResultType);
16798 
16799   // Update call argument to use the possibly converted matrix argument.
16800   TheCall->setArg(0, Matrix);
16801   return CallResult;
16802 }
16803 
16804 // Get and verify the matrix dimensions.
16805 static llvm::Optional<unsigned>
16806 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16807   SourceLocation ErrorPos;
16808   Optional<llvm::APSInt> Value =
16809       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16810   if (!Value) {
16811     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16812         << Name;
16813     return {};
16814   }
16815   uint64_t Dim = Value->getZExtValue();
16816   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16817     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16818         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16819     return {};
16820   }
16821   return Dim;
16822 }
16823 
16824 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16825                                                   ExprResult CallResult) {
16826   if (!getLangOpts().MatrixTypes) {
16827     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16828     return ExprError();
16829   }
16830 
16831   if (checkArgCount(*this, TheCall, 4))
16832     return ExprError();
16833 
16834   unsigned PtrArgIdx = 0;
16835   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16836   Expr *RowsExpr = TheCall->getArg(1);
16837   Expr *ColumnsExpr = TheCall->getArg(2);
16838   Expr *StrideExpr = TheCall->getArg(3);
16839 
16840   bool ArgError = false;
16841 
16842   // Check pointer argument.
16843   {
16844     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16845     if (PtrConv.isInvalid())
16846       return PtrConv;
16847     PtrExpr = PtrConv.get();
16848     TheCall->setArg(0, PtrExpr);
16849     if (PtrExpr->isTypeDependent()) {
16850       TheCall->setType(Context.DependentTy);
16851       return TheCall;
16852     }
16853   }
16854 
16855   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16856   QualType ElementTy;
16857   if (!PtrTy) {
16858     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16859         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
16860     ArgError = true;
16861   } else {
16862     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16863 
16864     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16865       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16866           << PtrArgIdx + 1 << /* pointer to element ty*/ 2
16867           << PtrExpr->getType();
16868       ArgError = true;
16869     }
16870   }
16871 
16872   // Apply default Lvalue conversions and convert the expression to size_t.
16873   auto ApplyArgumentConversions = [this](Expr *E) {
16874     ExprResult Conv = DefaultLvalueConversion(E);
16875     if (Conv.isInvalid())
16876       return Conv;
16877 
16878     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16879   };
16880 
16881   // Apply conversion to row and column expressions.
16882   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16883   if (!RowsConv.isInvalid()) {
16884     RowsExpr = RowsConv.get();
16885     TheCall->setArg(1, RowsExpr);
16886   } else
16887     RowsExpr = nullptr;
16888 
16889   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16890   if (!ColumnsConv.isInvalid()) {
16891     ColumnsExpr = ColumnsConv.get();
16892     TheCall->setArg(2, ColumnsExpr);
16893   } else
16894     ColumnsExpr = nullptr;
16895 
16896   // If any any part of the result matrix type is still pending, just use
16897   // Context.DependentTy, until all parts are resolved.
16898   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16899       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16900     TheCall->setType(Context.DependentTy);
16901     return CallResult;
16902   }
16903 
16904   // Check row and column dimensions.
16905   llvm::Optional<unsigned> MaybeRows;
16906   if (RowsExpr)
16907     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16908 
16909   llvm::Optional<unsigned> MaybeColumns;
16910   if (ColumnsExpr)
16911     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16912 
16913   // Check stride argument.
16914   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16915   if (StrideConv.isInvalid())
16916     return ExprError();
16917   StrideExpr = StrideConv.get();
16918   TheCall->setArg(3, StrideExpr);
16919 
16920   if (MaybeRows) {
16921     if (Optional<llvm::APSInt> Value =
16922             StrideExpr->getIntegerConstantExpr(Context)) {
16923       uint64_t Stride = Value->getZExtValue();
16924       if (Stride < *MaybeRows) {
16925         Diag(StrideExpr->getBeginLoc(),
16926              diag::err_builtin_matrix_stride_too_small);
16927         ArgError = true;
16928       }
16929     }
16930   }
16931 
16932   if (ArgError || !MaybeRows || !MaybeColumns)
16933     return ExprError();
16934 
16935   TheCall->setType(
16936       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16937   return CallResult;
16938 }
16939 
16940 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16941                                                    ExprResult CallResult) {
16942   if (checkArgCount(*this, TheCall, 3))
16943     return ExprError();
16944 
16945   unsigned PtrArgIdx = 1;
16946   Expr *MatrixExpr = TheCall->getArg(0);
16947   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16948   Expr *StrideExpr = TheCall->getArg(2);
16949 
16950   bool ArgError = false;
16951 
16952   {
16953     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16954     if (MatrixConv.isInvalid())
16955       return MatrixConv;
16956     MatrixExpr = MatrixConv.get();
16957     TheCall->setArg(0, MatrixExpr);
16958   }
16959   if (MatrixExpr->isTypeDependent()) {
16960     TheCall->setType(Context.DependentTy);
16961     return TheCall;
16962   }
16963 
16964   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16965   if (!MatrixTy) {
16966     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16967         << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
16968     ArgError = true;
16969   }
16970 
16971   {
16972     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16973     if (PtrConv.isInvalid())
16974       return PtrConv;
16975     PtrExpr = PtrConv.get();
16976     TheCall->setArg(1, PtrExpr);
16977     if (PtrExpr->isTypeDependent()) {
16978       TheCall->setType(Context.DependentTy);
16979       return TheCall;
16980     }
16981   }
16982 
16983   // Check pointer argument.
16984   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16985   if (!PtrTy) {
16986     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16987         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
16988     ArgError = true;
16989   } else {
16990     QualType ElementTy = PtrTy->getPointeeType();
16991     if (ElementTy.isConstQualified()) {
16992       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16993       ArgError = true;
16994     }
16995     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16996     if (MatrixTy &&
16997         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16998       Diag(PtrExpr->getBeginLoc(),
16999            diag::err_builtin_matrix_pointer_arg_mismatch)
17000           << ElementTy << MatrixTy->getElementType();
17001       ArgError = true;
17002     }
17003   }
17004 
17005   // Apply default Lvalue conversions and convert the stride expression to
17006   // size_t.
17007   {
17008     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17009     if (StrideConv.isInvalid())
17010       return StrideConv;
17011 
17012     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17013     if (StrideConv.isInvalid())
17014       return StrideConv;
17015     StrideExpr = StrideConv.get();
17016     TheCall->setArg(2, StrideExpr);
17017   }
17018 
17019   // Check stride argument.
17020   if (MatrixTy) {
17021     if (Optional<llvm::APSInt> Value =
17022             StrideExpr->getIntegerConstantExpr(Context)) {
17023       uint64_t Stride = Value->getZExtValue();
17024       if (Stride < MatrixTy->getNumRows()) {
17025         Diag(StrideExpr->getBeginLoc(),
17026              diag::err_builtin_matrix_stride_too_small);
17027         ArgError = true;
17028       }
17029     }
17030   }
17031 
17032   if (ArgError)
17033     return ExprError();
17034 
17035   return CallResult;
17036 }
17037 
17038 /// \brief Enforce the bounds of a TCB
17039 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
17040 /// directly calls other functions in the same TCB as marked by the enforce_tcb
17041 /// and enforce_tcb_leaf attributes.
17042 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
17043                                const FunctionDecl *Callee) {
17044   const FunctionDecl *Caller = getCurFunctionDecl();
17045 
17046   // Calls to builtins are not enforced.
17047   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
17048       Callee->getBuiltinID() != 0)
17049     return;
17050 
17051   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17052   // all TCBs the callee is a part of.
17053   llvm::StringSet<> CalleeTCBs;
17054   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
17055            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17056   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
17057            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17058 
17059   // Go through the TCBs the caller is a part of and emit warnings if Caller
17060   // is in a TCB that the Callee is not.
17061   for_each(
17062       Caller->specific_attrs<EnforceTCBAttr>(),
17063       [&](const auto *A) {
17064         StringRef CallerTCB = A->getTCBName();
17065         if (CalleeTCBs.count(CallerTCB) == 0) {
17066           this->Diag(TheCall->getExprLoc(),
17067                      diag::warn_tcb_enforcement_violation) << Callee
17068                                                            << CallerTCB;
17069         }
17070       });
17071 }
17072